three.module.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475
  1. // import { TTFLoader } from 'three/addons/loaders/TTFLoader.js';
  2. // import { Font } from 'three/addons/loaders/FontLoader.js';
  3. // import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
  4. /**
  5. * @license
  6. * Copyright 2010-2022 Three.js Authors
  7. * SPDX-License-Identifier: MIT
  8. */
  9. const REVISION = '166dev';
  10. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  11. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  12. const CullFaceNone = 0;
  13. const CullFaceBack = 1;
  14. const CullFaceFront = 2;
  15. const CullFaceFrontBack = 3;
  16. const BasicShadowMap = 0;
  17. const PCFShadowMap = 1;
  18. const PCFSoftShadowMap = 2;
  19. const VSMShadowMap = 3;
  20. const FrontSide = 0;
  21. const BackSide = 1;
  22. const DoubleSide = 2;
  23. const NoBlending = 0;
  24. const NormalBlending = 1;
  25. const AdditiveBlending = 2;
  26. const SubtractiveBlending = 3;
  27. const MultiplyBlending = 4;
  28. const CustomBlending = 5;
  29. const AddEquation = 100;
  30. const SubtractEquation = 101;
  31. const ReverseSubtractEquation = 102;
  32. const MinEquation = 103;
  33. const MaxEquation = 104;
  34. const ZeroFactor = 200;
  35. const OneFactor = 201;
  36. const SrcColorFactor = 202;
  37. const OneMinusSrcColorFactor = 203;
  38. const SrcAlphaFactor = 204;
  39. const OneMinusSrcAlphaFactor = 205;
  40. const DstAlphaFactor = 206;
  41. const OneMinusDstAlphaFactor = 207;
  42. const DstColorFactor = 208;
  43. const OneMinusDstColorFactor = 209;
  44. const SrcAlphaSaturateFactor = 210;
  45. const NeverDepth = 0;
  46. const AlwaysDepth = 1;
  47. const LessDepth = 2;
  48. const LessEqualDepth = 3;
  49. const EqualDepth = 4;
  50. const GreaterEqualDepth = 5;
  51. const GreaterDepth = 6;
  52. const NotEqualDepth = 7;
  53. const MultiplyOperation = 0;
  54. const MixOperation = 1;
  55. const AddOperation = 2;
  56. const NoToneMapping = 0;
  57. const LinearToneMapping = 1;
  58. const ReinhardToneMapping = 2;
  59. const CineonToneMapping = 3;
  60. const ACESFilmicToneMapping = 4;
  61. const CustomToneMapping = 5;
  62. const UVMapping = 300;
  63. const CubeReflectionMapping = 301;
  64. const CubeRefractionMapping = 302;
  65. const EquirectangularReflectionMapping = 303;
  66. const EquirectangularRefractionMapping = 304;
  67. const CubeUVReflectionMapping = 306;
  68. const RepeatWrapping = 1000;
  69. const ClampToEdgeWrapping = 1001;
  70. const MirroredRepeatWrapping = 1002;
  71. const NearestFilter = 1003;
  72. const NearestMipmapNearestFilter = 1004;
  73. const NearestMipMapNearestFilter = 1004;
  74. const NearestMipmapLinearFilter = 1005;
  75. const NearestMipMapLinearFilter = 1005;
  76. const LinearFilter = 1006;
  77. const LinearMipmapNearestFilter = 1007;
  78. const LinearMipMapNearestFilter = 1007;
  79. const LinearMipmapLinearFilter = 1008;
  80. const LinearMipMapLinearFilter = 1008;
  81. const UnsignedByteType = 1009;
  82. const ByteType = 1010;
  83. const ShortType = 1011;
  84. const UnsignedShortType = 1012;
  85. const IntType = 1013;
  86. const UnsignedIntType = 1014;
  87. const FloatType = 1015;
  88. const HalfFloatType = 1016;
  89. const UnsignedShort4444Type = 1017;
  90. const UnsignedShort5551Type = 1018;
  91. const UnsignedInt248Type = 1020;
  92. const AlphaFormat = 1021;
  93. const RGBFormat = 1022; // @deprecated since r137
  94. const RGBAFormat = 1023;
  95. const LuminanceFormat = 1024;
  96. const LuminanceAlphaFormat = 1025;
  97. const DepthFormat = 1026;
  98. const DepthStencilFormat = 1027;
  99. const RedFormat = 1028;
  100. const RedIntegerFormat = 1029;
  101. const RGFormat = 1030;
  102. const RGIntegerFormat = 1031;
  103. const RGBAIntegerFormat = 1033;
  104. const RGB_S3TC_DXT1_Format = 33776;
  105. const RGBA_S3TC_DXT1_Format = 33777;
  106. const RGBA_S3TC_DXT3_Format = 33778;
  107. const RGBA_S3TC_DXT5_Format = 33779;
  108. const RGB_PVRTC_4BPPV1_Format = 35840;
  109. const RGB_PVRTC_2BPPV1_Format = 35841;
  110. const RGBA_PVRTC_4BPPV1_Format = 35842;
  111. const RGBA_PVRTC_2BPPV1_Format = 35843;
  112. const RGB_ETC1_Format = 36196;
  113. const RGB_ETC2_Format = 37492;
  114. const RGBA_ETC2_EAC_Format = 37496;
  115. const RGBA_ASTC_4x4_Format = 37808;
  116. const RGBA_ASTC_5x4_Format = 37809;
  117. const RGBA_ASTC_5x5_Format = 37810;
  118. const RGBA_ASTC_6x5_Format = 37811;
  119. const RGBA_ASTC_6x6_Format = 37812;
  120. const RGBA_ASTC_8x5_Format = 37813;
  121. const RGBA_ASTC_8x6_Format = 37814;
  122. const RGBA_ASTC_8x8_Format = 37815;
  123. const RGBA_ASTC_10x5_Format = 37816;
  124. const RGBA_ASTC_10x6_Format = 37817;
  125. const RGBA_ASTC_10x8_Format = 37818;
  126. const RGBA_ASTC_10x10_Format = 37819;
  127. const RGBA_ASTC_12x10_Format = 37820;
  128. const RGBA_ASTC_12x12_Format = 37821;
  129. const RGBA_BPTC_Format = 36492;
  130. const LoopOnce = 2200;
  131. const LoopRepeat = 2201;
  132. const LoopPingPong = 2202;
  133. const InterpolateDiscrete = 2300;
  134. const InterpolateLinear = 2301;
  135. const InterpolateSmooth = 2302;
  136. const ZeroCurvatureEnding = 2400;
  137. const ZeroSlopeEnding = 2401;
  138. const WrapAroundEnding = 2402;
  139. const NormalAnimationBlendMode = 2500;
  140. const AdditiveAnimationBlendMode = 2501;
  141. const TrianglesDrawMode = 0;
  142. const TriangleStripDrawMode = 1;
  143. const TriangleFanDrawMode = 2;
  144. const LinearEncoding = 3000;
  145. const sRGBEncoding = 3001;
  146. const BasicDepthPacking = 3200;
  147. const RGBADepthPacking = 3201;
  148. const TangentSpaceNormalMap = 0;
  149. const ObjectSpaceNormalMap = 1;
  150. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  151. const NoColorSpace = '';
  152. const SRGBColorSpace = 'srgb';
  153. const LinearSRGBColorSpace = 'srgb-linear';
  154. const ZeroStencilOp = 0;
  155. const KeepStencilOp = 7680;
  156. const ReplaceStencilOp = 7681;
  157. const IncrementStencilOp = 7682;
  158. const DecrementStencilOp = 7683;
  159. const IncrementWrapStencilOp = 34055;
  160. const DecrementWrapStencilOp = 34056;
  161. const InvertStencilOp = 5386;
  162. const NeverStencilFunc = 512;
  163. const LessStencilFunc = 513;
  164. const EqualStencilFunc = 514;
  165. const LessEqualStencilFunc = 515;
  166. const GreaterStencilFunc = 516;
  167. const NotEqualStencilFunc = 517;
  168. const GreaterEqualStencilFunc = 518;
  169. const AlwaysStencilFunc = 519;
  170. const StaticDrawUsage = 35044;
  171. const DynamicDrawUsage = 35048;
  172. const StreamDrawUsage = 35040;
  173. const StaticReadUsage = 35045;
  174. const DynamicReadUsage = 35049;
  175. const StreamReadUsage = 35041;
  176. const StaticCopyUsage = 35046;
  177. const DynamicCopyUsage = 35050;
  178. const StreamCopyUsage = 35042;
  179. const GLSL1 = '100';
  180. const GLSL3 = '300 es';
  181. const _SRGBAFormat = 1035; // fallback for WebGL 1
  182. //end load function
  183. /**
  184. * https://github.com/mrdoob/eventdispatcher.js/
  185. */
  186. class EventDispatcher {
  187. addEventListener( type, listener ) {
  188. if ( this._listeners === undefined ) this._listeners = {};
  189. const listeners = this._listeners;
  190. if ( listeners[ type ] === undefined ) {
  191. listeners[ type ] = [];
  192. }
  193. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  194. listeners[ type ].push( listener );
  195. }
  196. }
  197. hasEventListener( type, listener ) {
  198. if ( this._listeners === undefined ) return false;
  199. const listeners = this._listeners;
  200. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  201. }
  202. removeEventListener( type, listener ) {
  203. if ( this._listeners === undefined ) return;
  204. const listeners = this._listeners;
  205. const listenerArray = listeners[ type ];
  206. if ( listenerArray !== undefined ) {
  207. const index = listenerArray.indexOf( listener );
  208. if ( index !== - 1 ) {
  209. listenerArray.splice( index, 1 );
  210. }
  211. }
  212. }
  213. dispatchEvent( event ) {
  214. if ( this._listeners === undefined ) return;
  215. const listeners = this._listeners;
  216. const listenerArray = listeners[ event.type ];
  217. if ( listenerArray !== undefined ) {
  218. event.target = this;
  219. // Make a copy, in case listeners are removed while iterating.
  220. const array = listenerArray.slice( 0 );
  221. for ( let i = 0, l = array.length; i < l; i ++ ) {
  222. array[ i ].call( this, event );
  223. }
  224. event.target = null;
  225. }
  226. }
  227. }
  228. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  229. let _seed = 1234567;
  230. const DEG2RAD = Math.PI / 180;
  231. const RAD2DEG = 180 / Math.PI;
  232. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  233. function generateUUID() {
  234. const d0 = Math.random() * 0xffffffff | 0;
  235. const d1 = Math.random() * 0xffffffff | 0;
  236. const d2 = Math.random() * 0xffffffff | 0;
  237. const d3 = Math.random() * 0xffffffff | 0;
  238. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  239. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  240. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  241. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  242. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  243. return uuid.toLowerCase();
  244. }
  245. function clamp( value, min, max ) {
  246. return Math.max( min, Math.min( max, value ) );
  247. }
  248. // compute euclidean modulo of m % n
  249. // https://en.wikipedia.org/wiki/Modulo_operation
  250. function euclideanModulo( n, m ) {
  251. return ( ( n % m ) + m ) % m;
  252. }
  253. // Linear mapping from range <a1, a2> to range <b1, b2>
  254. function mapLinear( x, a1, a2, b1, b2 ) {
  255. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  256. }
  257. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  258. function inverseLerp( x, y, value ) {
  259. if ( x !== y ) {
  260. return ( value - x ) / ( y - x );
  261. } else {
  262. return 0;
  263. }
  264. }
  265. // https://en.wikipedia.org/wiki/Linear_interpolation
  266. function lerp( x, y, t ) {
  267. return ( 1 - t ) * x + t * y;
  268. }
  269. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  270. function damp( x, y, lambda, dt ) {
  271. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  272. }
  273. // https://www.desmos.com/calculator/vcsjnyz7x4
  274. function pingpong( x, length = 1 ) {
  275. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  276. }
  277. // http://en.wikipedia.org/wiki/Smoothstep
  278. function smoothstep( x, min, max ) {
  279. if ( x <= min ) return 0;
  280. if ( x >= max ) return 1;
  281. x = ( x - min ) / ( max - min );
  282. return x * x * ( 3 - 2 * x );
  283. }
  284. function smootherstep( x, min, max ) {
  285. if ( x <= min ) return 0;
  286. if ( x >= max ) return 1;
  287. x = ( x - min ) / ( max - min );
  288. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  289. }
  290. // Random integer from <low, high> interval
  291. function randInt( low, high ) {
  292. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  293. }
  294. // Random float from <low, high> interval
  295. function randFloat( low, high ) {
  296. return low + Math.random() * ( high - low );
  297. }
  298. // Random float from <-range/2, range/2> interval
  299. function randFloatSpread( range ) {
  300. return range * ( 0.5 - Math.random() );
  301. }
  302. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  303. function seededRandom( s ) {
  304. if ( s !== undefined ) _seed = s;
  305. // Mulberry32 generator
  306. let t = _seed += 0x6D2B79F5;
  307. t = Math.imul( t ^ t >>> 15, t | 1 );
  308. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  309. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  310. }
  311. function degToRad( degrees ) {
  312. return degrees * DEG2RAD;
  313. }
  314. function radToDeg( radians ) {
  315. return radians * RAD2DEG;
  316. }
  317. function isPowerOfTwo( value ) {
  318. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  319. }
  320. function ceilPowerOfTwo( value ) {
  321. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  322. }
  323. function floorPowerOfTwo( value ) {
  324. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  325. }
  326. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  327. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  328. // rotations are applied to the axes in the order specified by 'order'
  329. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  330. // angles are in radians
  331. const cos = Math.cos;
  332. const sin = Math.sin;
  333. const c2 = cos( b / 2 );
  334. const s2 = sin( b / 2 );
  335. const c13 = cos( ( a + c ) / 2 );
  336. const s13 = sin( ( a + c ) / 2 );
  337. const c1_3 = cos( ( a - c ) / 2 );
  338. const s1_3 = sin( ( a - c ) / 2 );
  339. const c3_1 = cos( ( c - a ) / 2 );
  340. const s3_1 = sin( ( c - a ) / 2 );
  341. switch ( order ) {
  342. case 'XYX':
  343. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  344. break;
  345. case 'YZY':
  346. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  347. break;
  348. case 'ZXZ':
  349. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  350. break;
  351. case 'XZX':
  352. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  353. break;
  354. case 'YXY':
  355. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  356. break;
  357. case 'ZYZ':
  358. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  359. break;
  360. default:
  361. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  362. }
  363. }
  364. function denormalize( value, array ) {
  365. switch ( array.constructor ) {
  366. case Float32Array:
  367. return value;
  368. case Uint16Array:
  369. return value / 65535.0;
  370. case Uint8Array:
  371. return value / 255.0;
  372. case Int16Array:
  373. return Math.max( value / 32767.0, - 1.0 );
  374. case Int8Array:
  375. return Math.max( value / 127.0, - 1.0 );
  376. default:
  377. throw new Error( 'Invalid component type.' );
  378. }
  379. }
  380. function normalize( value, array ) {
  381. switch ( array.constructor ) {
  382. case Float32Array:
  383. return value;
  384. case Uint16Array:
  385. return Math.round( value * 65535.0 );
  386. case Uint8Array:
  387. return Math.round( value * 255.0 );
  388. case Int16Array:
  389. return Math.round( value * 32767.0 );
  390. case Int8Array:
  391. return Math.round( value * 127.0 );
  392. default:
  393. throw new Error( 'Invalid component type.' );
  394. }
  395. }
  396. var MathUtils = /*#__PURE__*/Object.freeze({
  397. __proto__: null,
  398. DEG2RAD: DEG2RAD,
  399. RAD2DEG: RAD2DEG,
  400. generateUUID: generateUUID,
  401. clamp: clamp,
  402. euclideanModulo: euclideanModulo,
  403. mapLinear: mapLinear,
  404. inverseLerp: inverseLerp,
  405. lerp: lerp,
  406. damp: damp,
  407. pingpong: pingpong,
  408. smoothstep: smoothstep,
  409. smootherstep: smootherstep,
  410. randInt: randInt,
  411. randFloat: randFloat,
  412. randFloatSpread: randFloatSpread,
  413. seededRandom: seededRandom,
  414. degToRad: degToRad,
  415. radToDeg: radToDeg,
  416. isPowerOfTwo: isPowerOfTwo,
  417. ceilPowerOfTwo: ceilPowerOfTwo,
  418. floorPowerOfTwo: floorPowerOfTwo,
  419. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  420. normalize: normalize,
  421. denormalize: denormalize
  422. });
  423. class Vector2 {
  424. constructor( x = 0, y = 0 ) {
  425. Vector2.prototype.isVector2 = true;
  426. this.x = x;
  427. this.y = y;
  428. }
  429. get width() {
  430. return this.x;
  431. }
  432. set width( value ) {
  433. this.x = value;
  434. }
  435. get height() {
  436. return this.y;
  437. }
  438. set height( value ) {
  439. this.y = value;
  440. }
  441. set( x, y ) {
  442. this.x = x;
  443. this.y = y;
  444. return this;
  445. }
  446. setScalar( scalar ) {
  447. this.x = scalar;
  448. this.y = scalar;
  449. return this;
  450. }
  451. setX( x ) {
  452. this.x = x;
  453. return this;
  454. }
  455. setY( y ) {
  456. this.y = y;
  457. return this;
  458. }
  459. setComponent( index, value ) {
  460. switch ( index ) {
  461. case 0: this.x = value; break;
  462. case 1: this.y = value; break;
  463. default: throw new Error( 'index is out of range: ' + index );
  464. }
  465. return this;
  466. }
  467. getComponent( index ) {
  468. switch ( index ) {
  469. case 0: return this.x;
  470. case 1: return this.y;
  471. default: throw new Error( 'index is out of range: ' + index );
  472. }
  473. }
  474. clone() {
  475. return new this.constructor( this.x, this.y );
  476. }
  477. copy( v ) {
  478. this.x = v.x;
  479. this.y = v.y;
  480. return this;
  481. }
  482. add( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. return this;
  486. }
  487. addScalar( s ) {
  488. this.x += s;
  489. this.y += s;
  490. return this;
  491. }
  492. addVectors( a, b ) {
  493. this.x = a.x + b.x;
  494. this.y = a.y + b.y;
  495. return this;
  496. }
  497. addScaledVector( v, s ) {
  498. this.x += v.x * s;
  499. this.y += v.y * s;
  500. return this;
  501. }
  502. sub( v ) {
  503. this.x -= v.x;
  504. this.y -= v.y;
  505. return this;
  506. }
  507. subScalar( s ) {
  508. this.x -= s;
  509. this.y -= s;
  510. return this;
  511. }
  512. subVectors( a, b ) {
  513. this.x = a.x - b.x;
  514. this.y = a.y - b.y;
  515. return this;
  516. }
  517. multiply( v ) {
  518. this.x *= v.x;
  519. this.y *= v.y;
  520. return this;
  521. }
  522. multiplyScalar( scalar ) {
  523. this.x *= scalar;
  524. this.y *= scalar;
  525. return this;
  526. }
  527. divide( v ) {
  528. this.x /= v.x;
  529. this.y /= v.y;
  530. return this;
  531. }
  532. divideScalar( scalar ) {
  533. return this.multiplyScalar( 1 / scalar );
  534. }
  535. applyMatrix3( m ) {
  536. const x = this.x, y = this.y;
  537. const e = m.elements;
  538. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  539. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  540. return this;
  541. }
  542. min( v ) {
  543. this.x = Math.min( this.x, v.x );
  544. this.y = Math.min( this.y, v.y );
  545. return this;
  546. }
  547. max( v ) {
  548. this.x = Math.max( this.x, v.x );
  549. this.y = Math.max( this.y, v.y );
  550. return this;
  551. }
  552. clamp( min, max ) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  555. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  556. return this;
  557. }
  558. clampScalar( minVal, maxVal ) {
  559. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  560. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  561. return this;
  562. }
  563. clampLength( min, max ) {
  564. const length = this.length();
  565. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  566. }
  567. floor() {
  568. this.x = Math.floor( this.x );
  569. this.y = Math.floor( this.y );
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil( this.x );
  574. this.y = Math.ceil( this.y );
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round( this.x );
  579. this.y = Math.round( this.y );
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  584. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  585. return this;
  586. }
  587. negate() {
  588. this.x = - this.x;
  589. this.y = - this.y;
  590. return this;
  591. }
  592. dot( v ) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross( v ) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt( this.x * this.x + this.y * this.y );
  603. }
  604. manhattanLength() {
  605. return Math.abs( this.x ) + Math.abs( this.y );
  606. }
  607. normalize() {
  608. return this.divideScalar( this.length() || 1 );
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo( v ) {
  616. return Math.sqrt( this.distanceToSquared( v ) );
  617. }
  618. distanceToSquared( v ) {
  619. const dx = this.x - v.x, dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo( v ) {
  623. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  624. }
  625. setLength( length ) {
  626. return this.normalize().multiplyScalar( length );
  627. }
  628. lerp( v, alpha ) {
  629. this.x += ( v.x - this.x ) * alpha;
  630. this.y += ( v.y - this.y ) * alpha;
  631. return this;
  632. }
  633. lerpVectors( v1, v2, alpha ) {
  634. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  635. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  636. return this;
  637. }
  638. equals( v ) {
  639. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  640. }
  641. fromArray( array, offset = 0 ) {
  642. this.x = array[ offset ];
  643. this.y = array[ offset + 1 ];
  644. return this;
  645. }
  646. toArray( array = [], offset = 0 ) {
  647. array[ offset ] = this.x;
  648. array[ offset + 1 ] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute( attribute, index ) {
  652. this.x = attribute.getX( index );
  653. this.y = attribute.getY( index );
  654. return this;
  655. }
  656. rotateAround( center, angle ) {
  657. const c = Math.cos( angle ), s = Math.sin( angle );
  658. const x = this.x - center.x;
  659. const y = this.y - center.y;
  660. this.x = x * c - y * s + center.x;
  661. this.y = x * s + y * c + center.y;
  662. return this;
  663. }
  664. random() {
  665. this.x = Math.random();
  666. this.y = Math.random();
  667. return this;
  668. }
  669. *[ Symbol.iterator ]() {
  670. yield this.x;
  671. yield this.y;
  672. }
  673. }
  674. class Matrix3 {
  675. constructor() {
  676. Matrix3.prototype.isMatrix3 = true;
  677. this.elements = [
  678. 1, 0, 0,
  679. 0, 1, 0,
  680. 0, 0, 1
  681. ];
  682. }
  683. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  684. const te = this.elements;
  685. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  686. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  687. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  688. return this;
  689. }
  690. identity() {
  691. this.set(
  692. 1, 0, 0,
  693. 0, 1, 0,
  694. 0, 0, 1
  695. );
  696. return this;
  697. }
  698. copy( m ) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  702. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  703. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  704. return this;
  705. }
  706. extractBasis( xAxis, yAxis, zAxis ) {
  707. xAxis.setFromMatrix3Column( this, 0 );
  708. yAxis.setFromMatrix3Column( this, 1 );
  709. zAxis.setFromMatrix3Column( this, 2 );
  710. return this;
  711. }
  712. setFromMatrix4( m ) {
  713. const me = m.elements;
  714. this.set(
  715. me[ 0 ], me[ 4 ], me[ 8 ],
  716. me[ 1 ], me[ 5 ], me[ 9 ],
  717. me[ 2 ], me[ 6 ], me[ 10 ]
  718. );
  719. return this;
  720. }
  721. multiply( m ) {
  722. return this.multiplyMatrices( this, m );
  723. }
  724. premultiply( m ) {
  725. return this.multiplyMatrices( m, this );
  726. }
  727. multiplyMatrices( a, b ) {
  728. const ae = a.elements;
  729. const be = b.elements;
  730. const te = this.elements;
  731. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  732. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  733. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  734. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  735. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  736. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  737. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  738. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  739. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  740. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  741. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  742. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  743. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  744. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  745. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  746. return this;
  747. }
  748. multiplyScalar( s ) {
  749. const te = this.elements;
  750. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  751. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  752. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  753. return this;
  754. }
  755. determinant() {
  756. const te = this.elements;
  757. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  758. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  759. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  760. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  761. }
  762. invert() {
  763. const te = this.elements,
  764. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  765. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  766. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  767. t11 = n33 * n22 - n32 * n23,
  768. t12 = n32 * n13 - n33 * n12,
  769. t13 = n23 * n12 - n22 * n13,
  770. det = n11 * t11 + n21 * t12 + n31 * t13;
  771. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  772. const detInv = 1 / det;
  773. te[ 0 ] = t11 * detInv;
  774. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  775. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  776. te[ 3 ] = t12 * detInv;
  777. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  778. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  779. te[ 6 ] = t13 * detInv;
  780. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  781. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  782. return this;
  783. }
  784. transpose() {
  785. let tmp;
  786. const m = this.elements;
  787. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  788. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  789. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  790. return this;
  791. }
  792. getNormalMatrix( matrix4 ) {
  793. return this.setFromMatrix4( matrix4 ).invert().transpose();
  794. }
  795. transposeIntoArray( r ) {
  796. const m = this.elements;
  797. r[ 0 ] = m[ 0 ];
  798. r[ 1 ] = m[ 3 ];
  799. r[ 2 ] = m[ 6 ];
  800. r[ 3 ] = m[ 1 ];
  801. r[ 4 ] = m[ 4 ];
  802. r[ 5 ] = m[ 7 ];
  803. r[ 6 ] = m[ 2 ];
  804. r[ 7 ] = m[ 5 ];
  805. r[ 8 ] = m[ 8 ];
  806. return this;
  807. }
  808. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  809. const c = Math.cos( rotation );
  810. const s = Math.sin( rotation );
  811. this.set(
  812. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  813. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  814. 0, 0, 1
  815. );
  816. return this;
  817. }
  818. scale( sx, sy ) {
  819. const te = this.elements;
  820. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  821. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  822. return this;
  823. }
  824. rotate( theta ) {
  825. const c = Math.cos( theta );
  826. const s = Math.sin( theta );
  827. const te = this.elements;
  828. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  829. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  830. te[ 0 ] = c * a11 + s * a21;
  831. te[ 3 ] = c * a12 + s * a22;
  832. te[ 6 ] = c * a13 + s * a23;
  833. te[ 1 ] = - s * a11 + c * a21;
  834. te[ 4 ] = - s * a12 + c * a22;
  835. te[ 7 ] = - s * a13 + c * a23;
  836. return this;
  837. }
  838. translate( tx, ty ) {
  839. const te = this.elements;
  840. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  841. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  842. return this;
  843. }
  844. equals( matrix ) {
  845. const te = this.elements;
  846. const me = matrix.elements;
  847. for ( let i = 0; i < 9; i ++ ) {
  848. if ( te[ i ] !== me[ i ] ) return false;
  849. }
  850. return true;
  851. }
  852. fromArray( array, offset = 0 ) {
  853. for ( let i = 0; i < 9; i ++ ) {
  854. this.elements[ i ] = array[ i + offset ];
  855. }
  856. return this;
  857. }
  858. toArray( array = [], offset = 0 ) {
  859. const te = this.elements;
  860. array[ offset ] = te[ 0 ];
  861. array[ offset + 1 ] = te[ 1 ];
  862. array[ offset + 2 ] = te[ 2 ];
  863. array[ offset + 3 ] = te[ 3 ];
  864. array[ offset + 4 ] = te[ 4 ];
  865. array[ offset + 5 ] = te[ 5 ];
  866. array[ offset + 6 ] = te[ 6 ];
  867. array[ offset + 7 ] = te[ 7 ];
  868. array[ offset + 8 ] = te[ 8 ];
  869. return array;
  870. }
  871. clone() {
  872. return new this.constructor().fromArray( this.elements );
  873. }
  874. }
  875. function arrayNeedsUint32( array ) {
  876. // assumes larger values usually on last
  877. for ( let i = array.length - 1; i >= 0; -- i ) {
  878. if ( array[ i ] > 65535 ) return true;
  879. }
  880. return false;
  881. }
  882. const TYPED_ARRAYS = {
  883. Int8Array: Int8Array,
  884. Uint8Array: Uint8Array,
  885. Uint8ClampedArray: Uint8ClampedArray,
  886. Int16Array: Int16Array,
  887. Uint16Array: Uint16Array,
  888. Int32Array: Int32Array,
  889. Uint32Array: Uint32Array,
  890. Float32Array: Float32Array,
  891. Float64Array: Float64Array
  892. };
  893. function getTypedArray( type, buffer ) {
  894. return new TYPED_ARRAYS[ type ]( buffer );
  895. }
  896. function createElementNS( name ) {
  897. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  898. }
  899. function SRGBToLinear( c ) {
  900. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  901. }
  902. function LinearToSRGB( c ) {
  903. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  904. }
  905. // JavaScript RGB-to-RGB transforms, defined as
  906. // FN[InputColorSpace][OutputColorSpace] callback functions.
  907. const FN = {
  908. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  909. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  910. };
  911. const ColorManagement = {
  912. legacyMode: true,
  913. get workingColorSpace() {
  914. return LinearSRGBColorSpace;
  915. },
  916. set workingColorSpace( colorSpace ) {
  917. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  918. },
  919. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  920. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  921. return color;
  922. }
  923. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  924. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  925. color.r = fn( color.r );
  926. color.g = fn( color.g );
  927. color.b = fn( color.b );
  928. return color;
  929. }
  930. throw new Error( 'Unsupported color space conversion.' );
  931. },
  932. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  933. return this.convert( color, this.workingColorSpace, targetColorSpace );
  934. },
  935. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  936. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  937. },
  938. };
  939. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  940. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  941. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  942. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  943. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  944. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  945. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  946. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  947. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  948. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  949. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  950. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  951. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  952. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  953. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  954. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  955. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  956. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  957. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  958. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  959. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  960. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  961. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  962. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  963. const _rgb = { r: 0, g: 0, b: 0 };
  964. const _hslA = { h: 0, s: 0, l: 0 };
  965. const _hslB = { h: 0, s: 0, l: 0 };
  966. function hue2rgb( p, q, t ) {
  967. if ( t < 0 ) t += 1;
  968. if ( t > 1 ) t -= 1;
  969. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  970. if ( t < 1 / 2 ) return q;
  971. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  972. return p;
  973. }
  974. function toComponents( source, target ) {
  975. target.r = source.r;
  976. target.g = source.g;
  977. target.b = source.b;
  978. return target;
  979. }
  980. class Color {
  981. constructor( r, g, b ) {
  982. this.isColor = true;
  983. this.r = 1;
  984. this.g = 1;
  985. this.b = 1;
  986. if ( g === undefined && b === undefined ) {
  987. // r is THREE.Color, hex or string
  988. return this.set( r );
  989. }
  990. return this.setRGB( r, g, b );
  991. }
  992. set( value ) {
  993. if ( value && value.isColor ) {
  994. this.copy( value );
  995. } else if ( typeof value === 'number' ) {
  996. this.setHex( value );
  997. } else if ( typeof value === 'string' ) {
  998. this.setStyle( value );
  999. }
  1000. return this;
  1001. }
  1002. setScalar( scalar ) {
  1003. this.r = scalar;
  1004. this.g = scalar;
  1005. this.b = scalar;
  1006. return this;
  1007. }
  1008. setHex( hex, colorSpace = SRGBColorSpace ) {
  1009. hex = Math.floor( hex );
  1010. this.r = ( hex >> 16 & 255 ) / 255;
  1011. this.g = ( hex >> 8 & 255 ) / 255;
  1012. this.b = ( hex & 255 ) / 255;
  1013. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1014. return this;
  1015. }
  1016. setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) {
  1017. this.r = r;
  1018. this.g = g;
  1019. this.b = b;
  1020. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1021. return this;
  1022. }
  1023. setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) {
  1024. // h,s,l ranges are in 0.0 - 1.0
  1025. h = euclideanModulo( h, 1 );
  1026. s = clamp( s, 0, 1 );
  1027. l = clamp( l, 0, 1 );
  1028. if ( s === 0 ) {
  1029. this.r = this.g = this.b = l;
  1030. } else {
  1031. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1032. const q = ( 2 * l ) - p;
  1033. this.r = hue2rgb( q, p, h + 1 / 3 );
  1034. this.g = hue2rgb( q, p, h );
  1035. this.b = hue2rgb( q, p, h - 1 / 3 );
  1036. }
  1037. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1038. return this;
  1039. }
  1040. setStyle( style, colorSpace = SRGBColorSpace ) {
  1041. function handleAlpha( string ) {
  1042. if ( string === undefined ) return;
  1043. if ( parseFloat( string ) < 1 ) {
  1044. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1045. }
  1046. }
  1047. let m;
  1048. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1049. // rgb / hsl
  1050. let color;
  1051. const name = m[ 1 ];
  1052. const components = m[ 2 ];
  1053. switch ( name ) {
  1054. case 'rgb':
  1055. case 'rgba':
  1056. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1057. // rgb(255,0,0) rgba(255,0,0,0.5)
  1058. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1059. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1060. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1061. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1062. handleAlpha( color[ 4 ] );
  1063. return this;
  1064. }
  1065. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1066. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1067. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1068. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1069. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1070. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1071. handleAlpha( color[ 4 ] );
  1072. return this;
  1073. }
  1074. break;
  1075. case 'hsl':
  1076. case 'hsla':
  1077. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1078. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1079. const h = parseFloat( color[ 1 ] ) / 360;
  1080. const s = parseFloat( color[ 2 ] ) / 100;
  1081. const l = parseFloat( color[ 3 ] ) / 100;
  1082. handleAlpha( color[ 4 ] );
  1083. return this.setHSL( h, s, l, colorSpace );
  1084. }
  1085. break;
  1086. }
  1087. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1088. // hex color
  1089. const hex = m[ 1 ];
  1090. const size = hex.length;
  1091. if ( size === 3 ) {
  1092. // #ff0
  1093. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1094. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1095. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1096. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1097. return this;
  1098. } else if ( size === 6 ) {
  1099. // #ff0000
  1100. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1101. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1102. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1103. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1104. return this;
  1105. }
  1106. }
  1107. if ( style && style.length > 0 ) {
  1108. return this.setColorName( style, colorSpace );
  1109. }
  1110. return this;
  1111. }
  1112. setColorName( style, colorSpace = SRGBColorSpace ) {
  1113. // color keywords
  1114. const hex = _colorKeywords[ style.toLowerCase() ];
  1115. if ( hex !== undefined ) {
  1116. // red
  1117. this.setHex( hex, colorSpace );
  1118. } else {
  1119. // unknown color
  1120. console.warn( 'THREE.Color: Unknown color ' + style );
  1121. }
  1122. return this;
  1123. }
  1124. clone() {
  1125. return new this.constructor( this.r, this.g, this.b );
  1126. }
  1127. copy( color ) {
  1128. this.r = color.r;
  1129. this.g = color.g;
  1130. this.b = color.b;
  1131. return this;
  1132. }
  1133. copySRGBToLinear( color ) {
  1134. this.r = SRGBToLinear( color.r );
  1135. this.g = SRGBToLinear( color.g );
  1136. this.b = SRGBToLinear( color.b );
  1137. return this;
  1138. }
  1139. copyLinearToSRGB( color ) {
  1140. this.r = LinearToSRGB( color.r );
  1141. this.g = LinearToSRGB( color.g );
  1142. this.b = LinearToSRGB( color.b );
  1143. return this;
  1144. }
  1145. convertSRGBToLinear() {
  1146. this.copySRGBToLinear( this );
  1147. return this;
  1148. }
  1149. convertLinearToSRGB() {
  1150. this.copyLinearToSRGB( this );
  1151. return this;
  1152. }
  1153. getHex( colorSpace = SRGBColorSpace ) {
  1154. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1155. return clamp( _rgb.r * 255, 0, 255 ) << 16 ^ clamp( _rgb.g * 255, 0, 255 ) << 8 ^ clamp( _rgb.b * 255, 0, 255 ) << 0;
  1156. }
  1157. getHexString( colorSpace = SRGBColorSpace ) {
  1158. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1159. }
  1160. getHSL( target, colorSpace = LinearSRGBColorSpace ) {
  1161. // h,s,l ranges are in 0.0 - 1.0
  1162. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1163. const r = _rgb.r, g = _rgb.g, b = _rgb.b;
  1164. const max = Math.max( r, g, b );
  1165. const min = Math.min( r, g, b );
  1166. let hue, saturation;
  1167. const lightness = ( min + max ) / 2.0;
  1168. if ( min === max ) {
  1169. hue = 0;
  1170. saturation = 0;
  1171. } else {
  1172. const delta = max - min;
  1173. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1174. switch ( max ) {
  1175. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1176. case g: hue = ( b - r ) / delta + 2; break;
  1177. case b: hue = ( r - g ) / delta + 4; break;
  1178. }
  1179. hue /= 6;
  1180. }
  1181. target.h = hue;
  1182. target.s = saturation;
  1183. target.l = lightness;
  1184. return target;
  1185. }
  1186. getRGB( target, colorSpace = LinearSRGBColorSpace ) {
  1187. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1188. target.r = _rgb.r;
  1189. target.g = _rgb.g;
  1190. target.b = _rgb.b;
  1191. return target;
  1192. }
  1193. getStyle( colorSpace = SRGBColorSpace ) {
  1194. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1195. if ( colorSpace !== SRGBColorSpace ) {
  1196. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1197. return `color(${ colorSpace } ${ _rgb.r } ${ _rgb.g } ${ _rgb.b })`;
  1198. }
  1199. return `rgb(${( _rgb.r * 255 ) | 0},${( _rgb.g * 255 ) | 0},${( _rgb.b * 255 ) | 0})`;
  1200. }
  1201. offsetHSL( h, s, l ) {
  1202. this.getHSL( _hslA );
  1203. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1204. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1205. return this;
  1206. }
  1207. add( color ) {
  1208. this.r += color.r;
  1209. this.g += color.g;
  1210. this.b += color.b;
  1211. return this;
  1212. }
  1213. addColors( color1, color2 ) {
  1214. this.r = color1.r + color2.r;
  1215. this.g = color1.g + color2.g;
  1216. this.b = color1.b + color2.b;
  1217. return this;
  1218. }
  1219. addScalar( s ) {
  1220. this.r += s;
  1221. this.g += s;
  1222. this.b += s;
  1223. return this;
  1224. }
  1225. sub( color ) {
  1226. this.r = Math.max( 0, this.r - color.r );
  1227. this.g = Math.max( 0, this.g - color.g );
  1228. this.b = Math.max( 0, this.b - color.b );
  1229. return this;
  1230. }
  1231. multiply( color ) {
  1232. this.r *= color.r;
  1233. this.g *= color.g;
  1234. this.b *= color.b;
  1235. return this;
  1236. }
  1237. multiplyScalar( s ) {
  1238. this.r *= s;
  1239. this.g *= s;
  1240. this.b *= s;
  1241. return this;
  1242. }
  1243. lerp( color, alpha ) {
  1244. this.r += ( color.r - this.r ) * alpha;
  1245. this.g += ( color.g - this.g ) * alpha;
  1246. this.b += ( color.b - this.b ) * alpha;
  1247. return this;
  1248. }
  1249. lerpColors( color1, color2, alpha ) {
  1250. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1251. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1252. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1253. return this;
  1254. }
  1255. lerpHSL( color, alpha ) {
  1256. this.getHSL( _hslA );
  1257. color.getHSL( _hslB );
  1258. const h = lerp( _hslA.h, _hslB.h, alpha );
  1259. const s = lerp( _hslA.s, _hslB.s, alpha );
  1260. const l = lerp( _hslA.l, _hslB.l, alpha );
  1261. this.setHSL( h, s, l );
  1262. return this;
  1263. }
  1264. equals( c ) {
  1265. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1266. }
  1267. fromArray( array, offset = 0 ) {
  1268. this.r = array[ offset ];
  1269. this.g = array[ offset + 1 ];
  1270. this.b = array[ offset + 2 ];
  1271. return this;
  1272. }
  1273. toArray( array = [], offset = 0 ) {
  1274. array[ offset ] = this.r;
  1275. array[ offset + 1 ] = this.g;
  1276. array[ offset + 2 ] = this.b;
  1277. return array;
  1278. }
  1279. fromBufferAttribute( attribute, index ) {
  1280. this.r = attribute.getX( index );
  1281. this.g = attribute.getY( index );
  1282. this.b = attribute.getZ( index );
  1283. return this;
  1284. }
  1285. toJSON() {
  1286. return this.getHex();
  1287. }
  1288. *[ Symbol.iterator ]() {
  1289. yield this.r;
  1290. yield this.g;
  1291. yield this.b;
  1292. }
  1293. }
  1294. Color.NAMES = _colorKeywords;
  1295. let _canvas;
  1296. class ImageUtils {
  1297. static getDataURL( image ) {
  1298. if ( /^data:/i.test( image.src ) ) {
  1299. return image.src;
  1300. }
  1301. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1302. return image.src;
  1303. }
  1304. let canvas;
  1305. if ( image instanceof HTMLCanvasElement ) {
  1306. canvas = image;
  1307. } else {
  1308. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1309. _canvas.width = image.width;
  1310. _canvas.height = image.height;
  1311. const context = _canvas.getContext( '2d' );
  1312. if ( image instanceof ImageData ) {
  1313. context.putImageData( image, 0, 0 );
  1314. } else {
  1315. context.drawImage( image, 0, 0, image.width, image.height );
  1316. }
  1317. canvas = _canvas;
  1318. }
  1319. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1320. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1321. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1322. } else {
  1323. return canvas.toDataURL( 'image/png' );
  1324. }
  1325. }
  1326. static sRGBToLinear( image ) {
  1327. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1328. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1329. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1330. const canvas = createElementNS( 'canvas' );
  1331. canvas.width = image.width;
  1332. canvas.height = image.height;
  1333. const context = canvas.getContext( '2d' );
  1334. context.drawImage( image, 0, 0, image.width, image.height );
  1335. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1336. const data = imageData.data;
  1337. for ( let i = 0; i < data.length; i ++ ) {
  1338. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1339. }
  1340. context.putImageData( imageData, 0, 0 );
  1341. return canvas;
  1342. } else if ( image.data ) {
  1343. const data = image.data.slice( 0 );
  1344. for ( let i = 0; i < data.length; i ++ ) {
  1345. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1346. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1347. } else {
  1348. // assuming float
  1349. data[ i ] = SRGBToLinear( data[ i ] );
  1350. }
  1351. }
  1352. return {
  1353. data: data,
  1354. width: image.width,
  1355. height: image.height
  1356. };
  1357. } else {
  1358. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1359. return image;
  1360. }
  1361. }
  1362. }
  1363. class Source {
  1364. constructor( data = null ) {
  1365. this.isSource = true;
  1366. this.uuid = generateUUID();
  1367. this.data = data;
  1368. this.version = 0;
  1369. }
  1370. set needsUpdate( value ) {
  1371. if ( value === true ) this.version ++;
  1372. }
  1373. toJSON( meta ) {
  1374. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1375. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1376. return meta.images[ this.uuid ];
  1377. }
  1378. const output = {
  1379. uuid: this.uuid,
  1380. url: ''
  1381. };
  1382. const data = this.data;
  1383. if ( data !== null ) {
  1384. let url;
  1385. if ( Array.isArray( data ) ) {
  1386. // cube texture
  1387. url = [];
  1388. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1389. if ( data[ i ].isDataTexture ) {
  1390. url.push( serializeImage( data[ i ].image ) );
  1391. } else {
  1392. url.push( serializeImage( data[ i ] ) );
  1393. }
  1394. }
  1395. } else {
  1396. // texture
  1397. url = serializeImage( data );
  1398. }
  1399. output.url = url;
  1400. }
  1401. if ( ! isRootObject ) {
  1402. meta.images[ this.uuid ] = output;
  1403. }
  1404. return output;
  1405. }
  1406. }
  1407. function serializeImage( image ) {
  1408. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1409. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1410. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1411. // default images
  1412. return ImageUtils.getDataURL( image );
  1413. } else {
  1414. if ( image.data ) {
  1415. // images of DataTexture
  1416. return {
  1417. data: Array.from( image.data ),
  1418. width: image.width,
  1419. height: image.height,
  1420. type: image.data.constructor.name
  1421. };
  1422. } else {
  1423. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1424. return {};
  1425. }
  1426. }
  1427. }
  1428. let textureId = 0;
  1429. class Texture extends EventDispatcher {
  1430. 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 ) {
  1431. super();
  1432. this.isTexture = true;
  1433. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1434. this.uuid = generateUUID();
  1435. this.name = '';
  1436. this.source = new Source( image );
  1437. this.mipmaps = [];
  1438. this.mapping = mapping;
  1439. this.wrapS = wrapS;
  1440. this.wrapT = wrapT;
  1441. this.magFilter = magFilter;
  1442. this.minFilter = minFilter;
  1443. this.anisotropy = anisotropy;
  1444. this.format = format;
  1445. this.internalFormat = null;
  1446. this.type = type;
  1447. this.offset = new Vector2( 0, 0 );
  1448. this.repeat = new Vector2( 1, 1 );
  1449. this.center = new Vector2( 0, 0 );
  1450. this.rotation = 0;
  1451. this.matrixAutoUpdate = true;
  1452. this.matrix = new Matrix3();
  1453. this.generateMipmaps = true;
  1454. this.premultiplyAlpha = false;
  1455. this.flipY = true;
  1456. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1457. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1458. //
  1459. // Also changing the encoding after already used by a Material will not automatically make the Material
  1460. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1461. this.encoding = encoding;
  1462. this.userData = {};
  1463. this.version = 0;
  1464. this.onUpdate = null;
  1465. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1466. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1467. }
  1468. get image() {
  1469. return this.source.data;
  1470. }
  1471. set image( value ) {
  1472. this.source.data = value;
  1473. }
  1474. updateMatrix() {
  1475. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1476. }
  1477. clone() {
  1478. return new this.constructor().copy( this );
  1479. }
  1480. copy( source ) {
  1481. this.name = source.name;
  1482. this.source = source.source;
  1483. this.mipmaps = source.mipmaps.slice( 0 );
  1484. this.mapping = source.mapping;
  1485. this.wrapS = source.wrapS;
  1486. this.wrapT = source.wrapT;
  1487. this.magFilter = source.magFilter;
  1488. this.minFilter = source.minFilter;
  1489. this.anisotropy = source.anisotropy;
  1490. this.format = source.format;
  1491. this.internalFormat = source.internalFormat;
  1492. this.type = source.type;
  1493. this.offset.copy( source.offset );
  1494. this.repeat.copy( source.repeat );
  1495. this.center.copy( source.center );
  1496. this.rotation = source.rotation;
  1497. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1498. this.matrix.copy( source.matrix );
  1499. this.generateMipmaps = source.generateMipmaps;
  1500. this.premultiplyAlpha = source.premultiplyAlpha;
  1501. this.flipY = source.flipY;
  1502. this.unpackAlignment = source.unpackAlignment;
  1503. this.encoding = source.encoding;
  1504. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1505. this.needsUpdate = true;
  1506. return this;
  1507. }
  1508. toJSON( meta ) {
  1509. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1510. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1511. return meta.textures[ this.uuid ];
  1512. }
  1513. const output = {
  1514. metadata: {
  1515. version: 4.5,
  1516. type: 'Texture',
  1517. generator: 'Texture.toJSON'
  1518. },
  1519. uuid: this.uuid,
  1520. name: this.name,
  1521. image: this.source.toJSON( meta ).uuid,
  1522. mapping: this.mapping,
  1523. repeat: [ this.repeat.x, this.repeat.y ],
  1524. offset: [ this.offset.x, this.offset.y ],
  1525. center: [ this.center.x, this.center.y ],
  1526. rotation: this.rotation,
  1527. wrap: [ this.wrapS, this.wrapT ],
  1528. format: this.format,
  1529. type: this.type,
  1530. encoding: this.encoding,
  1531. minFilter: this.minFilter,
  1532. magFilter: this.magFilter,
  1533. anisotropy: this.anisotropy,
  1534. flipY: this.flipY,
  1535. premultiplyAlpha: this.premultiplyAlpha,
  1536. unpackAlignment: this.unpackAlignment
  1537. };
  1538. if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData;
  1539. if ( ! isRootObject ) {
  1540. meta.textures[ this.uuid ] = output;
  1541. }
  1542. return output;
  1543. }
  1544. dispose() {
  1545. this.dispatchEvent( { type: 'dispose' } );
  1546. }
  1547. transformUv( uv ) {
  1548. if ( this.mapping !== UVMapping ) return uv;
  1549. uv.applyMatrix3( this.matrix );
  1550. if ( uv.x < 0 || uv.x > 1 ) {
  1551. switch ( this.wrapS ) {
  1552. case RepeatWrapping:
  1553. uv.x = uv.x - Math.floor( uv.x );
  1554. break;
  1555. case ClampToEdgeWrapping:
  1556. uv.x = uv.x < 0 ? 0 : 1;
  1557. break;
  1558. case MirroredRepeatWrapping:
  1559. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1560. uv.x = Math.ceil( uv.x ) - uv.x;
  1561. } else {
  1562. uv.x = uv.x - Math.floor( uv.x );
  1563. }
  1564. break;
  1565. }
  1566. }
  1567. if ( uv.y < 0 || uv.y > 1 ) {
  1568. switch ( this.wrapT ) {
  1569. case RepeatWrapping:
  1570. uv.y = uv.y - Math.floor( uv.y );
  1571. break;
  1572. case ClampToEdgeWrapping:
  1573. uv.y = uv.y < 0 ? 0 : 1;
  1574. break;
  1575. case MirroredRepeatWrapping:
  1576. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1577. uv.y = Math.ceil( uv.y ) - uv.y;
  1578. } else {
  1579. uv.y = uv.y - Math.floor( uv.y );
  1580. }
  1581. break;
  1582. }
  1583. }
  1584. if ( this.flipY ) {
  1585. uv.y = 1 - uv.y;
  1586. }
  1587. return uv;
  1588. }
  1589. set needsUpdate( value ) {
  1590. if ( value === true ) {
  1591. this.version ++;
  1592. this.source.needsUpdate = true;
  1593. }
  1594. }
  1595. }
  1596. Texture.DEFAULT_IMAGE = null;
  1597. Texture.DEFAULT_MAPPING = UVMapping;
  1598. class Vector4 {
  1599. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1600. Vector4.prototype.isVector4 = true;
  1601. this.x = x;
  1602. this.y = y;
  1603. this.z = z;
  1604. this.w = w;
  1605. }
  1606. get width() {
  1607. return this.z;
  1608. }
  1609. set width( value ) {
  1610. this.z = value;
  1611. }
  1612. get height() {
  1613. return this.w;
  1614. }
  1615. set height( value ) {
  1616. this.w = value;
  1617. }
  1618. set( x, y, z, w ) {
  1619. this.x = x;
  1620. this.y = y;
  1621. this.z = z;
  1622. this.w = w;
  1623. return this;
  1624. }
  1625. setScalar( scalar ) {
  1626. this.x = scalar;
  1627. this.y = scalar;
  1628. this.z = scalar;
  1629. this.w = scalar;
  1630. return this;
  1631. }
  1632. setX( x ) {
  1633. this.x = x;
  1634. return this;
  1635. }
  1636. setY( y ) {
  1637. this.y = y;
  1638. return this;
  1639. }
  1640. setZ( z ) {
  1641. this.z = z;
  1642. return this;
  1643. }
  1644. setW( w ) {
  1645. this.w = w;
  1646. return this;
  1647. }
  1648. setComponent( index, value ) {
  1649. switch ( index ) {
  1650. case 0: this.x = value; break;
  1651. case 1: this.y = value; break;
  1652. case 2: this.z = value; break;
  1653. case 3: this.w = value; break;
  1654. default: throw new Error( 'index is out of range: ' + index );
  1655. }
  1656. return this;
  1657. }
  1658. getComponent( index ) {
  1659. switch ( index ) {
  1660. case 0: return this.x;
  1661. case 1: return this.y;
  1662. case 2: return this.z;
  1663. case 3: return this.w;
  1664. default: throw new Error( 'index is out of range: ' + index );
  1665. }
  1666. }
  1667. clone() {
  1668. return new this.constructor( this.x, this.y, this.z, this.w );
  1669. }
  1670. copy( v ) {
  1671. this.x = v.x;
  1672. this.y = v.y;
  1673. this.z = v.z;
  1674. this.w = ( v.w !== undefined ) ? v.w : 1;
  1675. return this;
  1676. }
  1677. add( v ) {
  1678. this.x += v.x;
  1679. this.y += v.y;
  1680. this.z += v.z;
  1681. this.w += v.w;
  1682. return this;
  1683. }
  1684. addScalar( s ) {
  1685. this.x += s;
  1686. this.y += s;
  1687. this.z += s;
  1688. this.w += s;
  1689. return this;
  1690. }
  1691. addVectors( a, b ) {
  1692. this.x = a.x + b.x;
  1693. this.y = a.y + b.y;
  1694. this.z = a.z + b.z;
  1695. this.w = a.w + b.w;
  1696. return this;
  1697. }
  1698. addScaledVector( v, s ) {
  1699. this.x += v.x * s;
  1700. this.y += v.y * s;
  1701. this.z += v.z * s;
  1702. this.w += v.w * s;
  1703. return this;
  1704. }
  1705. sub( v ) {
  1706. this.x -= v.x;
  1707. this.y -= v.y;
  1708. this.z -= v.z;
  1709. this.w -= v.w;
  1710. return this;
  1711. }
  1712. subScalar( s ) {
  1713. this.x -= s;
  1714. this.y -= s;
  1715. this.z -= s;
  1716. this.w -= s;
  1717. return this;
  1718. }
  1719. subVectors( a, b ) {
  1720. this.x = a.x - b.x;
  1721. this.y = a.y - b.y;
  1722. this.z = a.z - b.z;
  1723. this.w = a.w - b.w;
  1724. return this;
  1725. }
  1726. multiply( v ) {
  1727. this.x *= v.x;
  1728. this.y *= v.y;
  1729. this.z *= v.z;
  1730. this.w *= v.w;
  1731. return this;
  1732. }
  1733. multiplyScalar( scalar ) {
  1734. this.x *= scalar;
  1735. this.y *= scalar;
  1736. this.z *= scalar;
  1737. this.w *= scalar;
  1738. return this;
  1739. }
  1740. applyMatrix4( m ) {
  1741. const x = this.x, y = this.y, z = this.z, w = this.w;
  1742. const e = m.elements;
  1743. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1744. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1745. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1746. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1747. return this;
  1748. }
  1749. divideScalar( scalar ) {
  1750. return this.multiplyScalar( 1 / scalar );
  1751. }
  1752. setAxisAngleFromQuaternion( q ) {
  1753. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1754. // q is assumed to be normalized
  1755. this.w = 2 * Math.acos( q.w );
  1756. const s = Math.sqrt( 1 - q.w * q.w );
  1757. if ( s < 0.0001 ) {
  1758. this.x = 1;
  1759. this.y = 0;
  1760. this.z = 0;
  1761. } else {
  1762. this.x = q.x / s;
  1763. this.y = q.y / s;
  1764. this.z = q.z / s;
  1765. }
  1766. return this;
  1767. }
  1768. setAxisAngleFromRotationMatrix( m ) {
  1769. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1770. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1771. let angle, x, y, z; // variables for result
  1772. const epsilon = 0.01, // margin to allow for rounding errors
  1773. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1774. te = m.elements,
  1775. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1776. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1777. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1778. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1779. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1780. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1781. // singularity found
  1782. // first check for identity matrix which must have +1 for all terms
  1783. // in leading diagonal and zero in other terms
  1784. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1785. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1786. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1787. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1788. // this singularity is identity matrix so angle = 0
  1789. this.set( 1, 0, 0, 0 );
  1790. return this; // zero angle, arbitrary axis
  1791. }
  1792. // otherwise this singularity is angle = 180
  1793. angle = Math.PI;
  1794. const xx = ( m11 + 1 ) / 2;
  1795. const yy = ( m22 + 1 ) / 2;
  1796. const zz = ( m33 + 1 ) / 2;
  1797. const xy = ( m12 + m21 ) / 4;
  1798. const xz = ( m13 + m31 ) / 4;
  1799. const yz = ( m23 + m32 ) / 4;
  1800. if ( ( xx > yy ) && ( xx > zz ) ) {
  1801. // m11 is the largest diagonal term
  1802. if ( xx < epsilon ) {
  1803. x = 0;
  1804. y = 0.707106781;
  1805. z = 0.707106781;
  1806. } else {
  1807. x = Math.sqrt( xx );
  1808. y = xy / x;
  1809. z = xz / x;
  1810. }
  1811. } else if ( yy > zz ) {
  1812. // m22 is the largest diagonal term
  1813. if ( yy < epsilon ) {
  1814. x = 0.707106781;
  1815. y = 0;
  1816. z = 0.707106781;
  1817. } else {
  1818. y = Math.sqrt( yy );
  1819. x = xy / y;
  1820. z = yz / y;
  1821. }
  1822. } else {
  1823. // m33 is the largest diagonal term so base result on this
  1824. if ( zz < epsilon ) {
  1825. x = 0.707106781;
  1826. y = 0.707106781;
  1827. z = 0;
  1828. } else {
  1829. z = Math.sqrt( zz );
  1830. x = xz / z;
  1831. y = yz / z;
  1832. }
  1833. }
  1834. this.set( x, y, z, angle );
  1835. return this; // return 180 deg rotation
  1836. }
  1837. // as we have reached here there are no singularities so we can handle normally
  1838. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1839. ( m13 - m31 ) * ( m13 - m31 ) +
  1840. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1841. if ( Math.abs( s ) < 0.001 ) s = 1;
  1842. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1843. // caught by singularity test above, but I've left it in just in case
  1844. this.x = ( m32 - m23 ) / s;
  1845. this.y = ( m13 - m31 ) / s;
  1846. this.z = ( m21 - m12 ) / s;
  1847. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1848. return this;
  1849. }
  1850. min( v ) {
  1851. this.x = Math.min( this.x, v.x );
  1852. this.y = Math.min( this.y, v.y );
  1853. this.z = Math.min( this.z, v.z );
  1854. this.w = Math.min( this.w, v.w );
  1855. return this;
  1856. }
  1857. max( v ) {
  1858. this.x = Math.max( this.x, v.x );
  1859. this.y = Math.max( this.y, v.y );
  1860. this.z = Math.max( this.z, v.z );
  1861. this.w = Math.max( this.w, v.w );
  1862. return this;
  1863. }
  1864. clamp( min, max ) {
  1865. // assumes min < max, componentwise
  1866. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1867. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1868. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1869. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1870. return this;
  1871. }
  1872. clampScalar( minVal, maxVal ) {
  1873. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1874. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1875. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1876. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1877. return this;
  1878. }
  1879. clampLength( min, max ) {
  1880. const length = this.length();
  1881. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1882. }
  1883. floor() {
  1884. this.x = Math.floor( this.x );
  1885. this.y = Math.floor( this.y );
  1886. this.z = Math.floor( this.z );
  1887. this.w = Math.floor( this.w );
  1888. return this;
  1889. }
  1890. ceil() {
  1891. this.x = Math.ceil( this.x );
  1892. this.y = Math.ceil( this.y );
  1893. this.z = Math.ceil( this.z );
  1894. this.w = Math.ceil( this.w );
  1895. return this;
  1896. }
  1897. round() {
  1898. this.x = Math.round( this.x );
  1899. this.y = Math.round( this.y );
  1900. this.z = Math.round( this.z );
  1901. this.w = Math.round( this.w );
  1902. return this;
  1903. }
  1904. roundToZero() {
  1905. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1906. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1907. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1908. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1909. return this;
  1910. }
  1911. negate() {
  1912. this.x = - this.x;
  1913. this.y = - this.y;
  1914. this.z = - this.z;
  1915. this.w = - this.w;
  1916. return this;
  1917. }
  1918. dot( v ) {
  1919. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1920. }
  1921. lengthSq() {
  1922. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1923. }
  1924. length() {
  1925. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1926. }
  1927. manhattanLength() {
  1928. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1929. }
  1930. normalize() {
  1931. return this.divideScalar( this.length() || 1 );
  1932. }
  1933. setLength( length ) {
  1934. return this.normalize().multiplyScalar( length );
  1935. }
  1936. lerp( v, alpha ) {
  1937. this.x += ( v.x - this.x ) * alpha;
  1938. this.y += ( v.y - this.y ) * alpha;
  1939. this.z += ( v.z - this.z ) * alpha;
  1940. this.w += ( v.w - this.w ) * alpha;
  1941. return this;
  1942. }
  1943. lerpVectors( v1, v2, alpha ) {
  1944. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1945. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1946. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1947. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1948. return this;
  1949. }
  1950. equals( v ) {
  1951. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1952. }
  1953. fromArray( array, offset = 0 ) {
  1954. this.x = array[ offset ];
  1955. this.y = array[ offset + 1 ];
  1956. this.z = array[ offset + 2 ];
  1957. this.w = array[ offset + 3 ];
  1958. return this;
  1959. }
  1960. toArray( array = [], offset = 0 ) {
  1961. array[ offset ] = this.x;
  1962. array[ offset + 1 ] = this.y;
  1963. array[ offset + 2 ] = this.z;
  1964. array[ offset + 3 ] = this.w;
  1965. return array;
  1966. }
  1967. fromBufferAttribute( attribute, index ) {
  1968. this.x = attribute.getX( index );
  1969. this.y = attribute.getY( index );
  1970. this.z = attribute.getZ( index );
  1971. this.w = attribute.getW( index );
  1972. return this;
  1973. }
  1974. random() {
  1975. this.x = Math.random();
  1976. this.y = Math.random();
  1977. this.z = Math.random();
  1978. this.w = Math.random();
  1979. return this;
  1980. }
  1981. *[ Symbol.iterator ]() {
  1982. yield this.x;
  1983. yield this.y;
  1984. yield this.z;
  1985. yield this.w;
  1986. }
  1987. }
  1988. /*
  1989. In options, we can specify:
  1990. * Texture parameters for an auto-generated target texture
  1991. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1992. */
  1993. class WebGLRenderTarget extends EventDispatcher {
  1994. constructor( width, height, options = {} ) {
  1995. super();
  1996. this.isWebGLRenderTarget = true;
  1997. this.width = width;
  1998. this.height = height;
  1999. this.depth = 1;
  2000. this.scissor = new Vector4( 0, 0, width, height );
  2001. this.scissorTest = false;
  2002. this.viewport = new Vector4( 0, 0, width, height );
  2003. const image = { width: width, height: height, depth: 1 };
  2004. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2005. this.texture.isRenderTargetTexture = true;
  2006. this.texture.flipY = false;
  2007. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2008. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2009. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2010. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2011. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2012. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2013. this.samples = options.samples !== undefined ? options.samples : 0;
  2014. }
  2015. setSize( width, height, depth = 1 ) {
  2016. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2017. this.width = width;
  2018. this.height = height;
  2019. this.depth = depth;
  2020. this.texture.image.width = width;
  2021. this.texture.image.height = height;
  2022. this.texture.image.depth = depth;
  2023. this.dispose();
  2024. }
  2025. this.viewport.set( 0, 0, width, height );
  2026. this.scissor.set( 0, 0, width, height );
  2027. }
  2028. clone() {
  2029. return new this.constructor().copy( this );
  2030. }
  2031. copy( source ) {
  2032. this.width = source.width;
  2033. this.height = source.height;
  2034. this.depth = source.depth;
  2035. this.viewport.copy( source.viewport );
  2036. this.texture = source.texture.clone();
  2037. this.texture.isRenderTargetTexture = true;
  2038. // ensure image object is not shared, see #20328
  2039. const image = Object.assign( {}, source.texture.image );
  2040. this.texture.source = new Source( image );
  2041. this.depthBuffer = source.depthBuffer;
  2042. this.stencilBuffer = source.stencilBuffer;
  2043. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2044. this.samples = source.samples;
  2045. return this;
  2046. }
  2047. dispose() {
  2048. this.dispatchEvent( { type: 'dispose' } );
  2049. }
  2050. }
  2051. class DataArrayTexture extends Texture {
  2052. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2053. super( null );
  2054. this.isDataArrayTexture = true;
  2055. this.image = { data, width, height, depth };
  2056. this.magFilter = NearestFilter;
  2057. this.minFilter = NearestFilter;
  2058. this.wrapR = ClampToEdgeWrapping;
  2059. this.generateMipmaps = false;
  2060. this.flipY = false;
  2061. this.unpackAlignment = 1;
  2062. }
  2063. }
  2064. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2065. constructor( width, height, depth ) {
  2066. super( width, height );
  2067. this.isWebGLArrayRenderTarget = true;
  2068. this.depth = depth;
  2069. this.texture = new DataArrayTexture( null, width, height, depth );
  2070. this.texture.isRenderTargetTexture = true;
  2071. }
  2072. }
  2073. class Data3DTexture extends Texture {
  2074. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2075. // We're going to add .setXXX() methods for setting properties later.
  2076. // Users can still set in DataTexture3D directly.
  2077. //
  2078. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2079. // texture.anisotropy = 16;
  2080. //
  2081. // See #14839
  2082. super( null );
  2083. this.isData3DTexture = true;
  2084. this.image = { data, width, height, depth };
  2085. this.magFilter = NearestFilter;
  2086. this.minFilter = NearestFilter;
  2087. this.wrapR = ClampToEdgeWrapping;
  2088. this.generateMipmaps = false;
  2089. this.flipY = false;
  2090. this.unpackAlignment = 1;
  2091. }
  2092. }
  2093. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2094. constructor( width, height, depth ) {
  2095. super( width, height );
  2096. this.isWebGL3DRenderTarget = true;
  2097. this.depth = depth;
  2098. this.texture = new Data3DTexture( null, width, height, depth );
  2099. this.texture.isRenderTargetTexture = true;
  2100. }
  2101. }
  2102. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2103. constructor( width, height, count, options = {} ) {
  2104. super( width, height, options );
  2105. this.isWebGLMultipleRenderTargets = true;
  2106. const texture = this.texture;
  2107. this.texture = [];
  2108. for ( let i = 0; i < count; i ++ ) {
  2109. this.texture[ i ] = texture.clone();
  2110. this.texture[ i ].isRenderTargetTexture = true;
  2111. }
  2112. }
  2113. setSize( width, height, depth = 1 ) {
  2114. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2115. this.width = width;
  2116. this.height = height;
  2117. this.depth = depth;
  2118. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2119. this.texture[ i ].image.width = width;
  2120. this.texture[ i ].image.height = height;
  2121. this.texture[ i ].image.depth = depth;
  2122. }
  2123. this.dispose();
  2124. }
  2125. this.viewport.set( 0, 0, width, height );
  2126. this.scissor.set( 0, 0, width, height );
  2127. return this;
  2128. }
  2129. copy( source ) {
  2130. this.dispose();
  2131. this.width = source.width;
  2132. this.height = source.height;
  2133. this.depth = source.depth;
  2134. this.viewport.set( 0, 0, this.width, this.height );
  2135. this.scissor.set( 0, 0, this.width, this.height );
  2136. this.depthBuffer = source.depthBuffer;
  2137. this.stencilBuffer = source.stencilBuffer;
  2138. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2139. this.texture.length = 0;
  2140. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2141. this.texture[ i ] = source.texture[ i ].clone();
  2142. this.texture[ i ].isRenderTargetTexture = true;
  2143. }
  2144. return this;
  2145. }
  2146. }
  2147. class Quaternion {
  2148. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2149. this.isQuaternion = true;
  2150. this._x = x;
  2151. this._y = y;
  2152. this._z = z;
  2153. this._w = w;
  2154. }
  2155. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2156. // fuzz-free, array-based Quaternion SLERP operation
  2157. let x0 = src0[ srcOffset0 + 0 ],
  2158. y0 = src0[ srcOffset0 + 1 ],
  2159. z0 = src0[ srcOffset0 + 2 ],
  2160. w0 = src0[ srcOffset0 + 3 ];
  2161. const x1 = src1[ srcOffset1 + 0 ],
  2162. y1 = src1[ srcOffset1 + 1 ],
  2163. z1 = src1[ srcOffset1 + 2 ],
  2164. w1 = src1[ srcOffset1 + 3 ];
  2165. if ( t === 0 ) {
  2166. dst[ dstOffset + 0 ] = x0;
  2167. dst[ dstOffset + 1 ] = y0;
  2168. dst[ dstOffset + 2 ] = z0;
  2169. dst[ dstOffset + 3 ] = w0;
  2170. return;
  2171. }
  2172. if ( t === 1 ) {
  2173. dst[ dstOffset + 0 ] = x1;
  2174. dst[ dstOffset + 1 ] = y1;
  2175. dst[ dstOffset + 2 ] = z1;
  2176. dst[ dstOffset + 3 ] = w1;
  2177. return;
  2178. }
  2179. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2180. let s = 1 - t;
  2181. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2182. dir = ( cos >= 0 ? 1 : - 1 ),
  2183. sqrSin = 1 - cos * cos;
  2184. // Skip the Slerp for tiny steps to avoid numeric problems:
  2185. if ( sqrSin > Number.EPSILON ) {
  2186. const sin = Math.sqrt( sqrSin ),
  2187. len = Math.atan2( sin, cos * dir );
  2188. s = Math.sin( s * len ) / sin;
  2189. t = Math.sin( t * len ) / sin;
  2190. }
  2191. const tDir = t * dir;
  2192. x0 = x0 * s + x1 * tDir;
  2193. y0 = y0 * s + y1 * tDir;
  2194. z0 = z0 * s + z1 * tDir;
  2195. w0 = w0 * s + w1 * tDir;
  2196. // Normalize in case we just did a lerp:
  2197. if ( s === 1 - t ) {
  2198. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2199. x0 *= f;
  2200. y0 *= f;
  2201. z0 *= f;
  2202. w0 *= f;
  2203. }
  2204. }
  2205. dst[ dstOffset ] = x0;
  2206. dst[ dstOffset + 1 ] = y0;
  2207. dst[ dstOffset + 2 ] = z0;
  2208. dst[ dstOffset + 3 ] = w0;
  2209. }
  2210. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2211. const x0 = src0[ srcOffset0 ];
  2212. const y0 = src0[ srcOffset0 + 1 ];
  2213. const z0 = src0[ srcOffset0 + 2 ];
  2214. const w0 = src0[ srcOffset0 + 3 ];
  2215. const x1 = src1[ srcOffset1 ];
  2216. const y1 = src1[ srcOffset1 + 1 ];
  2217. const z1 = src1[ srcOffset1 + 2 ];
  2218. const w1 = src1[ srcOffset1 + 3 ];
  2219. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2220. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2221. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2222. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2223. return dst;
  2224. }
  2225. get x() {
  2226. return this._x;
  2227. }
  2228. set x( value ) {
  2229. this._x = value;
  2230. this._onChangeCallback();
  2231. }
  2232. get y() {
  2233. return this._y;
  2234. }
  2235. set y( value ) {
  2236. this._y = value;
  2237. this._onChangeCallback();
  2238. }
  2239. get z() {
  2240. return this._z;
  2241. }
  2242. set z( value ) {
  2243. this._z = value;
  2244. this._onChangeCallback();
  2245. }
  2246. get w() {
  2247. return this._w;
  2248. }
  2249. set w( value ) {
  2250. this._w = value;
  2251. this._onChangeCallback();
  2252. }
  2253. set( x, y, z, w ) {
  2254. this._x = x;
  2255. this._y = y;
  2256. this._z = z;
  2257. this._w = w;
  2258. this._onChangeCallback();
  2259. return this;
  2260. }
  2261. clone() {
  2262. return new this.constructor( this._x, this._y, this._z, this._w );
  2263. }
  2264. copy( quaternion ) {
  2265. this._x = quaternion.x;
  2266. this._y = quaternion.y;
  2267. this._z = quaternion.z;
  2268. this._w = quaternion.w;
  2269. this._onChangeCallback();
  2270. return this;
  2271. }
  2272. setFromEuler( euler, update ) {
  2273. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2274. // http://www.mathworks.com/matlabcentral/fileexchange/
  2275. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2276. // content/SpinCalc.m
  2277. const cos = Math.cos;
  2278. const sin = Math.sin;
  2279. const c1 = cos( x / 2 );
  2280. const c2 = cos( y / 2 );
  2281. const c3 = cos( z / 2 );
  2282. const s1 = sin( x / 2 );
  2283. const s2 = sin( y / 2 );
  2284. const s3 = sin( z / 2 );
  2285. switch ( order ) {
  2286. case 'XYZ':
  2287. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2288. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2289. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2290. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2291. break;
  2292. case 'YXZ':
  2293. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2294. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2295. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2296. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2297. break;
  2298. case 'ZXY':
  2299. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2300. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2301. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2302. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2303. break;
  2304. case 'ZYX':
  2305. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2306. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2307. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2308. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2309. break;
  2310. case 'YZX':
  2311. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2312. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2313. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2314. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2315. break;
  2316. case 'XZY':
  2317. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2318. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2319. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2320. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2321. break;
  2322. default:
  2323. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2324. }
  2325. if ( update !== false ) this._onChangeCallback();
  2326. return this;
  2327. }
  2328. setFromAxisAngle( axis, angle ) {
  2329. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2330. // assumes axis is normalized
  2331. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2332. this._x = axis.x * s;
  2333. this._y = axis.y * s;
  2334. this._z = axis.z * s;
  2335. this._w = Math.cos( halfAngle );
  2336. this._onChangeCallback();
  2337. return this;
  2338. }
  2339. setFromRotationMatrix( m ) {
  2340. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2341. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2342. const te = m.elements,
  2343. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2344. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2345. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2346. trace = m11 + m22 + m33;
  2347. if ( trace > 0 ) {
  2348. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2349. this._w = 0.25 / s;
  2350. this._x = ( m32 - m23 ) * s;
  2351. this._y = ( m13 - m31 ) * s;
  2352. this._z = ( m21 - m12 ) * s;
  2353. } else if ( m11 > m22 && m11 > m33 ) {
  2354. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2355. this._w = ( m32 - m23 ) / s;
  2356. this._x = 0.25 * s;
  2357. this._y = ( m12 + m21 ) / s;
  2358. this._z = ( m13 + m31 ) / s;
  2359. } else if ( m22 > m33 ) {
  2360. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2361. this._w = ( m13 - m31 ) / s;
  2362. this._x = ( m12 + m21 ) / s;
  2363. this._y = 0.25 * s;
  2364. this._z = ( m23 + m32 ) / s;
  2365. } else {
  2366. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2367. this._w = ( m21 - m12 ) / s;
  2368. this._x = ( m13 + m31 ) / s;
  2369. this._y = ( m23 + m32 ) / s;
  2370. this._z = 0.25 * s;
  2371. }
  2372. this._onChangeCallback();
  2373. return this;
  2374. }
  2375. setFromUnitVectors( vFrom, vTo ) {
  2376. // assumes direction vectors vFrom and vTo are normalized
  2377. let r = vFrom.dot( vTo ) + 1;
  2378. if ( r < Number.EPSILON ) {
  2379. // vFrom and vTo point in opposite directions
  2380. r = 0;
  2381. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2382. this._x = - vFrom.y;
  2383. this._y = vFrom.x;
  2384. this._z = 0;
  2385. this._w = r;
  2386. } else {
  2387. this._x = 0;
  2388. this._y = - vFrom.z;
  2389. this._z = vFrom.y;
  2390. this._w = r;
  2391. }
  2392. } else {
  2393. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2394. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2395. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2396. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2397. this._w = r;
  2398. }
  2399. return this.normalize();
  2400. }
  2401. angleTo( q ) {
  2402. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2403. }
  2404. rotateTowards( q, step ) {
  2405. const angle = this.angleTo( q );
  2406. if ( angle === 0 ) return this;
  2407. const t = Math.min( 1, step / angle );
  2408. this.slerp( q, t );
  2409. return this;
  2410. }
  2411. identity() {
  2412. return this.set( 0, 0, 0, 1 );
  2413. }
  2414. invert() {
  2415. // quaternion is assumed to have unit length
  2416. return this.conjugate();
  2417. }
  2418. conjugate() {
  2419. this._x *= - 1;
  2420. this._y *= - 1;
  2421. this._z *= - 1;
  2422. this._onChangeCallback();
  2423. return this;
  2424. }
  2425. dot( v ) {
  2426. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2427. }
  2428. lengthSq() {
  2429. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2430. }
  2431. length() {
  2432. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2433. }
  2434. normalize() {
  2435. let l = this.length();
  2436. if ( l === 0 ) {
  2437. this._x = 0;
  2438. this._y = 0;
  2439. this._z = 0;
  2440. this._w = 1;
  2441. } else {
  2442. l = 1 / l;
  2443. this._x = this._x * l;
  2444. this._y = this._y * l;
  2445. this._z = this._z * l;
  2446. this._w = this._w * l;
  2447. }
  2448. this._onChangeCallback();
  2449. return this;
  2450. }
  2451. multiply( q ) {
  2452. return this.multiplyQuaternions( this, q );
  2453. }
  2454. premultiply( q ) {
  2455. return this.multiplyQuaternions( q, this );
  2456. }
  2457. multiplyQuaternions( a, b ) {
  2458. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2459. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2460. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2461. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2462. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2463. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2464. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2465. this._onChangeCallback();
  2466. return this;
  2467. }
  2468. slerp( qb, t ) {
  2469. if ( t === 0 ) return this;
  2470. if ( t === 1 ) return this.copy( qb );
  2471. const x = this._x, y = this._y, z = this._z, w = this._w;
  2472. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2473. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2474. if ( cosHalfTheta < 0 ) {
  2475. this._w = - qb._w;
  2476. this._x = - qb._x;
  2477. this._y = - qb._y;
  2478. this._z = - qb._z;
  2479. cosHalfTheta = - cosHalfTheta;
  2480. } else {
  2481. this.copy( qb );
  2482. }
  2483. if ( cosHalfTheta >= 1.0 ) {
  2484. this._w = w;
  2485. this._x = x;
  2486. this._y = y;
  2487. this._z = z;
  2488. return this;
  2489. }
  2490. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2491. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2492. const s = 1 - t;
  2493. this._w = s * w + t * this._w;
  2494. this._x = s * x + t * this._x;
  2495. this._y = s * y + t * this._y;
  2496. this._z = s * z + t * this._z;
  2497. this.normalize();
  2498. this._onChangeCallback();
  2499. return this;
  2500. }
  2501. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2502. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2503. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2504. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2505. this._w = ( w * ratioA + this._w * ratioB );
  2506. this._x = ( x * ratioA + this._x * ratioB );
  2507. this._y = ( y * ratioA + this._y * ratioB );
  2508. this._z = ( z * ratioA + this._z * ratioB );
  2509. this._onChangeCallback();
  2510. return this;
  2511. }
  2512. slerpQuaternions( qa, qb, t ) {
  2513. return this.copy( qa ).slerp( qb, t );
  2514. }
  2515. random() {
  2516. // Derived from http://planning.cs.uiuc.edu/node198.html
  2517. // Note, this source uses w, x, y, z ordering,
  2518. // so we swap the order below.
  2519. const u1 = Math.random();
  2520. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2521. const sqrtu1 = Math.sqrt( u1 );
  2522. const u2 = 2 * Math.PI * Math.random();
  2523. const u3 = 2 * Math.PI * Math.random();
  2524. return this.set(
  2525. sqrt1u1 * Math.cos( u2 ),
  2526. sqrtu1 * Math.sin( u3 ),
  2527. sqrtu1 * Math.cos( u3 ),
  2528. sqrt1u1 * Math.sin( u2 ),
  2529. );
  2530. }
  2531. equals( quaternion ) {
  2532. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2533. }
  2534. fromArray( array, offset = 0 ) {
  2535. this._x = array[ offset ];
  2536. this._y = array[ offset + 1 ];
  2537. this._z = array[ offset + 2 ];
  2538. this._w = array[ offset + 3 ];
  2539. this._onChangeCallback();
  2540. return this;
  2541. }
  2542. toArray( array = [], offset = 0 ) {
  2543. array[ offset ] = this._x;
  2544. array[ offset + 1 ] = this._y;
  2545. array[ offset + 2 ] = this._z;
  2546. array[ offset + 3 ] = this._w;
  2547. return array;
  2548. }
  2549. fromBufferAttribute( attribute, index ) {
  2550. this._x = attribute.getX( index );
  2551. this._y = attribute.getY( index );
  2552. this._z = attribute.getZ( index );
  2553. this._w = attribute.getW( index );
  2554. return this;
  2555. }
  2556. _onChange( callback ) {
  2557. this._onChangeCallback = callback;
  2558. return this;
  2559. }
  2560. _onChangeCallback() {}
  2561. *[ Symbol.iterator ]() {
  2562. yield this._x;
  2563. yield this._y;
  2564. yield this._z;
  2565. yield this._w;
  2566. }
  2567. }
  2568. class Vector3 {
  2569. constructor( x = 0, y = 0, z = 0 ) {
  2570. Vector3.prototype.isVector3 = true;
  2571. this.x = x;
  2572. this.y = y;
  2573. this.z = z;
  2574. }
  2575. set( x, y, z ) {
  2576. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2577. this.x = x;
  2578. this.y = y;
  2579. this.z = z;
  2580. return this;
  2581. }
  2582. setScalar( scalar ) {
  2583. this.x = scalar;
  2584. this.y = scalar;
  2585. this.z = scalar;
  2586. return this;
  2587. }
  2588. setX( x ) {
  2589. this.x = x;
  2590. return this;
  2591. }
  2592. setY( y ) {
  2593. this.y = y;
  2594. return this;
  2595. }
  2596. setZ( z ) {
  2597. this.z = z;
  2598. return this;
  2599. }
  2600. setComponent( index, value ) {
  2601. switch ( index ) {
  2602. case 0: this.x = value; break;
  2603. case 1: this.y = value; break;
  2604. case 2: this.z = value; break;
  2605. default: throw new Error( 'index is out of range: ' + index );
  2606. }
  2607. return this;
  2608. }
  2609. getComponent( index ) {
  2610. switch ( index ) {
  2611. case 0: return this.x;
  2612. case 1: return this.y;
  2613. case 2: return this.z;
  2614. default: throw new Error( 'index is out of range: ' + index );
  2615. }
  2616. }
  2617. clone() {
  2618. return new this.constructor( this.x, this.y, this.z );
  2619. }
  2620. copy( v ) {
  2621. this.x = v.x;
  2622. this.y = v.y;
  2623. this.z = v.z;
  2624. return this;
  2625. }
  2626. add( v ) {
  2627. this.x += v.x;
  2628. this.y += v.y;
  2629. this.z += v.z;
  2630. return this;
  2631. }
  2632. addScalar( s ) {
  2633. this.x += s;
  2634. this.y += s;
  2635. this.z += s;
  2636. return this;
  2637. }
  2638. addVectors( a, b ) {
  2639. this.x = a.x + b.x;
  2640. this.y = a.y + b.y;
  2641. this.z = a.z + b.z;
  2642. return this;
  2643. }
  2644. addScaledVector( v, s ) {
  2645. this.x += v.x * s;
  2646. this.y += v.y * s;
  2647. this.z += v.z * s;
  2648. return this;
  2649. }
  2650. sub( v ) {
  2651. this.x -= v.x;
  2652. this.y -= v.y;
  2653. this.z -= v.z;
  2654. return this;
  2655. }
  2656. subScalar( s ) {
  2657. this.x -= s;
  2658. this.y -= s;
  2659. this.z -= s;
  2660. return this;
  2661. }
  2662. subVectors( a, b ) {
  2663. this.x = a.x - b.x;
  2664. this.y = a.y - b.y;
  2665. this.z = a.z - b.z;
  2666. return this;
  2667. }
  2668. multiply( v ) {
  2669. this.x *= v.x;
  2670. this.y *= v.y;
  2671. this.z *= v.z;
  2672. return this;
  2673. }
  2674. multiplyScalar( scalar ) {
  2675. this.x *= scalar;
  2676. this.y *= scalar;
  2677. this.z *= scalar;
  2678. return this;
  2679. }
  2680. multiplyVectors( a, b ) {
  2681. this.x = a.x * b.x;
  2682. this.y = a.y * b.y;
  2683. this.z = a.z * b.z;
  2684. return this;
  2685. }
  2686. applyEuler( euler ) {
  2687. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2688. }
  2689. applyAxisAngle( axis, angle ) {
  2690. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2691. }
  2692. applyMatrix3( m ) {
  2693. const x = this.x, y = this.y, z = this.z;
  2694. const e = m.elements;
  2695. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2696. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2697. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2698. return this;
  2699. }
  2700. applyNormalMatrix( m ) {
  2701. return this.applyMatrix3( m ).normalize();
  2702. }
  2703. applyMatrix4( m ) {
  2704. const x = this.x, y = this.y, z = this.z;
  2705. const e = m.elements;
  2706. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2707. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2708. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2709. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2710. return this;
  2711. }
  2712. applyQuaternion( q ) {
  2713. const x = this.x, y = this.y, z = this.z;
  2714. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2715. // calculate quat * vector
  2716. const ix = qw * x + qy * z - qz * y;
  2717. const iy = qw * y + qz * x - qx * z;
  2718. const iz = qw * z + qx * y - qy * x;
  2719. const iw = - qx * x - qy * y - qz * z;
  2720. // calculate result * inverse quat
  2721. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2722. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2723. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2724. return this;
  2725. }
  2726. project( camera ) {
  2727. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2728. }
  2729. unproject( camera ) {
  2730. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2731. }
  2732. transformDirection( m ) {
  2733. // input: THREE.Matrix4 affine matrix
  2734. // vector interpreted as a direction
  2735. const x = this.x, y = this.y, z = this.z;
  2736. const e = m.elements;
  2737. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2738. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2739. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2740. return this.normalize();
  2741. }
  2742. divide( v ) {
  2743. this.x /= v.x;
  2744. this.y /= v.y;
  2745. this.z /= v.z;
  2746. return this;
  2747. }
  2748. divideScalar( scalar ) {
  2749. return this.multiplyScalar( 1 / scalar );
  2750. }
  2751. min( v ) {
  2752. this.x = Math.min( this.x, v.x );
  2753. this.y = Math.min( this.y, v.y );
  2754. this.z = Math.min( this.z, v.z );
  2755. return this;
  2756. }
  2757. max( v ) {
  2758. this.x = Math.max( this.x, v.x );
  2759. this.y = Math.max( this.y, v.y );
  2760. this.z = Math.max( this.z, v.z );
  2761. return this;
  2762. }
  2763. clamp( min, max ) {
  2764. // assumes min < max, componentwise
  2765. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2766. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2767. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2768. return this;
  2769. }
  2770. clampScalar( minVal, maxVal ) {
  2771. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2772. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2773. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2774. return this;
  2775. }
  2776. clampLength( min, max ) {
  2777. const length = this.length();
  2778. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2779. }
  2780. floor() {
  2781. this.x = Math.floor( this.x );
  2782. this.y = Math.floor( this.y );
  2783. this.z = Math.floor( this.z );
  2784. return this;
  2785. }
  2786. ceil() {
  2787. this.x = Math.ceil( this.x );
  2788. this.y = Math.ceil( this.y );
  2789. this.z = Math.ceil( this.z );
  2790. return this;
  2791. }
  2792. round() {
  2793. this.x = Math.round( this.x );
  2794. this.y = Math.round( this.y );
  2795. this.z = Math.round( this.z );
  2796. return this;
  2797. }
  2798. roundToZero() {
  2799. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2800. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2801. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2802. return this;
  2803. }
  2804. negate() {
  2805. this.x = - this.x;
  2806. this.y = - this.y;
  2807. this.z = - this.z;
  2808. return this;
  2809. }
  2810. dot( v ) {
  2811. return this.x * v.x + this.y * v.y + this.z * v.z;
  2812. }
  2813. // TODO lengthSquared?
  2814. lengthSq() {
  2815. return this.x * this.x + this.y * this.y + this.z * this.z;
  2816. }
  2817. length() {
  2818. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2819. }
  2820. manhattanLength() {
  2821. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2822. }
  2823. normalize() {
  2824. return this.divideScalar( this.length() || 1 );
  2825. }
  2826. setLength( length ) {
  2827. return this.normalize().multiplyScalar( length );
  2828. }
  2829. lerp( v, alpha ) {
  2830. this.x += ( v.x - this.x ) * alpha;
  2831. this.y += ( v.y - this.y ) * alpha;
  2832. this.z += ( v.z - this.z ) * alpha;
  2833. return this;
  2834. }
  2835. lerpVectors( v1, v2, alpha ) {
  2836. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2837. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2838. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2839. return this;
  2840. }
  2841. cross( v ) {
  2842. return this.crossVectors( this, v );
  2843. }
  2844. crossVectors( a, b ) {
  2845. const ax = a.x, ay = a.y, az = a.z;
  2846. const bx = b.x, by = b.y, bz = b.z;
  2847. this.x = ay * bz - az * by;
  2848. this.y = az * bx - ax * bz;
  2849. this.z = ax * by - ay * bx;
  2850. return this;
  2851. }
  2852. projectOnVector( v ) {
  2853. const denominator = v.lengthSq();
  2854. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2855. const scalar = v.dot( this ) / denominator;
  2856. return this.copy( v ).multiplyScalar( scalar );
  2857. }
  2858. projectOnPlane( planeNormal ) {
  2859. _vector$c.copy( this ).projectOnVector( planeNormal );
  2860. return this.sub( _vector$c );
  2861. }
  2862. reflect( normal ) {
  2863. // reflect incident vector off plane orthogonal to normal
  2864. // normal is assumed to have unit length
  2865. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2866. }
  2867. angleTo( v ) {
  2868. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2869. if ( denominator === 0 ) return Math.PI / 2;
  2870. const theta = this.dot( v ) / denominator;
  2871. // clamp, to handle numerical problems
  2872. return Math.acos( clamp( theta, - 1, 1 ) );
  2873. }
  2874. distanceTo( v ) {
  2875. return Math.sqrt( this.distanceToSquared( v ) );
  2876. }
  2877. distanceToSquared( v ) {
  2878. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2879. return dx * dx + dy * dy + dz * dz;
  2880. }
  2881. manhattanDistanceTo( v ) {
  2882. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2883. }
  2884. setFromSpherical( s ) {
  2885. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2886. }
  2887. setFromSphericalCoords( radius, phi, theta ) {
  2888. const sinPhiRadius = Math.sin( phi ) * radius;
  2889. this.x = sinPhiRadius * Math.sin( theta );
  2890. this.y = Math.cos( phi ) * radius;
  2891. this.z = sinPhiRadius * Math.cos( theta );
  2892. return this;
  2893. }
  2894. setFromCylindrical( c ) {
  2895. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2896. }
  2897. setFromCylindricalCoords( radius, theta, y ) {
  2898. this.x = radius * Math.sin( theta );
  2899. this.y = y;
  2900. this.z = radius * Math.cos( theta );
  2901. return this;
  2902. }
  2903. setFromMatrixPosition( m ) {
  2904. const e = m.elements;
  2905. this.x = e[ 12 ];
  2906. this.y = e[ 13 ];
  2907. this.z = e[ 14 ];
  2908. return this;
  2909. }
  2910. setFromMatrixScale( m ) {
  2911. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2912. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2913. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2914. this.x = sx;
  2915. this.y = sy;
  2916. this.z = sz;
  2917. return this;
  2918. }
  2919. setFromMatrixColumn( m, index ) {
  2920. return this.fromArray( m.elements, index * 4 );
  2921. }
  2922. setFromMatrix3Column( m, index ) {
  2923. return this.fromArray( m.elements, index * 3 );
  2924. }
  2925. setFromEuler( e ) {
  2926. this.x = e._x;
  2927. this.y = e._y;
  2928. this.z = e._z;
  2929. return this;
  2930. }
  2931. equals( v ) {
  2932. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2933. }
  2934. fromArray( array, offset = 0 ) {
  2935. this.x = array[ offset ];
  2936. this.y = array[ offset + 1 ];
  2937. this.z = array[ offset + 2 ];
  2938. return this;
  2939. }
  2940. toArray( array = [], offset = 0 ) {
  2941. array[ offset ] = this.x;
  2942. array[ offset + 1 ] = this.y;
  2943. array[ offset + 2 ] = this.z;
  2944. return array;
  2945. }
  2946. fromBufferAttribute( attribute, index ) {
  2947. this.x = attribute.getX( index );
  2948. this.y = attribute.getY( index );
  2949. this.z = attribute.getZ( index );
  2950. return this;
  2951. }
  2952. random() {
  2953. this.x = Math.random();
  2954. this.y = Math.random();
  2955. this.z = Math.random();
  2956. return this;
  2957. }
  2958. randomDirection() {
  2959. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2960. const u = ( Math.random() - 0.5 ) * 2;
  2961. const t = Math.random() * Math.PI * 2;
  2962. const f = Math.sqrt( 1 - u ** 2 );
  2963. this.x = f * Math.cos( t );
  2964. this.y = f * Math.sin( t );
  2965. this.z = u;
  2966. return this;
  2967. }
  2968. *[ Symbol.iterator ]() {
  2969. yield this.x;
  2970. yield this.y;
  2971. yield this.z;
  2972. }
  2973. }
  2974. const _vector$c = /*@__PURE__*/ new Vector3();
  2975. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2976. class Box3 {
  2977. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2978. this.isBox3 = true;
  2979. this.min = min;
  2980. this.max = max;
  2981. }
  2982. set( min, max ) {
  2983. this.min.copy( min );
  2984. this.max.copy( max );
  2985. return this;
  2986. }
  2987. setFromArray( array ) {
  2988. let minX = + Infinity;
  2989. let minY = + Infinity;
  2990. let minZ = + Infinity;
  2991. let maxX = - Infinity;
  2992. let maxY = - Infinity;
  2993. let maxZ = - Infinity;
  2994. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2995. const x = array[ i ];
  2996. const y = array[ i + 1 ];
  2997. const z = array[ i + 2 ];
  2998. if ( x < minX ) minX = x;
  2999. if ( y < minY ) minY = y;
  3000. if ( z < minZ ) minZ = z;
  3001. if ( x > maxX ) maxX = x;
  3002. if ( y > maxY ) maxY = y;
  3003. if ( z > maxZ ) maxZ = z;
  3004. }
  3005. this.min.set( minX, minY, minZ );
  3006. this.max.set( maxX, maxY, maxZ );
  3007. return this;
  3008. }
  3009. setFromBufferAttribute( attribute ) {
  3010. let minX = + Infinity;
  3011. let minY = + Infinity;
  3012. let minZ = + Infinity;
  3013. let maxX = - Infinity;
  3014. let maxY = - Infinity;
  3015. let maxZ = - Infinity;
  3016. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3017. const x = attribute.getX( i );
  3018. const y = attribute.getY( i );
  3019. const z = attribute.getZ( i );
  3020. if ( x < minX ) minX = x;
  3021. if ( y < minY ) minY = y;
  3022. if ( z < minZ ) minZ = z;
  3023. if ( x > maxX ) maxX = x;
  3024. if ( y > maxY ) maxY = y;
  3025. if ( z > maxZ ) maxZ = z;
  3026. }
  3027. this.min.set( minX, minY, minZ );
  3028. this.max.set( maxX, maxY, maxZ );
  3029. return this;
  3030. }
  3031. setFromPoints( points ) {
  3032. this.makeEmpty();
  3033. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3034. this.expandByPoint( points[ i ] );
  3035. }
  3036. return this;
  3037. }
  3038. setFromCenterAndSize( center, size ) {
  3039. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3040. this.min.copy( center ).sub( halfSize );
  3041. this.max.copy( center ).add( halfSize );
  3042. return this;
  3043. }
  3044. setFromObject( object, precise = false ) {
  3045. this.makeEmpty();
  3046. return this.expandByObject( object, precise );
  3047. }
  3048. clone() {
  3049. return new this.constructor().copy( this );
  3050. }
  3051. copy( box ) {
  3052. this.min.copy( box.min );
  3053. this.max.copy( box.max );
  3054. return this;
  3055. }
  3056. makeEmpty() {
  3057. this.min.x = this.min.y = this.min.z = + Infinity;
  3058. this.max.x = this.max.y = this.max.z = - Infinity;
  3059. return this;
  3060. }
  3061. isEmpty() {
  3062. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3063. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3064. }
  3065. getCenter( target ) {
  3066. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3067. }
  3068. getSize( target ) {
  3069. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3070. }
  3071. expandByPoint( point ) {
  3072. this.min.min( point );
  3073. this.max.max( point );
  3074. return this;
  3075. }
  3076. expandByVector( vector ) {
  3077. this.min.sub( vector );
  3078. this.max.add( vector );
  3079. return this;
  3080. }
  3081. expandByScalar( scalar ) {
  3082. this.min.addScalar( - scalar );
  3083. this.max.addScalar( scalar );
  3084. return this;
  3085. }
  3086. expandByObject( object, precise = false ) {
  3087. // Computes the world-axis-aligned bounding box of an object (including its children),
  3088. // accounting for both the object's, and children's, world transforms
  3089. object.updateWorldMatrix( false, false );
  3090. const geometry = object.geometry;
  3091. if ( geometry !== undefined ) {
  3092. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3093. const position = geometry.attributes.position;
  3094. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3095. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3096. this.expandByPoint( _vector$b );
  3097. }
  3098. } else {
  3099. if ( geometry.boundingBox === null ) {
  3100. geometry.computeBoundingBox();
  3101. }
  3102. _box$3.copy( geometry.boundingBox );
  3103. _box$3.applyMatrix4( object.matrixWorld );
  3104. this.union( _box$3 );
  3105. }
  3106. }
  3107. const children = object.children;
  3108. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3109. this.expandByObject( children[ i ], precise );
  3110. }
  3111. return this;
  3112. }
  3113. containsPoint( point ) {
  3114. return point.x < this.min.x || point.x > this.max.x ||
  3115. point.y < this.min.y || point.y > this.max.y ||
  3116. point.z < this.min.z || point.z > this.max.z ? false : true;
  3117. }
  3118. containsBox( box ) {
  3119. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3120. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3121. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3122. }
  3123. getParameter( point, target ) {
  3124. // This can potentially have a divide by zero if the box
  3125. // has a size dimension of 0.
  3126. return target.set(
  3127. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3128. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3129. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3130. );
  3131. }
  3132. intersectsBox( box ) {
  3133. // using 6 splitting planes to rule out intersections.
  3134. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3135. box.max.y < this.min.y || box.min.y > this.max.y ||
  3136. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3137. }
  3138. intersectsSphere( sphere ) {
  3139. // Find the point on the AABB closest to the sphere center.
  3140. this.clampPoint( sphere.center, _vector$b );
  3141. // If that point is inside the sphere, the AABB and sphere intersect.
  3142. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3143. }
  3144. intersectsPlane( plane ) {
  3145. // We compute the minimum and maximum dot product values. If those values
  3146. // are on the same side (back or front) of the plane, then there is no intersection.
  3147. let min, max;
  3148. if ( plane.normal.x > 0 ) {
  3149. min = plane.normal.x * this.min.x;
  3150. max = plane.normal.x * this.max.x;
  3151. } else {
  3152. min = plane.normal.x * this.max.x;
  3153. max = plane.normal.x * this.min.x;
  3154. }
  3155. if ( plane.normal.y > 0 ) {
  3156. min += plane.normal.y * this.min.y;
  3157. max += plane.normal.y * this.max.y;
  3158. } else {
  3159. min += plane.normal.y * this.max.y;
  3160. max += plane.normal.y * this.min.y;
  3161. }
  3162. if ( plane.normal.z > 0 ) {
  3163. min += plane.normal.z * this.min.z;
  3164. max += plane.normal.z * this.max.z;
  3165. } else {
  3166. min += plane.normal.z * this.max.z;
  3167. max += plane.normal.z * this.min.z;
  3168. }
  3169. return ( min <= - plane.constant && max >= - plane.constant );
  3170. }
  3171. intersectsTriangle( triangle ) {
  3172. if ( this.isEmpty() ) {
  3173. return false;
  3174. }
  3175. // compute box center and extents
  3176. this.getCenter( _center );
  3177. _extents.subVectors( this.max, _center );
  3178. // translate triangle to aabb origin
  3179. _v0$2.subVectors( triangle.a, _center );
  3180. _v1$7.subVectors( triangle.b, _center );
  3181. _v2$3.subVectors( triangle.c, _center );
  3182. // compute edge vectors for triangle
  3183. _f0.subVectors( _v1$7, _v0$2 );
  3184. _f1.subVectors( _v2$3, _v1$7 );
  3185. _f2.subVectors( _v0$2, _v2$3 );
  3186. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3187. // 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
  3188. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3189. let axes = [
  3190. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3191. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3192. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3193. ];
  3194. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3195. return false;
  3196. }
  3197. // test 3 face normals from the aabb
  3198. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3199. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3200. return false;
  3201. }
  3202. // finally testing the face normal of the triangle
  3203. // use already existing triangle edge vectors here
  3204. _triangleNormal.crossVectors( _f0, _f1 );
  3205. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3206. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  3207. }
  3208. clampPoint( point, target ) {
  3209. return target.copy( point ).clamp( this.min, this.max );
  3210. }
  3211. distanceToPoint( point ) {
  3212. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3213. return clampedPoint.sub( point ).length();
  3214. }
  3215. getBoundingSphere( target ) {
  3216. this.getCenter( target.center );
  3217. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3218. return target;
  3219. }
  3220. intersect( box ) {
  3221. this.min.max( box.min );
  3222. this.max.min( box.max );
  3223. // 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.
  3224. if ( this.isEmpty() ) this.makeEmpty();
  3225. return this;
  3226. }
  3227. union( box ) {
  3228. this.min.min( box.min );
  3229. this.max.max( box.max );
  3230. return this;
  3231. }
  3232. applyMatrix4( matrix ) {
  3233. // transform of empty box is an empty box.
  3234. if ( this.isEmpty() ) return this;
  3235. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3236. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3237. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3238. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3239. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3240. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3241. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3242. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3243. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3244. this.setFromPoints( _points );
  3245. return this;
  3246. }
  3247. translate( offset ) {
  3248. this.min.add( offset );
  3249. this.max.add( offset );
  3250. return this;
  3251. }
  3252. equals( box ) {
  3253. return box.min.equals( this.min ) && box.max.equals( this.max );
  3254. }
  3255. }
  3256. const _points = [
  3257. /*@__PURE__*/ new Vector3(),
  3258. /*@__PURE__*/ new Vector3(),
  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. ];
  3266. const _vector$b = /*@__PURE__*/ new Vector3();
  3267. const _box$3 = /*@__PURE__*/ new Box3();
  3268. // triangle centered vertices
  3269. const _v0$2 = /*@__PURE__*/ new Vector3();
  3270. const _v1$7 = /*@__PURE__*/ new Vector3();
  3271. const _v2$3 = /*@__PURE__*/ new Vector3();
  3272. // triangle edge vectors
  3273. const _f0 = /*@__PURE__*/ new Vector3();
  3274. const _f1 = /*@__PURE__*/ new Vector3();
  3275. const _f2 = /*@__PURE__*/ new Vector3();
  3276. const _center = /*@__PURE__*/ new Vector3();
  3277. const _extents = /*@__PURE__*/ new Vector3();
  3278. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3279. const _testAxis = /*@__PURE__*/ new Vector3();
  3280. function satForAxes( axes, v0, v1, v2, extents ) {
  3281. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3282. _testAxis.fromArray( axes, i );
  3283. // project the aabb onto the separating axis
  3284. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3285. // project all 3 vertices of the triangle onto the separating axis
  3286. const p0 = v0.dot( _testAxis );
  3287. const p1 = v1.dot( _testAxis );
  3288. const p2 = v2.dot( _testAxis );
  3289. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3290. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3291. // points of the projected triangle are outside the projected half-length of the aabb
  3292. // the axis is separating and we can exit
  3293. return false;
  3294. }
  3295. }
  3296. return true;
  3297. }
  3298. const _box$2 = /*@__PURE__*/ new Box3();
  3299. const _v1$6 = /*@__PURE__*/ new Vector3();
  3300. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  3301. const _toPoint = /*@__PURE__*/ new Vector3();
  3302. class Sphere {
  3303. constructor( center = new Vector3(), radius = - 1 ) {
  3304. this.center = center;
  3305. this.radius = radius;
  3306. }
  3307. set( center, radius ) {
  3308. this.center.copy( center );
  3309. this.radius = radius;
  3310. return this;
  3311. }
  3312. setFromPoints( points, optionalCenter ) {
  3313. const center = this.center;
  3314. if ( optionalCenter !== undefined ) {
  3315. center.copy( optionalCenter );
  3316. } else {
  3317. _box$2.setFromPoints( points ).getCenter( center );
  3318. }
  3319. let maxRadiusSq = 0;
  3320. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3321. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3322. }
  3323. this.radius = Math.sqrt( maxRadiusSq );
  3324. return this;
  3325. }
  3326. copy( sphere ) {
  3327. this.center.copy( sphere.center );
  3328. this.radius = sphere.radius;
  3329. return this;
  3330. }
  3331. isEmpty() {
  3332. return ( this.radius < 0 );
  3333. }
  3334. makeEmpty() {
  3335. this.center.set( 0, 0, 0 );
  3336. this.radius = - 1;
  3337. return this;
  3338. }
  3339. containsPoint( point ) {
  3340. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3341. }
  3342. distanceToPoint( point ) {
  3343. return ( point.distanceTo( this.center ) - this.radius );
  3344. }
  3345. intersectsSphere( sphere ) {
  3346. const radiusSum = this.radius + sphere.radius;
  3347. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3348. }
  3349. intersectsBox( box ) {
  3350. return box.intersectsSphere( this );
  3351. }
  3352. intersectsPlane( plane ) {
  3353. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3354. }
  3355. clampPoint( point, target ) {
  3356. const deltaLengthSq = this.center.distanceToSquared( point );
  3357. target.copy( point );
  3358. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3359. target.sub( this.center ).normalize();
  3360. target.multiplyScalar( this.radius ).add( this.center );
  3361. }
  3362. return target;
  3363. }
  3364. getBoundingBox( target ) {
  3365. if ( this.isEmpty() ) {
  3366. // Empty sphere produces empty bounding box
  3367. target.makeEmpty();
  3368. return target;
  3369. }
  3370. target.set( this.center, this.center );
  3371. target.expandByScalar( this.radius );
  3372. return target;
  3373. }
  3374. applyMatrix4( matrix ) {
  3375. this.center.applyMatrix4( matrix );
  3376. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3377. return this;
  3378. }
  3379. translate( offset ) {
  3380. this.center.add( offset );
  3381. return this;
  3382. }
  3383. expandByPoint( point ) {
  3384. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3385. _toPoint.subVectors( point, this.center );
  3386. const lengthSq = _toPoint.lengthSq();
  3387. if ( lengthSq > ( this.radius * this.radius ) ) {
  3388. const length = Math.sqrt( lengthSq );
  3389. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  3390. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3391. // and the other half to position. This gives a tighter enclosure, instead of if
  3392. // the whole missing distance were just added to radius.
  3393. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  3394. this.radius += missingRadiusHalf;
  3395. }
  3396. return this;
  3397. }
  3398. union( sphere ) {
  3399. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3400. // To enclose another sphere into this sphere, we only need to enclose two points:
  3401. // 1) Enclose the farthest point on the other sphere into this sphere.
  3402. // 2) Enclose the opposite point of the farthest point into this sphere.
  3403. if ( this.center.equals( sphere.center ) === true ) {
  3404. _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius );
  3405. } else {
  3406. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  3407. }
  3408. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  3409. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  3410. return this;
  3411. }
  3412. equals( sphere ) {
  3413. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3414. }
  3415. clone() {
  3416. return new this.constructor().copy( this );
  3417. }
  3418. }
  3419. const _vector$a = /*@__PURE__*/ new Vector3();
  3420. const _segCenter = /*@__PURE__*/ new Vector3();
  3421. const _segDir = /*@__PURE__*/ new Vector3();
  3422. const _diff = /*@__PURE__*/ new Vector3();
  3423. const _edge1 = /*@__PURE__*/ new Vector3();
  3424. const _edge2 = /*@__PURE__*/ new Vector3();
  3425. const _normal$1 = /*@__PURE__*/ new Vector3();
  3426. class Ray {
  3427. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3428. this.origin = origin;
  3429. this.direction = direction;
  3430. }
  3431. set( origin, direction ) {
  3432. this.origin.copy( origin );
  3433. this.direction.copy( direction );
  3434. return this;
  3435. }
  3436. copy( ray ) {
  3437. this.origin.copy( ray.origin );
  3438. this.direction.copy( ray.direction );
  3439. return this;
  3440. }
  3441. at( t, target ) {
  3442. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3443. }
  3444. lookAt( v ) {
  3445. this.direction.copy( v ).sub( this.origin ).normalize();
  3446. return this;
  3447. }
  3448. recast( t ) {
  3449. this.origin.copy( this.at( t, _vector$a ) );
  3450. return this;
  3451. }
  3452. closestPointToPoint( point, target ) {
  3453. target.subVectors( point, this.origin );
  3454. const directionDistance = target.dot( this.direction );
  3455. if ( directionDistance < 0 ) {
  3456. return target.copy( this.origin );
  3457. }
  3458. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3459. }
  3460. distanceToPoint( point ) {
  3461. return Math.sqrt( this.distanceSqToPoint( point ) );
  3462. }
  3463. distanceSqToPoint( point ) {
  3464. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3465. // point behind the ray
  3466. if ( directionDistance < 0 ) {
  3467. return this.origin.distanceToSquared( point );
  3468. }
  3469. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3470. return _vector$a.distanceToSquared( point );
  3471. }
  3472. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3473. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3474. // It returns the min distance between the ray and the segment
  3475. // defined by v0 and v1
  3476. // It can also set two optional targets :
  3477. // - The closest point on the ray
  3478. // - The closest point on the segment
  3479. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3480. _segDir.copy( v1 ).sub( v0 ).normalize();
  3481. _diff.copy( this.origin ).sub( _segCenter );
  3482. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3483. const a01 = - this.direction.dot( _segDir );
  3484. const b0 = _diff.dot( this.direction );
  3485. const b1 = - _diff.dot( _segDir );
  3486. const c = _diff.lengthSq();
  3487. const det = Math.abs( 1 - a01 * a01 );
  3488. let s0, s1, sqrDist, extDet;
  3489. if ( det > 0 ) {
  3490. // The ray and segment are not parallel.
  3491. s0 = a01 * b1 - b0;
  3492. s1 = a01 * b0 - b1;
  3493. extDet = segExtent * det;
  3494. if ( s0 >= 0 ) {
  3495. if ( s1 >= - extDet ) {
  3496. if ( s1 <= extDet ) {
  3497. // region 0
  3498. // Minimum at interior points of ray and segment.
  3499. const invDet = 1 / det;
  3500. s0 *= invDet;
  3501. s1 *= invDet;
  3502. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3503. } else {
  3504. // region 1
  3505. s1 = segExtent;
  3506. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3507. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3508. }
  3509. } else {
  3510. // region 5
  3511. s1 = - segExtent;
  3512. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3513. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3514. }
  3515. } else {
  3516. if ( s1 <= - extDet ) {
  3517. // region 4
  3518. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3519. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3520. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3521. } else if ( s1 <= extDet ) {
  3522. // region 3
  3523. s0 = 0;
  3524. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3525. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3526. } else {
  3527. // region 2
  3528. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3529. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3530. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3531. }
  3532. }
  3533. } else {
  3534. // Ray and segment are parallel.
  3535. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3536. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3537. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3538. }
  3539. if ( optionalPointOnRay ) {
  3540. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3541. }
  3542. if ( optionalPointOnSegment ) {
  3543. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3544. }
  3545. return sqrDist;
  3546. }
  3547. intersectSphere( sphere, target ) {
  3548. _vector$a.subVectors( sphere.center, this.origin );
  3549. const tca = _vector$a.dot( this.direction );
  3550. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3551. const radius2 = sphere.radius * sphere.radius;
  3552. if ( d2 > radius2 ) return null;
  3553. const thc = Math.sqrt( radius2 - d2 );
  3554. // t0 = first intersect point - entrance on front of sphere
  3555. const t0 = tca - thc;
  3556. // t1 = second intersect point - exit point on back of sphere
  3557. const t1 = tca + thc;
  3558. // test to see if both t0 and t1 are behind the ray - if so, return null
  3559. if ( t0 < 0 && t1 < 0 ) return null;
  3560. // test to see if t0 is behind the ray:
  3561. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3562. // in order to always return an intersect point that is in front of the ray.
  3563. if ( t0 < 0 ) return this.at( t1, target );
  3564. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3565. return this.at( t0, target );
  3566. }
  3567. intersectsSphere( sphere ) {
  3568. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3569. }
  3570. distanceToPlane( plane ) {
  3571. const denominator = plane.normal.dot( this.direction );
  3572. if ( denominator === 0 ) {
  3573. // line is coplanar, return origin
  3574. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3575. return 0;
  3576. }
  3577. // Null is preferable to undefined since undefined means.... it is undefined
  3578. return null;
  3579. }
  3580. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3581. // Return if the ray never intersects the plane
  3582. return t >= 0 ? t : null;
  3583. }
  3584. intersectPlane( plane, target ) {
  3585. const t = this.distanceToPlane( plane );
  3586. if ( t === null ) {
  3587. return null;
  3588. }
  3589. return this.at( t, target );
  3590. }
  3591. intersectsPlane( plane ) {
  3592. // check if the ray lies on the plane first
  3593. const distToPoint = plane.distanceToPoint( this.origin );
  3594. if ( distToPoint === 0 ) {
  3595. return true;
  3596. }
  3597. const denominator = plane.normal.dot( this.direction );
  3598. if ( denominator * distToPoint < 0 ) {
  3599. return true;
  3600. }
  3601. // ray origin is behind the plane (and is pointing behind it)
  3602. return false;
  3603. }
  3604. intersectBox( box, target ) {
  3605. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3606. const invdirx = 1 / this.direction.x,
  3607. invdiry = 1 / this.direction.y,
  3608. invdirz = 1 / this.direction.z;
  3609. const origin = this.origin;
  3610. if ( invdirx >= 0 ) {
  3611. tmin = ( box.min.x - origin.x ) * invdirx;
  3612. tmax = ( box.max.x - origin.x ) * invdirx;
  3613. } else {
  3614. tmin = ( box.max.x - origin.x ) * invdirx;
  3615. tmax = ( box.min.x - origin.x ) * invdirx;
  3616. }
  3617. if ( invdiry >= 0 ) {
  3618. tymin = ( box.min.y - origin.y ) * invdiry;
  3619. tymax = ( box.max.y - origin.y ) * invdiry;
  3620. } else {
  3621. tymin = ( box.max.y - origin.y ) * invdiry;
  3622. tymax = ( box.min.y - origin.y ) * invdiry;
  3623. }
  3624. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3625. // These lines also handle the case where tmin or tmax is NaN
  3626. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3627. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3628. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3629. if ( invdirz >= 0 ) {
  3630. tzmin = ( box.min.z - origin.z ) * invdirz;
  3631. tzmax = ( box.max.z - origin.z ) * invdirz;
  3632. } else {
  3633. tzmin = ( box.max.z - origin.z ) * invdirz;
  3634. tzmax = ( box.min.z - origin.z ) * invdirz;
  3635. }
  3636. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3637. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3638. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3639. //return point closest to the ray (positive side)
  3640. if ( tmax < 0 ) return null;
  3641. return this.at( tmin >= 0 ? tmin : tmax, target );
  3642. }
  3643. intersectsBox( box ) {
  3644. return this.intersectBox( box, _vector$a ) !== null;
  3645. }
  3646. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3647. // Compute the offset origin, edges, and normal.
  3648. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3649. _edge1.subVectors( b, a );
  3650. _edge2.subVectors( c, a );
  3651. _normal$1.crossVectors( _edge1, _edge2 );
  3652. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3653. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3654. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3655. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3656. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3657. let DdN = this.direction.dot( _normal$1 );
  3658. let sign;
  3659. if ( DdN > 0 ) {
  3660. if ( backfaceCulling ) return null;
  3661. sign = 1;
  3662. } else if ( DdN < 0 ) {
  3663. sign = - 1;
  3664. DdN = - DdN;
  3665. } else {
  3666. return null;
  3667. }
  3668. _diff.subVectors( this.origin, a );
  3669. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3670. // b1 < 0, no intersection
  3671. if ( DdQxE2 < 0 ) {
  3672. return null;
  3673. }
  3674. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3675. // b2 < 0, no intersection
  3676. if ( DdE1xQ < 0 ) {
  3677. return null;
  3678. }
  3679. // b1+b2 > 1, no intersection
  3680. if ( DdQxE2 + DdE1xQ > DdN ) {
  3681. return null;
  3682. }
  3683. // Line intersects triangle, check if ray does.
  3684. const QdN = - sign * _diff.dot( _normal$1 );
  3685. // t < 0, no intersection
  3686. if ( QdN < 0 ) {
  3687. return null;
  3688. }
  3689. // Ray intersects triangle.
  3690. return this.at( QdN / DdN, target );
  3691. }
  3692. applyMatrix4( matrix4 ) {
  3693. this.origin.applyMatrix4( matrix4 );
  3694. this.direction.transformDirection( matrix4 );
  3695. return this;
  3696. }
  3697. equals( ray ) {
  3698. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3699. }
  3700. clone() {
  3701. return new this.constructor().copy( this );
  3702. }
  3703. }
  3704. class Matrix4 {
  3705. constructor() {
  3706. Matrix4.prototype.isMatrix4 = true;
  3707. this.elements = [
  3708. 1, 0, 0, 0,
  3709. 0, 1, 0, 0,
  3710. 0, 0, 1, 0,
  3711. 0, 0, 0, 1
  3712. ];
  3713. }
  3714. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3715. const te = this.elements;
  3716. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3717. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3718. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3719. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3720. return this;
  3721. }
  3722. identity() {
  3723. this.set(
  3724. 1, 0, 0, 0,
  3725. 0, 1, 0, 0,
  3726. 0, 0, 1, 0,
  3727. 0, 0, 0, 1
  3728. );
  3729. return this;
  3730. }
  3731. clone() {
  3732. return new Matrix4().fromArray( this.elements );
  3733. }
  3734. copy( m ) {
  3735. const te = this.elements;
  3736. const me = m.elements;
  3737. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3738. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3739. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3740. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3741. return this;
  3742. }
  3743. copyPosition( m ) {
  3744. const te = this.elements, me = m.elements;
  3745. te[ 12 ] = me[ 12 ];
  3746. te[ 13 ] = me[ 13 ];
  3747. te[ 14 ] = me[ 14 ];
  3748. return this;
  3749. }
  3750. setFromMatrix3( m ) {
  3751. const me = m.elements;
  3752. this.set(
  3753. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3754. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3755. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3756. 0, 0, 0, 1
  3757. );
  3758. return this;
  3759. }
  3760. extractBasis( xAxis, yAxis, zAxis ) {
  3761. xAxis.setFromMatrixColumn( this, 0 );
  3762. yAxis.setFromMatrixColumn( this, 1 );
  3763. zAxis.setFromMatrixColumn( this, 2 );
  3764. return this;
  3765. }
  3766. makeBasis( xAxis, yAxis, zAxis ) {
  3767. this.set(
  3768. xAxis.x, yAxis.x, zAxis.x, 0,
  3769. xAxis.y, yAxis.y, zAxis.y, 0,
  3770. xAxis.z, yAxis.z, zAxis.z, 0,
  3771. 0, 0, 0, 1
  3772. );
  3773. return this;
  3774. }
  3775. extractRotation( m ) {
  3776. // this method does not support reflection matrices
  3777. const te = this.elements;
  3778. const me = m.elements;
  3779. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3780. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3781. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3782. te[ 0 ] = me[ 0 ] * scaleX;
  3783. te[ 1 ] = me[ 1 ] * scaleX;
  3784. te[ 2 ] = me[ 2 ] * scaleX;
  3785. te[ 3 ] = 0;
  3786. te[ 4 ] = me[ 4 ] * scaleY;
  3787. te[ 5 ] = me[ 5 ] * scaleY;
  3788. te[ 6 ] = me[ 6 ] * scaleY;
  3789. te[ 7 ] = 0;
  3790. te[ 8 ] = me[ 8 ] * scaleZ;
  3791. te[ 9 ] = me[ 9 ] * scaleZ;
  3792. te[ 10 ] = me[ 10 ] * scaleZ;
  3793. te[ 11 ] = 0;
  3794. te[ 12 ] = 0;
  3795. te[ 13 ] = 0;
  3796. te[ 14 ] = 0;
  3797. te[ 15 ] = 1;
  3798. return this;
  3799. }
  3800. makeRotationFromEuler( euler ) {
  3801. const te = this.elements;
  3802. const x = euler.x, y = euler.y, z = euler.z;
  3803. const a = Math.cos( x ), b = Math.sin( x );
  3804. const c = Math.cos( y ), d = Math.sin( y );
  3805. const e = Math.cos( z ), f = Math.sin( z );
  3806. if ( euler.order === 'XYZ' ) {
  3807. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3808. te[ 0 ] = c * e;
  3809. te[ 4 ] = - c * f;
  3810. te[ 8 ] = d;
  3811. te[ 1 ] = af + be * d;
  3812. te[ 5 ] = ae - bf * d;
  3813. te[ 9 ] = - b * c;
  3814. te[ 2 ] = bf - ae * d;
  3815. te[ 6 ] = be + af * d;
  3816. te[ 10 ] = a * c;
  3817. } else if ( euler.order === 'YXZ' ) {
  3818. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3819. te[ 0 ] = ce + df * b;
  3820. te[ 4 ] = de * b - cf;
  3821. te[ 8 ] = a * d;
  3822. te[ 1 ] = a * f;
  3823. te[ 5 ] = a * e;
  3824. te[ 9 ] = - b;
  3825. te[ 2 ] = cf * b - de;
  3826. te[ 6 ] = df + ce * b;
  3827. te[ 10 ] = a * c;
  3828. } else if ( euler.order === 'ZXY' ) {
  3829. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3830. te[ 0 ] = ce - df * b;
  3831. te[ 4 ] = - a * f;
  3832. te[ 8 ] = de + cf * b;
  3833. te[ 1 ] = cf + de * b;
  3834. te[ 5 ] = a * e;
  3835. te[ 9 ] = df - ce * b;
  3836. te[ 2 ] = - a * d;
  3837. te[ 6 ] = b;
  3838. te[ 10 ] = a * c;
  3839. } else if ( euler.order === 'ZYX' ) {
  3840. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3841. te[ 0 ] = c * e;
  3842. te[ 4 ] = be * d - af;
  3843. te[ 8 ] = ae * d + bf;
  3844. te[ 1 ] = c * f;
  3845. te[ 5 ] = bf * d + ae;
  3846. te[ 9 ] = af * d - be;
  3847. te[ 2 ] = - d;
  3848. te[ 6 ] = b * c;
  3849. te[ 10 ] = a * c;
  3850. } else if ( euler.order === 'YZX' ) {
  3851. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3852. te[ 0 ] = c * e;
  3853. te[ 4 ] = bd - ac * f;
  3854. te[ 8 ] = bc * f + ad;
  3855. te[ 1 ] = f;
  3856. te[ 5 ] = a * e;
  3857. te[ 9 ] = - b * e;
  3858. te[ 2 ] = - d * e;
  3859. te[ 6 ] = ad * f + bc;
  3860. te[ 10 ] = ac - bd * f;
  3861. } else if ( euler.order === 'XZY' ) {
  3862. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3863. te[ 0 ] = c * e;
  3864. te[ 4 ] = - f;
  3865. te[ 8 ] = d * e;
  3866. te[ 1 ] = ac * f + bd;
  3867. te[ 5 ] = a * e;
  3868. te[ 9 ] = ad * f - bc;
  3869. te[ 2 ] = bc * f - ad;
  3870. te[ 6 ] = b * e;
  3871. te[ 10 ] = bd * f + ac;
  3872. }
  3873. // bottom row
  3874. te[ 3 ] = 0;
  3875. te[ 7 ] = 0;
  3876. te[ 11 ] = 0;
  3877. // last column
  3878. te[ 12 ] = 0;
  3879. te[ 13 ] = 0;
  3880. te[ 14 ] = 0;
  3881. te[ 15 ] = 1;
  3882. return this;
  3883. }
  3884. makeRotationFromQuaternion( q ) {
  3885. return this.compose( _zero, q, _one );
  3886. }
  3887. lookAt( eye, target, up ) {
  3888. const te = this.elements;
  3889. _z.subVectors( eye, target );
  3890. if ( _z.lengthSq() === 0 ) {
  3891. // eye and target are in the same position
  3892. _z.z = 1;
  3893. }
  3894. _z.normalize();
  3895. _x.crossVectors( up, _z );
  3896. if ( _x.lengthSq() === 0 ) {
  3897. // up and z are parallel
  3898. if ( Math.abs( up.z ) === 1 ) {
  3899. _z.x += 0.0001;
  3900. } else {
  3901. _z.z += 0.0001;
  3902. }
  3903. _z.normalize();
  3904. _x.crossVectors( up, _z );
  3905. }
  3906. _x.normalize();
  3907. _y.crossVectors( _z, _x );
  3908. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3909. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3910. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3911. return this;
  3912. }
  3913. multiply( m ) {
  3914. return this.multiplyMatrices( this, m );
  3915. }
  3916. premultiply( m ) {
  3917. return this.multiplyMatrices( m, this );
  3918. }
  3919. multiplyMatrices( a, b ) {
  3920. const ae = a.elements;
  3921. const be = b.elements;
  3922. const te = this.elements;
  3923. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3924. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3925. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3926. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3927. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3928. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3929. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3930. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3931. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3932. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3933. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3934. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3935. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3936. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3937. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3938. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3939. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3940. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3941. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3942. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3943. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3944. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3945. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3946. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3947. return this;
  3948. }
  3949. multiplyScalar( s ) {
  3950. const te = this.elements;
  3951. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3952. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3953. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3954. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3955. return this;
  3956. }
  3957. determinant() {
  3958. const te = this.elements;
  3959. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3960. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3961. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3962. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3963. //TODO: make this more efficient
  3964. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3965. return (
  3966. n41 * (
  3967. + n14 * n23 * n32
  3968. - n13 * n24 * n32
  3969. - n14 * n22 * n33
  3970. + n12 * n24 * n33
  3971. + n13 * n22 * n34
  3972. - n12 * n23 * n34
  3973. ) +
  3974. n42 * (
  3975. + n11 * n23 * n34
  3976. - n11 * n24 * n33
  3977. + n14 * n21 * n33
  3978. - n13 * n21 * n34
  3979. + n13 * n24 * n31
  3980. - n14 * n23 * n31
  3981. ) +
  3982. n43 * (
  3983. + n11 * n24 * n32
  3984. - n11 * n22 * n34
  3985. - n14 * n21 * n32
  3986. + n12 * n21 * n34
  3987. + n14 * n22 * n31
  3988. - n12 * n24 * n31
  3989. ) +
  3990. n44 * (
  3991. - n13 * n22 * n31
  3992. - n11 * n23 * n32
  3993. + n11 * n22 * n33
  3994. + n13 * n21 * n32
  3995. - n12 * n21 * n33
  3996. + n12 * n23 * n31
  3997. )
  3998. );
  3999. }
  4000. transpose() {
  4001. const te = this.elements;
  4002. let tmp;
  4003. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4004. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4005. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4006. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4007. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4008. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4009. return this;
  4010. }
  4011. setPosition( x, y, z ) {
  4012. const te = this.elements;
  4013. if ( x.isVector3 ) {
  4014. te[ 12 ] = x.x;
  4015. te[ 13 ] = x.y;
  4016. te[ 14 ] = x.z;
  4017. } else {
  4018. te[ 12 ] = x;
  4019. te[ 13 ] = y;
  4020. te[ 14 ] = z;
  4021. }
  4022. return this;
  4023. }
  4024. invert() {
  4025. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4026. const te = this.elements,
  4027. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4028. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4029. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4030. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4031. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4032. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4033. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4034. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4035. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4036. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4037. const detInv = 1 / det;
  4038. te[ 0 ] = t11 * detInv;
  4039. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4040. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4041. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4042. te[ 4 ] = t12 * detInv;
  4043. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4044. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4045. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4046. te[ 8 ] = t13 * detInv;
  4047. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4048. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4049. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4050. te[ 12 ] = t14 * detInv;
  4051. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4052. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4053. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4054. return this;
  4055. }
  4056. scale( v ) {
  4057. const te = this.elements;
  4058. const x = v.x, y = v.y, z = v.z;
  4059. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4060. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4061. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4062. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4063. return this;
  4064. }
  4065. getMaxScaleOnAxis() {
  4066. const te = this.elements;
  4067. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4068. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4069. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4070. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4071. }
  4072. makeTranslation( x, y, z ) {
  4073. this.set(
  4074. 1, 0, 0, x,
  4075. 0, 1, 0, y,
  4076. 0, 0, 1, z,
  4077. 0, 0, 0, 1
  4078. );
  4079. return this;
  4080. }
  4081. makeRotationX( theta ) {
  4082. const c = Math.cos( theta ), s = Math.sin( theta );
  4083. this.set(
  4084. 1, 0, 0, 0,
  4085. 0, c, - s, 0,
  4086. 0, s, c, 0,
  4087. 0, 0, 0, 1
  4088. );
  4089. return this;
  4090. }
  4091. makeRotationY( theta ) {
  4092. const c = Math.cos( theta ), s = Math.sin( theta );
  4093. this.set(
  4094. c, 0, s, 0,
  4095. 0, 1, 0, 0,
  4096. - s, 0, c, 0,
  4097. 0, 0, 0, 1
  4098. );
  4099. return this;
  4100. }
  4101. makeRotationZ( theta ) {
  4102. const c = Math.cos( theta ), s = Math.sin( theta );
  4103. this.set(
  4104. c, - s, 0, 0,
  4105. s, c, 0, 0,
  4106. 0, 0, 1, 0,
  4107. 0, 0, 0, 1
  4108. );
  4109. return this;
  4110. }
  4111. makeRotationAxis( axis, angle ) {
  4112. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4113. const c = Math.cos( angle );
  4114. const s = Math.sin( angle );
  4115. const t = 1 - c;
  4116. const x = axis.x, y = axis.y, z = axis.z;
  4117. const tx = t * x, ty = t * y;
  4118. this.set(
  4119. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4120. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4121. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4122. 0, 0, 0, 1
  4123. );
  4124. return this;
  4125. }
  4126. makeScale( x, y, z ) {
  4127. this.set(
  4128. x, 0, 0, 0,
  4129. 0, y, 0, 0,
  4130. 0, 0, z, 0,
  4131. 0, 0, 0, 1
  4132. );
  4133. return this;
  4134. }
  4135. makeShear( xy, xz, yx, yz, zx, zy ) {
  4136. this.set(
  4137. 1, yx, zx, 0,
  4138. xy, 1, zy, 0,
  4139. xz, yz, 1, 0,
  4140. 0, 0, 0, 1
  4141. );
  4142. return this;
  4143. }
  4144. compose( position, quaternion, scale ) {
  4145. const te = this.elements;
  4146. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4147. const x2 = x + x, y2 = y + y, z2 = z + z;
  4148. const xx = x * x2, xy = x * y2, xz = x * z2;
  4149. const yy = y * y2, yz = y * z2, zz = z * z2;
  4150. const wx = w * x2, wy = w * y2, wz = w * z2;
  4151. const sx = scale.x, sy = scale.y, sz = scale.z;
  4152. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4153. te[ 1 ] = ( xy + wz ) * sx;
  4154. te[ 2 ] = ( xz - wy ) * sx;
  4155. te[ 3 ] = 0;
  4156. te[ 4 ] = ( xy - wz ) * sy;
  4157. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4158. te[ 6 ] = ( yz + wx ) * sy;
  4159. te[ 7 ] = 0;
  4160. te[ 8 ] = ( xz + wy ) * sz;
  4161. te[ 9 ] = ( yz - wx ) * sz;
  4162. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4163. te[ 11 ] = 0;
  4164. te[ 12 ] = position.x;
  4165. te[ 13 ] = position.y;
  4166. te[ 14 ] = position.z;
  4167. te[ 15 ] = 1;
  4168. return this;
  4169. }
  4170. decompose( position, quaternion, scale ) {
  4171. const te = this.elements;
  4172. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4173. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4174. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4175. // if determine is negative, we need to invert one scale
  4176. const det = this.determinant();
  4177. if ( det < 0 ) sx = - sx;
  4178. position.x = te[ 12 ];
  4179. position.y = te[ 13 ];
  4180. position.z = te[ 14 ];
  4181. // scale the rotation part
  4182. _m1$2.copy( this );
  4183. const invSX = 1 / sx;
  4184. const invSY = 1 / sy;
  4185. const invSZ = 1 / sz;
  4186. _m1$2.elements[ 0 ] *= invSX;
  4187. _m1$2.elements[ 1 ] *= invSX;
  4188. _m1$2.elements[ 2 ] *= invSX;
  4189. _m1$2.elements[ 4 ] *= invSY;
  4190. _m1$2.elements[ 5 ] *= invSY;
  4191. _m1$2.elements[ 6 ] *= invSY;
  4192. _m1$2.elements[ 8 ] *= invSZ;
  4193. _m1$2.elements[ 9 ] *= invSZ;
  4194. _m1$2.elements[ 10 ] *= invSZ;
  4195. quaternion.setFromRotationMatrix( _m1$2 );
  4196. scale.x = sx;
  4197. scale.y = sy;
  4198. scale.z = sz;
  4199. return this;
  4200. }
  4201. makePerspective( left, right, top, bottom, near, far ) {
  4202. const te = this.elements;
  4203. const x = 2 * near / ( right - left );
  4204. const y = 2 * near / ( top - bottom );
  4205. const a = ( right + left ) / ( right - left );
  4206. const b = ( top + bottom ) / ( top - bottom );
  4207. const c = - ( far + near ) / ( far - near );
  4208. const d = - 2 * far * near / ( far - near );
  4209. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4210. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4211. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4212. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4213. return this;
  4214. }
  4215. makeOrthographic( left, right, top, bottom, near, far ) {
  4216. const te = this.elements;
  4217. const w = 1.0 / ( right - left );
  4218. const h = 1.0 / ( top - bottom );
  4219. const p = 1.0 / ( far - near );
  4220. const x = ( right + left ) * w;
  4221. const y = ( top + bottom ) * h;
  4222. const z = ( far + near ) * p;
  4223. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4224. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4225. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4226. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4227. return this;
  4228. }
  4229. equals( matrix ) {
  4230. const te = this.elements;
  4231. const me = matrix.elements;
  4232. for ( let i = 0; i < 16; i ++ ) {
  4233. if ( te[ i ] !== me[ i ] ) return false;
  4234. }
  4235. return true;
  4236. }
  4237. fromArray( array, offset = 0 ) {
  4238. for ( let i = 0; i < 16; i ++ ) {
  4239. this.elements[ i ] = array[ i + offset ];
  4240. }
  4241. return this;
  4242. }
  4243. toArray( array = [], offset = 0 ) {
  4244. const te = this.elements;
  4245. array[ offset ] = te[ 0 ];
  4246. array[ offset + 1 ] = te[ 1 ];
  4247. array[ offset + 2 ] = te[ 2 ];
  4248. array[ offset + 3 ] = te[ 3 ];
  4249. array[ offset + 4 ] = te[ 4 ];
  4250. array[ offset + 5 ] = te[ 5 ];
  4251. array[ offset + 6 ] = te[ 6 ];
  4252. array[ offset + 7 ] = te[ 7 ];
  4253. array[ offset + 8 ] = te[ 8 ];
  4254. array[ offset + 9 ] = te[ 9 ];
  4255. array[ offset + 10 ] = te[ 10 ];
  4256. array[ offset + 11 ] = te[ 11 ];
  4257. array[ offset + 12 ] = te[ 12 ];
  4258. array[ offset + 13 ] = te[ 13 ];
  4259. array[ offset + 14 ] = te[ 14 ];
  4260. array[ offset + 15 ] = te[ 15 ];
  4261. return array;
  4262. }
  4263. }
  4264. const _v1$5 = /*@__PURE__*/ new Vector3();
  4265. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4266. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4267. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4268. const _x = /*@__PURE__*/ new Vector3();
  4269. const _y = /*@__PURE__*/ new Vector3();
  4270. const _z = /*@__PURE__*/ new Vector3();
  4271. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4272. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4273. class Euler {
  4274. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4275. this.isEuler = true;
  4276. this._x = x;
  4277. this._y = y;
  4278. this._z = z;
  4279. this._order = order;
  4280. }
  4281. get x() {
  4282. return this._x;
  4283. }
  4284. set x( value ) {
  4285. this._x = value;
  4286. this._onChangeCallback();
  4287. }
  4288. get y() {
  4289. return this._y;
  4290. }
  4291. set y( value ) {
  4292. this._y = value;
  4293. this._onChangeCallback();
  4294. }
  4295. get z() {
  4296. return this._z;
  4297. }
  4298. set z( value ) {
  4299. this._z = value;
  4300. this._onChangeCallback();
  4301. }
  4302. get order() {
  4303. return this._order;
  4304. }
  4305. set order( value ) {
  4306. this._order = value;
  4307. this._onChangeCallback();
  4308. }
  4309. set( x, y, z, order = this._order ) {
  4310. this._x = x;
  4311. this._y = y;
  4312. this._z = z;
  4313. this._order = order;
  4314. this._onChangeCallback();
  4315. return this;
  4316. }
  4317. clone() {
  4318. return new this.constructor( this._x, this._y, this._z, this._order );
  4319. }
  4320. copy( euler ) {
  4321. this._x = euler._x;
  4322. this._y = euler._y;
  4323. this._z = euler._z;
  4324. this._order = euler._order;
  4325. this._onChangeCallback();
  4326. return this;
  4327. }
  4328. setFromRotationMatrix( m, order = this._order, update = true ) {
  4329. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4330. const te = m.elements;
  4331. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4332. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4333. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4334. switch ( order ) {
  4335. case 'XYZ':
  4336. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4337. if ( Math.abs( m13 ) < 0.9999999 ) {
  4338. this._x = Math.atan2( - m23, m33 );
  4339. this._z = Math.atan2( - m12, m11 );
  4340. } else {
  4341. this._x = Math.atan2( m32, m22 );
  4342. this._z = 0;
  4343. }
  4344. break;
  4345. case 'YXZ':
  4346. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4347. if ( Math.abs( m23 ) < 0.9999999 ) {
  4348. this._y = Math.atan2( m13, m33 );
  4349. this._z = Math.atan2( m21, m22 );
  4350. } else {
  4351. this._y = Math.atan2( - m31, m11 );
  4352. this._z = 0;
  4353. }
  4354. break;
  4355. case 'ZXY':
  4356. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4357. if ( Math.abs( m32 ) < 0.9999999 ) {
  4358. this._y = Math.atan2( - m31, m33 );
  4359. this._z = Math.atan2( - m12, m22 );
  4360. } else {
  4361. this._y = 0;
  4362. this._z = Math.atan2( m21, m11 );
  4363. }
  4364. break;
  4365. case 'ZYX':
  4366. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4367. if ( Math.abs( m31 ) < 0.9999999 ) {
  4368. this._x = Math.atan2( m32, m33 );
  4369. this._z = Math.atan2( m21, m11 );
  4370. } else {
  4371. this._x = 0;
  4372. this._z = Math.atan2( - m12, m22 );
  4373. }
  4374. break;
  4375. case 'YZX':
  4376. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4377. if ( Math.abs( m21 ) < 0.9999999 ) {
  4378. this._x = Math.atan2( - m23, m22 );
  4379. this._y = Math.atan2( - m31, m11 );
  4380. } else {
  4381. this._x = 0;
  4382. this._y = Math.atan2( m13, m33 );
  4383. }
  4384. break;
  4385. case 'XZY':
  4386. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4387. if ( Math.abs( m12 ) < 0.9999999 ) {
  4388. this._x = Math.atan2( m32, m22 );
  4389. this._y = Math.atan2( m13, m11 );
  4390. } else {
  4391. this._x = Math.atan2( - m23, m33 );
  4392. this._y = 0;
  4393. }
  4394. break;
  4395. default:
  4396. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4397. }
  4398. this._order = order;
  4399. if ( update === true ) this._onChangeCallback();
  4400. return this;
  4401. }
  4402. setFromQuaternion( q, order, update ) {
  4403. _matrix$1.makeRotationFromQuaternion( q );
  4404. return this.setFromRotationMatrix( _matrix$1, order, update );
  4405. }
  4406. setFromVector3( v, order = this._order ) {
  4407. return this.set( v.x, v.y, v.z, order );
  4408. }
  4409. reorder( newOrder ) {
  4410. // WARNING: this discards revolution information -bhouston
  4411. _quaternion$3.setFromEuler( this );
  4412. return this.setFromQuaternion( _quaternion$3, newOrder );
  4413. }
  4414. equals( euler ) {
  4415. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4416. }
  4417. fromArray( array ) {
  4418. this._x = array[ 0 ];
  4419. this._y = array[ 1 ];
  4420. this._z = array[ 2 ];
  4421. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4422. this._onChangeCallback();
  4423. return this;
  4424. }
  4425. toArray( array = [], offset = 0 ) {
  4426. array[ offset ] = this._x;
  4427. array[ offset + 1 ] = this._y;
  4428. array[ offset + 2 ] = this._z;
  4429. array[ offset + 3 ] = this._order;
  4430. return array;
  4431. }
  4432. _onChange( callback ) {
  4433. this._onChangeCallback = callback;
  4434. return this;
  4435. }
  4436. _onChangeCallback() {}
  4437. *[ Symbol.iterator ]() {
  4438. yield this._x;
  4439. yield this._y;
  4440. yield this._z;
  4441. yield this._order;
  4442. }
  4443. // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4444. toVector3() {
  4445. console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' );
  4446. }
  4447. }
  4448. Euler.DefaultOrder = 'XYZ';
  4449. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4450. class Layers {
  4451. constructor() {
  4452. this.mask = 1 | 0;
  4453. }
  4454. set( channel ) {
  4455. this.mask = ( 1 << channel | 0 ) >>> 0;
  4456. }
  4457. enable( channel ) {
  4458. this.mask |= 1 << channel | 0;
  4459. }
  4460. enableAll() {
  4461. this.mask = 0xffffffff | 0;
  4462. }
  4463. toggle( channel ) {
  4464. this.mask ^= 1 << channel | 0;
  4465. }
  4466. disable( channel ) {
  4467. this.mask &= ~ ( 1 << channel | 0 );
  4468. }
  4469. disableAll() {
  4470. this.mask = 0;
  4471. }
  4472. test( layers ) {
  4473. return ( this.mask & layers.mask ) !== 0;
  4474. }
  4475. isEnabled( channel ) {
  4476. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4477. }
  4478. }
  4479. let _object3DId = 0;
  4480. const _v1$4 = /*@__PURE__*/ new Vector3();
  4481. const _q1 = /*@__PURE__*/ new Quaternion();
  4482. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4483. const _target = /*@__PURE__*/ new Vector3();
  4484. const _position$3 = /*@__PURE__*/ new Vector3();
  4485. const _scale$2 = /*@__PURE__*/ new Vector3();
  4486. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4487. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4488. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4489. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4490. const _addedEvent = { type: 'added' };
  4491. const _removedEvent = { type: 'removed' };
  4492. class Object3D extends EventDispatcher {
  4493. constructor() {
  4494. super();
  4495. this.isObject3D = true;
  4496. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4497. this.uuid = generateUUID();
  4498. this.name = '';
  4499. this.type = 'Object3D';
  4500. this.parent = null;
  4501. this.children = [];
  4502. this.up = Object3D.DefaultUp.clone();
  4503. const position = new Vector3();
  4504. const rotation = new Euler();
  4505. const quaternion = new Quaternion();
  4506. const scale = new Vector3( 1, 1, 1 );
  4507. function onRotationChange() {
  4508. quaternion.setFromEuler( rotation, false );
  4509. }
  4510. function onQuaternionChange() {
  4511. rotation.setFromQuaternion( quaternion, undefined, false );
  4512. }
  4513. rotation._onChange( onRotationChange );
  4514. quaternion._onChange( onQuaternionChange );
  4515. Object.defineProperties( this, {
  4516. position: {
  4517. configurable: true,
  4518. enumerable: true,
  4519. value: position
  4520. },
  4521. rotation: {
  4522. configurable: true,
  4523. enumerable: true,
  4524. value: rotation
  4525. },
  4526. quaternion: {
  4527. configurable: true,
  4528. enumerable: true,
  4529. value: quaternion
  4530. },
  4531. scale: {
  4532. configurable: true,
  4533. enumerable: true,
  4534. value: scale
  4535. },
  4536. modelViewMatrix: {
  4537. value: new Matrix4()
  4538. },
  4539. normalMatrix: {
  4540. value: new Matrix3()
  4541. }
  4542. } );
  4543. this.matrix = new Matrix4();
  4544. this.matrixWorld = new Matrix4();
  4545. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4546. this.matrixWorldNeedsUpdate = false;
  4547. this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer
  4548. this.layers = new Layers();
  4549. this.visible = true;
  4550. this.choice = false;
  4551. this.play = true;
  4552. this.whole = false; //整体
  4553. this.castShadow = false;
  4554. this.receiveShadow = false;
  4555. this.frustumCulled = true;
  4556. this.renderOrder = 0;
  4557. this.animations = [];
  4558. this.userData = {};
  4559. this.scripts = [];
  4560. }
  4561. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4562. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4563. applyMatrix4( matrix ) {
  4564. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4565. this.matrix.premultiply( matrix );
  4566. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4567. }
  4568. applyQuaternion( q ) {
  4569. this.quaternion.premultiply( q );
  4570. return this;
  4571. }
  4572. setRotationFromAxisAngle( axis, angle ) {
  4573. // assumes axis is normalized
  4574. this.quaternion.setFromAxisAngle( axis, angle );
  4575. }
  4576. setRotationFromEuler( euler ) {
  4577. this.quaternion.setFromEuler( euler, true );
  4578. }
  4579. setRotationFromMatrix( m ) {
  4580. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4581. this.quaternion.setFromRotationMatrix( m );
  4582. }
  4583. setRotationFromQuaternion( q ) {
  4584. // assumes q is normalized
  4585. this.quaternion.copy( q );
  4586. }
  4587. rotateOnAxis( axis, angle ) {
  4588. // rotate object on axis in object space
  4589. // axis is assumed to be normalized
  4590. _q1.setFromAxisAngle( axis, angle );
  4591. this.quaternion.multiply( _q1 );
  4592. return this;
  4593. }
  4594. rotateOnWorldAxis( axis, angle ) {
  4595. // rotate object on axis in world space
  4596. // axis is assumed to be normalized
  4597. // method assumes no rotated parent
  4598. _q1.setFromAxisAngle( axis, angle );
  4599. this.quaternion.premultiply( _q1 );
  4600. return this;
  4601. }
  4602. rotateX( angle ) {
  4603. return this.rotateOnAxis( _xAxis, angle );
  4604. }
  4605. rotateY( angle ) {
  4606. return this.rotateOnAxis( _yAxis, angle );
  4607. }
  4608. rotateZ( angle ) {
  4609. return this.rotateOnAxis( _zAxis, angle );
  4610. }
  4611. translateOnAxis( axis, distance ) {
  4612. // translate object by distance along axis in object space
  4613. // axis is assumed to be normalized
  4614. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4615. this.position.add( _v1$4.multiplyScalar( distance ) );
  4616. return this;
  4617. }
  4618. translateX( distance ) {
  4619. return this.translateOnAxis( _xAxis, distance );
  4620. }
  4621. translateY( distance ) {
  4622. return this.translateOnAxis( _yAxis, distance );
  4623. }
  4624. translateZ( distance ) {
  4625. return this.translateOnAxis( _zAxis, distance );
  4626. }
  4627. localToWorld( vector ) {
  4628. return vector.applyMatrix4( this.matrixWorld );
  4629. }
  4630. worldToLocal( vector ) {
  4631. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4632. }
  4633. lookAt( x, y, z ) {
  4634. // This method does not support objects having non-uniformly-scaled parent(s)
  4635. if ( x.isVector3 ) {
  4636. _target.copy( x );
  4637. } else {
  4638. _target.set( x, y, z );
  4639. }
  4640. const parent = this.parent;
  4641. this.updateWorldMatrix( true, false );
  4642. _position$3.setFromMatrixPosition( this.matrixWorld );
  4643. if ( this.isCamera || this.isLight ) {
  4644. _m1$1.lookAt( _position$3, _target, this.up );
  4645. } else {
  4646. _m1$1.lookAt( _target, _position$3, this.up );
  4647. }
  4648. this.quaternion.setFromRotationMatrix( _m1$1 );
  4649. if ( parent ) {
  4650. _m1$1.extractRotation( parent.matrixWorld );
  4651. _q1.setFromRotationMatrix( _m1$1 );
  4652. this.quaternion.premultiply( _q1.invert() );
  4653. }
  4654. }
  4655. add( object ) {
  4656. if ( arguments.length > 1 ) {
  4657. for ( let i = 0; i < arguments.length; i ++ ) {
  4658. this.add( arguments[ i ] );
  4659. }
  4660. return this;
  4661. }
  4662. if ( object === this ) {
  4663. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4664. return this;
  4665. }
  4666. if ( object && object.isObject3D ) {
  4667. if ( object.parent !== null ) {
  4668. object.parent.remove( object );
  4669. }
  4670. object.parent = this;
  4671. this.children.push( object );
  4672. object.dispatchEvent( _addedEvent );
  4673. } else {
  4674. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4675. }
  4676. return this;
  4677. }
  4678. remove( object ) {
  4679. if ( arguments.length > 1 ) {
  4680. for ( let i = 0; i < arguments.length; i ++ ) {
  4681. this.remove( arguments[ i ] );
  4682. }
  4683. return this;
  4684. }
  4685. const index = this.children.indexOf( object );
  4686. if ( index !== - 1 ) {
  4687. object.parent = null;
  4688. this.children.splice( index, 1 );
  4689. object.dispatchEvent( _removedEvent );
  4690. }
  4691. return this;
  4692. }
  4693. removeFromParent() {
  4694. const parent = this.parent;
  4695. if ( parent !== null ) {
  4696. parent.remove( this );
  4697. }
  4698. return this;
  4699. }
  4700. clear() {
  4701. for ( let i = 0; i < this.children.length; i ++ ) {
  4702. const object = this.children[ i ];
  4703. object.parent = null;
  4704. object.dispatchEvent( _removedEvent );
  4705. }
  4706. this.children.length = 0;
  4707. return this;
  4708. }
  4709. attach( object ) {
  4710. // adds object as a child of this, while maintaining the object's world transform
  4711. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4712. this.updateWorldMatrix( true, false );
  4713. _m1$1.copy( this.matrixWorld ).invert();
  4714. if ( object.parent !== null ) {
  4715. object.parent.updateWorldMatrix( true, false );
  4716. _m1$1.multiply( object.parent.matrixWorld );
  4717. }
  4718. object.applyMatrix4( _m1$1 );
  4719. this.add( object );
  4720. object.updateWorldMatrix( false, true );
  4721. return this;
  4722. }
  4723. getObjectById( id ) {
  4724. return this.getObjectByProperty( 'id', id );
  4725. }
  4726. getObjectByName( name ) {
  4727. return this.getObjectByProperty( 'name', name );
  4728. }
  4729. getObjectByProperty( name, value ) {
  4730. if ( this[ name ] === value ) return this;
  4731. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4732. const child = this.children[ i ];
  4733. const object = child.getObjectByProperty( name, value );
  4734. if ( object !== undefined ) {
  4735. return object;
  4736. }
  4737. }
  4738. return undefined;
  4739. }
  4740. getWorldPosition( target ) {
  4741. this.updateWorldMatrix( true, false );
  4742. return target.setFromMatrixPosition( this.matrixWorld );
  4743. }
  4744. getWorldQuaternion( target ) {
  4745. this.updateWorldMatrix( true, false );
  4746. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4747. return target;
  4748. }
  4749. getWorldScale( target ) {
  4750. this.updateWorldMatrix( true, false );
  4751. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4752. return target;
  4753. }
  4754. getWorldDirection( target ) {
  4755. this.updateWorldMatrix( true, false );
  4756. const e = this.matrixWorld.elements;
  4757. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4758. }
  4759. raycast( /* raycaster, intersects */ ) {}
  4760. traverse( callback ) {
  4761. callback( this );
  4762. const children = this.children;
  4763. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4764. children[ i ].traverse( callback );
  4765. }
  4766. }
  4767. traverseVisible( callback ) {
  4768. if ( this.visible === false ) return;
  4769. callback( this );
  4770. const children = this.children;
  4771. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4772. children[ i ].traverseVisible( callback );
  4773. }
  4774. }
  4775. traverseAncestors( callback ) {
  4776. const parent = this.parent;
  4777. if ( parent !== null ) {
  4778. callback( parent );
  4779. parent.traverseAncestors( callback );
  4780. }
  4781. }
  4782. updateMatrix() {
  4783. this.matrix.compose( this.position, this.quaternion, this.scale );
  4784. this.matrixWorldNeedsUpdate = true;
  4785. }
  4786. updateMatrixWorld( force ) {
  4787. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4788. if ( this.matrixWorldNeedsUpdate || force ) {
  4789. if ( this.parent === null ) {
  4790. this.matrixWorld.copy( this.matrix );
  4791. } else {
  4792. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4793. }
  4794. this.matrixWorldNeedsUpdate = false;
  4795. force = true;
  4796. }
  4797. // update children
  4798. const children = this.children;
  4799. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4800. const child = children[ i ];
  4801. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4802. child.updateMatrixWorld( force );
  4803. }
  4804. }
  4805. }
  4806. updateWorldMatrix( updateParents, updateChildren ) {
  4807. const parent = this.parent;
  4808. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4809. parent.updateWorldMatrix( true, false );
  4810. }
  4811. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4812. if ( this.parent === null ) {
  4813. this.matrixWorld.copy( this.matrix );
  4814. } else {
  4815. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4816. }
  4817. // update children
  4818. if ( updateChildren === true ) {
  4819. const children = this.children;
  4820. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4821. const child = children[ i ];
  4822. if ( child.matrixWorldAutoUpdate === true ) {
  4823. child.updateWorldMatrix( false, true );
  4824. }
  4825. }
  4826. }
  4827. }
  4828. // 导出时
  4829. toJSON( meta ) {
  4830. // meta is a string when called from JSON.stringify
  4831. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4832. const output = {};
  4833. // meta is a hash used to collect geometries, materials.
  4834. // not providing it implies that this is the root object
  4835. // being serialized.
  4836. if ( isRootObject ) {
  4837. // initialize meta obj
  4838. meta = {
  4839. geometries: {},
  4840. materials: {},
  4841. textures: {},
  4842. images: {},
  4843. shapes: {},
  4844. skeletons: {},
  4845. animations: {},
  4846. nodes: {}
  4847. };
  4848. output.metadata = {
  4849. version: 4.5,
  4850. type: 'Object',
  4851. generator: 'Object3D.toJSON'
  4852. };
  4853. }
  4854. // standard Object3D serialization
  4855. const object = {};
  4856. object.uuid = this.uuid;
  4857. object.type = this.type;
  4858. object.choice = this.choice;
  4859. object.play = this.play;
  4860. object.whole = this.whole;
  4861. object.scripts = this.scripts;
  4862. if ( this.name !== '' ) object.name = this.name;
  4863. if ( this.castShadow === true ) object.castShadow = true;
  4864. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4865. if ( this.visible === false ) object.visible = false;
  4866. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4867. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4868. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4869. object.layers = this.layers.mask;
  4870. object.matrix = this.matrix.toArray();
  4871. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4872. // object specific properties
  4873. if ( this.isInstancedMesh ) {
  4874. object.type = 'InstancedMesh';
  4875. object.count = this.count;
  4876. object.instanceMatrix = this.instanceMatrix.toJSON();
  4877. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4878. }
  4879. //
  4880. function serialize( library, element ) {
  4881. if ( library[ element.uuid ] === undefined ) {
  4882. library[ element.uuid ] = element.toJSON( meta );
  4883. }
  4884. return element.uuid;
  4885. }
  4886. if ( this.isScene ) {
  4887. if ( this.background ) {
  4888. var project_background = editor.config.getKey( 'project/background' )
  4889. // console.log("data.background 打包",project_background)
  4890. if(project_background === "Color" || project_background === "Texture" || project_background === "Equirect"){
  4891. if ( this.background.isColor ) {
  4892. object.background = this.background.toJSON();
  4893. } else if ( this.background.isTexture ) {
  4894. object.background = this.background.toJSON( meta ).uuid;
  4895. }
  4896. }else {
  4897. object.background = project_background
  4898. }
  4899. }
  4900. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4901. object.environment = this.environment.toJSON( meta ).uuid;
  4902. }
  4903. if(window.T_mode === "EditorProject"){
  4904. var project_sceneplane = editor.config.getKey( 'project/sceneplane' )
  4905. console.log("sceneplane:",project_sceneplane)
  4906. object.sceneplane = project_sceneplane
  4907. }
  4908. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4909. object.geometry = serialize( meta.geometries, this.geometry );
  4910. const parameters = this.geometry.parameters;
  4911. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4912. const shapes = parameters.shapes;
  4913. if ( Array.isArray( shapes ) ) {
  4914. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4915. const shape = shapes[ i ];
  4916. serialize( meta.shapes, shape );
  4917. }
  4918. } else {
  4919. serialize( meta.shapes, shapes );
  4920. }
  4921. }
  4922. }
  4923. if ( this.isSkinnedMesh ) {
  4924. object.bindMode = this.bindMode;
  4925. object.bindMatrix = this.bindMatrix.toArray();
  4926. if ( this.skeleton !== undefined ) {
  4927. serialize( meta.skeletons, this.skeleton );
  4928. object.skeleton = this.skeleton.uuid;
  4929. }
  4930. }
  4931. if ( this.material !== undefined ) {
  4932. if ( Array.isArray( this.material ) ) {
  4933. const uuids = [];
  4934. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4935. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4936. }
  4937. object.material = uuids;
  4938. } else {
  4939. object.material = serialize( meta.materials, this.material );
  4940. }
  4941. }
  4942. //
  4943. if ( this.children.length > 0 ) {
  4944. object.children = [];
  4945. for ( let i = 0; i < this.children.length; i ++ ) {
  4946. if(window.T_mode === "EditorProduct" & this.children[ i ].isAmbientLight){
  4947. // console.log("window.T_mode === \"EditorProduct\" & this.children[ i ].isAmbientLight 跳过!")
  4948. continue;
  4949. }
  4950. object.children.push( this.children[ i ].toJSON( meta ).object );
  4951. }
  4952. }
  4953. //
  4954. if ( this.animations.length > 0 ) {
  4955. object.animations = [];
  4956. for ( let i = 0; i < this.animations.length; i ++ ) {
  4957. const animation = this.animations[ i ];
  4958. object.animations.push( serialize( meta.animations, animation ) );
  4959. }
  4960. }
  4961. if ( isRootObject ) {
  4962. const geometries = extractFromCache( meta.geometries );
  4963. const materials = extractFromCache( meta.materials );
  4964. const textures = extractFromCache( meta.textures );
  4965. const images = extractFromCache( meta.images );
  4966. const shapes = extractFromCache( meta.shapes );
  4967. const skeletons = extractFromCache( meta.skeletons );
  4968. const animations = extractFromCache( meta.animations );
  4969. const nodes = extractFromCache( meta.nodes );
  4970. if ( geometries.length > 0 ) output.geometries = geometries;
  4971. if ( materials.length > 0 ) output.materials = materials;
  4972. if ( textures.length > 0 ) output.textures = textures;
  4973. if ( images.length > 0 ) output.images = images;
  4974. if ( shapes.length > 0 ) output.shapes = shapes;
  4975. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4976. if ( animations.length > 0 ) output.animations = animations;
  4977. if ( nodes.length > 0 ) output.nodes = nodes;
  4978. }
  4979. output.object = object;
  4980. return output;
  4981. // extract data from the cache hash
  4982. // remove metadata on each item
  4983. // and return as array
  4984. function extractFromCache( cache ) {
  4985. const values = [];
  4986. for ( const key in cache ) {
  4987. const data = cache[ key ];
  4988. delete data.metadata;
  4989. values.push( data );
  4990. }
  4991. return values;
  4992. }
  4993. }
  4994. clone( recursive ) {
  4995. return new this.constructor().copy( this, recursive );
  4996. }
  4997. copy( source, recursive = true ) {
  4998. this.name = source.name;
  4999. this.up.copy( source.up );
  5000. this.position.copy( source.position );
  5001. this.rotation.order = source.rotation.order;
  5002. this.quaternion.copy( source.quaternion );
  5003. this.scale.copy( source.scale );
  5004. this.matrix.copy( source.matrix );
  5005. this.matrixWorld.copy( source.matrixWorld );
  5006. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5007. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5008. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5009. this.layers.mask = source.layers.mask;
  5010. this.visible = source.visible;
  5011. this.choice = source.choice;
  5012. this.play = source.play;
  5013. this.whole = source.whole;
  5014. this.castShadow = source.castShadow;
  5015. this.receiveShadow = source.receiveShadow;
  5016. this.frustumCulled = source.frustumCulled;
  5017. this.renderOrder = source.renderOrder;
  5018. this.scripts = source.scripts;
  5019. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5020. if ( recursive === true ) {
  5021. for ( let i = 0; i < source.children.length; i ++ ) {
  5022. const child = source.children[ i ];
  5023. this.add( child.clone() );
  5024. }
  5025. }
  5026. if ( JSON.stringify( this.userData ) !== '{}' ) this.userData = source.userData;
  5027. return this;
  5028. }
  5029. }
  5030. Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5031. Object3D.DefaultMatrixAutoUpdate = true;
  5032. Object3D.DefaultMatrixWorldAutoUpdate = true;
  5033. const _v0$1 = /*@__PURE__*/ new Vector3();
  5034. const _v1$3 = /*@__PURE__*/ new Vector3();
  5035. const _v2$2 = /*@__PURE__*/ new Vector3();
  5036. const _v3$1 = /*@__PURE__*/ new Vector3();
  5037. const _vab = /*@__PURE__*/ new Vector3();
  5038. const _vac = /*@__PURE__*/ new Vector3();
  5039. const _vbc = /*@__PURE__*/ new Vector3();
  5040. const _vap = /*@__PURE__*/ new Vector3();
  5041. const _vbp = /*@__PURE__*/ new Vector3();
  5042. const _vcp = /*@__PURE__*/ new Vector3();
  5043. class Triangle {
  5044. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5045. this.a = a;
  5046. this.b = b;
  5047. this.c = c;
  5048. }
  5049. static getNormal( a, b, c, target ) {
  5050. target.subVectors( c, b );
  5051. _v0$1.subVectors( a, b );
  5052. target.cross( _v0$1 );
  5053. const targetLengthSq = target.lengthSq();
  5054. if ( targetLengthSq > 0 ) {
  5055. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5056. }
  5057. return target.set( 0, 0, 0 );
  5058. }
  5059. // static/instance method to calculate barycentric coordinates
  5060. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5061. static getBarycoord( point, a, b, c, target ) {
  5062. _v0$1.subVectors( c, a );
  5063. _v1$3.subVectors( b, a );
  5064. _v2$2.subVectors( point, a );
  5065. const dot00 = _v0$1.dot( _v0$1 );
  5066. const dot01 = _v0$1.dot( _v1$3 );
  5067. const dot02 = _v0$1.dot( _v2$2 );
  5068. const dot11 = _v1$3.dot( _v1$3 );
  5069. const dot12 = _v1$3.dot( _v2$2 );
  5070. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5071. // collinear or singular triangle
  5072. if ( denom === 0 ) {
  5073. // arbitrary location outside of triangle?
  5074. // not sure if this is the best idea, maybe should be returning undefined
  5075. return target.set( - 2, - 1, - 1 );
  5076. }
  5077. const invDenom = 1 / denom;
  5078. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5079. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5080. // barycentric coordinates must always sum to 1
  5081. return target.set( 1 - u - v, v, u );
  5082. }
  5083. static containsPoint( point, a, b, c ) {
  5084. this.getBarycoord( point, a, b, c, _v3$1 );
  5085. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5086. }
  5087. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5088. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5089. target.set( 0, 0 );
  5090. target.addScaledVector( uv1, _v3$1.x );
  5091. target.addScaledVector( uv2, _v3$1.y );
  5092. target.addScaledVector( uv3, _v3$1.z );
  5093. return target;
  5094. }
  5095. static isFrontFacing( a, b, c, direction ) {
  5096. _v0$1.subVectors( c, b );
  5097. _v1$3.subVectors( a, b );
  5098. // strictly front facing
  5099. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5100. }
  5101. set( a, b, c ) {
  5102. this.a.copy( a );
  5103. this.b.copy( b );
  5104. this.c.copy( c );
  5105. return this;
  5106. }
  5107. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5108. this.a.copy( points[ i0 ] );
  5109. this.b.copy( points[ i1 ] );
  5110. this.c.copy( points[ i2 ] );
  5111. return this;
  5112. }
  5113. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5114. this.a.fromBufferAttribute( attribute, i0 );
  5115. this.b.fromBufferAttribute( attribute, i1 );
  5116. this.c.fromBufferAttribute( attribute, i2 );
  5117. return this;
  5118. }
  5119. clone() {
  5120. return new this.constructor().copy( this );
  5121. }
  5122. copy( triangle ) {
  5123. this.a.copy( triangle.a );
  5124. this.b.copy( triangle.b );
  5125. this.c.copy( triangle.c );
  5126. return this;
  5127. }
  5128. getArea() {
  5129. _v0$1.subVectors( this.c, this.b );
  5130. _v1$3.subVectors( this.a, this.b );
  5131. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5132. }
  5133. getMidpoint( target ) {
  5134. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5135. }
  5136. getNormal( target ) {
  5137. return Triangle.getNormal( this.a, this.b, this.c, target );
  5138. }
  5139. getPlane( target ) {
  5140. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5141. }
  5142. getBarycoord( point, target ) {
  5143. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5144. }
  5145. getUV( point, uv1, uv2, uv3, target ) {
  5146. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5147. }
  5148. containsPoint( point ) {
  5149. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5150. }
  5151. isFrontFacing( direction ) {
  5152. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5153. }
  5154. intersectsBox( box ) {
  5155. return box.intersectsTriangle( this );
  5156. }
  5157. closestPointToPoint( p, target ) {
  5158. const a = this.a, b = this.b, c = this.c;
  5159. let v, w;
  5160. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5161. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5162. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5163. // basically, we're distinguishing which of the voronoi regions of the triangle
  5164. // the point lies in with the minimum amount of redundant computation.
  5165. _vab.subVectors( b, a );
  5166. _vac.subVectors( c, a );
  5167. _vap.subVectors( p, a );
  5168. const d1 = _vab.dot( _vap );
  5169. const d2 = _vac.dot( _vap );
  5170. if ( d1 <= 0 && d2 <= 0 ) {
  5171. // vertex region of A; barycentric coords (1, 0, 0)
  5172. return target.copy( a );
  5173. }
  5174. _vbp.subVectors( p, b );
  5175. const d3 = _vab.dot( _vbp );
  5176. const d4 = _vac.dot( _vbp );
  5177. if ( d3 >= 0 && d4 <= d3 ) {
  5178. // vertex region of B; barycentric coords (0, 1, 0)
  5179. return target.copy( b );
  5180. }
  5181. const vc = d1 * d4 - d3 * d2;
  5182. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5183. v = d1 / ( d1 - d3 );
  5184. // edge region of AB; barycentric coords (1-v, v, 0)
  5185. return target.copy( a ).addScaledVector( _vab, v );
  5186. }
  5187. _vcp.subVectors( p, c );
  5188. const d5 = _vab.dot( _vcp );
  5189. const d6 = _vac.dot( _vcp );
  5190. if ( d6 >= 0 && d5 <= d6 ) {
  5191. // vertex region of C; barycentric coords (0, 0, 1)
  5192. return target.copy( c );
  5193. }
  5194. const vb = d5 * d2 - d1 * d6;
  5195. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5196. w = d2 / ( d2 - d6 );
  5197. // edge region of AC; barycentric coords (1-w, 0, w)
  5198. return target.copy( a ).addScaledVector( _vac, w );
  5199. }
  5200. const va = d3 * d6 - d5 * d4;
  5201. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5202. _vbc.subVectors( c, b );
  5203. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5204. // edge region of BC; barycentric coords (0, 1-w, w)
  5205. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5206. }
  5207. // face region
  5208. const denom = 1 / ( va + vb + vc );
  5209. // u = va * denom
  5210. v = vb * denom;
  5211. w = vc * denom;
  5212. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5213. }
  5214. equals( triangle ) {
  5215. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5216. }
  5217. }
  5218. let materialId = 0;
  5219. class Material extends EventDispatcher {
  5220. constructor() {
  5221. super();
  5222. this.isMaterial = true;
  5223. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5224. this.uuid = generateUUID();
  5225. this.name = '';
  5226. this.type = 'Material';
  5227. this.blending = NormalBlending;
  5228. this.side = FrontSide;
  5229. this.vertexColors = false;
  5230. this.opacity = 1;
  5231. this.transparent = false;
  5232. this.blendSrc = SrcAlphaFactor;
  5233. this.blendDst = OneMinusSrcAlphaFactor;
  5234. this.blendEquation = AddEquation;
  5235. this.blendSrcAlpha = null;
  5236. this.blendDstAlpha = null;
  5237. this.blendEquationAlpha = null;
  5238. this.depthFunc = LessEqualDepth;
  5239. this.depthTest = true;
  5240. this.depthWrite = true;
  5241. this.stencilWriteMask = 0xff;
  5242. this.stencilFunc = AlwaysStencilFunc;
  5243. this.stencilRef = 0;
  5244. this.stencilFuncMask = 0xff;
  5245. this.stencilFail = KeepStencilOp;
  5246. this.stencilZFail = KeepStencilOp;
  5247. this.stencilZPass = KeepStencilOp;
  5248. this.stencilWrite = false;
  5249. this.clippingPlanes = null;
  5250. this.clipIntersection = false;
  5251. this.clipShadows = false;
  5252. this.shadowSide = null;
  5253. this.colorWrite = true;
  5254. this.precision = null; // override the renderer's default precision for this material
  5255. this.polygonOffset = false;
  5256. this.polygonOffsetFactor = 0;
  5257. this.polygonOffsetUnits = 0;
  5258. this.dithering = false;
  5259. this.alphaToCoverage = false;
  5260. this.premultipliedAlpha = false;
  5261. this.visible = true;
  5262. this.toneMapped = true;
  5263. this.userData = {};
  5264. this.version = 0;
  5265. this._alphaTest = 0;
  5266. }
  5267. get alphaTest() {
  5268. return this._alphaTest;
  5269. }
  5270. set alphaTest( value ) {
  5271. if ( this._alphaTest > 0 !== value > 0 ) {
  5272. this.version ++;
  5273. }
  5274. this._alphaTest = value;
  5275. }
  5276. onBuild( /* shaderobject, renderer */ ) {}
  5277. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5278. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5279. customProgramCacheKey() {
  5280. return this.onBeforeCompile.toString();
  5281. }
  5282. setValues( values ) {
  5283. if ( values === undefined ) return;
  5284. for ( const key in values ) {
  5285. const newValue = values[ key ];
  5286. if ( newValue === undefined ) {
  5287. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5288. continue;
  5289. }
  5290. const currentValue = this[ key ];
  5291. if ( currentValue === undefined ) {
  5292. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5293. continue;
  5294. }
  5295. if ( currentValue && currentValue.isColor ) {
  5296. currentValue.set( newValue );
  5297. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5298. currentValue.copy( newValue );
  5299. } else {
  5300. this[ key ] = newValue;
  5301. }
  5302. }
  5303. }
  5304. toJSON( meta ) {
  5305. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5306. if ( isRootObject ) {
  5307. meta = {
  5308. textures: {},
  5309. images: {}
  5310. };
  5311. }
  5312. const data = {
  5313. metadata: {
  5314. version: 4.5,
  5315. type: 'Material',
  5316. generator: 'Material.toJSON'
  5317. }
  5318. };
  5319. // standard Material serialization
  5320. data.uuid = this.uuid;
  5321. data.type = this.type;
  5322. if ( this.name !== '' ) data.name = this.name;
  5323. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5324. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5325. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5326. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5327. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5328. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5329. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5330. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5331. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5332. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5333. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5334. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5335. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5336. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5337. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5338. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5339. }
  5340. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5341. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5342. }
  5343. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5344. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5345. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5346. }
  5347. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5348. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5349. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5350. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5351. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5352. }
  5353. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5354. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5355. }
  5356. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5357. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5358. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5359. if ( this.lightMap && this.lightMap.isTexture ) {
  5360. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5361. data.lightMapIntensity = this.lightMapIntensity;
  5362. }
  5363. if ( this.aoMap && this.aoMap.isTexture ) {
  5364. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5365. data.aoMapIntensity = this.aoMapIntensity;
  5366. }
  5367. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5368. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5369. data.bumpScale = this.bumpScale;
  5370. }
  5371. if ( this.normalMap && this.normalMap.isTexture ) {
  5372. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5373. data.normalMapType = this.normalMapType;
  5374. data.normalScale = this.normalScale.toArray();
  5375. }
  5376. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5377. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5378. data.displacementScale = this.displacementScale;
  5379. data.displacementBias = this.displacementBias;
  5380. }
  5381. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5382. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5383. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5384. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5385. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5386. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5387. if ( this.envMap && this.envMap.isTexture ) {
  5388. data.envMap = this.envMap.toJSON( meta ).uuid;
  5389. if ( this.combine !== undefined ) data.combine = this.combine;
  5390. }
  5391. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5392. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5393. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5394. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5395. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5396. }
  5397. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5398. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5399. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5400. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5401. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  5402. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5403. if ( this.size !== undefined ) data.size = this.size;
  5404. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5405. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5406. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5407. if ( this.side !== FrontSide ) data.side = this.side;
  5408. if ( this.vertexColors ) data.vertexColors = true;
  5409. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5410. if ( this.transparent === true ) data.transparent = this.transparent;
  5411. data.depthFunc = this.depthFunc;
  5412. data.depthTest = this.depthTest;
  5413. data.depthWrite = this.depthWrite;
  5414. data.colorWrite = this.colorWrite;
  5415. data.stencilWrite = this.stencilWrite;
  5416. data.stencilWriteMask = this.stencilWriteMask;
  5417. data.stencilFunc = this.stencilFunc;
  5418. data.stencilRef = this.stencilRef;
  5419. data.stencilFuncMask = this.stencilFuncMask;
  5420. data.stencilFail = this.stencilFail;
  5421. data.stencilZFail = this.stencilZFail;
  5422. data.stencilZPass = this.stencilZPass;
  5423. // rotation (SpriteMaterial)
  5424. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5425. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5426. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5427. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5428. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5429. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5430. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5431. if ( this.scale !== undefined ) data.scale = this.scale;
  5432. if ( this.dithering === true ) data.dithering = true;
  5433. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5434. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5435. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5436. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5437. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5438. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5439. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5440. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5441. if ( this.visible === false ) data.visible = false;
  5442. if ( this.toneMapped === false ) data.toneMapped = false;
  5443. if ( this.fog === false ) data.fog = false;
  5444. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5445. // TODO: Copied from Object3D.toJSON
  5446. function extractFromCache( cache ) {
  5447. const values = [];
  5448. for ( const key in cache ) {
  5449. const data = cache[ key ];
  5450. delete data.metadata;
  5451. values.push( data );
  5452. }
  5453. return values;
  5454. }
  5455. if ( isRootObject ) {
  5456. const textures = extractFromCache( meta.textures );
  5457. const images = extractFromCache( meta.images );
  5458. if ( textures.length > 0 ) data.textures = textures;
  5459. if ( images.length > 0 ) data.images = images;
  5460. }
  5461. return data;
  5462. }
  5463. clone() {
  5464. return new this.constructor().copy( this );
  5465. }
  5466. copy( source ) {
  5467. this.name = source.name;
  5468. this.blending = source.blending;
  5469. this.side = source.side;
  5470. this.vertexColors = source.vertexColors;
  5471. this.opacity = source.opacity;
  5472. this.transparent = source.transparent;
  5473. this.blendSrc = source.blendSrc;
  5474. this.blendDst = source.blendDst;
  5475. this.blendEquation = source.blendEquation;
  5476. this.blendSrcAlpha = source.blendSrcAlpha;
  5477. this.blendDstAlpha = source.blendDstAlpha;
  5478. this.blendEquationAlpha = source.blendEquationAlpha;
  5479. this.depthFunc = source.depthFunc;
  5480. this.depthTest = source.depthTest;
  5481. this.depthWrite = source.depthWrite;
  5482. this.stencilWriteMask = source.stencilWriteMask;
  5483. this.stencilFunc = source.stencilFunc;
  5484. this.stencilRef = source.stencilRef;
  5485. this.stencilFuncMask = source.stencilFuncMask;
  5486. this.stencilFail = source.stencilFail;
  5487. this.stencilZFail = source.stencilZFail;
  5488. this.stencilZPass = source.stencilZPass;
  5489. this.stencilWrite = source.stencilWrite;
  5490. const srcPlanes = source.clippingPlanes;
  5491. let dstPlanes = null;
  5492. if ( srcPlanes !== null ) {
  5493. const n = srcPlanes.length;
  5494. dstPlanes = new Array( n );
  5495. for ( let i = 0; i !== n; ++ i ) {
  5496. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5497. }
  5498. }
  5499. this.clippingPlanes = dstPlanes;
  5500. this.clipIntersection = source.clipIntersection;
  5501. this.clipShadows = source.clipShadows;
  5502. this.shadowSide = source.shadowSide;
  5503. this.colorWrite = source.colorWrite;
  5504. this.precision = source.precision;
  5505. this.polygonOffset = source.polygonOffset;
  5506. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5507. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5508. this.dithering = source.dithering;
  5509. this.alphaTest = source.alphaTest;
  5510. this.alphaToCoverage = source.alphaToCoverage;
  5511. this.premultipliedAlpha = source.premultipliedAlpha;
  5512. this.visible = source.visible;
  5513. this.toneMapped = source.toneMapped;
  5514. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5515. return this;
  5516. }
  5517. dispose() {
  5518. this.dispatchEvent( { type: 'dispose' } );
  5519. }
  5520. set needsUpdate( value ) {
  5521. if ( value === true ) this.version ++;
  5522. }
  5523. }
  5524. class MeshBasicMaterial extends Material {
  5525. constructor( parameters ) {
  5526. super();
  5527. this.isMeshBasicMaterial = true;
  5528. this.type = 'MeshBasicMaterial';
  5529. this.color = new Color( 0xffffff ); // emissive
  5530. this.map = null;
  5531. this.lightMap = null;
  5532. this.lightMapIntensity = 1.0;
  5533. this.aoMap = null;
  5534. this.aoMapIntensity = 1.0;
  5535. this.specularMap = null;
  5536. this.alphaMap = null;
  5537. this.envMap = null;
  5538. this.combine = MultiplyOperation;
  5539. this.reflectivity = 1;
  5540. this.refractionRatio = 0.98;
  5541. this.wireframe = false;
  5542. this.wireframeLinewidth = 1;
  5543. this.wireframeLinecap = 'round';
  5544. this.wireframeLinejoin = 'round';
  5545. this.fog = true;
  5546. this.setValues( parameters );
  5547. }
  5548. copy( source ) {
  5549. super.copy( source );
  5550. this.color.copy( source.color );
  5551. this.map = source.map;
  5552. this.lightMap = source.lightMap;
  5553. this.lightMapIntensity = source.lightMapIntensity;
  5554. this.aoMap = source.aoMap;
  5555. this.aoMapIntensity = source.aoMapIntensity;
  5556. this.specularMap = source.specularMap;
  5557. this.alphaMap = source.alphaMap;
  5558. this.envMap = source.envMap;
  5559. this.combine = source.combine;
  5560. this.reflectivity = source.reflectivity;
  5561. this.refractionRatio = source.refractionRatio;
  5562. this.wireframe = source.wireframe;
  5563. this.wireframeLinewidth = source.wireframeLinewidth;
  5564. this.wireframeLinecap = source.wireframeLinecap;
  5565. this.wireframeLinejoin = source.wireframeLinejoin;
  5566. this.fog = source.fog;
  5567. return this;
  5568. }
  5569. }
  5570. const _vector$9 = /*@__PURE__*/ new Vector3();
  5571. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5572. class BufferAttribute {
  5573. constructor( array, itemSize, normalized ) {
  5574. if ( Array.isArray( array ) ) {
  5575. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5576. }
  5577. this.isBufferAttribute = true;
  5578. this.name = '';
  5579. this.array = array;
  5580. this.itemSize = itemSize;
  5581. this.count = array !== undefined ? array.length / itemSize : 0;
  5582. this.normalized = normalized === true;
  5583. this.usage = StaticDrawUsage;
  5584. this.updateRange = { offset: 0, count: - 1 };
  5585. this.version = 0;
  5586. }
  5587. onUploadCallback() {}
  5588. set needsUpdate( value ) {
  5589. if ( value === true ) this.version ++;
  5590. }
  5591. setUsage( value ) {
  5592. this.usage = value;
  5593. return this;
  5594. }
  5595. copy( source ) {
  5596. this.name = source.name;
  5597. this.array = new source.array.constructor( source.array );
  5598. this.itemSize = source.itemSize;
  5599. this.count = source.count;
  5600. this.normalized = source.normalized;
  5601. this.usage = source.usage;
  5602. return this;
  5603. }
  5604. copyAt( index1, attribute, index2 ) {
  5605. index1 *= this.itemSize;
  5606. index2 *= attribute.itemSize;
  5607. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5608. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5609. }
  5610. return this;
  5611. }
  5612. copyArray( array ) {
  5613. this.array.set( array );
  5614. return this;
  5615. }
  5616. copyColorsArray( colors ) {
  5617. const array = this.array;
  5618. let offset = 0;
  5619. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5620. let color = colors[ i ];
  5621. if ( color === undefined ) {
  5622. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5623. color = new Color();
  5624. }
  5625. if ( this.normalized ) {
  5626. array[ offset ++ ] = normalize( color.r, array );
  5627. array[ offset ++ ] = normalize( color.g, array );
  5628. array[ offset ++ ] = normalize( color.b, array );
  5629. } else {
  5630. array[ offset ++ ] = color.r;
  5631. array[ offset ++ ] = color.g;
  5632. array[ offset ++ ] = color.b;
  5633. }
  5634. }
  5635. return this;
  5636. }
  5637. copyVector2sArray( vectors ) {
  5638. const array = this.array;
  5639. let offset = 0;
  5640. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5641. let vector = vectors[ i ];
  5642. if ( vector === undefined ) {
  5643. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5644. vector = new Vector2();
  5645. }
  5646. if ( this.normalized ) {
  5647. array[ offset ++ ] = normalize( vector.x, array );
  5648. array[ offset ++ ] = normalize( vector.y, array );
  5649. } else {
  5650. array[ offset ++ ] = vector.x;
  5651. array[ offset ++ ] = vector.y;
  5652. }
  5653. }
  5654. return this;
  5655. }
  5656. copyVector3sArray( vectors ) {
  5657. const array = this.array;
  5658. let offset = 0;
  5659. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5660. let vector = vectors[ i ];
  5661. if ( vector === undefined ) {
  5662. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5663. vector = new Vector3();
  5664. }
  5665. if ( this.normalized ) {
  5666. array[ offset ++ ] = normalize( vector.x, array );
  5667. array[ offset ++ ] = normalize( vector.y, array );
  5668. array[ offset ++ ] = normalize( vector.z, array );
  5669. } else {
  5670. array[ offset ++ ] = vector.x;
  5671. array[ offset ++ ] = vector.y;
  5672. array[ offset ++ ] = vector.z;
  5673. }
  5674. }
  5675. return this;
  5676. }
  5677. copyVector4sArray( vectors ) {
  5678. const array = this.array;
  5679. let offset = 0;
  5680. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5681. let vector = vectors[ i ];
  5682. if ( vector === undefined ) {
  5683. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5684. vector = new Vector4();
  5685. }
  5686. if ( this.normalized ) {
  5687. array[ offset ++ ] = normalize( vector.x, array );
  5688. array[ offset ++ ] = normalize( vector.y, array );
  5689. array[ offset ++ ] = normalize( vector.z, array );
  5690. array[ offset ++ ] = normalize( vector.w, array );
  5691. } else {
  5692. array[ offset ++ ] = vector.x;
  5693. array[ offset ++ ] = vector.y;
  5694. array[ offset ++ ] = vector.z;
  5695. array[ offset ++ ] = vector.w;
  5696. }
  5697. }
  5698. return this;
  5699. }
  5700. applyMatrix3( m ) {
  5701. if ( this.itemSize === 2 ) {
  5702. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5703. _vector2$1.fromBufferAttribute( this, i );
  5704. _vector2$1.applyMatrix3( m );
  5705. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5706. }
  5707. } else if ( this.itemSize === 3 ) {
  5708. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5709. _vector$9.fromBufferAttribute( this, i );
  5710. _vector$9.applyMatrix3( m );
  5711. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5712. }
  5713. }
  5714. return this;
  5715. }
  5716. applyMatrix4( m ) {
  5717. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5718. _vector$9.fromBufferAttribute( this, i );
  5719. _vector$9.applyMatrix4( m );
  5720. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5721. }
  5722. return this;
  5723. }
  5724. applyNormalMatrix( m ) {
  5725. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5726. _vector$9.fromBufferAttribute( this, i );
  5727. _vector$9.applyNormalMatrix( m );
  5728. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5729. }
  5730. return this;
  5731. }
  5732. transformDirection( m ) {
  5733. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5734. _vector$9.fromBufferAttribute( this, i );
  5735. _vector$9.transformDirection( m );
  5736. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5737. }
  5738. return this;
  5739. }
  5740. set( value, offset = 0 ) {
  5741. // Matching BufferAttribute constructor, do not normalize the array.
  5742. this.array.set( value, offset );
  5743. return this;
  5744. }
  5745. getX( index ) {
  5746. let x = this.array[ index * this.itemSize ];
  5747. if ( this.normalized ) x = denormalize( x, this.array );
  5748. return x;
  5749. }
  5750. setX( index, x ) {
  5751. if ( this.normalized ) x = normalize( x, this.array );
  5752. this.array[ index * this.itemSize ] = x;
  5753. return this;
  5754. }
  5755. getY( index ) {
  5756. let y = this.array[ index * this.itemSize + 1 ];
  5757. if ( this.normalized ) y = denormalize( y, this.array );
  5758. return y;
  5759. }
  5760. setY( index, y ) {
  5761. if ( this.normalized ) y = normalize( y, this.array );
  5762. this.array[ index * this.itemSize + 1 ] = y;
  5763. return this;
  5764. }
  5765. getZ( index ) {
  5766. let z = this.array[ index * this.itemSize + 2 ];
  5767. if ( this.normalized ) z = denormalize( z, this.array );
  5768. return z;
  5769. }
  5770. setZ( index, z ) {
  5771. if ( this.normalized ) z = normalize( z, this.array );
  5772. this.array[ index * this.itemSize + 2 ] = z;
  5773. return this;
  5774. }
  5775. getW( index ) {
  5776. let w = this.array[ index * this.itemSize + 3 ];
  5777. if ( this.normalized ) w = denormalize( w, this.array );
  5778. return w;
  5779. }
  5780. setW( index, w ) {
  5781. if ( this.normalized ) w = normalize( w, this.array );
  5782. this.array[ index * this.itemSize + 3 ] = w;
  5783. return this;
  5784. }
  5785. setXY( index, x, y ) {
  5786. index *= this.itemSize;
  5787. if ( this.normalized ) {
  5788. x = normalize( x, this.array );
  5789. y = normalize( y, this.array );
  5790. }
  5791. this.array[ index + 0 ] = x;
  5792. this.array[ index + 1 ] = y;
  5793. return this;
  5794. }
  5795. setXYZ( index, x, y, z ) {
  5796. index *= this.itemSize;
  5797. if ( this.normalized ) {
  5798. x = normalize( x, this.array );
  5799. y = normalize( y, this.array );
  5800. z = normalize( z, this.array );
  5801. }
  5802. this.array[ index + 0 ] = x;
  5803. this.array[ index + 1 ] = y;
  5804. this.array[ index + 2 ] = z;
  5805. return this;
  5806. }
  5807. setXYZW( index, x, y, z, w ) {
  5808. index *= this.itemSize;
  5809. if ( this.normalized ) {
  5810. x = normalize( x, this.array );
  5811. y = normalize( y, this.array );
  5812. z = normalize( z, this.array );
  5813. w = normalize( w, this.array );
  5814. }
  5815. this.array[ index + 0 ] = x;
  5816. this.array[ index + 1 ] = y;
  5817. this.array[ index + 2 ] = z;
  5818. this.array[ index + 3 ] = w;
  5819. return this;
  5820. }
  5821. onUpload( callback ) {
  5822. this.onUploadCallback = callback;
  5823. return this;
  5824. }
  5825. clone() {
  5826. return new this.constructor( this.array, this.itemSize ).copy( this );
  5827. }
  5828. toJSON() {
  5829. const data = {
  5830. itemSize: this.itemSize,
  5831. type: this.array.constructor.name,
  5832. array: Array.from( this.array ),
  5833. normalized: this.normalized
  5834. };
  5835. if ( this.name !== '' ) data.name = this.name;
  5836. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5837. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5838. return data;
  5839. }
  5840. }
  5841. //
  5842. class Int8BufferAttribute extends BufferAttribute {
  5843. constructor( array, itemSize, normalized ) {
  5844. super( new Int8Array( array ), itemSize, normalized );
  5845. }
  5846. }
  5847. class Uint8BufferAttribute extends BufferAttribute {
  5848. constructor( array, itemSize, normalized ) {
  5849. super( new Uint8Array( array ), itemSize, normalized );
  5850. }
  5851. }
  5852. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5853. constructor( array, itemSize, normalized ) {
  5854. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5855. }
  5856. }
  5857. class Int16BufferAttribute extends BufferAttribute {
  5858. constructor( array, itemSize, normalized ) {
  5859. super( new Int16Array( array ), itemSize, normalized );
  5860. }
  5861. }
  5862. class Uint16BufferAttribute extends BufferAttribute {
  5863. constructor( array, itemSize, normalized ) {
  5864. super( new Uint16Array( array ), itemSize, normalized );
  5865. }
  5866. }
  5867. class Int32BufferAttribute extends BufferAttribute {
  5868. constructor( array, itemSize, normalized ) {
  5869. super( new Int32Array( array ), itemSize, normalized );
  5870. }
  5871. }
  5872. class Uint32BufferAttribute extends BufferAttribute {
  5873. constructor( array, itemSize, normalized ) {
  5874. super( new Uint32Array( array ), itemSize, normalized );
  5875. }
  5876. }
  5877. class Float16BufferAttribute extends BufferAttribute {
  5878. constructor( array, itemSize, normalized ) {
  5879. super( new Uint16Array( array ), itemSize, normalized );
  5880. this.isFloat16BufferAttribute = true;
  5881. }
  5882. }
  5883. class Float32BufferAttribute extends BufferAttribute {
  5884. constructor( array, itemSize, normalized ) {
  5885. super( new Float32Array( array ), itemSize, normalized );
  5886. }
  5887. }
  5888. class Float64BufferAttribute extends BufferAttribute {
  5889. constructor( array, itemSize, normalized ) {
  5890. super( new Float64Array( array ), itemSize, normalized );
  5891. }
  5892. }
  5893. let _id$1 = 0;
  5894. const _m1 = /*@__PURE__*/ new Matrix4();
  5895. const _obj = /*@__PURE__*/ new Object3D();
  5896. const _offset = /*@__PURE__*/ new Vector3();
  5897. const _box$1 = /*@__PURE__*/ new Box3();
  5898. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5899. const _vector$8 = /*@__PURE__*/ new Vector3();
  5900. class BufferGeometry extends EventDispatcher {
  5901. constructor() {
  5902. super();
  5903. this.isBufferGeometry = true;
  5904. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5905. this.uuid = generateUUID();
  5906. this.name = '';
  5907. this.type = 'BufferGeometry';
  5908. this.index = null;
  5909. this.attributes = {};
  5910. this.morphAttributes = {};
  5911. this.morphTargetsRelative = false;
  5912. this.groups = [];
  5913. this.boundingBox = null;
  5914. this.boundingSphere = null;
  5915. this.drawRange = { start: 0, count: Infinity };
  5916. this.userData = {};
  5917. }
  5918. getIndex() {
  5919. return this.index;
  5920. }
  5921. setIndex( index ) {
  5922. if ( Array.isArray( index ) ) {
  5923. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5924. } else {
  5925. this.index = index;
  5926. }
  5927. return this;
  5928. }
  5929. getAttribute( name ) {
  5930. return this.attributes[ name ];
  5931. }
  5932. setAttribute( name, attribute ) {
  5933. this.attributes[ name ] = attribute;
  5934. return this;
  5935. }
  5936. deleteAttribute( name ) {
  5937. delete this.attributes[ name ];
  5938. return this;
  5939. }
  5940. hasAttribute( name ) {
  5941. return this.attributes[ name ] !== undefined;
  5942. }
  5943. addGroup( start, count, materialIndex = 0 ) {
  5944. this.groups.push( {
  5945. start: start,
  5946. count: count,
  5947. materialIndex: materialIndex
  5948. } );
  5949. }
  5950. clearGroups() {
  5951. this.groups = [];
  5952. }
  5953. setDrawRange( start, count ) {
  5954. this.drawRange.start = start;
  5955. this.drawRange.count = count;
  5956. }
  5957. applyMatrix4( matrix ) {
  5958. const position = this.attributes.position;
  5959. if ( position !== undefined ) {
  5960. position.applyMatrix4( matrix );
  5961. position.needsUpdate = true;
  5962. }
  5963. const normal = this.attributes.normal;
  5964. if ( normal !== undefined ) {
  5965. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5966. normal.applyNormalMatrix( normalMatrix );
  5967. normal.needsUpdate = true;
  5968. }
  5969. const tangent = this.attributes.tangent;
  5970. if ( tangent !== undefined ) {
  5971. tangent.transformDirection( matrix );
  5972. tangent.needsUpdate = true;
  5973. }
  5974. if ( this.boundingBox !== null ) {
  5975. this.computeBoundingBox();
  5976. }
  5977. if ( this.boundingSphere !== null ) {
  5978. this.computeBoundingSphere();
  5979. }
  5980. return this;
  5981. }
  5982. applyQuaternion( q ) {
  5983. _m1.makeRotationFromQuaternion( q );
  5984. this.applyMatrix4( _m1 );
  5985. return this;
  5986. }
  5987. rotateX( angle ) {
  5988. // rotate geometry around world x-axis
  5989. _m1.makeRotationX( angle );
  5990. this.applyMatrix4( _m1 );
  5991. return this;
  5992. }
  5993. rotateY( angle ) {
  5994. // rotate geometry around world y-axis
  5995. _m1.makeRotationY( angle );
  5996. this.applyMatrix4( _m1 );
  5997. return this;
  5998. }
  5999. rotateZ( angle ) {
  6000. // rotate geometry around world z-axis
  6001. _m1.makeRotationZ( angle );
  6002. this.applyMatrix4( _m1 );
  6003. return this;
  6004. }
  6005. translate( x, y, z ) {
  6006. // translate geometry
  6007. _m1.makeTranslation( x, y, z );
  6008. this.applyMatrix4( _m1 );
  6009. return this;
  6010. }
  6011. scale( x, y, z ) {
  6012. // scale geometry
  6013. _m1.makeScale( x, y, z );
  6014. this.applyMatrix4( _m1 );
  6015. return this;
  6016. }
  6017. lookAt( vector ) {
  6018. _obj.lookAt( vector );
  6019. _obj.updateMatrix();
  6020. this.applyMatrix4( _obj.matrix );
  6021. return this;
  6022. }
  6023. center() {
  6024. this.computeBoundingBox();
  6025. this.boundingBox.getCenter( _offset ).negate();
  6026. this.translate( _offset.x, _offset.y, _offset.z );
  6027. return this;
  6028. }
  6029. setFromPoints( points ) {
  6030. const position = [];
  6031. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6032. const point = points[ i ];
  6033. position.push( point.x, point.y, point.z || 0 );
  6034. }
  6035. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6036. return this;
  6037. }
  6038. computeBoundingBox() {
  6039. if ( this.boundingBox === null ) {
  6040. this.boundingBox = new Box3();
  6041. }
  6042. const position = this.attributes.position;
  6043. const morphAttributesPosition = this.morphAttributes.position;
  6044. if ( position && position.isGLBufferAttribute ) {
  6045. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6046. this.boundingBox.set(
  6047. new Vector3( - Infinity, - Infinity, - Infinity ),
  6048. new Vector3( + Infinity, + Infinity, + Infinity )
  6049. );
  6050. return;
  6051. }
  6052. if ( position !== undefined ) {
  6053. this.boundingBox.setFromBufferAttribute( position );
  6054. // process morph attributes if present
  6055. if ( morphAttributesPosition ) {
  6056. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6057. const morphAttribute = morphAttributesPosition[ i ];
  6058. _box$1.setFromBufferAttribute( morphAttribute );
  6059. if ( this.morphTargetsRelative ) {
  6060. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  6061. this.boundingBox.expandByPoint( _vector$8 );
  6062. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6063. this.boundingBox.expandByPoint( _vector$8 );
  6064. } else {
  6065. this.boundingBox.expandByPoint( _box$1.min );
  6066. this.boundingBox.expandByPoint( _box$1.max );
  6067. }
  6068. }
  6069. }
  6070. } else {
  6071. this.boundingBox.makeEmpty();
  6072. }
  6073. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6074. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6075. }
  6076. }
  6077. computeBoundingSphere() {
  6078. if ( this.boundingSphere === null ) {
  6079. this.boundingSphere = new Sphere();
  6080. }
  6081. const position = this.attributes.position;
  6082. const morphAttributesPosition = this.morphAttributes.position;
  6083. if ( position && position.isGLBufferAttribute ) {
  6084. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6085. this.boundingSphere.set( new Vector3(), Infinity );
  6086. return;
  6087. }
  6088. if ( position ) {
  6089. // first, find the center of the bounding sphere
  6090. const center = this.boundingSphere.center;
  6091. _box$1.setFromBufferAttribute( position );
  6092. // process morph attributes if present
  6093. if ( morphAttributesPosition ) {
  6094. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6095. const morphAttribute = morphAttributesPosition[ i ];
  6096. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6097. if ( this.morphTargetsRelative ) {
  6098. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6099. _box$1.expandByPoint( _vector$8 );
  6100. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6101. _box$1.expandByPoint( _vector$8 );
  6102. } else {
  6103. _box$1.expandByPoint( _boxMorphTargets.min );
  6104. _box$1.expandByPoint( _boxMorphTargets.max );
  6105. }
  6106. }
  6107. }
  6108. _box$1.getCenter( center );
  6109. // second, try to find a boundingSphere with a radius smaller than the
  6110. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6111. let maxRadiusSq = 0;
  6112. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6113. _vector$8.fromBufferAttribute( position, i );
  6114. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6115. }
  6116. // process morph attributes if present
  6117. if ( morphAttributesPosition ) {
  6118. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6119. const morphAttribute = morphAttributesPosition[ i ];
  6120. const morphTargetsRelative = this.morphTargetsRelative;
  6121. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6122. _vector$8.fromBufferAttribute( morphAttribute, j );
  6123. if ( morphTargetsRelative ) {
  6124. _offset.fromBufferAttribute( position, j );
  6125. _vector$8.add( _offset );
  6126. }
  6127. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6128. }
  6129. }
  6130. }
  6131. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6132. if ( isNaN( this.boundingSphere.radius ) ) {
  6133. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6134. }
  6135. }
  6136. }
  6137. computeTangents() {
  6138. const index = this.index;
  6139. const attributes = this.attributes;
  6140. // based on http://www.terathon.com/code/tangent.html
  6141. // (per vertex tangents)
  6142. if ( index === null ||
  6143. attributes.position === undefined ||
  6144. attributes.normal === undefined ||
  6145. attributes.uv === undefined ) {
  6146. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6147. return;
  6148. }
  6149. const indices = index.array;
  6150. const positions = attributes.position.array;
  6151. const normals = attributes.normal.array;
  6152. const uvs = attributes.uv.array;
  6153. const nVertices = positions.length / 3;
  6154. if ( this.hasAttribute( 'tangent' ) === false ) {
  6155. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6156. }
  6157. const tangents = this.getAttribute( 'tangent' ).array;
  6158. const tan1 = [], tan2 = [];
  6159. for ( let i = 0; i < nVertices; i ++ ) {
  6160. tan1[ i ] = new Vector3();
  6161. tan2[ i ] = new Vector3();
  6162. }
  6163. const vA = new Vector3(),
  6164. vB = new Vector3(),
  6165. vC = new Vector3(),
  6166. uvA = new Vector2(),
  6167. uvB = new Vector2(),
  6168. uvC = new Vector2(),
  6169. sdir = new Vector3(),
  6170. tdir = new Vector3();
  6171. function handleTriangle( a, b, c ) {
  6172. vA.fromArray( positions, a * 3 );
  6173. vB.fromArray( positions, b * 3 );
  6174. vC.fromArray( positions, c * 3 );
  6175. uvA.fromArray( uvs, a * 2 );
  6176. uvB.fromArray( uvs, b * 2 );
  6177. uvC.fromArray( uvs, c * 2 );
  6178. vB.sub( vA );
  6179. vC.sub( vA );
  6180. uvB.sub( uvA );
  6181. uvC.sub( uvA );
  6182. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6183. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6184. if ( ! isFinite( r ) ) return;
  6185. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6186. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6187. tan1[ a ].add( sdir );
  6188. tan1[ b ].add( sdir );
  6189. tan1[ c ].add( sdir );
  6190. tan2[ a ].add( tdir );
  6191. tan2[ b ].add( tdir );
  6192. tan2[ c ].add( tdir );
  6193. }
  6194. let groups = this.groups;
  6195. if ( groups.length === 0 ) {
  6196. groups = [ {
  6197. start: 0,
  6198. count: indices.length
  6199. } ];
  6200. }
  6201. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6202. const group = groups[ i ];
  6203. const start = group.start;
  6204. const count = group.count;
  6205. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6206. handleTriangle(
  6207. indices[ j + 0 ],
  6208. indices[ j + 1 ],
  6209. indices[ j + 2 ]
  6210. );
  6211. }
  6212. }
  6213. const tmp = new Vector3(), tmp2 = new Vector3();
  6214. const n = new Vector3(), n2 = new Vector3();
  6215. function handleVertex( v ) {
  6216. n.fromArray( normals, v * 3 );
  6217. n2.copy( n );
  6218. const t = tan1[ v ];
  6219. // Gram-Schmidt orthogonalize
  6220. tmp.copy( t );
  6221. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6222. // Calculate handedness
  6223. tmp2.crossVectors( n2, t );
  6224. const test = tmp2.dot( tan2[ v ] );
  6225. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6226. tangents[ v * 4 ] = tmp.x;
  6227. tangents[ v * 4 + 1 ] = tmp.y;
  6228. tangents[ v * 4 + 2 ] = tmp.z;
  6229. tangents[ v * 4 + 3 ] = w;
  6230. }
  6231. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6232. const group = groups[ i ];
  6233. const start = group.start;
  6234. const count = group.count;
  6235. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6236. handleVertex( indices[ j + 0 ] );
  6237. handleVertex( indices[ j + 1 ] );
  6238. handleVertex( indices[ j + 2 ] );
  6239. }
  6240. }
  6241. }
  6242. computeVertexNormals() {
  6243. const index = this.index;
  6244. const positionAttribute = this.getAttribute( 'position' );
  6245. if ( positionAttribute !== undefined ) {
  6246. let normalAttribute = this.getAttribute( 'normal' );
  6247. if ( normalAttribute === undefined ) {
  6248. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6249. this.setAttribute( 'normal', normalAttribute );
  6250. } else {
  6251. // reset existing normals to zero
  6252. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6253. normalAttribute.setXYZ( i, 0, 0, 0 );
  6254. }
  6255. }
  6256. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6257. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6258. const cb = new Vector3(), ab = new Vector3();
  6259. // indexed elements
  6260. if ( index ) {
  6261. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6262. const vA = index.getX( i + 0 );
  6263. const vB = index.getX( i + 1 );
  6264. const vC = index.getX( i + 2 );
  6265. pA.fromBufferAttribute( positionAttribute, vA );
  6266. pB.fromBufferAttribute( positionAttribute, vB );
  6267. pC.fromBufferAttribute( positionAttribute, vC );
  6268. cb.subVectors( pC, pB );
  6269. ab.subVectors( pA, pB );
  6270. cb.cross( ab );
  6271. nA.fromBufferAttribute( normalAttribute, vA );
  6272. nB.fromBufferAttribute( normalAttribute, vB );
  6273. nC.fromBufferAttribute( normalAttribute, vC );
  6274. nA.add( cb );
  6275. nB.add( cb );
  6276. nC.add( cb );
  6277. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6278. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6279. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6280. }
  6281. } else {
  6282. // non-indexed elements (unconnected triangle soup)
  6283. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6284. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6285. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6286. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6287. cb.subVectors( pC, pB );
  6288. ab.subVectors( pA, pB );
  6289. cb.cross( ab );
  6290. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6291. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6292. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6293. }
  6294. }
  6295. this.normalizeNormals();
  6296. normalAttribute.needsUpdate = true;
  6297. }
  6298. }
  6299. // @deprecated since r144
  6300. merge() {
  6301. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6302. return this;
  6303. }
  6304. normalizeNormals() {
  6305. const normals = this.attributes.normal;
  6306. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6307. _vector$8.fromBufferAttribute( normals, i );
  6308. _vector$8.normalize();
  6309. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6310. }
  6311. }
  6312. toNonIndexed() {
  6313. function convertBufferAttribute( attribute, indices ) {
  6314. const array = attribute.array;
  6315. const itemSize = attribute.itemSize;
  6316. const normalized = attribute.normalized;
  6317. const array2 = new array.constructor( indices.length * itemSize );
  6318. let index = 0, index2 = 0;
  6319. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6320. if ( attribute.isInterleavedBufferAttribute ) {
  6321. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6322. } else {
  6323. index = indices[ i ] * itemSize;
  6324. }
  6325. for ( let j = 0; j < itemSize; j ++ ) {
  6326. array2[ index2 ++ ] = array[ index ++ ];
  6327. }
  6328. }
  6329. return new BufferAttribute( array2, itemSize, normalized );
  6330. }
  6331. //
  6332. if ( this.index === null ) {
  6333. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6334. return this;
  6335. }
  6336. const geometry2 = new BufferGeometry();
  6337. const indices = this.index.array;
  6338. const attributes = this.attributes;
  6339. // attributes
  6340. for ( const name in attributes ) {
  6341. const attribute = attributes[ name ];
  6342. const newAttribute = convertBufferAttribute( attribute, indices );
  6343. geometry2.setAttribute( name, newAttribute );
  6344. }
  6345. // morph attributes
  6346. const morphAttributes = this.morphAttributes;
  6347. for ( const name in morphAttributes ) {
  6348. const morphArray = [];
  6349. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6350. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6351. const attribute = morphAttribute[ i ];
  6352. const newAttribute = convertBufferAttribute( attribute, indices );
  6353. morphArray.push( newAttribute );
  6354. }
  6355. geometry2.morphAttributes[ name ] = morphArray;
  6356. }
  6357. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6358. // groups
  6359. const groups = this.groups;
  6360. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6361. const group = groups[ i ];
  6362. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6363. }
  6364. return geometry2;
  6365. }
  6366. toJSON() {
  6367. const data = {
  6368. metadata: {
  6369. version: 4.5,
  6370. type: 'BufferGeometry',
  6371. generator: 'BufferGeometry.toJSON'
  6372. }
  6373. };
  6374. // standard BufferGeometry serialization
  6375. data.uuid = this.uuid;
  6376. data.type = this.type;
  6377. if ( this.name !== '' ) data.name = this.name;
  6378. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6379. if ( this.parameters !== undefined ) {
  6380. const parameters = this.parameters;
  6381. for ( const key in parameters ) {
  6382. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6383. }
  6384. return data;
  6385. }
  6386. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6387. data.data = { attributes: {} };
  6388. const index = this.index;
  6389. if ( index !== null ) {
  6390. data.data.index = {
  6391. type: index.array.constructor.name,
  6392. array: Array.prototype.slice.call( index.array )
  6393. };
  6394. }
  6395. const attributes = this.attributes;
  6396. for ( const key in attributes ) {
  6397. const attribute = attributes[ key ];
  6398. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6399. }
  6400. const morphAttributes = {};
  6401. let hasMorphAttributes = false;
  6402. for ( const key in this.morphAttributes ) {
  6403. const attributeArray = this.morphAttributes[ key ];
  6404. const array = [];
  6405. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6406. const attribute = attributeArray[ i ];
  6407. array.push( attribute.toJSON( data.data ) );
  6408. }
  6409. if ( array.length > 0 ) {
  6410. morphAttributes[ key ] = array;
  6411. hasMorphAttributes = true;
  6412. }
  6413. }
  6414. if ( hasMorphAttributes ) {
  6415. data.data.morphAttributes = morphAttributes;
  6416. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6417. }
  6418. const groups = this.groups;
  6419. if ( groups.length > 0 ) {
  6420. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6421. }
  6422. const boundingSphere = this.boundingSphere;
  6423. if ( boundingSphere !== null ) {
  6424. data.data.boundingSphere = {
  6425. center: boundingSphere.center.toArray(),
  6426. radius: boundingSphere.radius
  6427. };
  6428. }
  6429. return data;
  6430. }
  6431. clone() {
  6432. return new this.constructor().copy( this );
  6433. }
  6434. copy( source ) {
  6435. // reset
  6436. this.index = null;
  6437. this.attributes = {};
  6438. this.morphAttributes = {};
  6439. this.groups = [];
  6440. this.boundingBox = null;
  6441. this.boundingSphere = null;
  6442. // used for storing cloned, shared data
  6443. const data = {};
  6444. // name
  6445. this.name = source.name;
  6446. // index
  6447. const index = source.index;
  6448. if ( index !== null ) {
  6449. this.setIndex( index.clone( data ) );
  6450. }
  6451. // attributes
  6452. const attributes = source.attributes;
  6453. for ( const name in attributes ) {
  6454. const attribute = attributes[ name ];
  6455. this.setAttribute( name, attribute.clone( data ) );
  6456. }
  6457. // morph attributes
  6458. const morphAttributes = source.morphAttributes;
  6459. for ( const name in morphAttributes ) {
  6460. const array = [];
  6461. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6462. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6463. array.push( morphAttribute[ i ].clone( data ) );
  6464. }
  6465. this.morphAttributes[ name ] = array;
  6466. }
  6467. this.morphTargetsRelative = source.morphTargetsRelative;
  6468. // groups
  6469. const groups = source.groups;
  6470. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6471. const group = groups[ i ];
  6472. this.addGroup( group.start, group.count, group.materialIndex );
  6473. }
  6474. // bounding box
  6475. const boundingBox = source.boundingBox;
  6476. if ( boundingBox !== null ) {
  6477. this.boundingBox = boundingBox.clone();
  6478. }
  6479. // bounding sphere
  6480. const boundingSphere = source.boundingSphere;
  6481. if ( boundingSphere !== null ) {
  6482. this.boundingSphere = boundingSphere.clone();
  6483. }
  6484. // draw range
  6485. this.drawRange.start = source.drawRange.start;
  6486. this.drawRange.count = source.drawRange.count;
  6487. // user data
  6488. this.userData = source.userData;
  6489. // geometry generator parameters
  6490. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6491. return this;
  6492. }
  6493. dispose() {
  6494. this.dispatchEvent( { type: 'dispose' } );
  6495. }
  6496. }
  6497. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6498. const _ray$2 = /*@__PURE__*/ new Ray();
  6499. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6500. const _vA$1 = /*@__PURE__*/ new Vector3();
  6501. const _vB$1 = /*@__PURE__*/ new Vector3();
  6502. const _vC$1 = /*@__PURE__*/ new Vector3();
  6503. const _tempA = /*@__PURE__*/ new Vector3();
  6504. const _tempB = /*@__PURE__*/ new Vector3();
  6505. const _tempC = /*@__PURE__*/ new Vector3();
  6506. const _morphA = /*@__PURE__*/ new Vector3();
  6507. const _morphB = /*@__PURE__*/ new Vector3();
  6508. const _morphC = /*@__PURE__*/ new Vector3();
  6509. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6510. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6511. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6512. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6513. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6514. class Mesh extends Object3D {
  6515. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6516. super();
  6517. this.isMesh = true;
  6518. this.type = 'Mesh';
  6519. this.geometry = geometry;
  6520. this.material = material;
  6521. this.updateMorphTargets();
  6522. }
  6523. copy( source, recursive ) {
  6524. super.copy( source, recursive );
  6525. if ( source.morphTargetInfluences !== undefined ) {
  6526. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6527. }
  6528. if ( source.morphTargetDictionary !== undefined ) {
  6529. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6530. }
  6531. this.material = source.material;
  6532. this.geometry = source.geometry;
  6533. return this;
  6534. }
  6535. updateMorphTargets() {
  6536. const geometry = this.geometry;
  6537. const morphAttributes = geometry.morphAttributes;
  6538. const keys = Object.keys( morphAttributes );
  6539. if ( keys.length > 0 ) {
  6540. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6541. if ( morphAttribute !== undefined ) {
  6542. this.morphTargetInfluences = [];
  6543. this.morphTargetDictionary = {};
  6544. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6545. const name = morphAttribute[ m ].name || String( m );
  6546. this.morphTargetInfluences.push( 0 );
  6547. this.morphTargetDictionary[ name ] = m;
  6548. }
  6549. }
  6550. }
  6551. }
  6552. raycast( raycaster, intersects ) {
  6553. const geometry = this.geometry;
  6554. const material = this.material;
  6555. const matrixWorld = this.matrixWorld;
  6556. if ( material === undefined ) return;
  6557. // Checking boundingSphere distance to ray
  6558. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6559. _sphere$3.copy( geometry.boundingSphere );
  6560. _sphere$3.applyMatrix4( matrixWorld );
  6561. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6562. //
  6563. _inverseMatrix$2.copy( matrixWorld ).invert();
  6564. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6565. // Check boundingBox before continuing
  6566. if ( geometry.boundingBox !== null ) {
  6567. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6568. }
  6569. let intersection;
  6570. const index = geometry.index;
  6571. const position = geometry.attributes.position;
  6572. const morphPosition = geometry.morphAttributes.position;
  6573. const morphTargetsRelative = geometry.morphTargetsRelative;
  6574. const uv = geometry.attributes.uv;
  6575. const uv2 = geometry.attributes.uv2;
  6576. const groups = geometry.groups;
  6577. const drawRange = geometry.drawRange;
  6578. if ( index !== null ) {
  6579. // indexed buffer geometry
  6580. if ( Array.isArray( material ) ) {
  6581. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6582. const group = groups[ i ];
  6583. const groupMaterial = material[ group.materialIndex ];
  6584. const start = Math.max( group.start, drawRange.start );
  6585. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6586. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6587. const a = index.getX( j );
  6588. const b = index.getX( j + 1 );
  6589. const c = index.getX( j + 2 );
  6590. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6591. if ( intersection ) {
  6592. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6593. intersection.face.materialIndex = group.materialIndex;
  6594. intersects.push( intersection );
  6595. }
  6596. }
  6597. }
  6598. } else {
  6599. const start = Math.max( 0, drawRange.start );
  6600. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6601. for ( let i = start, il = end; i < il; i += 3 ) {
  6602. const a = index.getX( i );
  6603. const b = index.getX( i + 1 );
  6604. const c = index.getX( i + 2 );
  6605. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6606. if ( intersection ) {
  6607. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6608. intersects.push( intersection );
  6609. }
  6610. }
  6611. }
  6612. } else if ( position !== undefined ) {
  6613. // non-indexed buffer geometry
  6614. if ( Array.isArray( material ) ) {
  6615. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6616. const group = groups[ i ];
  6617. const groupMaterial = material[ group.materialIndex ];
  6618. const start = Math.max( group.start, drawRange.start );
  6619. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6620. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6621. const a = j;
  6622. const b = j + 1;
  6623. const c = j + 2;
  6624. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6625. if ( intersection ) {
  6626. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6627. intersection.face.materialIndex = group.materialIndex;
  6628. intersects.push( intersection );
  6629. }
  6630. }
  6631. }
  6632. } else {
  6633. const start = Math.max( 0, drawRange.start );
  6634. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6635. for ( let i = start, il = end; i < il; i += 3 ) {
  6636. const a = i;
  6637. const b = i + 1;
  6638. const c = i + 2;
  6639. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6640. if ( intersection ) {
  6641. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6642. intersects.push( intersection );
  6643. }
  6644. }
  6645. }
  6646. }
  6647. }
  6648. }
  6649. class CSS2DObject extends Object3D {
  6650. constructor( element = document.createElement( 'div' ) ) {
  6651. super();
  6652. this.isCSS2DObject = true;
  6653. this.type = 'CSS2D';
  6654. this.name = 'CSS2D';
  6655. this.element = element;
  6656. this.userData = { "HTML":"<span>CSS2DObject</span>"} ;
  6657. this.element.style.position = 'absolute';
  6658. this.element.style.userSelect = 'none';
  6659. this.element.setAttribute( 'draggable', false );
  6660. this.addEventListener( 'removed', function () {
  6661. this.traverse( function ( object ) {
  6662. if ( object.element instanceof Element && object.element.parentNode !== null ) {
  6663. object.element.parentNode.removeChild( object.element );
  6664. }
  6665. } );
  6666. } );
  6667. }
  6668. copy( source, recursive ) {
  6669. super.copy( source, recursive );
  6670. this.element = source.element.cloneNode( true );
  6671. return this;
  6672. }
  6673. Up_Html(element = null ){
  6674. if(element == null) return
  6675. this.element.innerHTML = element;
  6676. }
  6677. }
  6678. class CSS3DObject extends Object3D {
  6679. constructor( element = document.createElement( 'div' ) ) {
  6680. super();
  6681. this.isCSS3DObject = true;
  6682. this.type = 'CSS3D';
  6683. this.name = 'CSS3D';
  6684. this.element = element;
  6685. this.userData = { "HTML":"<span>CSS3DObject</span>"} ;
  6686. this.element.style.position = 'absolute';
  6687. this.element.style.pointerEvents = 'none';
  6688. // this.element.style.userSelect = 'none';
  6689. this.element.setAttribute( 'draggable', false );
  6690. this.addEventListener( 'removed', function () {
  6691. this.traverse( function ( object ) {
  6692. if ( object.element instanceof Element && object.element.parentNode !== null ) {
  6693. object.element.parentNode.removeChild( object.element );
  6694. }
  6695. } );
  6696. } );
  6697. }
  6698. copy( source, recursive ) {
  6699. super.copy( source, recursive );
  6700. this.element = source.element.cloneNode( true );
  6701. return this;
  6702. }
  6703. Up_Html(element = null ){
  6704. if(element == null) return
  6705. this.element.innerHTML = element;
  6706. }
  6707. }
  6708. class Text extends Object3D {
  6709. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6710. if(window.TextFontLoader === undefined){
  6711. new FontLoader().load(window.Oss+'/js/fonts/FZYaoTi_Regular.json', function (font) {
  6712. window.TextFontLoader = font
  6713. });
  6714. }
  6715. super();
  6716. this.isMesh = true;
  6717. this.type = 'Text';
  6718. this.name = 'Text';
  6719. this.font_size = 0.3;
  6720. this.text = "文本内容";
  6721. this.geometry = geometry;
  6722. this.material = material;
  6723. this.updateMorphTargets();
  6724. }
  6725. copy( source, recursive ) {
  6726. super.copy( source, recursive );
  6727. if ( source.morphTargetInfluences !== undefined ) {
  6728. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6729. }
  6730. if ( source.morphTargetDictionary !== undefined ) {
  6731. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6732. }
  6733. this.material = source.material;
  6734. this.geometry = source.geometry;
  6735. return this;
  6736. }
  6737. updateMorphTargets() {
  6738. if(window.TextFontLoader === undefined) {
  6739. console.log("window.TextFontLoader === null")
  6740. return
  6741. }
  6742. // console.log("this.text",this.text)
  6743. this.geometry = new THREE.ShapeGeometry(window.TextFontLoader.generateShapes(this.text, this.font_size));
  6744. this.geometry.computeBoundingBox();
  6745. //
  6746. // const morphAttributes = geometry.morphAttributes;
  6747. // console.log(":",Object,geometry,morphAttributes)
  6748. // const keys = Object.keys( morphAttributes );
  6749. //
  6750. // if ( keys.length > 0 ) {
  6751. //
  6752. // const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6753. //
  6754. // if ( morphAttribute !== undefined ) {
  6755. //
  6756. // this.morphTargetInfluences = [];
  6757. // this.morphTargetDictionary = {};
  6758. //
  6759. // for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6760. //
  6761. // const name = morphAttribute[ m ].name || String( m );
  6762. //
  6763. // this.morphTargetInfluences.push( 0 );
  6764. // this.morphTargetDictionary[ name ] = m;
  6765. //
  6766. // }
  6767. //
  6768. // }
  6769. //
  6770. // }
  6771. }
  6772. raycast( raycaster, intersects ) {
  6773. const geometry = this.geometry;
  6774. const material = this.material;
  6775. const matrixWorld = this.matrixWorld;
  6776. if ( material === undefined ) return;
  6777. // Checking boundingSphere distance to ray
  6778. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6779. _sphere$3.copy( geometry.boundingSphere );
  6780. _sphere$3.applyMatrix4( matrixWorld );
  6781. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6782. //
  6783. _inverseMatrix$2.copy( matrixWorld ).invert();
  6784. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6785. // Check boundingBox before continuing
  6786. if ( geometry.boundingBox !== null ) {
  6787. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6788. }
  6789. let intersection;
  6790. const index = geometry.index;
  6791. const position = geometry.attributes.position;
  6792. const morphPosition = geometry.morphAttributes.position;
  6793. const morphTargetsRelative = geometry.morphTargetsRelative;
  6794. const uv = geometry.attributes.uv;
  6795. const uv2 = geometry.attributes.uv2;
  6796. const groups = geometry.groups;
  6797. const drawRange = geometry.drawRange;
  6798. if ( index !== null ) {
  6799. // indexed buffer geometry
  6800. if ( Array.isArray( material ) ) {
  6801. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6802. const group = groups[ i ];
  6803. const groupMaterial = material[ group.materialIndex ];
  6804. const start = Math.max( group.start, drawRange.start );
  6805. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6806. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6807. const a = index.getX( j );
  6808. const b = index.getX( j + 1 );
  6809. const c = index.getX( j + 2 );
  6810. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6811. if ( intersection ) {
  6812. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6813. intersection.face.materialIndex = group.materialIndex;
  6814. intersects.push( intersection );
  6815. }
  6816. }
  6817. }
  6818. } else {
  6819. const start = Math.max( 0, drawRange.start );
  6820. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6821. for ( let i = start, il = end; i < il; i += 3 ) {
  6822. const a = index.getX( i );
  6823. const b = index.getX( i + 1 );
  6824. const c = index.getX( i + 2 );
  6825. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6826. if ( intersection ) {
  6827. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6828. intersects.push( intersection );
  6829. }
  6830. }
  6831. }
  6832. } else if ( position !== undefined ) {
  6833. // non-indexed buffer geometry
  6834. if ( Array.isArray( material ) ) {
  6835. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6836. const group = groups[ i ];
  6837. const groupMaterial = material[ group.materialIndex ];
  6838. const start = Math.max( group.start, drawRange.start );
  6839. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6840. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6841. const a = j;
  6842. const b = j + 1;
  6843. const c = j + 2;
  6844. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6845. if ( intersection ) {
  6846. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6847. intersection.face.materialIndex = group.materialIndex;
  6848. intersects.push( intersection );
  6849. }
  6850. }
  6851. }
  6852. } else {
  6853. const start = Math.max( 0, drawRange.start );
  6854. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6855. for ( let i = start, il = end; i < il; i += 3 ) {
  6856. const a = i;
  6857. const b = i + 1;
  6858. const c = i + 2;
  6859. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6860. if ( intersection ) {
  6861. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6862. intersects.push( intersection );
  6863. }
  6864. }
  6865. }
  6866. }
  6867. }
  6868. }
  6869. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6870. let intersect;
  6871. if ( material.side === BackSide ) {
  6872. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6873. } else {
  6874. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6875. }
  6876. if ( intersect === null ) return null;
  6877. _intersectionPointWorld.copy( point );
  6878. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6879. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6880. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6881. return {
  6882. distance: distance,
  6883. point: _intersectionPointWorld.clone(),
  6884. object: object
  6885. };
  6886. }
  6887. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6888. _vA$1.fromBufferAttribute( position, a );
  6889. _vB$1.fromBufferAttribute( position, b );
  6890. _vC$1.fromBufferAttribute( position, c );
  6891. const morphInfluences = object.morphTargetInfluences;
  6892. if ( morphPosition && morphInfluences ) {
  6893. _morphA.set( 0, 0, 0 );
  6894. _morphB.set( 0, 0, 0 );
  6895. _morphC.set( 0, 0, 0 );
  6896. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6897. const influence = morphInfluences[ i ];
  6898. const morphAttribute = morphPosition[ i ];
  6899. if ( influence === 0 ) continue;
  6900. _tempA.fromBufferAttribute( morphAttribute, a );
  6901. _tempB.fromBufferAttribute( morphAttribute, b );
  6902. _tempC.fromBufferAttribute( morphAttribute, c );
  6903. if ( morphTargetsRelative ) {
  6904. _morphA.addScaledVector( _tempA, influence );
  6905. _morphB.addScaledVector( _tempB, influence );
  6906. _morphC.addScaledVector( _tempC, influence );
  6907. } else {
  6908. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6909. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6910. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6911. }
  6912. }
  6913. _vA$1.add( _morphA );
  6914. _vB$1.add( _morphB );
  6915. _vC$1.add( _morphC );
  6916. }
  6917. if ( object.isSkinnedMesh ) {
  6918. object.boneTransform( a, _vA$1 );
  6919. object.boneTransform( b, _vB$1 );
  6920. object.boneTransform( c, _vC$1 );
  6921. }
  6922. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6923. if ( intersection ) {
  6924. if ( uv ) {
  6925. _uvA$1.fromBufferAttribute( uv, a );
  6926. _uvB$1.fromBufferAttribute( uv, b );
  6927. _uvC$1.fromBufferAttribute( uv, c );
  6928. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6929. }
  6930. if ( uv2 ) {
  6931. _uvA$1.fromBufferAttribute( uv2, a );
  6932. _uvB$1.fromBufferAttribute( uv2, b );
  6933. _uvC$1.fromBufferAttribute( uv2, c );
  6934. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6935. }
  6936. const face = {
  6937. a: a,
  6938. b: b,
  6939. c: c,
  6940. normal: new Vector3(),
  6941. materialIndex: 0
  6942. };
  6943. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6944. intersection.face = face;
  6945. }
  6946. return intersection;
  6947. }
  6948. class BoxGeometry extends BufferGeometry {
  6949. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6950. super();
  6951. this.type = 'BoxGeometry';
  6952. this.parameters = {
  6953. width: width,
  6954. height: height,
  6955. depth: depth,
  6956. widthSegments: widthSegments,
  6957. heightSegments: heightSegments,
  6958. depthSegments: depthSegments
  6959. };
  6960. const scope = this;
  6961. // segments
  6962. widthSegments = Math.floor( widthSegments );
  6963. heightSegments = Math.floor( heightSegments );
  6964. depthSegments = Math.floor( depthSegments );
  6965. // buffers
  6966. const indices = [];
  6967. const vertices = [];
  6968. const normals = [];
  6969. const uvs = [];
  6970. // helper variables
  6971. let numberOfVertices = 0;
  6972. let groupStart = 0;
  6973. // build each side of the box geometry
  6974. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6975. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6976. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6977. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6978. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6979. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6980. // build geometry
  6981. this.setIndex( indices );
  6982. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6983. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6984. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6985. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6986. const segmentWidth = width / gridX;
  6987. const segmentHeight = height / gridY;
  6988. const widthHalf = width / 2;
  6989. const heightHalf = height / 2;
  6990. const depthHalf = depth / 2;
  6991. const gridX1 = gridX + 1;
  6992. const gridY1 = gridY + 1;
  6993. let vertexCounter = 0;
  6994. let groupCount = 0;
  6995. const vector = new Vector3();
  6996. // generate vertices, normals and uvs
  6997. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6998. const y = iy * segmentHeight - heightHalf;
  6999. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7000. const x = ix * segmentWidth - widthHalf;
  7001. // set values to correct vector component
  7002. vector[ u ] = x * udir;
  7003. vector[ v ] = y * vdir;
  7004. vector[ w ] = depthHalf;
  7005. // now apply vector to vertex buffer
  7006. vertices.push( vector.x, vector.y, vector.z );
  7007. // set values to correct vector component
  7008. vector[ u ] = 0;
  7009. vector[ v ] = 0;
  7010. vector[ w ] = depth > 0 ? 1 : - 1;
  7011. // now apply vector to normal buffer
  7012. normals.push( vector.x, vector.y, vector.z );
  7013. // uvs
  7014. uvs.push( ix / gridX );
  7015. uvs.push( 1 - ( iy / gridY ) );
  7016. // counters
  7017. vertexCounter += 1;
  7018. }
  7019. }
  7020. // indices
  7021. // 1. you need three indices to draw a single face
  7022. // 2. a single segment consists of two faces
  7023. // 3. so we need to generate six (2*3) indices per segment
  7024. for ( let iy = 0; iy < gridY; iy ++ ) {
  7025. for ( let ix = 0; ix < gridX; ix ++ ) {
  7026. const a = numberOfVertices + ix + gridX1 * iy;
  7027. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7028. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7029. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7030. // faces
  7031. indices.push( a, b, d );
  7032. indices.push( b, c, d );
  7033. // increase counter
  7034. groupCount += 6;
  7035. }
  7036. }
  7037. // add a group to the geometry. this will ensure multi material support
  7038. scope.addGroup( groupStart, groupCount, materialIndex );
  7039. // calculate new start value for groups
  7040. groupStart += groupCount;
  7041. // update total number of vertices
  7042. numberOfVertices += vertexCounter;
  7043. }
  7044. }
  7045. static fromJSON( data ) {
  7046. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7047. }
  7048. }
  7049. /**
  7050. * Uniform Utilities
  7051. */
  7052. function cloneUniforms( src ) {
  7053. const dst = {};
  7054. for ( const u in src ) {
  7055. dst[ u ] = {};
  7056. for ( const p in src[ u ] ) {
  7057. const property = src[ u ][ p ];
  7058. if ( property && ( property.isColor ||
  7059. property.isMatrix3 || property.isMatrix4 ||
  7060. property.isVector2 || property.isVector3 || property.isVector4 ||
  7061. property.isTexture || property.isQuaternion ) ) {
  7062. dst[ u ][ p ] = property.clone();
  7063. } else if ( Array.isArray( property ) ) {
  7064. dst[ u ][ p ] = property.slice();
  7065. } else {
  7066. dst[ u ][ p ] = property;
  7067. }
  7068. }
  7069. }
  7070. return dst;
  7071. }
  7072. function mergeUniforms( uniforms ) {
  7073. const merged = {};
  7074. for ( let u = 0; u < uniforms.length; u ++ ) {
  7075. const tmp = cloneUniforms( uniforms[ u ] );
  7076. for ( const p in tmp ) {
  7077. merged[ p ] = tmp[ p ];
  7078. }
  7079. }
  7080. return merged;
  7081. }
  7082. function cloneUniformsGroups( src ) {
  7083. const dst = [];
  7084. for ( let u = 0; u < src.length; u ++ ) {
  7085. dst.push( src[ u ].clone() );
  7086. }
  7087. return dst;
  7088. }
  7089. // Legacy
  7090. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7091. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7092. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7093. class ShaderMaterial extends Material {
  7094. constructor( parameters ) {
  7095. super();
  7096. this.isShaderMaterial = true;
  7097. this.type = 'ShaderMaterial';
  7098. this.defines = {};
  7099. this.uniforms = {};
  7100. this.uniformsGroups = [];
  7101. this.vertexShader = default_vertex;
  7102. this.fragmentShader = default_fragment;
  7103. this.linewidth = 1;
  7104. this.wireframe = false;
  7105. this.wireframeLinewidth = 1;
  7106. this.fog = false; // set to use scene fog
  7107. this.lights = false; // set to use scene lights
  7108. this.clipping = false; // set to use user-defined clipping planes
  7109. this.extensions = {
  7110. derivatives: false, // set to use derivatives
  7111. fragDepth: false, // set to use fragment depth values
  7112. drawBuffers: false, // set to use draw buffers
  7113. shaderTextureLOD: false // set to use shader texture LOD
  7114. };
  7115. // When rendered geometry doesn't include these attributes but the material does,
  7116. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7117. this.defaultAttributeValues = {
  7118. 'color': [ 1, 1, 1 ],
  7119. 'uv': [ 0, 0 ],
  7120. 'uv2': [ 0, 0 ]
  7121. };
  7122. this.index0AttributeName = undefined;
  7123. this.uniformsNeedUpdate = false;
  7124. this.glslVersion = null;
  7125. if ( parameters !== undefined ) {
  7126. this.setValues( parameters );
  7127. }
  7128. }
  7129. copy( source ) {
  7130. super.copy( source );
  7131. this.fragmentShader = source.fragmentShader;
  7132. this.vertexShader = source.vertexShader;
  7133. this.uniforms = cloneUniforms( source.uniforms );
  7134. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7135. this.defines = Object.assign( {}, source.defines );
  7136. this.wireframe = source.wireframe;
  7137. this.wireframeLinewidth = source.wireframeLinewidth;
  7138. this.fog = source.fog;
  7139. this.lights = source.lights;
  7140. this.clipping = source.clipping;
  7141. this.extensions = Object.assign( {}, source.extensions );
  7142. this.glslVersion = source.glslVersion;
  7143. return this;
  7144. }
  7145. toJSON( meta ) {
  7146. const data = super.toJSON( meta );
  7147. data.glslVersion = this.glslVersion;
  7148. data.uniforms = {};
  7149. for ( const name in this.uniforms ) {
  7150. const uniform = this.uniforms[ name ];
  7151. const value = uniform.value;
  7152. if ( value && value.isTexture ) {
  7153. data.uniforms[ name ] = {
  7154. type: 't',
  7155. value: value.toJSON( meta ).uuid
  7156. };
  7157. } else if ( value && value.isColor ) {
  7158. data.uniforms[ name ] = {
  7159. type: 'c',
  7160. value: value.getHex()
  7161. };
  7162. } else if ( value && value.isVector2 ) {
  7163. data.uniforms[ name ] = {
  7164. type: 'v2',
  7165. value: value.toArray()
  7166. };
  7167. } else if ( value && value.isVector3 ) {
  7168. data.uniforms[ name ] = {
  7169. type: 'v3',
  7170. value: value.toArray()
  7171. };
  7172. } else if ( value && value.isVector4 ) {
  7173. data.uniforms[ name ] = {
  7174. type: 'v4',
  7175. value: value.toArray()
  7176. };
  7177. } else if ( value && value.isMatrix3 ) {
  7178. data.uniforms[ name ] = {
  7179. type: 'm3',
  7180. value: value.toArray()
  7181. };
  7182. } else if ( value && value.isMatrix4 ) {
  7183. data.uniforms[ name ] = {
  7184. type: 'm4',
  7185. value: value.toArray()
  7186. };
  7187. } else {
  7188. data.uniforms[ name ] = {
  7189. value: value
  7190. };
  7191. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7192. }
  7193. }
  7194. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7195. data.vertexShader = this.vertexShader;
  7196. data.fragmentShader = this.fragmentShader;
  7197. const extensions = {};
  7198. for ( const key in this.extensions ) {
  7199. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7200. }
  7201. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7202. return data;
  7203. }
  7204. }
  7205. class Camera extends Object3D {
  7206. constructor() {
  7207. super();
  7208. this.isCamera = true;
  7209. this.type = 'Camera';
  7210. this.matrixWorldInverse = new Matrix4();
  7211. this.projectionMatrix = new Matrix4();
  7212. this.projectionMatrixInverse = new Matrix4();
  7213. }
  7214. copy( source, recursive ) {
  7215. super.copy( source, recursive );
  7216. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7217. this.projectionMatrix.copy( source.projectionMatrix );
  7218. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7219. return this;
  7220. }
  7221. getWorldDirection( target ) {
  7222. this.updateWorldMatrix( true, false );
  7223. const e = this.matrixWorld.elements;
  7224. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7225. }
  7226. updateMatrixWorld( force ) {
  7227. super.updateMatrixWorld( force );
  7228. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7229. }
  7230. updateWorldMatrix( updateParents, updateChildren ) {
  7231. super.updateWorldMatrix( updateParents, updateChildren );
  7232. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7233. }
  7234. clone() {
  7235. return new this.constructor().copy( this );
  7236. }
  7237. }
  7238. class PerspectiveCamera extends Camera {
  7239. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7240. super();
  7241. this.isPerspectiveCamera = true;
  7242. this.type = 'PerspectiveCamera';
  7243. this.fov = fov;
  7244. this.zoom = 1;
  7245. this.near = near;
  7246. this.far = far;
  7247. this.focus = 10;
  7248. this.aspect = aspect;
  7249. this.view = null;
  7250. this.filmGauge = 35; // width of the film (default in millimeters)
  7251. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7252. this.updateProjectionMatrix();
  7253. }
  7254. copy( source, recursive ) {
  7255. super.copy( source, recursive );
  7256. this.fov = source.fov;
  7257. this.zoom = source.zoom;
  7258. this.near = source.near;
  7259. this.far = source.far;
  7260. this.focus = source.focus;
  7261. this.aspect = source.aspect;
  7262. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7263. this.filmGauge = source.filmGauge;
  7264. this.filmOffset = source.filmOffset;
  7265. return this;
  7266. }
  7267. /**
  7268. * Sets the FOV by focal length in respect to the current .filmGauge.
  7269. *
  7270. * The default film gauge is 35, so that the focal length can be specified for
  7271. * a 35mm (full frame) camera.
  7272. *
  7273. * Values for focal length and film gauge must have the same unit.
  7274. */
  7275. setFocalLength( focalLength ) {
  7276. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7277. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7278. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7279. this.updateProjectionMatrix();
  7280. }
  7281. /**
  7282. * Calculates the focal length from the current .fov and .filmGauge.
  7283. */
  7284. getFocalLength() {
  7285. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7286. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7287. }
  7288. getEffectiveFOV() {
  7289. return RAD2DEG * 2 * Math.atan(
  7290. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7291. }
  7292. getFilmWidth() {
  7293. // film not completely covered in portrait format (aspect < 1)
  7294. return this.filmGauge * Math.min( this.aspect, 1 );
  7295. }
  7296. getFilmHeight() {
  7297. // film not completely covered in landscape format (aspect > 1)
  7298. return this.filmGauge / Math.max( this.aspect, 1 );
  7299. }
  7300. /**
  7301. * Sets an offset in a larger frustum. This is useful for multi-window or
  7302. * multi-monitor/multi-machine setups.
  7303. *
  7304. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7305. * the monitors are in grid like this
  7306. *
  7307. * +---+---+---+
  7308. * | A | B | C |
  7309. * +---+---+---+
  7310. * | D | E | F |
  7311. * +---+---+---+
  7312. *
  7313. * then for each monitor you would call it like this
  7314. *
  7315. * const w = 1920;
  7316. * const h = 1080;
  7317. * const fullWidth = w * 3;
  7318. * const fullHeight = h * 2;
  7319. *
  7320. * --A--
  7321. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7322. * --B--
  7323. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7324. * --C--
  7325. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7326. * --D--
  7327. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7328. * --E--
  7329. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7330. * --F--
  7331. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7332. *
  7333. * Note there is no reason monitors have to be the same size or in a grid.
  7334. */
  7335. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7336. this.aspect = fullWidth / fullHeight;
  7337. if ( this.view === null ) {
  7338. this.view = {
  7339. enabled: true,
  7340. fullWidth: 1,
  7341. fullHeight: 1,
  7342. offsetX: 0,
  7343. offsetY: 0,
  7344. width: 1,
  7345. height: 1
  7346. };
  7347. }
  7348. this.view.enabled = true;
  7349. this.view.fullWidth = fullWidth;
  7350. this.view.fullHeight = fullHeight;
  7351. this.view.offsetX = x;
  7352. this.view.offsetY = y;
  7353. this.view.width = width;
  7354. this.view.height = height;
  7355. this.updateProjectionMatrix();
  7356. }
  7357. clearViewOffset() {
  7358. if ( this.view !== null ) {
  7359. this.view.enabled = false;
  7360. }
  7361. this.updateProjectionMatrix();
  7362. }
  7363. updateProjectionMatrix() {
  7364. const near = this.near;
  7365. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7366. let height = 2 * top;
  7367. let width = this.aspect * height;
  7368. let left = - 0.5 * width;
  7369. const view = this.view;
  7370. if ( this.view !== null && this.view.enabled ) {
  7371. const fullWidth = view.fullWidth,
  7372. fullHeight = view.fullHeight;
  7373. left += view.offsetX * width / fullWidth;
  7374. top -= view.offsetY * height / fullHeight;
  7375. width *= view.width / fullWidth;
  7376. height *= view.height / fullHeight;
  7377. }
  7378. const skew = this.filmOffset;
  7379. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7380. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7381. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7382. }
  7383. toJSON( meta ) {
  7384. const data = super.toJSON( meta );
  7385. data.object.fov = this.fov;
  7386. data.object.zoom = this.zoom;
  7387. data.object.near = this.near;
  7388. data.object.far = this.far;
  7389. data.object.focus = this.focus;
  7390. data.object.aspect = this.aspect;
  7391. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7392. data.object.filmGauge = this.filmGauge;
  7393. data.object.filmOffset = this.filmOffset;
  7394. return data;
  7395. }
  7396. }
  7397. const fov = 90, aspect = 1;
  7398. class CubeCamera extends Object3D {
  7399. constructor( near, far, renderTarget ) {
  7400. super();
  7401. this.type = 'CubeCamera';
  7402. this.renderTarget = renderTarget;
  7403. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7404. cameraPX.layers = this.layers;
  7405. cameraPX.up.set( 0, - 1, 0 );
  7406. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7407. this.add( cameraPX );
  7408. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7409. cameraNX.layers = this.layers;
  7410. cameraNX.up.set( 0, - 1, 0 );
  7411. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7412. this.add( cameraNX );
  7413. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7414. cameraPY.layers = this.layers;
  7415. cameraPY.up.set( 0, 0, 1 );
  7416. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7417. this.add( cameraPY );
  7418. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7419. cameraNY.layers = this.layers;
  7420. cameraNY.up.set( 0, 0, - 1 );
  7421. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7422. this.add( cameraNY );
  7423. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7424. cameraPZ.layers = this.layers;
  7425. cameraPZ.up.set( 0, - 1, 0 );
  7426. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7427. this.add( cameraPZ );
  7428. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7429. cameraNZ.layers = this.layers;
  7430. cameraNZ.up.set( 0, - 1, 0 );
  7431. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7432. this.add( cameraNZ );
  7433. }
  7434. update( renderer, scene ) {
  7435. if ( this.parent === null ) this.updateMatrixWorld();
  7436. const renderTarget = this.renderTarget;
  7437. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7438. const currentRenderTarget = renderer.getRenderTarget();
  7439. const currentToneMapping = renderer.toneMapping;
  7440. const currentXrEnabled = renderer.xr.enabled;
  7441. renderer.toneMapping = NoToneMapping;
  7442. renderer.xr.enabled = false;
  7443. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7444. renderTarget.texture.generateMipmaps = false;
  7445. renderer.setRenderTarget( renderTarget, 0 );
  7446. renderer.render( scene, cameraPX );
  7447. renderer.setRenderTarget( renderTarget, 1 );
  7448. renderer.render( scene, cameraNX );
  7449. renderer.setRenderTarget( renderTarget, 2 );
  7450. renderer.render( scene, cameraPY );
  7451. renderer.setRenderTarget( renderTarget, 3 );
  7452. renderer.render( scene, cameraNY );
  7453. renderer.setRenderTarget( renderTarget, 4 );
  7454. renderer.render( scene, cameraPZ );
  7455. renderTarget.texture.generateMipmaps = generateMipmaps;
  7456. renderer.setRenderTarget( renderTarget, 5 );
  7457. renderer.render( scene, cameraNZ );
  7458. renderer.setRenderTarget( currentRenderTarget );
  7459. renderer.toneMapping = currentToneMapping;
  7460. renderer.xr.enabled = currentXrEnabled;
  7461. renderTarget.texture.needsPMREMUpdate = true;
  7462. }
  7463. }
  7464. class CubeTexture extends Texture {
  7465. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7466. images = images !== undefined ? images : [];
  7467. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7468. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7469. this.isCubeTexture = true;
  7470. this.flipY = false;
  7471. }
  7472. get images() {
  7473. return this.image;
  7474. }
  7475. set images( value ) {
  7476. this.image = value;
  7477. }
  7478. }
  7479. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7480. constructor( size, options = {} ) {
  7481. super( size, size, options );
  7482. this.isWebGLCubeRenderTarget = true;
  7483. const image = { width: size, height: size, depth: 1 };
  7484. const images = [ image, image, image, image, image, image ];
  7485. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7486. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7487. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7488. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7489. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7490. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7491. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7492. this.texture.isRenderTargetTexture = true;
  7493. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7494. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7495. }
  7496. fromEquirectangularTexture( renderer, texture ) {
  7497. this.texture.type = texture.type;
  7498. this.texture.encoding = texture.encoding;
  7499. this.texture.generateMipmaps = texture.generateMipmaps;
  7500. this.texture.minFilter = texture.minFilter;
  7501. this.texture.magFilter = texture.magFilter;
  7502. const shader = {
  7503. uniforms: {
  7504. tEquirect: { value: null },
  7505. },
  7506. vertexShader: /* glsl */`
  7507. varying vec3 vWorldDirection;
  7508. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7509. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7510. }
  7511. void main() {
  7512. vWorldDirection = transformDirection( position, modelMatrix );
  7513. #include <begin_vertex>
  7514. #include <project_vertex>
  7515. }
  7516. `,
  7517. fragmentShader: /* glsl */`
  7518. uniform sampler2D tEquirect;
  7519. varying vec3 vWorldDirection;
  7520. #include <common>
  7521. void main() {
  7522. vec3 direction = normalize( vWorldDirection );
  7523. vec2 sampleUV = equirectUv( direction );
  7524. gl_FragColor = texture2D( tEquirect, sampleUV );
  7525. }
  7526. `
  7527. };
  7528. const geometry = new BoxGeometry( 5, 5, 5 );
  7529. const material = new ShaderMaterial( {
  7530. name: 'CubemapFromEquirect',
  7531. uniforms: cloneUniforms( shader.uniforms ),
  7532. vertexShader: shader.vertexShader,
  7533. fragmentShader: shader.fragmentShader,
  7534. side: BackSide,
  7535. blending: NoBlending
  7536. } );
  7537. material.uniforms.tEquirect.value = texture;
  7538. const mesh = new Mesh( geometry, material );
  7539. const currentMinFilter = texture.minFilter;
  7540. // Avoid blurred poles
  7541. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7542. const camera = new CubeCamera( 1, 10, this );
  7543. camera.update( renderer, mesh );
  7544. texture.minFilter = currentMinFilter;
  7545. mesh.geometry.dispose();
  7546. mesh.material.dispose();
  7547. return this;
  7548. }
  7549. clear( renderer, color, depth, stencil ) {
  7550. const currentRenderTarget = renderer.getRenderTarget();
  7551. for ( let i = 0; i < 6; i ++ ) {
  7552. renderer.setRenderTarget( this, i );
  7553. renderer.clear( color, depth, stencil );
  7554. }
  7555. renderer.setRenderTarget( currentRenderTarget );
  7556. }
  7557. }
  7558. const _vector1 = /*@__PURE__*/ new Vector3();
  7559. const _vector2 = /*@__PURE__*/ new Vector3();
  7560. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7561. class Plane {
  7562. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7563. this.isPlane = true;
  7564. // normal is assumed to be normalized
  7565. this.normal = normal;
  7566. this.constant = constant;
  7567. }
  7568. set( normal, constant ) {
  7569. this.normal.copy( normal );
  7570. this.constant = constant;
  7571. return this;
  7572. }
  7573. setComponents( x, y, z, w ) {
  7574. this.normal.set( x, y, z );
  7575. this.constant = w;
  7576. return this;
  7577. }
  7578. setFromNormalAndCoplanarPoint( normal, point ) {
  7579. this.normal.copy( normal );
  7580. this.constant = - point.dot( this.normal );
  7581. return this;
  7582. }
  7583. setFromCoplanarPoints( a, b, c ) {
  7584. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7585. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7586. this.setFromNormalAndCoplanarPoint( normal, a );
  7587. return this;
  7588. }
  7589. copy( plane ) {
  7590. this.normal.copy( plane.normal );
  7591. this.constant = plane.constant;
  7592. return this;
  7593. }
  7594. normalize() {
  7595. // Note: will lead to a divide by zero if the plane is invalid.
  7596. const inverseNormalLength = 1.0 / this.normal.length();
  7597. this.normal.multiplyScalar( inverseNormalLength );
  7598. this.constant *= inverseNormalLength;
  7599. return this;
  7600. }
  7601. negate() {
  7602. this.constant *= - 1;
  7603. this.normal.negate();
  7604. return this;
  7605. }
  7606. distanceToPoint( point ) {
  7607. return this.normal.dot( point ) + this.constant;
  7608. }
  7609. distanceToSphere( sphere ) {
  7610. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7611. }
  7612. projectPoint( point, target ) {
  7613. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7614. }
  7615. intersectLine( line, target ) {
  7616. const direction = line.delta( _vector1 );
  7617. const denominator = this.normal.dot( direction );
  7618. if ( denominator === 0 ) {
  7619. // line is coplanar, return origin
  7620. if ( this.distanceToPoint( line.start ) === 0 ) {
  7621. return target.copy( line.start );
  7622. }
  7623. // Unsure if this is the correct method to handle this case.
  7624. return null;
  7625. }
  7626. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7627. if ( t < 0 || t > 1 ) {
  7628. return null;
  7629. }
  7630. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7631. }
  7632. intersectsLine( line ) {
  7633. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7634. const startSign = this.distanceToPoint( line.start );
  7635. const endSign = this.distanceToPoint( line.end );
  7636. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7637. }
  7638. intersectsBox( box ) {
  7639. return box.intersectsPlane( this );
  7640. }
  7641. intersectsSphere( sphere ) {
  7642. return sphere.intersectsPlane( this );
  7643. }
  7644. coplanarPoint( target ) {
  7645. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7646. }
  7647. applyMatrix4( matrix, optionalNormalMatrix ) {
  7648. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7649. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7650. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7651. this.constant = - referencePoint.dot( normal );
  7652. return this;
  7653. }
  7654. translate( offset ) {
  7655. this.constant -= offset.dot( this.normal );
  7656. return this;
  7657. }
  7658. equals( plane ) {
  7659. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7660. }
  7661. clone() {
  7662. return new this.constructor().copy( this );
  7663. }
  7664. }
  7665. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7666. const _vector$7 = /*@__PURE__*/ new Vector3();
  7667. class Frustum {
  7668. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7669. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7670. }
  7671. set( p0, p1, p2, p3, p4, p5 ) {
  7672. const planes = this.planes;
  7673. planes[ 0 ].copy( p0 );
  7674. planes[ 1 ].copy( p1 );
  7675. planes[ 2 ].copy( p2 );
  7676. planes[ 3 ].copy( p3 );
  7677. planes[ 4 ].copy( p4 );
  7678. planes[ 5 ].copy( p5 );
  7679. return this;
  7680. }
  7681. copy( frustum ) {
  7682. const planes = this.planes;
  7683. for ( let i = 0; i < 6; i ++ ) {
  7684. planes[ i ].copy( frustum.planes[ i ] );
  7685. }
  7686. return this;
  7687. }
  7688. setFromProjectionMatrix( m ) {
  7689. const planes = this.planes;
  7690. const me = m.elements;
  7691. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7692. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7693. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7694. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7695. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7696. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7697. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7698. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7699. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7700. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7701. return this;
  7702. }
  7703. intersectsObject( object ) {
  7704. const geometry = object.geometry;
  7705. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7706. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7707. return this.intersectsSphere( _sphere$2 );
  7708. }
  7709. intersectsSprite( sprite ) {
  7710. _sphere$2.center.set( 0, 0, 0 );
  7711. _sphere$2.radius = 0.7071067811865476;
  7712. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7713. return this.intersectsSphere( _sphere$2 );
  7714. }
  7715. intersectsSphere( sphere ) {
  7716. const planes = this.planes;
  7717. const center = sphere.center;
  7718. const negRadius = - sphere.radius;
  7719. for ( let i = 0; i < 6; i ++ ) {
  7720. const distance = planes[ i ].distanceToPoint( center );
  7721. if ( distance < negRadius ) {
  7722. return false;
  7723. }
  7724. }
  7725. return true;
  7726. }
  7727. intersectsBox( box ) {
  7728. const planes = this.planes;
  7729. for ( let i = 0; i < 6; i ++ ) {
  7730. const plane = planes[ i ];
  7731. // corner at max distance
  7732. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7733. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7734. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7735. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7736. return false;
  7737. }
  7738. }
  7739. return true;
  7740. }
  7741. containsPoint( point ) {
  7742. const planes = this.planes;
  7743. for ( let i = 0; i < 6; i ++ ) {
  7744. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7745. return false;
  7746. }
  7747. }
  7748. return true;
  7749. }
  7750. clone() {
  7751. return new this.constructor().copy( this );
  7752. }
  7753. }
  7754. function WebGLAnimation() {
  7755. let context = null;
  7756. let isAnimating = false;
  7757. let animationLoop = null;
  7758. let requestId = null;
  7759. function onAnimationFrame( time, frame ) {
  7760. animationLoop( time, frame );
  7761. requestId = context.requestAnimationFrame( onAnimationFrame );
  7762. }
  7763. return {
  7764. start: function () {
  7765. if ( isAnimating === true ) return;
  7766. if ( animationLoop === null ) return;
  7767. requestId = context.requestAnimationFrame( onAnimationFrame );
  7768. isAnimating = true;
  7769. },
  7770. stop: function () {
  7771. context.cancelAnimationFrame( requestId );
  7772. isAnimating = false;
  7773. },
  7774. setAnimationLoop: function ( callback ) {
  7775. animationLoop = callback;
  7776. },
  7777. setContext: function ( value ) {
  7778. context = value;
  7779. }
  7780. };
  7781. }
  7782. function WebGLAttributes( gl, capabilities ) {
  7783. const isWebGL2 = capabilities.isWebGL2;
  7784. const buffers = new WeakMap();
  7785. function createBuffer( attribute, bufferType ) {
  7786. const array = attribute.array;
  7787. const usage = attribute.usage;
  7788. const buffer = gl.createBuffer();
  7789. gl.bindBuffer( bufferType, buffer );
  7790. gl.bufferData( bufferType, array, usage );
  7791. attribute.onUploadCallback();
  7792. let type;
  7793. if ( array instanceof Float32Array ) {
  7794. type = 5126;
  7795. } else if ( array instanceof Uint16Array ) {
  7796. if ( attribute.isFloat16BufferAttribute ) {
  7797. if ( isWebGL2 ) {
  7798. type = 5131;
  7799. } else {
  7800. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7801. }
  7802. } else {
  7803. type = 5123;
  7804. }
  7805. } else if ( array instanceof Int16Array ) {
  7806. type = 5122;
  7807. } else if ( array instanceof Uint32Array ) {
  7808. type = 5125;
  7809. } else if ( array instanceof Int32Array ) {
  7810. type = 5124;
  7811. } else if ( array instanceof Int8Array ) {
  7812. type = 5120;
  7813. } else if ( array instanceof Uint8Array ) {
  7814. type = 5121;
  7815. } else if ( array instanceof Uint8ClampedArray ) {
  7816. type = 5121;
  7817. } else {
  7818. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7819. }
  7820. return {
  7821. buffer: buffer,
  7822. type: type,
  7823. bytesPerElement: array.BYTES_PER_ELEMENT,
  7824. version: attribute.version
  7825. };
  7826. }
  7827. function updateBuffer( buffer, attribute, bufferType ) {
  7828. const array = attribute.array;
  7829. const updateRange = attribute.updateRange;
  7830. gl.bindBuffer( bufferType, buffer );
  7831. if ( updateRange.count === - 1 ) {
  7832. // Not using update ranges
  7833. gl.bufferSubData( bufferType, 0, array );
  7834. } else {
  7835. if ( isWebGL2 ) {
  7836. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7837. array, updateRange.offset, updateRange.count );
  7838. } else {
  7839. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7840. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7841. }
  7842. updateRange.count = - 1; // reset range
  7843. }
  7844. }
  7845. //
  7846. function get( attribute ) {
  7847. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7848. return buffers.get( attribute );
  7849. }
  7850. function remove( attribute ) {
  7851. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7852. const data = buffers.get( attribute );
  7853. if ( data ) {
  7854. gl.deleteBuffer( data.buffer );
  7855. buffers.delete( attribute );
  7856. }
  7857. }
  7858. function update( attribute, bufferType ) {
  7859. if ( attribute.isGLBufferAttribute ) {
  7860. const cached = buffers.get( attribute );
  7861. if ( ! cached || cached.version < attribute.version ) {
  7862. buffers.set( attribute, {
  7863. buffer: attribute.buffer,
  7864. type: attribute.type,
  7865. bytesPerElement: attribute.elementSize,
  7866. version: attribute.version
  7867. } );
  7868. }
  7869. return;
  7870. }
  7871. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7872. const data = buffers.get( attribute );
  7873. if ( data === undefined ) {
  7874. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7875. } else if ( data.version < attribute.version ) {
  7876. updateBuffer( data.buffer, attribute, bufferType );
  7877. data.version = attribute.version;
  7878. }
  7879. }
  7880. return {
  7881. get: get,
  7882. remove: remove,
  7883. update: update
  7884. };
  7885. }
  7886. class PlaneGeometry extends BufferGeometry {
  7887. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7888. super();
  7889. this.type = 'PlaneGeometry';
  7890. this.parameters = {
  7891. width: width,
  7892. height: height,
  7893. widthSegments: widthSegments,
  7894. heightSegments: heightSegments
  7895. };
  7896. const width_half = width / 2;
  7897. const height_half = height / 2;
  7898. const gridX = Math.floor( widthSegments );
  7899. const gridY = Math.floor( heightSegments );
  7900. const gridX1 = gridX + 1;
  7901. const gridY1 = gridY + 1;
  7902. const segment_width = width / gridX;
  7903. const segment_height = height / gridY;
  7904. //
  7905. const indices = [];
  7906. const vertices = [];
  7907. const normals = [];
  7908. const uvs = [];
  7909. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7910. const y = iy * segment_height - height_half;
  7911. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7912. const x = ix * segment_width - width_half;
  7913. vertices.push( x, - y, 0 );
  7914. normals.push( 0, 0, 1 );
  7915. uvs.push( ix / gridX );
  7916. uvs.push( 1 - ( iy / gridY ) );
  7917. }
  7918. }
  7919. for ( let iy = 0; iy < gridY; iy ++ ) {
  7920. for ( let ix = 0; ix < gridX; ix ++ ) {
  7921. const a = ix + gridX1 * iy;
  7922. const b = ix + gridX1 * ( iy + 1 );
  7923. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7924. const d = ( ix + 1 ) + gridX1 * iy;
  7925. indices.push( a, b, d );
  7926. indices.push( b, c, d );
  7927. }
  7928. }
  7929. this.setIndex( indices );
  7930. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7931. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7932. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7933. }
  7934. static fromJSON( data ) {
  7935. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7936. }
  7937. }
  7938. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7939. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7940. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7941. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7942. 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";
  7943. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7944. var begin_vertex = "vec3 transformed = vec3( position );";
  7945. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7946. 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";
  7947. 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";
  7948. 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";
  7949. 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";
  7950. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7951. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7952. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7953. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7954. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7955. 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";
  7956. 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";
  7957. 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}";
  7958. 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";
  7959. 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";
  7960. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7961. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7962. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7963. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7964. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7965. 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}";
  7966. 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";
  7967. 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";
  7968. 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";
  7969. 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";
  7970. 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";
  7971. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7972. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7973. 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";
  7974. 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";
  7975. 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}";
  7976. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7977. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7978. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7979. 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)";
  7980. 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";
  7981. 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";
  7982. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7983. 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)";
  7984. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7985. 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)";
  7986. 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";
  7987. 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}";
  7988. 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\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tinSpotLightMap = inSpotLightMap && ( spotColor.a > 0. );\n\t\t\tdirectLight.visible = directLight.visible || inSpotLightMap;\n\t\t\tdirectLight.color = inSpotLightMap ? mix( directLight.color, spotLight.color * spotColor.rgb, spotColor.a ) : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= 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";
  7989. 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";
  7990. 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";
  7991. 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";
  7992. 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";
  7993. 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";
  7994. 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";
  7995. 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";
  7996. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7997. 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";
  7998. 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";
  7999. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8000. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8001. 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";
  8002. 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";
  8003. 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";
  8004. 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";
  8005. 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;";
  8006. 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";
  8007. 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";
  8008. 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";
  8009. 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";
  8010. 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";
  8011. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8012. 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";
  8013. 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";
  8014. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8015. 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 );";
  8016. 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}";
  8017. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8018. 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;";
  8019. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8020. 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";
  8021. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8022. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8023. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\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";
  8024. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8025. var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 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_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\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";
  8026. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8027. 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";
  8028. 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";
  8029. 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";
  8030. 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";
  8031. 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";
  8032. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8033. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8034. 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; }";
  8035. 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";
  8036. 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";
  8037. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8038. 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";
  8039. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8040. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8041. 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";
  8042. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8043. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_MAPS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8044. 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}";
  8045. 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}";
  8046. 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}";
  8047. 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}";
  8048. 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}";
  8049. 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}";
  8050. 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}";
  8051. 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}";
  8052. 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}";
  8053. 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}";
  8054. 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}";
  8055. 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}";
  8056. 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}";
  8057. 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}";
  8058. 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}";
  8059. 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}";
  8060. 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}";
  8061. 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}";
  8062. 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}";
  8063. 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}";
  8064. 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}";
  8065. 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}";
  8066. 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}";
  8067. 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}";
  8068. 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}";
  8069. 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}";
  8070. 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}";
  8071. 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}";
  8072. 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}";
  8073. 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}";
  8074. 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}";
  8075. 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}";
  8076. const ShaderChunk = {
  8077. alphamap_fragment: alphamap_fragment,
  8078. alphamap_pars_fragment: alphamap_pars_fragment,
  8079. alphatest_fragment: alphatest_fragment,
  8080. alphatest_pars_fragment: alphatest_pars_fragment,
  8081. aomap_fragment: aomap_fragment,
  8082. aomap_pars_fragment: aomap_pars_fragment,
  8083. begin_vertex: begin_vertex,
  8084. beginnormal_vertex: beginnormal_vertex,
  8085. bsdfs: bsdfs,
  8086. iridescence_fragment: iridescence_fragment,
  8087. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8088. clipping_planes_fragment: clipping_planes_fragment,
  8089. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8090. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8091. clipping_planes_vertex: clipping_planes_vertex,
  8092. color_fragment: color_fragment,
  8093. color_pars_fragment: color_pars_fragment,
  8094. color_pars_vertex: color_pars_vertex,
  8095. color_vertex: color_vertex,
  8096. common: common,
  8097. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8098. defaultnormal_vertex: defaultnormal_vertex,
  8099. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8100. displacementmap_vertex: displacementmap_vertex,
  8101. emissivemap_fragment: emissivemap_fragment,
  8102. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8103. encodings_fragment: encodings_fragment,
  8104. encodings_pars_fragment: encodings_pars_fragment,
  8105. envmap_fragment: envmap_fragment,
  8106. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8107. envmap_pars_fragment: envmap_pars_fragment,
  8108. envmap_pars_vertex: envmap_pars_vertex,
  8109. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8110. envmap_vertex: envmap_vertex,
  8111. fog_vertex: fog_vertex,
  8112. fog_pars_vertex: fog_pars_vertex,
  8113. fog_fragment: fog_fragment,
  8114. fog_pars_fragment: fog_pars_fragment,
  8115. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8116. lightmap_fragment: lightmap_fragment,
  8117. lightmap_pars_fragment: lightmap_pars_fragment,
  8118. lights_lambert_fragment: lights_lambert_fragment,
  8119. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8120. lights_pars_begin: lights_pars_begin,
  8121. lights_toon_fragment: lights_toon_fragment,
  8122. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8123. lights_phong_fragment: lights_phong_fragment,
  8124. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8125. lights_physical_fragment: lights_physical_fragment,
  8126. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8127. lights_fragment_begin: lights_fragment_begin,
  8128. lights_fragment_maps: lights_fragment_maps,
  8129. lights_fragment_end: lights_fragment_end,
  8130. logdepthbuf_fragment: logdepthbuf_fragment,
  8131. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8132. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8133. logdepthbuf_vertex: logdepthbuf_vertex,
  8134. map_fragment: map_fragment,
  8135. map_pars_fragment: map_pars_fragment,
  8136. map_particle_fragment: map_particle_fragment,
  8137. map_particle_pars_fragment: map_particle_pars_fragment,
  8138. metalnessmap_fragment: metalnessmap_fragment,
  8139. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8140. morphcolor_vertex: morphcolor_vertex,
  8141. morphnormal_vertex: morphnormal_vertex,
  8142. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8143. morphtarget_vertex: morphtarget_vertex,
  8144. normal_fragment_begin: normal_fragment_begin,
  8145. normal_fragment_maps: normal_fragment_maps,
  8146. normal_pars_fragment: normal_pars_fragment,
  8147. normal_pars_vertex: normal_pars_vertex,
  8148. normal_vertex: normal_vertex,
  8149. normalmap_pars_fragment: normalmap_pars_fragment,
  8150. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8151. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8152. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8153. iridescence_pars_fragment: iridescence_pars_fragment,
  8154. output_fragment: output_fragment,
  8155. packing: packing,
  8156. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8157. project_vertex: project_vertex,
  8158. dithering_fragment: dithering_fragment,
  8159. dithering_pars_fragment: dithering_pars_fragment,
  8160. roughnessmap_fragment: roughnessmap_fragment,
  8161. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8162. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8163. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8164. shadowmap_vertex: shadowmap_vertex,
  8165. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8166. skinbase_vertex: skinbase_vertex,
  8167. skinning_pars_vertex: skinning_pars_vertex,
  8168. skinning_vertex: skinning_vertex,
  8169. skinnormal_vertex: skinnormal_vertex,
  8170. specularmap_fragment: specularmap_fragment,
  8171. specularmap_pars_fragment: specularmap_pars_fragment,
  8172. tonemapping_fragment: tonemapping_fragment,
  8173. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8174. transmission_fragment: transmission_fragment,
  8175. transmission_pars_fragment: transmission_pars_fragment,
  8176. uv_pars_fragment: uv_pars_fragment,
  8177. uv_pars_vertex: uv_pars_vertex,
  8178. uv_vertex: uv_vertex,
  8179. uv2_pars_fragment: uv2_pars_fragment,
  8180. uv2_pars_vertex: uv2_pars_vertex,
  8181. uv2_vertex: uv2_vertex,
  8182. worldpos_vertex: worldpos_vertex,
  8183. background_vert: vertex$g,
  8184. background_frag: fragment$g,
  8185. cube_vert: vertex$f,
  8186. cube_frag: fragment$f,
  8187. depth_vert: vertex$e,
  8188. depth_frag: fragment$e,
  8189. distanceRGBA_vert: vertex$d,
  8190. distanceRGBA_frag: fragment$d,
  8191. equirect_vert: vertex$c,
  8192. equirect_frag: fragment$c,
  8193. linedashed_vert: vertex$b,
  8194. linedashed_frag: fragment$b,
  8195. meshbasic_vert: vertex$a,
  8196. meshbasic_frag: fragment$a,
  8197. meshlambert_vert: vertex$9,
  8198. meshlambert_frag: fragment$9,
  8199. meshmatcap_vert: vertex$8,
  8200. meshmatcap_frag: fragment$8,
  8201. meshnormal_vert: vertex$7,
  8202. meshnormal_frag: fragment$7,
  8203. meshphong_vert: vertex$6,
  8204. meshphong_frag: fragment$6,
  8205. meshphysical_vert: vertex$5,
  8206. meshphysical_frag: fragment$5,
  8207. meshtoon_vert: vertex$4,
  8208. meshtoon_frag: fragment$4,
  8209. points_vert: vertex$3,
  8210. points_frag: fragment$3,
  8211. shadow_vert: vertex$2,
  8212. shadow_frag: fragment$2,
  8213. sprite_vert: vertex$1,
  8214. sprite_frag: fragment$1
  8215. };
  8216. /**
  8217. * Uniforms library for shared webgl shaders
  8218. */
  8219. const UniformsLib = {
  8220. common: {
  8221. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8222. opacity: { value: 1.0 },
  8223. map: { value: null },
  8224. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8225. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  8226. alphaMap: { value: null },
  8227. alphaTest: { value: 0 }
  8228. },
  8229. specularmap: {
  8230. specularMap: { value: null },
  8231. },
  8232. envmap: {
  8233. envMap: { value: null },
  8234. flipEnvMap: { value: - 1 },
  8235. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8236. ior: { value: 1.5 }, // physical
  8237. refractionRatio: { value: 0.98 } // basic, lambert, phong
  8238. },
  8239. aomap: {
  8240. aoMap: { value: null },
  8241. aoMapIntensity: { value: 1 }
  8242. },
  8243. lightmap: {
  8244. lightMap: { value: null },
  8245. lightMapIntensity: { value: 1 }
  8246. },
  8247. emissivemap: {
  8248. emissiveMap: { value: null }
  8249. },
  8250. bumpmap: {
  8251. bumpMap: { value: null },
  8252. bumpScale: { value: 1 }
  8253. },
  8254. normalmap: {
  8255. normalMap: { value: null },
  8256. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8257. },
  8258. displacementmap: {
  8259. displacementMap: { value: null },
  8260. displacementScale: { value: 1 },
  8261. displacementBias: { value: 0 }
  8262. },
  8263. roughnessmap: {
  8264. roughnessMap: { value: null }
  8265. },
  8266. metalnessmap: {
  8267. metalnessMap: { value: null }
  8268. },
  8269. gradientmap: {
  8270. gradientMap: { value: null }
  8271. },
  8272. fog: {
  8273. fogDensity: { value: 0.00025 },
  8274. fogNear: { value: 1 },
  8275. fogFar: { value: 2000 },
  8276. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8277. },
  8278. lights: {
  8279. ambientLightColor: { value: [] },
  8280. lightProbe: { value: [] },
  8281. directionalLights: { value: [], properties: {
  8282. direction: {},
  8283. color: {}
  8284. } },
  8285. directionalLightShadows: { value: [], properties: {
  8286. shadowBias: {},
  8287. shadowNormalBias: {},
  8288. shadowRadius: {},
  8289. shadowMapSize: {}
  8290. } },
  8291. directionalShadowMap: { value: [] },
  8292. directionalShadowMatrix: { value: [] },
  8293. spotLights: { value: [], properties: {
  8294. color: {},
  8295. position: {},
  8296. direction: {},
  8297. distance: {},
  8298. coneCos: {},
  8299. penumbraCos: {},
  8300. decay: {}
  8301. } },
  8302. spotLightShadows: { value: [], properties: {
  8303. shadowBias: {},
  8304. shadowNormalBias: {},
  8305. shadowRadius: {},
  8306. shadowMapSize: {}
  8307. } },
  8308. spotLightMap: { value: [] },
  8309. spotShadowMap: { value: [] },
  8310. spotLightMatrix: { value: [] },
  8311. pointLights: { value: [], properties: {
  8312. color: {},
  8313. position: {},
  8314. decay: {},
  8315. distance: {}
  8316. } },
  8317. pointLightShadows: { value: [], properties: {
  8318. shadowBias: {},
  8319. shadowNormalBias: {},
  8320. shadowRadius: {},
  8321. shadowMapSize: {},
  8322. shadowCameraNear: {},
  8323. shadowCameraFar: {}
  8324. } },
  8325. pointShadowMap: { value: [] },
  8326. pointShadowMatrix: { value: [] },
  8327. hemisphereLights: { value: [], properties: {
  8328. direction: {},
  8329. skyColor: {},
  8330. groundColor: {}
  8331. } },
  8332. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8333. rectAreaLights: { value: [], properties: {
  8334. color: {},
  8335. position: {},
  8336. width: {},
  8337. height: {}
  8338. } },
  8339. ltc_1: { value: null },
  8340. ltc_2: { value: null }
  8341. },
  8342. points: {
  8343. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8344. opacity: { value: 1.0 },
  8345. size: { value: 1.0 },
  8346. scale: { value: 1.0 },
  8347. map: { value: null },
  8348. alphaMap: { value: null },
  8349. alphaTest: { value: 0 },
  8350. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8351. },
  8352. sprite: {
  8353. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8354. opacity: { value: 1.0 },
  8355. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8356. rotation: { value: 0.0 },
  8357. map: { value: null },
  8358. alphaMap: { value: null },
  8359. alphaTest: { value: 0 },
  8360. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8361. }
  8362. };
  8363. const ShaderLib = {
  8364. basic: {
  8365. uniforms: /*@__PURE__*/ mergeUniforms( [
  8366. UniformsLib.common,
  8367. UniformsLib.specularmap,
  8368. UniformsLib.envmap,
  8369. UniformsLib.aomap,
  8370. UniformsLib.lightmap,
  8371. UniformsLib.fog
  8372. ] ),
  8373. vertexShader: ShaderChunk.meshbasic_vert,
  8374. fragmentShader: ShaderChunk.meshbasic_frag
  8375. },
  8376. lambert: {
  8377. uniforms: /*@__PURE__*/ mergeUniforms( [
  8378. UniformsLib.common,
  8379. UniformsLib.specularmap,
  8380. UniformsLib.envmap,
  8381. UniformsLib.aomap,
  8382. UniformsLib.lightmap,
  8383. UniformsLib.emissivemap,
  8384. UniformsLib.bumpmap,
  8385. UniformsLib.normalmap,
  8386. UniformsLib.displacementmap,
  8387. UniformsLib.fog,
  8388. UniformsLib.lights,
  8389. {
  8390. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8391. }
  8392. ] ),
  8393. vertexShader: ShaderChunk.meshlambert_vert,
  8394. fragmentShader: ShaderChunk.meshlambert_frag
  8395. },
  8396. phong: {
  8397. uniforms: /*@__PURE__*/ mergeUniforms( [
  8398. UniformsLib.common,
  8399. UniformsLib.specularmap,
  8400. UniformsLib.envmap,
  8401. UniformsLib.aomap,
  8402. UniformsLib.lightmap,
  8403. UniformsLib.emissivemap,
  8404. UniformsLib.bumpmap,
  8405. UniformsLib.normalmap,
  8406. UniformsLib.displacementmap,
  8407. UniformsLib.fog,
  8408. UniformsLib.lights,
  8409. {
  8410. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8411. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8412. shininess: { value: 30 }
  8413. }
  8414. ] ),
  8415. vertexShader: ShaderChunk.meshphong_vert,
  8416. fragmentShader: ShaderChunk.meshphong_frag
  8417. },
  8418. standard: {
  8419. uniforms: /*@__PURE__*/ mergeUniforms( [
  8420. UniformsLib.common,
  8421. UniformsLib.envmap,
  8422. UniformsLib.aomap,
  8423. UniformsLib.lightmap,
  8424. UniformsLib.emissivemap,
  8425. UniformsLib.bumpmap,
  8426. UniformsLib.normalmap,
  8427. UniformsLib.displacementmap,
  8428. UniformsLib.roughnessmap,
  8429. UniformsLib.metalnessmap,
  8430. UniformsLib.fog,
  8431. UniformsLib.lights,
  8432. {
  8433. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8434. roughness: { value: 1.0 },
  8435. metalness: { value: 0.0 },
  8436. envMapIntensity: { value: 1 } // temporary
  8437. }
  8438. ] ),
  8439. vertexShader: ShaderChunk.meshphysical_vert,
  8440. fragmentShader: ShaderChunk.meshphysical_frag
  8441. },
  8442. toon: {
  8443. uniforms: /*@__PURE__*/ mergeUniforms( [
  8444. UniformsLib.common,
  8445. UniformsLib.aomap,
  8446. UniformsLib.lightmap,
  8447. UniformsLib.emissivemap,
  8448. UniformsLib.bumpmap,
  8449. UniformsLib.normalmap,
  8450. UniformsLib.displacementmap,
  8451. UniformsLib.gradientmap,
  8452. UniformsLib.fog,
  8453. UniformsLib.lights,
  8454. {
  8455. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8456. }
  8457. ] ),
  8458. vertexShader: ShaderChunk.meshtoon_vert,
  8459. fragmentShader: ShaderChunk.meshtoon_frag
  8460. },
  8461. matcap: {
  8462. uniforms: /*@__PURE__*/ mergeUniforms( [
  8463. UniformsLib.common,
  8464. UniformsLib.bumpmap,
  8465. UniformsLib.normalmap,
  8466. UniformsLib.displacementmap,
  8467. UniformsLib.fog,
  8468. {
  8469. matcap: { value: null }
  8470. }
  8471. ] ),
  8472. vertexShader: ShaderChunk.meshmatcap_vert,
  8473. fragmentShader: ShaderChunk.meshmatcap_frag
  8474. },
  8475. points: {
  8476. uniforms: /*@__PURE__*/ mergeUniforms( [
  8477. UniformsLib.points,
  8478. UniformsLib.fog
  8479. ] ),
  8480. vertexShader: ShaderChunk.points_vert,
  8481. fragmentShader: ShaderChunk.points_frag
  8482. },
  8483. dashed: {
  8484. uniforms: /*@__PURE__*/ mergeUniforms( [
  8485. UniformsLib.common,
  8486. UniformsLib.fog,
  8487. {
  8488. scale: { value: 1 },
  8489. dashSize: { value: 1 },
  8490. totalSize: { value: 2 }
  8491. }
  8492. ] ),
  8493. vertexShader: ShaderChunk.linedashed_vert,
  8494. fragmentShader: ShaderChunk.linedashed_frag
  8495. },
  8496. depth: {
  8497. uniforms: /*@__PURE__*/ mergeUniforms( [
  8498. UniformsLib.common,
  8499. UniformsLib.displacementmap
  8500. ] ),
  8501. vertexShader: ShaderChunk.depth_vert,
  8502. fragmentShader: ShaderChunk.depth_frag
  8503. },
  8504. normal: {
  8505. uniforms: /*@__PURE__*/ mergeUniforms( [
  8506. UniformsLib.common,
  8507. UniformsLib.bumpmap,
  8508. UniformsLib.normalmap,
  8509. UniformsLib.displacementmap,
  8510. {
  8511. opacity: { value: 1.0 }
  8512. }
  8513. ] ),
  8514. vertexShader: ShaderChunk.meshnormal_vert,
  8515. fragmentShader: ShaderChunk.meshnormal_frag
  8516. },
  8517. sprite: {
  8518. uniforms: /*@__PURE__*/ mergeUniforms( [
  8519. UniformsLib.sprite,
  8520. UniformsLib.fog
  8521. ] ),
  8522. vertexShader: ShaderChunk.sprite_vert,
  8523. fragmentShader: ShaderChunk.sprite_frag
  8524. },
  8525. background: {
  8526. uniforms: {
  8527. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8528. t2D: { value: null },
  8529. },
  8530. vertexShader: ShaderChunk.background_vert,
  8531. fragmentShader: ShaderChunk.background_frag
  8532. },
  8533. cube: {
  8534. uniforms: /*@__PURE__*/ mergeUniforms( [
  8535. UniformsLib.envmap,
  8536. {
  8537. opacity: { value: 1.0 }
  8538. }
  8539. ] ),
  8540. vertexShader: ShaderChunk.cube_vert,
  8541. fragmentShader: ShaderChunk.cube_frag
  8542. },
  8543. equirect: {
  8544. uniforms: {
  8545. tEquirect: { value: null },
  8546. },
  8547. vertexShader: ShaderChunk.equirect_vert,
  8548. fragmentShader: ShaderChunk.equirect_frag
  8549. },
  8550. distanceRGBA: {
  8551. uniforms: /*@__PURE__*/ mergeUniforms( [
  8552. UniformsLib.common,
  8553. UniformsLib.displacementmap,
  8554. {
  8555. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8556. nearDistance: { value: 1 },
  8557. farDistance: { value: 1000 }
  8558. }
  8559. ] ),
  8560. vertexShader: ShaderChunk.distanceRGBA_vert,
  8561. fragmentShader: ShaderChunk.distanceRGBA_frag
  8562. },
  8563. shadow: {
  8564. uniforms: /*@__PURE__*/ mergeUniforms( [
  8565. UniformsLib.lights,
  8566. UniformsLib.fog,
  8567. {
  8568. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8569. opacity: { value: 1.0 }
  8570. },
  8571. ] ),
  8572. vertexShader: ShaderChunk.shadow_vert,
  8573. fragmentShader: ShaderChunk.shadow_frag
  8574. }
  8575. };
  8576. ShaderLib.physical = {
  8577. uniforms: /*@__PURE__*/ mergeUniforms( [
  8578. ShaderLib.standard.uniforms,
  8579. {
  8580. clearcoat: { value: 0 },
  8581. clearcoatMap: { value: null },
  8582. clearcoatRoughness: { value: 0 },
  8583. clearcoatRoughnessMap: { value: null },
  8584. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8585. clearcoatNormalMap: { value: null },
  8586. iridescence: { value: 0 },
  8587. iridescenceMap: { value: null },
  8588. iridescenceIOR: { value: 1.3 },
  8589. iridescenceThicknessMinimum: { value: 100 },
  8590. iridescenceThicknessMaximum: { value: 400 },
  8591. iridescenceThicknessMap: { value: null },
  8592. sheen: { value: 0 },
  8593. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8594. sheenColorMap: { value: null },
  8595. sheenRoughness: { value: 1 },
  8596. sheenRoughnessMap: { value: null },
  8597. transmission: { value: 0 },
  8598. transmissionMap: { value: null },
  8599. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8600. transmissionSamplerMap: { value: null },
  8601. thickness: { value: 0 },
  8602. thicknessMap: { value: null },
  8603. attenuationDistance: { value: 0 },
  8604. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8605. specularIntensity: { value: 1 },
  8606. specularIntensityMap: { value: null },
  8607. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8608. specularColorMap: { value: null },
  8609. }
  8610. ] ),
  8611. vertexShader: ShaderChunk.meshphysical_vert,
  8612. fragmentShader: ShaderChunk.meshphysical_frag
  8613. };
  8614. function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
  8615. const clearColor = new Color( 0x000000 );
  8616. let clearAlpha = alpha === true ? 0 : 1;
  8617. let planeMesh;
  8618. let boxMesh;
  8619. let currentBackground = null;
  8620. let currentBackgroundVersion = 0;
  8621. let currentTonemapping = null;
  8622. function render( renderList, scene ) {
  8623. let forceClear = false;
  8624. let background = scene.isScene === true ? scene.background : null;
  8625. // console.log("background: ",background)
  8626. if ( background && background.isTexture ) {
  8627. // console.log("background.isTexture1111")
  8628. background = cubemaps.get( background );
  8629. }
  8630. // Ignore background in AR
  8631. // TODO: Reconsider this.
  8632. const xr = renderer.xr;
  8633. const session = xr.getSession && xr.getSession();
  8634. if ( session && session.environmentBlendMode === 'additive' ) {
  8635. background = null;
  8636. }
  8637. if ( background === null ) {
  8638. setClear( clearColor, clearAlpha );
  8639. } else if ( background && background.isColor ) {
  8640. setClear( background, 1 );
  8641. forceClear = true;
  8642. }
  8643. if ( renderer.autoClear || forceClear ) {
  8644. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8645. }
  8646. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8647. if ( boxMesh === undefined ) {
  8648. boxMesh = new Mesh(
  8649. new BoxGeometry( 1, 1, 1 ),
  8650. new ShaderMaterial( {
  8651. name: 'BackgroundCubeMaterial',
  8652. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8653. vertexShader: ShaderLib.cube.vertexShader,
  8654. fragmentShader: ShaderLib.cube.fragmentShader,
  8655. side: BackSide,
  8656. depthTest: false,
  8657. depthWrite: false,
  8658. fog: false
  8659. } )
  8660. );
  8661. boxMesh.geometry.deleteAttribute( 'normal' );
  8662. boxMesh.geometry.deleteAttribute( 'uv' );
  8663. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8664. this.matrixWorld.copyPosition( camera.matrixWorld );
  8665. };
  8666. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8667. Object.defineProperty( boxMesh.material, 'envMap', {
  8668. get: function () {
  8669. return this.uniforms.envMap.value;
  8670. }
  8671. } );
  8672. objects.update( boxMesh );
  8673. }
  8674. boxMesh.material.uniforms.envMap.value = background;
  8675. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8676. if ( currentBackground !== background ||
  8677. currentBackgroundVersion !== background.version ||
  8678. currentTonemapping !== renderer.toneMapping ) {
  8679. boxMesh.material.needsUpdate = true;
  8680. currentBackground = background;
  8681. currentBackgroundVersion = background.version;
  8682. currentTonemapping = renderer.toneMapping;
  8683. }
  8684. boxMesh.layers.enableAll();
  8685. // push to the pre-sorted opaque render list
  8686. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8687. } else if ( background && background.isTexture ) {
  8688. if ( planeMesh === undefined ) {
  8689. planeMesh = new Mesh(
  8690. new PlaneGeometry( 2, 2 ),
  8691. new ShaderMaterial( {
  8692. name: 'BackgroundMaterial',
  8693. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8694. vertexShader: ShaderLib.background.vertexShader,
  8695. fragmentShader: ShaderLib.background.fragmentShader,
  8696. side: FrontSide,
  8697. depthTest: false,
  8698. depthWrite: false,
  8699. fog: false
  8700. } )
  8701. );
  8702. planeMesh.geometry.deleteAttribute( 'normal' );
  8703. // add "map" material property so the renderer can evaluate it like for built-in materials
  8704. Object.defineProperty( planeMesh.material, 'map', {
  8705. get: function () {
  8706. return this.uniforms.t2D.value;
  8707. }
  8708. } );
  8709. objects.update( planeMesh );
  8710. }
  8711. planeMesh.material.uniforms.t2D.value = background;
  8712. if ( background.matrixAutoUpdate === true ) {
  8713. background.updateMatrix();
  8714. }
  8715. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8716. if ( currentBackground !== background ||
  8717. currentBackgroundVersion !== background.version ||
  8718. currentTonemapping !== renderer.toneMapping ) {
  8719. planeMesh.material.needsUpdate = true;
  8720. currentBackground = background;
  8721. currentBackgroundVersion = background.version;
  8722. currentTonemapping = renderer.toneMapping;
  8723. }
  8724. planeMesh.layers.enableAll();
  8725. // push to the pre-sorted opaque render list
  8726. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8727. }
  8728. }
  8729. function setClear( color, alpha ) {
  8730. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8731. }
  8732. return {
  8733. getClearColor: function () {
  8734. return clearColor;
  8735. },
  8736. setClearColor: function ( color, alpha = 1 ) {
  8737. clearColor.set( color );
  8738. clearAlpha = alpha;
  8739. setClear( clearColor, clearAlpha );
  8740. },
  8741. getClearAlpha: function () {
  8742. return clearAlpha;
  8743. },
  8744. setClearAlpha: function ( alpha ) {
  8745. clearAlpha = alpha;
  8746. setClear( clearColor, clearAlpha );
  8747. },
  8748. render: render
  8749. };
  8750. }
  8751. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8752. const maxVertexAttributes = gl.getParameter( 34921 );
  8753. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8754. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8755. const bindingStates = {};
  8756. const defaultState = createBindingState( null );
  8757. let currentState = defaultState;
  8758. let forceUpdate = false;
  8759. function setup( object, material, program, geometry, index ) {
  8760. let updateBuffers = false;
  8761. if ( vaoAvailable ) {
  8762. const state = getBindingState( geometry, program, material );
  8763. if ( currentState !== state ) {
  8764. currentState = state;
  8765. bindVertexArrayObject( currentState.object );
  8766. }
  8767. updateBuffers = needsUpdate( object, geometry, program, index );
  8768. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8769. } else {
  8770. const wireframe = ( material.wireframe === true );
  8771. if ( currentState.geometry !== geometry.id ||
  8772. currentState.program !== program.id ||
  8773. currentState.wireframe !== wireframe ) {
  8774. currentState.geometry = geometry.id;
  8775. currentState.program = program.id;
  8776. currentState.wireframe = wireframe;
  8777. updateBuffers = true;
  8778. }
  8779. }
  8780. if ( index !== null ) {
  8781. attributes.update( index, 34963 );
  8782. }
  8783. if ( updateBuffers || forceUpdate ) {
  8784. forceUpdate = false;
  8785. setupVertexAttributes( object, material, program, geometry );
  8786. if ( index !== null ) {
  8787. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8788. }
  8789. }
  8790. }
  8791. function createVertexArrayObject() {
  8792. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8793. return extension.createVertexArrayOES();
  8794. }
  8795. function bindVertexArrayObject( vao ) {
  8796. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8797. return extension.bindVertexArrayOES( vao );
  8798. }
  8799. function deleteVertexArrayObject( vao ) {
  8800. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8801. return extension.deleteVertexArrayOES( vao );
  8802. }
  8803. function getBindingState( geometry, program, material ) {
  8804. const wireframe = ( material.wireframe === true );
  8805. let programMap = bindingStates[ geometry.id ];
  8806. if ( programMap === undefined ) {
  8807. programMap = {};
  8808. bindingStates[ geometry.id ] = programMap;
  8809. }
  8810. let stateMap = programMap[ program.id ];
  8811. if ( stateMap === undefined ) {
  8812. stateMap = {};
  8813. programMap[ program.id ] = stateMap;
  8814. }
  8815. let state = stateMap[ wireframe ];
  8816. if ( state === undefined ) {
  8817. state = createBindingState( createVertexArrayObject() );
  8818. stateMap[ wireframe ] = state;
  8819. }
  8820. return state;
  8821. }
  8822. function createBindingState( vao ) {
  8823. const newAttributes = [];
  8824. const enabledAttributes = [];
  8825. const attributeDivisors = [];
  8826. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8827. newAttributes[ i ] = 0;
  8828. enabledAttributes[ i ] = 0;
  8829. attributeDivisors[ i ] = 0;
  8830. }
  8831. return {
  8832. // for backward compatibility on non-VAO support browser
  8833. geometry: null,
  8834. program: null,
  8835. wireframe: false,
  8836. newAttributes: newAttributes,
  8837. enabledAttributes: enabledAttributes,
  8838. attributeDivisors: attributeDivisors,
  8839. object: vao,
  8840. attributes: {},
  8841. index: null
  8842. };
  8843. }
  8844. function needsUpdate( object, geometry, program, index ) {
  8845. const cachedAttributes = currentState.attributes;
  8846. const geometryAttributes = geometry.attributes;
  8847. let attributesNum = 0;
  8848. const programAttributes = program.getAttributes();
  8849. for ( const name in programAttributes ) {
  8850. const programAttribute = programAttributes[ name ];
  8851. if ( programAttribute.location >= 0 ) {
  8852. const cachedAttribute = cachedAttributes[ name ];
  8853. let geometryAttribute = geometryAttributes[ name ];
  8854. if ( geometryAttribute === undefined ) {
  8855. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8856. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8857. }
  8858. if ( cachedAttribute === undefined ) return true;
  8859. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8860. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8861. attributesNum ++;
  8862. }
  8863. }
  8864. if ( currentState.attributesNum !== attributesNum ) return true;
  8865. if ( currentState.index !== index ) return true;
  8866. return false;
  8867. }
  8868. function saveCache( object, geometry, program, index ) {
  8869. const cache = {};
  8870. const attributes = geometry.attributes;
  8871. let attributesNum = 0;
  8872. const programAttributes = program.getAttributes();
  8873. for ( const name in programAttributes ) {
  8874. const programAttribute = programAttributes[ name ];
  8875. if ( programAttribute.location >= 0 ) {
  8876. let attribute = attributes[ name ];
  8877. if ( attribute === undefined ) {
  8878. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8879. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8880. }
  8881. const data = {};
  8882. data.attribute = attribute;
  8883. if ( attribute && attribute.data ) {
  8884. data.data = attribute.data;
  8885. }
  8886. cache[ name ] = data;
  8887. attributesNum ++;
  8888. }
  8889. }
  8890. currentState.attributes = cache;
  8891. currentState.attributesNum = attributesNum;
  8892. currentState.index = index;
  8893. }
  8894. function initAttributes() {
  8895. const newAttributes = currentState.newAttributes;
  8896. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8897. newAttributes[ i ] = 0;
  8898. }
  8899. }
  8900. function enableAttribute( attribute ) {
  8901. enableAttributeAndDivisor( attribute, 0 );
  8902. }
  8903. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8904. const newAttributes = currentState.newAttributes;
  8905. const enabledAttributes = currentState.enabledAttributes;
  8906. const attributeDivisors = currentState.attributeDivisors;
  8907. newAttributes[ attribute ] = 1;
  8908. if ( enabledAttributes[ attribute ] === 0 ) {
  8909. gl.enableVertexAttribArray( attribute );
  8910. enabledAttributes[ attribute ] = 1;
  8911. }
  8912. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8913. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8914. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8915. attributeDivisors[ attribute ] = meshPerAttribute;
  8916. }
  8917. }
  8918. function disableUnusedAttributes() {
  8919. const newAttributes = currentState.newAttributes;
  8920. const enabledAttributes = currentState.enabledAttributes;
  8921. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8922. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8923. gl.disableVertexAttribArray( i );
  8924. enabledAttributes[ i ] = 0;
  8925. }
  8926. }
  8927. }
  8928. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8929. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8930. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8931. } else {
  8932. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8933. }
  8934. }
  8935. function setupVertexAttributes( object, material, program, geometry ) {
  8936. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8937. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8938. }
  8939. initAttributes();
  8940. const geometryAttributes = geometry.attributes;
  8941. const programAttributes = program.getAttributes();
  8942. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8943. for ( const name in programAttributes ) {
  8944. const programAttribute = programAttributes[ name ];
  8945. if ( programAttribute.location >= 0 ) {
  8946. let geometryAttribute = geometryAttributes[ name ];
  8947. if ( geometryAttribute === undefined ) {
  8948. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8949. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8950. }
  8951. if ( geometryAttribute !== undefined ) {
  8952. const normalized = geometryAttribute.normalized;
  8953. const size = geometryAttribute.itemSize;
  8954. const attribute = attributes.get( geometryAttribute );
  8955. // TODO Attribute may not be available on context restore
  8956. if ( attribute === undefined ) continue;
  8957. const buffer = attribute.buffer;
  8958. const type = attribute.type;
  8959. const bytesPerElement = attribute.bytesPerElement;
  8960. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8961. const data = geometryAttribute.data;
  8962. const stride = data.stride;
  8963. const offset = geometryAttribute.offset;
  8964. if ( data.isInstancedInterleavedBuffer ) {
  8965. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8966. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8967. }
  8968. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8969. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8970. }
  8971. } else {
  8972. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8973. enableAttribute( programAttribute.location + i );
  8974. }
  8975. }
  8976. gl.bindBuffer( 34962, buffer );
  8977. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8978. vertexAttribPointer(
  8979. programAttribute.location + i,
  8980. size / programAttribute.locationSize,
  8981. type,
  8982. normalized,
  8983. stride * bytesPerElement,
  8984. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8985. );
  8986. }
  8987. } else {
  8988. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8989. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8990. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8991. }
  8992. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8993. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8994. }
  8995. } else {
  8996. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8997. enableAttribute( programAttribute.location + i );
  8998. }
  8999. }
  9000. gl.bindBuffer( 34962, buffer );
  9001. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9002. vertexAttribPointer(
  9003. programAttribute.location + i,
  9004. size / programAttribute.locationSize,
  9005. type,
  9006. normalized,
  9007. size * bytesPerElement,
  9008. ( size / programAttribute.locationSize ) * i * bytesPerElement
  9009. );
  9010. }
  9011. }
  9012. } else if ( materialDefaultAttributeValues !== undefined ) {
  9013. const value = materialDefaultAttributeValues[ name ];
  9014. if ( value !== undefined ) {
  9015. switch ( value.length ) {
  9016. case 2:
  9017. gl.vertexAttrib2fv( programAttribute.location, value );
  9018. break;
  9019. case 3:
  9020. gl.vertexAttrib3fv( programAttribute.location, value );
  9021. break;
  9022. case 4:
  9023. gl.vertexAttrib4fv( programAttribute.location, value );
  9024. break;
  9025. default:
  9026. gl.vertexAttrib1fv( programAttribute.location, value );
  9027. }
  9028. }
  9029. }
  9030. }
  9031. }
  9032. disableUnusedAttributes();
  9033. }
  9034. function dispose() {
  9035. reset();
  9036. for ( const geometryId in bindingStates ) {
  9037. const programMap = bindingStates[ geometryId ];
  9038. for ( const programId in programMap ) {
  9039. const stateMap = programMap[ programId ];
  9040. for ( const wireframe in stateMap ) {
  9041. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9042. delete stateMap[ wireframe ];
  9043. }
  9044. delete programMap[ programId ];
  9045. }
  9046. delete bindingStates[ geometryId ];
  9047. }
  9048. }
  9049. function releaseStatesOfGeometry( geometry ) {
  9050. if ( bindingStates[ geometry.id ] === undefined ) return;
  9051. const programMap = bindingStates[ geometry.id ];
  9052. for ( const programId in programMap ) {
  9053. const stateMap = programMap[ programId ];
  9054. for ( const wireframe in stateMap ) {
  9055. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9056. delete stateMap[ wireframe ];
  9057. }
  9058. delete programMap[ programId ];
  9059. }
  9060. delete bindingStates[ geometry.id ];
  9061. }
  9062. function releaseStatesOfProgram( program ) {
  9063. for ( const geometryId in bindingStates ) {
  9064. const programMap = bindingStates[ geometryId ];
  9065. if ( programMap[ program.id ] === undefined ) continue;
  9066. const stateMap = programMap[ program.id ];
  9067. for ( const wireframe in stateMap ) {
  9068. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9069. delete stateMap[ wireframe ];
  9070. }
  9071. delete programMap[ program.id ];
  9072. }
  9073. }
  9074. function reset() {
  9075. resetDefaultState();
  9076. forceUpdate = true;
  9077. if ( currentState === defaultState ) return;
  9078. currentState = defaultState;
  9079. bindVertexArrayObject( currentState.object );
  9080. }
  9081. // for backward-compatibility
  9082. function resetDefaultState() {
  9083. defaultState.geometry = null;
  9084. defaultState.program = null;
  9085. defaultState.wireframe = false;
  9086. }
  9087. return {
  9088. setup: setup,
  9089. reset: reset,
  9090. resetDefaultState: resetDefaultState,
  9091. dispose: dispose,
  9092. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9093. releaseStatesOfProgram: releaseStatesOfProgram,
  9094. initAttributes: initAttributes,
  9095. enableAttribute: enableAttribute,
  9096. disableUnusedAttributes: disableUnusedAttributes
  9097. };
  9098. }
  9099. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9100. const isWebGL2 = capabilities.isWebGL2;
  9101. let mode;
  9102. function setMode( value ) {
  9103. mode = value;
  9104. }
  9105. function render( start, count ) {
  9106. gl.drawArrays( mode, start, count );
  9107. info.update( count, mode, 1 );
  9108. }
  9109. function renderInstances( start, count, primcount ) {
  9110. if ( primcount === 0 ) return;
  9111. let extension, methodName;
  9112. if ( isWebGL2 ) {
  9113. extension = gl;
  9114. methodName = 'drawArraysInstanced';
  9115. } else {
  9116. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9117. methodName = 'drawArraysInstancedANGLE';
  9118. if ( extension === null ) {
  9119. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9120. return;
  9121. }
  9122. }
  9123. extension[ methodName ]( mode, start, count, primcount );
  9124. info.update( count, mode, primcount );
  9125. }
  9126. //
  9127. this.setMode = setMode;
  9128. this.render = render;
  9129. this.renderInstances = renderInstances;
  9130. }
  9131. function WebGLCapabilities( gl, extensions, parameters ) {
  9132. let maxAnisotropy;
  9133. function getMaxAnisotropy() {
  9134. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9135. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9136. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9137. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9138. } else {
  9139. maxAnisotropy = 0;
  9140. }
  9141. return maxAnisotropy;
  9142. }
  9143. function getMaxPrecision( precision ) {
  9144. if ( precision === 'highp' ) {
  9145. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9146. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9147. return 'highp';
  9148. }
  9149. precision = 'mediump';
  9150. }
  9151. if ( precision === 'mediump' ) {
  9152. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9153. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9154. return 'mediump';
  9155. }
  9156. }
  9157. return 'lowp';
  9158. }
  9159. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  9160. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  9161. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9162. const maxPrecision = getMaxPrecision( precision );
  9163. if ( maxPrecision !== precision ) {
  9164. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9165. precision = maxPrecision;
  9166. }
  9167. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9168. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9169. const maxTextures = gl.getParameter( 34930 );
  9170. const maxVertexTextures = gl.getParameter( 35660 );
  9171. const maxTextureSize = gl.getParameter( 3379 );
  9172. const maxCubemapSize = gl.getParameter( 34076 );
  9173. const maxAttributes = gl.getParameter( 34921 );
  9174. const maxVertexUniforms = gl.getParameter( 36347 );
  9175. const maxVaryings = gl.getParameter( 36348 );
  9176. const maxFragmentUniforms = gl.getParameter( 36349 );
  9177. const vertexTextures = maxVertexTextures > 0;
  9178. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9179. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9180. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9181. return {
  9182. isWebGL2: isWebGL2,
  9183. drawBuffers: drawBuffers,
  9184. getMaxAnisotropy: getMaxAnisotropy,
  9185. getMaxPrecision: getMaxPrecision,
  9186. precision: precision,
  9187. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9188. maxTextures: maxTextures,
  9189. maxVertexTextures: maxVertexTextures,
  9190. maxTextureSize: maxTextureSize,
  9191. maxCubemapSize: maxCubemapSize,
  9192. maxAttributes: maxAttributes,
  9193. maxVertexUniforms: maxVertexUniforms,
  9194. maxVaryings: maxVaryings,
  9195. maxFragmentUniforms: maxFragmentUniforms,
  9196. vertexTextures: vertexTextures,
  9197. floatFragmentTextures: floatFragmentTextures,
  9198. floatVertexTextures: floatVertexTextures,
  9199. maxSamples: maxSamples
  9200. };
  9201. }
  9202. function WebGLClipping( properties ) {
  9203. const scope = this;
  9204. let globalState = null,
  9205. numGlobalPlanes = 0,
  9206. localClippingEnabled = false,
  9207. renderingShadows = false;
  9208. const plane = new Plane(),
  9209. viewNormalMatrix = new Matrix3(),
  9210. uniform = { value: null, needsUpdate: false };
  9211. this.uniform = uniform;
  9212. this.numPlanes = 0;
  9213. this.numIntersection = 0;
  9214. this.init = function ( planes, enableLocalClipping, camera ) {
  9215. const enabled =
  9216. planes.length !== 0 ||
  9217. enableLocalClipping ||
  9218. // enable state of previous frame - the clipping code has to
  9219. // run another frame in order to reset the state:
  9220. numGlobalPlanes !== 0 ||
  9221. localClippingEnabled;
  9222. localClippingEnabled = enableLocalClipping;
  9223. globalState = projectPlanes( planes, camera, 0 );
  9224. numGlobalPlanes = planes.length;
  9225. return enabled;
  9226. };
  9227. this.beginShadows = function () {
  9228. renderingShadows = true;
  9229. projectPlanes( null );
  9230. };
  9231. this.endShadows = function () {
  9232. renderingShadows = false;
  9233. resetGlobalState();
  9234. };
  9235. this.setState = function ( material, camera, useCache ) {
  9236. const planes = material.clippingPlanes,
  9237. clipIntersection = material.clipIntersection,
  9238. clipShadows = material.clipShadows;
  9239. const materialProperties = properties.get( material );
  9240. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9241. // there's no local clipping
  9242. if ( renderingShadows ) {
  9243. // there's no global clipping
  9244. projectPlanes( null );
  9245. } else {
  9246. resetGlobalState();
  9247. }
  9248. } else {
  9249. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9250. lGlobal = nGlobal * 4;
  9251. let dstArray = materialProperties.clippingState || null;
  9252. uniform.value = dstArray; // ensure unique state
  9253. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9254. for ( let i = 0; i !== lGlobal; ++ i ) {
  9255. dstArray[ i ] = globalState[ i ];
  9256. }
  9257. materialProperties.clippingState = dstArray;
  9258. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9259. this.numPlanes += nGlobal;
  9260. }
  9261. };
  9262. function resetGlobalState() {
  9263. if ( uniform.value !== globalState ) {
  9264. uniform.value = globalState;
  9265. uniform.needsUpdate = numGlobalPlanes > 0;
  9266. }
  9267. scope.numPlanes = numGlobalPlanes;
  9268. scope.numIntersection = 0;
  9269. }
  9270. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9271. const nPlanes = planes !== null ? planes.length : 0;
  9272. let dstArray = null;
  9273. if ( nPlanes !== 0 ) {
  9274. dstArray = uniform.value;
  9275. if ( skipTransform !== true || dstArray === null ) {
  9276. const flatSize = dstOffset + nPlanes * 4,
  9277. viewMatrix = camera.matrixWorldInverse;
  9278. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9279. if ( dstArray === null || dstArray.length < flatSize ) {
  9280. dstArray = new Float32Array( flatSize );
  9281. }
  9282. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9283. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9284. plane.normal.toArray( dstArray, i4 );
  9285. dstArray[ i4 + 3 ] = plane.constant;
  9286. }
  9287. }
  9288. uniform.value = dstArray;
  9289. uniform.needsUpdate = true;
  9290. }
  9291. scope.numPlanes = nPlanes;
  9292. scope.numIntersection = 0;
  9293. return dstArray;
  9294. }
  9295. }
  9296. function WebGLCubeMaps( renderer ) {
  9297. let cubemaps = new WeakMap();
  9298. function mapTextureMapping( texture, mapping ) {
  9299. if ( mapping === EquirectangularReflectionMapping ) {
  9300. texture.mapping = CubeReflectionMapping;
  9301. } else if ( mapping === EquirectangularRefractionMapping ) {
  9302. texture.mapping = CubeRefractionMapping;
  9303. }
  9304. return texture;
  9305. }
  9306. function get( texture ) {
  9307. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9308. const mapping = texture.mapping;
  9309. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9310. if ( cubemaps.has( texture ) ) {
  9311. const cubemap = cubemaps.get( texture ).texture;
  9312. return mapTextureMapping( cubemap, texture.mapping );
  9313. } else {
  9314. const image = texture.image;
  9315. if ( image && image.height > 0 ) {
  9316. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9317. renderTarget.fromEquirectangularTexture( renderer, texture );
  9318. cubemaps.set( texture, renderTarget );
  9319. texture.addEventListener( 'dispose', onTextureDispose );
  9320. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9321. } else {
  9322. // image not yet ready. try the conversion next frame
  9323. return null;
  9324. }
  9325. }
  9326. }
  9327. }
  9328. return texture;
  9329. }
  9330. function onTextureDispose( event ) {
  9331. const texture = event.target;
  9332. texture.removeEventListener( 'dispose', onTextureDispose );
  9333. const cubemap = cubemaps.get( texture );
  9334. if ( cubemap !== undefined ) {
  9335. cubemaps.delete( texture );
  9336. cubemap.dispose();
  9337. }
  9338. }
  9339. function dispose() {
  9340. cubemaps = new WeakMap();
  9341. }
  9342. return {
  9343. get: get,
  9344. dispose: dispose
  9345. };
  9346. }
  9347. class OrthographicCamera extends Camera {
  9348. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9349. super();
  9350. this.isOrthographicCamera = true;
  9351. this.type = 'OrthographicCamera';
  9352. this.zoom = 1;
  9353. this.view = null;
  9354. this.left = left;
  9355. this.right = right;
  9356. this.top = top;
  9357. this.bottom = bottom;
  9358. this.near = near;
  9359. this.far = far;
  9360. this.updateProjectionMatrix();
  9361. }
  9362. copy( source, recursive ) {
  9363. super.copy( source, recursive );
  9364. this.left = source.left;
  9365. this.right = source.right;
  9366. this.top = source.top;
  9367. this.bottom = source.bottom;
  9368. this.near = source.near;
  9369. this.far = source.far;
  9370. this.zoom = source.zoom;
  9371. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9372. return this;
  9373. }
  9374. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9375. if ( this.view === null ) {
  9376. this.view = {
  9377. enabled: true,
  9378. fullWidth: 1,
  9379. fullHeight: 1,
  9380. offsetX: 0,
  9381. offsetY: 0,
  9382. width: 1,
  9383. height: 1
  9384. };
  9385. }
  9386. this.view.enabled = true;
  9387. this.view.fullWidth = fullWidth;
  9388. this.view.fullHeight = fullHeight;
  9389. this.view.offsetX = x;
  9390. this.view.offsetY = y;
  9391. this.view.width = width;
  9392. this.view.height = height;
  9393. this.updateProjectionMatrix();
  9394. }
  9395. clearViewOffset() {
  9396. if ( this.view !== null ) {
  9397. this.view.enabled = false;
  9398. }
  9399. this.updateProjectionMatrix();
  9400. }
  9401. updateProjectionMatrix() {
  9402. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9403. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9404. const cx = ( this.right + this.left ) / 2;
  9405. const cy = ( this.top + this.bottom ) / 2;
  9406. let left = cx - dx;
  9407. let right = cx + dx;
  9408. let top = cy + dy;
  9409. let bottom = cy - dy;
  9410. if ( this.view !== null && this.view.enabled ) {
  9411. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9412. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9413. left += scaleW * this.view.offsetX;
  9414. right = left + scaleW * this.view.width;
  9415. top -= scaleH * this.view.offsetY;
  9416. bottom = top - scaleH * this.view.height;
  9417. }
  9418. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9419. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9420. }
  9421. toJSON( meta ) {
  9422. const data = super.toJSON( meta );
  9423. data.object.zoom = this.zoom;
  9424. data.object.left = this.left;
  9425. data.object.right = this.right;
  9426. data.object.top = this.top;
  9427. data.object.bottom = this.bottom;
  9428. data.object.near = this.near;
  9429. data.object.far = this.far;
  9430. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9431. return data;
  9432. }
  9433. }
  9434. const LOD_MIN = 4;
  9435. // The standard deviations (radians) associated with the extra mips. These are
  9436. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9437. // geometric shadowing function. These sigma values squared must match the
  9438. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9439. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9440. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9441. // samples and exit early, but not recompile the shader.
  9442. const MAX_SAMPLES = 20;
  9443. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9444. const _clearColor = /*@__PURE__*/ new Color();
  9445. let _oldTarget = null;
  9446. // Golden Ratio
  9447. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9448. const INV_PHI = 1 / PHI;
  9449. // Vertices of a dodecahedron (except the opposites, which represent the
  9450. // same axis), used as axis directions evenly spread on a sphere.
  9451. const _axisDirections = [
  9452. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9453. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9454. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9455. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9456. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9457. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9458. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9459. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9460. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9461. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9462. /**
  9463. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9464. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9465. * blur to be quickly accessed based on material roughness. It is packed into a
  9466. * special CubeUV format that allows us to perform custom interpolation so that
  9467. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9468. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9469. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9470. * higher roughness levels. In this way we maintain resolution to smoothly
  9471. * interpolate diffuse lighting while limiting sampling computation.
  9472. *
  9473. * Paper: Fast, Accurate Image-Based Lighting
  9474. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9475. */
  9476. class PMREMGenerator {
  9477. constructor( renderer ) {
  9478. this._renderer = renderer;
  9479. this._pingPongRenderTarget = null;
  9480. this._lodMax = 0;
  9481. this._cubeSize = 0;
  9482. this._lodPlanes = [];
  9483. this._sizeLods = [];
  9484. this._sigmas = [];
  9485. this._blurMaterial = null;
  9486. this._cubemapMaterial = null;
  9487. this._equirectMaterial = null;
  9488. this._compileMaterial( this._blurMaterial );
  9489. }
  9490. /**
  9491. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9492. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9493. * in radians to be applied to the scene before PMREM generation. Optional near
  9494. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9495. * is placed at the origin).
  9496. */
  9497. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9498. _oldTarget = this._renderer.getRenderTarget();
  9499. this._setSize( 256 );
  9500. const cubeUVRenderTarget = this._allocateTargets();
  9501. cubeUVRenderTarget.depthBuffer = true;
  9502. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9503. if ( sigma > 0 ) {
  9504. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9505. }
  9506. this._applyPMREM( cubeUVRenderTarget );
  9507. this._cleanup( cubeUVRenderTarget );
  9508. return cubeUVRenderTarget;
  9509. }
  9510. /**
  9511. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9512. * or HDR. The ideal input image size is 1k (1024 x 512),
  9513. * as this matches best with the 256 x 256 cubemap output.
  9514. */
  9515. fromEquirectangular( equirectangular, renderTarget = null ) {
  9516. return this._fromTexture( equirectangular, renderTarget );
  9517. }
  9518. /**
  9519. * Generates a PMREM from an cubemap texture, which can be either LDR
  9520. * or HDR. The ideal input cube size is 256 x 256,
  9521. * as this matches best with the 256 x 256 cubemap output.
  9522. */
  9523. fromCubemap( cubemap, renderTarget = null ) {
  9524. return this._fromTexture( cubemap, renderTarget );
  9525. }
  9526. /**
  9527. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9528. * your texture's network fetch for increased concurrency.
  9529. */
  9530. compileCubemapShader() {
  9531. if ( this._cubemapMaterial === null ) {
  9532. this._cubemapMaterial = _getCubemapMaterial();
  9533. this._compileMaterial( this._cubemapMaterial );
  9534. }
  9535. }
  9536. /**
  9537. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9538. * your texture's network fetch for increased concurrency.
  9539. */
  9540. compileEquirectangularShader() {
  9541. if ( this._equirectMaterial === null ) {
  9542. this._equirectMaterial = _getEquirectMaterial();
  9543. this._compileMaterial( this._equirectMaterial );
  9544. }
  9545. }
  9546. /**
  9547. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9548. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9549. * one of them will cause any others to also become unusable.
  9550. */
  9551. dispose() {
  9552. this._dispose();
  9553. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9554. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9555. }
  9556. // private interface
  9557. _setSize( cubeSize ) {
  9558. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9559. this._cubeSize = Math.pow( 2, this._lodMax );
  9560. }
  9561. _dispose() {
  9562. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9563. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9564. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9565. this._lodPlanes[ i ].dispose();
  9566. }
  9567. }
  9568. _cleanup( outputTarget ) {
  9569. this._renderer.setRenderTarget( _oldTarget );
  9570. outputTarget.scissorTest = false;
  9571. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9572. }
  9573. _fromTexture( texture, renderTarget ) {
  9574. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9575. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9576. } else { // Equirectangular
  9577. this._setSize( texture.image.width / 4 );
  9578. }
  9579. _oldTarget = this._renderer.getRenderTarget();
  9580. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9581. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9582. this._applyPMREM( cubeUVRenderTarget );
  9583. this._cleanup( cubeUVRenderTarget );
  9584. return cubeUVRenderTarget;
  9585. }
  9586. _allocateTargets() {
  9587. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9588. const height = 4 * this._cubeSize;
  9589. const params = {
  9590. magFilter: LinearFilter,
  9591. minFilter: LinearFilter,
  9592. generateMipmaps: false,
  9593. type: HalfFloatType,
  9594. format: RGBAFormat,
  9595. encoding: LinearEncoding,
  9596. depthBuffer: false
  9597. };
  9598. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9599. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width ) {
  9600. if ( this._pingPongRenderTarget !== null ) {
  9601. this._dispose();
  9602. }
  9603. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9604. const { _lodMax } = this;
  9605. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9606. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9607. }
  9608. return cubeUVRenderTarget;
  9609. }
  9610. _compileMaterial( material ) {
  9611. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9612. this._renderer.compile( tmpMesh, _flatCamera );
  9613. }
  9614. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9615. const fov = 90;
  9616. const aspect = 1;
  9617. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9618. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9619. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9620. const renderer = this._renderer;
  9621. const originalAutoClear = renderer.autoClear;
  9622. const toneMapping = renderer.toneMapping;
  9623. renderer.getClearColor( _clearColor );
  9624. renderer.toneMapping = NoToneMapping;
  9625. renderer.autoClear = false;
  9626. const backgroundMaterial = new MeshBasicMaterial( {
  9627. name: 'PMREM.Background',
  9628. side: BackSide,
  9629. depthWrite: false,
  9630. depthTest: false,
  9631. } );
  9632. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9633. let useSolidColor = false;
  9634. const background = scene.background;
  9635. if ( background ) {
  9636. if ( background.isColor ) {
  9637. backgroundMaterial.color.copy( background );
  9638. scene.background = null;
  9639. useSolidColor = true;
  9640. }
  9641. } else {
  9642. backgroundMaterial.color.copy( _clearColor );
  9643. useSolidColor = true;
  9644. }
  9645. for ( let i = 0; i < 6; i ++ ) {
  9646. const col = i % 3;
  9647. if ( col === 0 ) {
  9648. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9649. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9650. } else if ( col === 1 ) {
  9651. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9652. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9653. } else {
  9654. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9655. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9656. }
  9657. const size = this._cubeSize;
  9658. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9659. renderer.setRenderTarget( cubeUVRenderTarget );
  9660. if ( useSolidColor ) {
  9661. renderer.render( backgroundBox, cubeCamera );
  9662. }
  9663. renderer.render( scene, cubeCamera );
  9664. }
  9665. backgroundBox.geometry.dispose();
  9666. backgroundBox.material.dispose();
  9667. renderer.toneMapping = toneMapping;
  9668. renderer.autoClear = originalAutoClear;
  9669. scene.background = background;
  9670. }
  9671. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9672. const renderer = this._renderer;
  9673. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9674. if ( isCubeTexture ) {
  9675. if ( this._cubemapMaterial === null ) {
  9676. this._cubemapMaterial = _getCubemapMaterial();
  9677. }
  9678. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9679. } else {
  9680. if ( this._equirectMaterial === null ) {
  9681. this._equirectMaterial = _getEquirectMaterial();
  9682. }
  9683. }
  9684. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9685. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9686. const uniforms = material.uniforms;
  9687. uniforms[ 'envMap' ].value = texture;
  9688. const size = this._cubeSize;
  9689. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9690. renderer.setRenderTarget( cubeUVRenderTarget );
  9691. renderer.render( mesh, _flatCamera );
  9692. }
  9693. _applyPMREM( cubeUVRenderTarget ) {
  9694. const renderer = this._renderer;
  9695. const autoClear = renderer.autoClear;
  9696. renderer.autoClear = false;
  9697. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9698. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9699. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9700. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9701. }
  9702. renderer.autoClear = autoClear;
  9703. }
  9704. /**
  9705. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9706. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9707. * the blur latitudinally (around the poles), and then longitudinally (towards
  9708. * the poles) to approximate the orthogonally-separable blur. It is least
  9709. * accurate at the poles, but still does a decent job.
  9710. */
  9711. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9712. const pingPongRenderTarget = this._pingPongRenderTarget;
  9713. this._halfBlur(
  9714. cubeUVRenderTarget,
  9715. pingPongRenderTarget,
  9716. lodIn,
  9717. lodOut,
  9718. sigma,
  9719. 'latitudinal',
  9720. poleAxis );
  9721. this._halfBlur(
  9722. pingPongRenderTarget,
  9723. cubeUVRenderTarget,
  9724. lodOut,
  9725. lodOut,
  9726. sigma,
  9727. 'longitudinal',
  9728. poleAxis );
  9729. }
  9730. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9731. const renderer = this._renderer;
  9732. const blurMaterial = this._blurMaterial;
  9733. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9734. console.error(
  9735. 'blur direction must be either latitudinal or longitudinal!' );
  9736. }
  9737. // Number of standard deviations at which to cut off the discrete approximation.
  9738. const STANDARD_DEVIATIONS = 3;
  9739. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9740. const blurUniforms = blurMaterial.uniforms;
  9741. const pixels = this._sizeLods[ lodIn ] - 1;
  9742. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9743. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9744. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9745. if ( samples > MAX_SAMPLES ) {
  9746. console.warn( `sigmaRadians, ${
  9747. sigmaRadians}, is too large and will clip, as it requested ${
  9748. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9749. }
  9750. const weights = [];
  9751. let sum = 0;
  9752. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9753. const x = i / sigmaPixels;
  9754. const weight = Math.exp( - x * x / 2 );
  9755. weights.push( weight );
  9756. if ( i === 0 ) {
  9757. sum += weight;
  9758. } else if ( i < samples ) {
  9759. sum += 2 * weight;
  9760. }
  9761. }
  9762. for ( let i = 0; i < weights.length; i ++ ) {
  9763. weights[ i ] = weights[ i ] / sum;
  9764. }
  9765. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9766. blurUniforms[ 'samples' ].value = samples;
  9767. blurUniforms[ 'weights' ].value = weights;
  9768. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9769. if ( poleAxis ) {
  9770. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9771. }
  9772. const { _lodMax } = this;
  9773. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9774. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9775. const outputSize = this._sizeLods[ lodOut ];
  9776. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9777. const y = 4 * ( this._cubeSize - outputSize );
  9778. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9779. renderer.setRenderTarget( targetOut );
  9780. renderer.render( blurMesh, _flatCamera );
  9781. }
  9782. }
  9783. function _createPlanes( lodMax ) {
  9784. const lodPlanes = [];
  9785. const sizeLods = [];
  9786. const sigmas = [];
  9787. let lod = lodMax;
  9788. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9789. for ( let i = 0; i < totalLods; i ++ ) {
  9790. const sizeLod = Math.pow( 2, lod );
  9791. sizeLods.push( sizeLod );
  9792. let sigma = 1.0 / sizeLod;
  9793. if ( i > lodMax - LOD_MIN ) {
  9794. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9795. } else if ( i === 0 ) {
  9796. sigma = 0;
  9797. }
  9798. sigmas.push( sigma );
  9799. const texelSize = 1.0 / ( sizeLod - 2 );
  9800. const min = - texelSize;
  9801. const max = 1 + texelSize;
  9802. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9803. const cubeFaces = 6;
  9804. const vertices = 6;
  9805. const positionSize = 3;
  9806. const uvSize = 2;
  9807. const faceIndexSize = 1;
  9808. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9809. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9810. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9811. for ( let face = 0; face < cubeFaces; face ++ ) {
  9812. const x = ( face % 3 ) * 2 / 3 - 1;
  9813. const y = face > 2 ? 0 : - 1;
  9814. const coordinates = [
  9815. x, y, 0,
  9816. x + 2 / 3, y, 0,
  9817. x + 2 / 3, y + 1, 0,
  9818. x, y, 0,
  9819. x + 2 / 3, y + 1, 0,
  9820. x, y + 1, 0
  9821. ];
  9822. position.set( coordinates, positionSize * vertices * face );
  9823. uv.set( uv1, uvSize * vertices * face );
  9824. const fill = [ face, face, face, face, face, face ];
  9825. faceIndex.set( fill, faceIndexSize * vertices * face );
  9826. }
  9827. const planes = new BufferGeometry();
  9828. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9829. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9830. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9831. lodPlanes.push( planes );
  9832. if ( lod > LOD_MIN ) {
  9833. lod --;
  9834. }
  9835. }
  9836. return { lodPlanes, sizeLods, sigmas };
  9837. }
  9838. function _createRenderTarget( width, height, params ) {
  9839. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9840. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9841. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9842. cubeUVRenderTarget.scissorTest = true;
  9843. return cubeUVRenderTarget;
  9844. }
  9845. function _setViewport( target, x, y, width, height ) {
  9846. target.viewport.set( x, y, width, height );
  9847. target.scissor.set( x, y, width, height );
  9848. }
  9849. function _getBlurShader( lodMax, width, height ) {
  9850. const weights = new Float32Array( MAX_SAMPLES );
  9851. const poleAxis = new Vector3( 0, 1, 0 );
  9852. const shaderMaterial = new ShaderMaterial( {
  9853. name: 'SphericalGaussianBlur',
  9854. defines: {
  9855. 'n': MAX_SAMPLES,
  9856. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9857. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9858. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9859. },
  9860. uniforms: {
  9861. 'envMap': { value: null },
  9862. 'samples': { value: 1 },
  9863. 'weights': { value: weights },
  9864. 'latitudinal': { value: false },
  9865. 'dTheta': { value: 0 },
  9866. 'mipInt': { value: 0 },
  9867. 'poleAxis': { value: poleAxis }
  9868. },
  9869. vertexShader: _getCommonVertexShader(),
  9870. fragmentShader: /* glsl */`
  9871. precision mediump float;
  9872. precision mediump int;
  9873. varying vec3 vOutputDirection;
  9874. uniform sampler2D envMap;
  9875. uniform int samples;
  9876. uniform float weights[ n ];
  9877. uniform bool latitudinal;
  9878. uniform float dTheta;
  9879. uniform float mipInt;
  9880. uniform vec3 poleAxis;
  9881. #define ENVMAP_TYPE_CUBE_UV
  9882. #include <cube_uv_reflection_fragment>
  9883. vec3 getSample( float theta, vec3 axis ) {
  9884. float cosTheta = cos( theta );
  9885. // Rodrigues' axis-angle rotation
  9886. vec3 sampleDirection = vOutputDirection * cosTheta
  9887. + cross( axis, vOutputDirection ) * sin( theta )
  9888. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9889. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9890. }
  9891. void main() {
  9892. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9893. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9894. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9895. }
  9896. axis = normalize( axis );
  9897. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9898. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9899. for ( int i = 1; i < n; i++ ) {
  9900. if ( i >= samples ) {
  9901. break;
  9902. }
  9903. float theta = dTheta * float( i );
  9904. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9905. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9906. }
  9907. }
  9908. `,
  9909. blending: NoBlending,
  9910. depthTest: false,
  9911. depthWrite: false
  9912. } );
  9913. return shaderMaterial;
  9914. }
  9915. function _getEquirectMaterial() {
  9916. return new ShaderMaterial( {
  9917. name: 'EquirectangularToCubeUV',
  9918. uniforms: {
  9919. 'envMap': { value: null }
  9920. },
  9921. vertexShader: _getCommonVertexShader(),
  9922. fragmentShader: /* glsl */`
  9923. precision mediump float;
  9924. precision mediump int;
  9925. varying vec3 vOutputDirection;
  9926. uniform sampler2D envMap;
  9927. #include <common>
  9928. void main() {
  9929. vec3 outputDirection = normalize( vOutputDirection );
  9930. vec2 uv = equirectUv( outputDirection );
  9931. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9932. }
  9933. `,
  9934. blending: NoBlending,
  9935. depthTest: false,
  9936. depthWrite: false
  9937. } );
  9938. }
  9939. function _getCubemapMaterial() {
  9940. return new ShaderMaterial( {
  9941. name: 'CubemapToCubeUV',
  9942. uniforms: {
  9943. 'envMap': { value: null },
  9944. 'flipEnvMap': { value: - 1 }
  9945. },
  9946. vertexShader: _getCommonVertexShader(),
  9947. fragmentShader: /* glsl */`
  9948. precision mediump float;
  9949. precision mediump int;
  9950. uniform float flipEnvMap;
  9951. varying vec3 vOutputDirection;
  9952. uniform samplerCube envMap;
  9953. void main() {
  9954. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9955. }
  9956. `,
  9957. blending: NoBlending,
  9958. depthTest: false,
  9959. depthWrite: false
  9960. } );
  9961. }
  9962. function _getCommonVertexShader() {
  9963. return /* glsl */`
  9964. precision mediump float;
  9965. precision mediump int;
  9966. attribute float faceIndex;
  9967. varying vec3 vOutputDirection;
  9968. // RH coordinate system; PMREM face-indexing convention
  9969. vec3 getDirection( vec2 uv, float face ) {
  9970. uv = 2.0 * uv - 1.0;
  9971. vec3 direction = vec3( uv, 1.0 );
  9972. if ( face == 0.0 ) {
  9973. direction = direction.zyx; // ( 1, v, u ) pos x
  9974. } else if ( face == 1.0 ) {
  9975. direction = direction.xzy;
  9976. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9977. } else if ( face == 2.0 ) {
  9978. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9979. } else if ( face == 3.0 ) {
  9980. direction = direction.zyx;
  9981. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9982. } else if ( face == 4.0 ) {
  9983. direction = direction.xzy;
  9984. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9985. } else if ( face == 5.0 ) {
  9986. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9987. }
  9988. return direction;
  9989. }
  9990. void main() {
  9991. vOutputDirection = getDirection( uv, faceIndex );
  9992. gl_Position = vec4( position, 1.0 );
  9993. }
  9994. `;
  9995. }
  9996. function WebGLCubeUVMaps( renderer ) {
  9997. let cubeUVmaps = new WeakMap();
  9998. let pmremGenerator = null;
  9999. function get( texture ) {
  10000. if ( texture && texture.isTexture ) {
  10001. const mapping = texture.mapping;
  10002. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10003. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10004. // equirect/cube map to cubeUV conversion
  10005. if ( isEquirectMap || isCubeMap ) {
  10006. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10007. texture.needsPMREMUpdate = false;
  10008. let renderTarget = cubeUVmaps.get( texture );
  10009. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10010. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10011. cubeUVmaps.set( texture, renderTarget );
  10012. return renderTarget.texture;
  10013. } else {
  10014. if ( cubeUVmaps.has( texture ) ) {
  10015. return cubeUVmaps.get( texture ).texture;
  10016. } else {
  10017. const image = texture.image;
  10018. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10019. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10020. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10021. cubeUVmaps.set( texture, renderTarget );
  10022. texture.addEventListener( 'dispose', onTextureDispose );
  10023. return renderTarget.texture;
  10024. } else {
  10025. // image not yet ready. try the conversion next frame
  10026. return null;
  10027. }
  10028. }
  10029. }
  10030. }
  10031. }
  10032. return texture;
  10033. }
  10034. function isCubeTextureComplete( image ) {
  10035. let count = 0;
  10036. const length = 6;
  10037. for ( let i = 0; i < length; i ++ ) {
  10038. if ( image[ i ] !== undefined ) count ++;
  10039. }
  10040. return count === length;
  10041. }
  10042. function onTextureDispose( event ) {
  10043. const texture = event.target;
  10044. texture.removeEventListener( 'dispose', onTextureDispose );
  10045. const cubemapUV = cubeUVmaps.get( texture );
  10046. if ( cubemapUV !== undefined ) {
  10047. cubeUVmaps.delete( texture );
  10048. cubemapUV.dispose();
  10049. }
  10050. }
  10051. function dispose() {
  10052. cubeUVmaps = new WeakMap();
  10053. if ( pmremGenerator !== null ) {
  10054. pmremGenerator.dispose();
  10055. pmremGenerator = null;
  10056. }
  10057. }
  10058. return {
  10059. get: get,
  10060. dispose: dispose
  10061. };
  10062. }
  10063. function WebGLExtensions( gl ) {
  10064. const extensions = {};
  10065. function getExtension( name ) {
  10066. if ( extensions[ name ] !== undefined ) {
  10067. return extensions[ name ];
  10068. }
  10069. let extension;
  10070. switch ( name ) {
  10071. case 'WEBGL_depth_texture':
  10072. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10073. break;
  10074. case 'EXT_texture_filter_anisotropic':
  10075. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10076. break;
  10077. case 'WEBGL_compressed_texture_s3tc':
  10078. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10079. break;
  10080. case 'WEBGL_compressed_texture_pvrtc':
  10081. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10082. break;
  10083. default:
  10084. extension = gl.getExtension( name );
  10085. }
  10086. extensions[ name ] = extension;
  10087. return extension;
  10088. }
  10089. return {
  10090. has: function ( name ) {
  10091. return getExtension( name ) !== null;
  10092. },
  10093. init: function ( capabilities ) {
  10094. if ( capabilities.isWebGL2 ) {
  10095. getExtension( 'EXT_color_buffer_float' );
  10096. } else {
  10097. getExtension( 'WEBGL_depth_texture' );
  10098. getExtension( 'OES_texture_float' );
  10099. getExtension( 'OES_texture_half_float' );
  10100. getExtension( 'OES_texture_half_float_linear' );
  10101. getExtension( 'OES_standard_derivatives' );
  10102. getExtension( 'OES_element_index_uint' );
  10103. getExtension( 'OES_vertex_array_object' );
  10104. getExtension( 'ANGLE_instanced_arrays' );
  10105. }
  10106. getExtension( 'OES_texture_float_linear' );
  10107. getExtension( 'EXT_color_buffer_half_float' );
  10108. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10109. },
  10110. get: function ( name ) {
  10111. const extension = getExtension( name );
  10112. if ( extension === null ) {
  10113. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10114. }
  10115. return extension;
  10116. }
  10117. };
  10118. }
  10119. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10120. const geometries = {};
  10121. const wireframeAttributes = new WeakMap();
  10122. function onGeometryDispose( event ) {
  10123. const geometry = event.target;
  10124. if ( geometry.index !== null ) {
  10125. attributes.remove( geometry.index );
  10126. }
  10127. for ( const name in geometry.attributes ) {
  10128. attributes.remove( geometry.attributes[ name ] );
  10129. }
  10130. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10131. delete geometries[ geometry.id ];
  10132. const attribute = wireframeAttributes.get( geometry );
  10133. if ( attribute ) {
  10134. attributes.remove( attribute );
  10135. wireframeAttributes.delete( geometry );
  10136. }
  10137. bindingStates.releaseStatesOfGeometry( geometry );
  10138. if ( geometry.isInstancedBufferGeometry === true ) {
  10139. delete geometry._maxInstanceCount;
  10140. }
  10141. //
  10142. info.memory.geometries --;
  10143. }
  10144. function get( object, geometry ) {
  10145. if ( geometries[ geometry.id ] === true ) return geometry;
  10146. geometry.addEventListener( 'dispose', onGeometryDispose );
  10147. geometries[ geometry.id ] = true;
  10148. info.memory.geometries ++;
  10149. return geometry;
  10150. }
  10151. function update( geometry ) {
  10152. const geometryAttributes = geometry.attributes;
  10153. // Updating index buffer in VAO now. See WebGLBindingStates.
  10154. for ( const name in geometryAttributes ) {
  10155. attributes.update( geometryAttributes[ name ], 34962 );
  10156. }
  10157. // morph targets
  10158. const morphAttributes = geometry.morphAttributes;
  10159. for ( const name in morphAttributes ) {
  10160. const array = morphAttributes[ name ];
  10161. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10162. attributes.update( array[ i ], 34962 );
  10163. }
  10164. }
  10165. }
  10166. function updateWireframeAttribute( geometry ) {
  10167. const indices = [];
  10168. const geometryIndex = geometry.index;
  10169. const geometryPosition = geometry.attributes.position;
  10170. let version = 0;
  10171. if ( geometryIndex !== null ) {
  10172. const array = geometryIndex.array;
  10173. version = geometryIndex.version;
  10174. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10175. const a = array[ i + 0 ];
  10176. const b = array[ i + 1 ];
  10177. const c = array[ i + 2 ];
  10178. indices.push( a, b, b, c, c, a );
  10179. }
  10180. } else {
  10181. const array = geometryPosition.array;
  10182. version = geometryPosition.version;
  10183. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10184. const a = i + 0;
  10185. const b = i + 1;
  10186. const c = i + 2;
  10187. indices.push( a, b, b, c, c, a );
  10188. }
  10189. }
  10190. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10191. attribute.version = version;
  10192. // Updating index buffer in VAO now. See WebGLBindingStates
  10193. //
  10194. const previousAttribute = wireframeAttributes.get( geometry );
  10195. if ( previousAttribute ) attributes.remove( previousAttribute );
  10196. //
  10197. wireframeAttributes.set( geometry, attribute );
  10198. }
  10199. function getWireframeAttribute( geometry ) {
  10200. const currentAttribute = wireframeAttributes.get( geometry );
  10201. if ( currentAttribute ) {
  10202. const geometryIndex = geometry.index;
  10203. if ( geometryIndex !== null ) {
  10204. // if the attribute is obsolete, create a new one
  10205. if ( currentAttribute.version < geometryIndex.version ) {
  10206. updateWireframeAttribute( geometry );
  10207. }
  10208. }
  10209. } else {
  10210. updateWireframeAttribute( geometry );
  10211. }
  10212. return wireframeAttributes.get( geometry );
  10213. }
  10214. return {
  10215. get: get,
  10216. update: update,
  10217. getWireframeAttribute: getWireframeAttribute
  10218. };
  10219. }
  10220. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10221. const isWebGL2 = capabilities.isWebGL2;
  10222. let mode;
  10223. function setMode( value ) {
  10224. mode = value;
  10225. }
  10226. let type, bytesPerElement;
  10227. function setIndex( value ) {
  10228. type = value.type;
  10229. bytesPerElement = value.bytesPerElement;
  10230. }
  10231. function render( start, count ) {
  10232. gl.drawElements( mode, count, type, start * bytesPerElement );
  10233. info.update( count, mode, 1 );
  10234. }
  10235. function renderInstances( start, count, primcount ) {
  10236. if ( primcount === 0 ) return;
  10237. let extension, methodName;
  10238. if ( isWebGL2 ) {
  10239. extension = gl;
  10240. methodName = 'drawElementsInstanced';
  10241. } else {
  10242. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10243. methodName = 'drawElementsInstancedANGLE';
  10244. if ( extension === null ) {
  10245. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10246. return;
  10247. }
  10248. }
  10249. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10250. info.update( count, mode, primcount );
  10251. }
  10252. //
  10253. this.setMode = setMode;
  10254. this.setIndex = setIndex;
  10255. this.render = render;
  10256. this.renderInstances = renderInstances;
  10257. }
  10258. function WebGLInfo( gl ) {
  10259. const memory = {
  10260. geometries: 0,
  10261. textures: 0
  10262. };
  10263. const render = {
  10264. frame: 0,
  10265. calls: 0,
  10266. triangles: 0,
  10267. points: 0,
  10268. lines: 0
  10269. };
  10270. function update( count, mode, instanceCount ) {
  10271. render.calls ++;
  10272. switch ( mode ) {
  10273. case 4:
  10274. render.triangles += instanceCount * ( count / 3 );
  10275. break;
  10276. case 1:
  10277. render.lines += instanceCount * ( count / 2 );
  10278. break;
  10279. case 3:
  10280. render.lines += instanceCount * ( count - 1 );
  10281. break;
  10282. case 2:
  10283. render.lines += instanceCount * count;
  10284. break;
  10285. case 0:
  10286. render.points += instanceCount * count;
  10287. break;
  10288. default:
  10289. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10290. break;
  10291. }
  10292. }
  10293. function reset() {
  10294. render.frame ++;
  10295. render.calls = 0;
  10296. render.triangles = 0;
  10297. render.points = 0;
  10298. render.lines = 0;
  10299. }
  10300. return {
  10301. memory: memory,
  10302. render: render,
  10303. programs: null,
  10304. autoReset: true,
  10305. reset: reset,
  10306. update: update
  10307. };
  10308. }
  10309. function numericalSort( a, b ) {
  10310. return a[ 0 ] - b[ 0 ];
  10311. }
  10312. function absNumericalSort( a, b ) {
  10313. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10314. }
  10315. function WebGLMorphtargets( gl, capabilities, textures ) {
  10316. const influencesList = {};
  10317. const morphInfluences = new Float32Array( 8 );
  10318. const morphTextures = new WeakMap();
  10319. const morph = new Vector4();
  10320. const workInfluences = [];
  10321. for ( let i = 0; i < 8; i ++ ) {
  10322. workInfluences[ i ] = [ i, 0 ];
  10323. }
  10324. function update( object, geometry, material, program ) {
  10325. const objectInfluences = object.morphTargetInfluences;
  10326. if ( capabilities.isWebGL2 === true ) {
  10327. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10328. // into an array of data textures. Each layer represents a single morph target.
  10329. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10330. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10331. let entry = morphTextures.get( geometry );
  10332. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10333. if ( entry !== undefined ) entry.texture.dispose();
  10334. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10335. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10336. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10337. const morphTargets = geometry.morphAttributes.position || [];
  10338. const morphNormals = geometry.morphAttributes.normal || [];
  10339. const morphColors = geometry.morphAttributes.color || [];
  10340. let vertexDataCount = 0;
  10341. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10342. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10343. if ( hasMorphColors === true ) vertexDataCount = 3;
  10344. let width = geometry.attributes.position.count * vertexDataCount;
  10345. let height = 1;
  10346. if ( width > capabilities.maxTextureSize ) {
  10347. height = Math.ceil( width / capabilities.maxTextureSize );
  10348. width = capabilities.maxTextureSize;
  10349. }
  10350. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10351. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10352. texture.type = FloatType;
  10353. texture.needsUpdate = true;
  10354. // fill buffer
  10355. const vertexDataStride = vertexDataCount * 4;
  10356. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10357. const morphTarget = morphTargets[ i ];
  10358. const morphNormal = morphNormals[ i ];
  10359. const morphColor = morphColors[ i ];
  10360. const offset = width * height * 4 * i;
  10361. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10362. const stride = j * vertexDataStride;
  10363. if ( hasMorphPosition === true ) {
  10364. morph.fromBufferAttribute( morphTarget, j );
  10365. buffer[ offset + stride + 0 ] = morph.x;
  10366. buffer[ offset + stride + 1 ] = morph.y;
  10367. buffer[ offset + stride + 2 ] = morph.z;
  10368. buffer[ offset + stride + 3 ] = 0;
  10369. }
  10370. if ( hasMorphNormals === true ) {
  10371. morph.fromBufferAttribute( morphNormal, j );
  10372. buffer[ offset + stride + 4 ] = morph.x;
  10373. buffer[ offset + stride + 5 ] = morph.y;
  10374. buffer[ offset + stride + 6 ] = morph.z;
  10375. buffer[ offset + stride + 7 ] = 0;
  10376. }
  10377. if ( hasMorphColors === true ) {
  10378. morph.fromBufferAttribute( morphColor, j );
  10379. buffer[ offset + stride + 8 ] = morph.x;
  10380. buffer[ offset + stride + 9 ] = morph.y;
  10381. buffer[ offset + stride + 10 ] = morph.z;
  10382. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10383. }
  10384. }
  10385. }
  10386. entry = {
  10387. count: morphTargetsCount,
  10388. texture: texture,
  10389. size: new Vector2( width, height )
  10390. };
  10391. morphTextures.set( geometry, entry );
  10392. function disposeTexture() {
  10393. texture.dispose();
  10394. morphTextures.delete( geometry );
  10395. geometry.removeEventListener( 'dispose', disposeTexture );
  10396. }
  10397. geometry.addEventListener( 'dispose', disposeTexture );
  10398. }
  10399. //
  10400. let morphInfluencesSum = 0;
  10401. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10402. morphInfluencesSum += objectInfluences[ i ];
  10403. }
  10404. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10405. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10406. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10407. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10408. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10409. } else {
  10410. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10411. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10412. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10413. let influences = influencesList[ geometry.id ];
  10414. if ( influences === undefined || influences.length !== length ) {
  10415. // initialise list
  10416. influences = [];
  10417. for ( let i = 0; i < length; i ++ ) {
  10418. influences[ i ] = [ i, 0 ];
  10419. }
  10420. influencesList[ geometry.id ] = influences;
  10421. }
  10422. // Collect influences
  10423. for ( let i = 0; i < length; i ++ ) {
  10424. const influence = influences[ i ];
  10425. influence[ 0 ] = i;
  10426. influence[ 1 ] = objectInfluences[ i ];
  10427. }
  10428. influences.sort( absNumericalSort );
  10429. for ( let i = 0; i < 8; i ++ ) {
  10430. if ( i < length && influences[ i ][ 1 ] ) {
  10431. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10432. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10433. } else {
  10434. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10435. workInfluences[ i ][ 1 ] = 0;
  10436. }
  10437. }
  10438. workInfluences.sort( numericalSort );
  10439. const morphTargets = geometry.morphAttributes.position;
  10440. const morphNormals = geometry.morphAttributes.normal;
  10441. let morphInfluencesSum = 0;
  10442. for ( let i = 0; i < 8; i ++ ) {
  10443. const influence = workInfluences[ i ];
  10444. const index = influence[ 0 ];
  10445. const value = influence[ 1 ];
  10446. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10447. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10448. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10449. }
  10450. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10451. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10452. }
  10453. morphInfluences[ i ] = value;
  10454. morphInfluencesSum += value;
  10455. } else {
  10456. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10457. geometry.deleteAttribute( 'morphTarget' + i );
  10458. }
  10459. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10460. geometry.deleteAttribute( 'morphNormal' + i );
  10461. }
  10462. morphInfluences[ i ] = 0;
  10463. }
  10464. }
  10465. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10466. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10467. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10468. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10469. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10470. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10471. }
  10472. }
  10473. return {
  10474. update: update
  10475. };
  10476. }
  10477. function WebGLObjects( gl, geometries, attributes, info ) {
  10478. let updateMap = new WeakMap();
  10479. function update( object ) {
  10480. const frame = info.render.frame;
  10481. const geometry = object.geometry;
  10482. const buffergeometry = geometries.get( object, geometry );
  10483. // Update once per frame
  10484. if ( updateMap.get( buffergeometry ) !== frame ) {
  10485. geometries.update( buffergeometry );
  10486. updateMap.set( buffergeometry, frame );
  10487. }
  10488. if ( object.isInstancedMesh ) {
  10489. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10490. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10491. }
  10492. attributes.update( object.instanceMatrix, 34962 );
  10493. if ( object.instanceColor !== null ) {
  10494. attributes.update( object.instanceColor, 34962 );
  10495. }
  10496. }
  10497. return buffergeometry;
  10498. }
  10499. function dispose() {
  10500. updateMap = new WeakMap();
  10501. }
  10502. function onInstancedMeshDispose( event ) {
  10503. const instancedMesh = event.target;
  10504. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10505. attributes.remove( instancedMesh.instanceMatrix );
  10506. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10507. }
  10508. return {
  10509. update: update,
  10510. dispose: dispose
  10511. };
  10512. }
  10513. /**
  10514. * Uniforms of a program.
  10515. * Those form a tree structure with a special top-level container for the root,
  10516. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10517. *
  10518. *
  10519. * Properties of inner nodes including the top-level container:
  10520. *
  10521. * .seq - array of nested uniforms
  10522. * .map - nested uniforms by name
  10523. *
  10524. *
  10525. * Methods of all nodes except the top-level container:
  10526. *
  10527. * .setValue( gl, value, [textures] )
  10528. *
  10529. * uploads a uniform value(s)
  10530. * the 'textures' parameter is needed for sampler uniforms
  10531. *
  10532. *
  10533. * Static methods of the top-level container (textures factorizations):
  10534. *
  10535. * .upload( gl, seq, values, textures )
  10536. *
  10537. * sets uniforms in 'seq' to 'values[id].value'
  10538. *
  10539. * .seqWithValue( seq, values ) : filteredSeq
  10540. *
  10541. * filters 'seq' entries with corresponding entry in values
  10542. *
  10543. *
  10544. * Methods of the top-level container (textures factorizations):
  10545. *
  10546. * .setValue( gl, name, value, textures )
  10547. *
  10548. * sets uniform with name 'name' to 'value'
  10549. *
  10550. * .setOptional( gl, obj, prop )
  10551. *
  10552. * like .set for an optional property of the object
  10553. *
  10554. */
  10555. const emptyTexture = /*@__PURE__*/ new Texture();
  10556. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10557. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10558. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10559. // --- Utilities ---
  10560. // Array Caches (provide typed arrays for temporary by size)
  10561. const arrayCacheF32 = [];
  10562. const arrayCacheI32 = [];
  10563. // Float32Array caches used for uploading Matrix uniforms
  10564. const mat4array = new Float32Array( 16 );
  10565. const mat3array = new Float32Array( 9 );
  10566. const mat2array = new Float32Array( 4 );
  10567. // Flattening for arrays of vectors and matrices
  10568. function flatten( array, nBlocks, blockSize ) {
  10569. const firstElem = array[ 0 ];
  10570. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10571. // unoptimized: ! isNaN( firstElem )
  10572. // see http://jacksondunstan.com/articles/983
  10573. const n = nBlocks * blockSize;
  10574. let r = arrayCacheF32[ n ];
  10575. if ( r === undefined ) {
  10576. r = new Float32Array( n );
  10577. arrayCacheF32[ n ] = r;
  10578. }
  10579. if ( nBlocks !== 0 ) {
  10580. firstElem.toArray( r, 0 );
  10581. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10582. offset += blockSize;
  10583. array[ i ].toArray( r, offset );
  10584. }
  10585. }
  10586. return r;
  10587. }
  10588. function arraysEqual( a, b ) {
  10589. if ( a.length !== b.length ) return false;
  10590. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10591. if ( a[ i ] !== b[ i ] ) return false;
  10592. }
  10593. return true;
  10594. }
  10595. function copyArray( a, b ) {
  10596. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10597. a[ i ] = b[ i ];
  10598. }
  10599. }
  10600. // Texture unit allocation
  10601. function allocTexUnits( textures, n ) {
  10602. let r = arrayCacheI32[ n ];
  10603. if ( r === undefined ) {
  10604. r = new Int32Array( n );
  10605. arrayCacheI32[ n ] = r;
  10606. }
  10607. for ( let i = 0; i !== n; ++ i ) {
  10608. r[ i ] = textures.allocateTextureUnit();
  10609. }
  10610. return r;
  10611. }
  10612. // --- Setters ---
  10613. // Note: Defining these methods externally, because they come in a bunch
  10614. // and this way their names minify.
  10615. // Single scalar
  10616. function setValueV1f( gl, v ) {
  10617. const cache = this.cache;
  10618. if ( cache[ 0 ] === v ) return;
  10619. gl.uniform1f( this.addr, v );
  10620. cache[ 0 ] = v;
  10621. }
  10622. // Single float vector (from flat array or THREE.VectorN)
  10623. function setValueV2f( gl, v ) {
  10624. const cache = this.cache;
  10625. if ( v.x !== undefined ) {
  10626. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10627. gl.uniform2f( this.addr, v.x, v.y );
  10628. cache[ 0 ] = v.x;
  10629. cache[ 1 ] = v.y;
  10630. }
  10631. } else {
  10632. if ( arraysEqual( cache, v ) ) return;
  10633. gl.uniform2fv( this.addr, v );
  10634. copyArray( cache, v );
  10635. }
  10636. }
  10637. function setValueV3f( gl, v ) {
  10638. const cache = this.cache;
  10639. if ( v.x !== undefined ) {
  10640. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10641. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10642. cache[ 0 ] = v.x;
  10643. cache[ 1 ] = v.y;
  10644. cache[ 2 ] = v.z;
  10645. }
  10646. } else if ( v.r !== undefined ) {
  10647. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10648. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10649. cache[ 0 ] = v.r;
  10650. cache[ 1 ] = v.g;
  10651. cache[ 2 ] = v.b;
  10652. }
  10653. } else {
  10654. if ( arraysEqual( cache, v ) ) return;
  10655. gl.uniform3fv( this.addr, v );
  10656. copyArray( cache, v );
  10657. }
  10658. }
  10659. function setValueV4f( gl, v ) {
  10660. const cache = this.cache;
  10661. if ( v.x !== undefined ) {
  10662. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10663. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10664. cache[ 0 ] = v.x;
  10665. cache[ 1 ] = v.y;
  10666. cache[ 2 ] = v.z;
  10667. cache[ 3 ] = v.w;
  10668. }
  10669. } else {
  10670. if ( arraysEqual( cache, v ) ) return;
  10671. gl.uniform4fv( this.addr, v );
  10672. copyArray( cache, v );
  10673. }
  10674. }
  10675. // Single matrix (from flat array or THREE.MatrixN)
  10676. function setValueM2( gl, v ) {
  10677. const cache = this.cache;
  10678. const elements = v.elements;
  10679. if ( elements === undefined ) {
  10680. if ( arraysEqual( cache, v ) ) return;
  10681. gl.uniformMatrix2fv( this.addr, false, v );
  10682. copyArray( cache, v );
  10683. } else {
  10684. if ( arraysEqual( cache, elements ) ) return;
  10685. mat2array.set( elements );
  10686. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10687. copyArray( cache, elements );
  10688. }
  10689. }
  10690. function setValueM3( gl, v ) {
  10691. const cache = this.cache;
  10692. const elements = v.elements;
  10693. if ( elements === undefined ) {
  10694. if ( arraysEqual( cache, v ) ) return;
  10695. gl.uniformMatrix3fv( this.addr, false, v );
  10696. copyArray( cache, v );
  10697. } else {
  10698. if ( arraysEqual( cache, elements ) ) return;
  10699. mat3array.set( elements );
  10700. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10701. copyArray( cache, elements );
  10702. }
  10703. }
  10704. function setValueM4( gl, v ) {
  10705. const cache = this.cache;
  10706. const elements = v.elements;
  10707. if ( elements === undefined ) {
  10708. if ( arraysEqual( cache, v ) ) return;
  10709. gl.uniformMatrix4fv( this.addr, false, v );
  10710. copyArray( cache, v );
  10711. } else {
  10712. if ( arraysEqual( cache, elements ) ) return;
  10713. mat4array.set( elements );
  10714. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10715. copyArray( cache, elements );
  10716. }
  10717. }
  10718. // Single integer / boolean
  10719. function setValueV1i( gl, v ) {
  10720. const cache = this.cache;
  10721. if ( cache[ 0 ] === v ) return;
  10722. gl.uniform1i( this.addr, v );
  10723. cache[ 0 ] = v;
  10724. }
  10725. // Single integer / boolean vector (from flat array)
  10726. function setValueV2i( gl, v ) {
  10727. const cache = this.cache;
  10728. if ( arraysEqual( cache, v ) ) return;
  10729. gl.uniform2iv( this.addr, v );
  10730. copyArray( cache, v );
  10731. }
  10732. function setValueV3i( gl, v ) {
  10733. const cache = this.cache;
  10734. if ( arraysEqual( cache, v ) ) return;
  10735. gl.uniform3iv( this.addr, v );
  10736. copyArray( cache, v );
  10737. }
  10738. function setValueV4i( gl, v ) {
  10739. const cache = this.cache;
  10740. if ( arraysEqual( cache, v ) ) return;
  10741. gl.uniform4iv( this.addr, v );
  10742. copyArray( cache, v );
  10743. }
  10744. // Single unsigned integer
  10745. function setValueV1ui( gl, v ) {
  10746. const cache = this.cache;
  10747. if ( cache[ 0 ] === v ) return;
  10748. gl.uniform1ui( this.addr, v );
  10749. cache[ 0 ] = v;
  10750. }
  10751. // Single unsigned integer vector (from flat array)
  10752. function setValueV2ui( gl, v ) {
  10753. const cache = this.cache;
  10754. if ( arraysEqual( cache, v ) ) return;
  10755. gl.uniform2uiv( this.addr, v );
  10756. copyArray( cache, v );
  10757. }
  10758. function setValueV3ui( gl, v ) {
  10759. const cache = this.cache;
  10760. if ( arraysEqual( cache, v ) ) return;
  10761. gl.uniform3uiv( this.addr, v );
  10762. copyArray( cache, v );
  10763. }
  10764. function setValueV4ui( gl, v ) {
  10765. const cache = this.cache;
  10766. if ( arraysEqual( cache, v ) ) return;
  10767. gl.uniform4uiv( this.addr, v );
  10768. copyArray( cache, v );
  10769. }
  10770. // Single texture (2D / Cube)
  10771. function setValueT1( gl, v, textures ) {
  10772. const cache = this.cache;
  10773. const unit = textures.allocateTextureUnit();
  10774. if ( cache[ 0 ] !== unit ) {
  10775. gl.uniform1i( this.addr, unit );
  10776. cache[ 0 ] = unit;
  10777. }
  10778. textures.setTexture2D( v || emptyTexture, unit );
  10779. }
  10780. function setValueT3D1( gl, v, textures ) {
  10781. const cache = this.cache;
  10782. const unit = textures.allocateTextureUnit();
  10783. if ( cache[ 0 ] !== unit ) {
  10784. gl.uniform1i( this.addr, unit );
  10785. cache[ 0 ] = unit;
  10786. }
  10787. textures.setTexture3D( v || empty3dTexture, unit );
  10788. }
  10789. function setValueT6( gl, v, textures ) {
  10790. const cache = this.cache;
  10791. const unit = textures.allocateTextureUnit();
  10792. if ( cache[ 0 ] !== unit ) {
  10793. gl.uniform1i( this.addr, unit );
  10794. cache[ 0 ] = unit;
  10795. }
  10796. textures.setTextureCube( v || emptyCubeTexture, unit );
  10797. }
  10798. function setValueT2DArray1( gl, v, textures ) {
  10799. const cache = this.cache;
  10800. const unit = textures.allocateTextureUnit();
  10801. if ( cache[ 0 ] !== unit ) {
  10802. gl.uniform1i( this.addr, unit );
  10803. cache[ 0 ] = unit;
  10804. }
  10805. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10806. }
  10807. // Helper to pick the right setter for the singular case
  10808. function getSingularSetter( type ) {
  10809. switch ( type ) {
  10810. case 0x1406: return setValueV1f; // FLOAT
  10811. case 0x8b50: return setValueV2f; // _VEC2
  10812. case 0x8b51: return setValueV3f; // _VEC3
  10813. case 0x8b52: return setValueV4f; // _VEC4
  10814. case 0x8b5a: return setValueM2; // _MAT2
  10815. case 0x8b5b: return setValueM3; // _MAT3
  10816. case 0x8b5c: return setValueM4; // _MAT4
  10817. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10818. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10819. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10820. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10821. case 0x1405: return setValueV1ui; // UINT
  10822. case 0x8dc6: return setValueV2ui; // _VEC2
  10823. case 0x8dc7: return setValueV3ui; // _VEC3
  10824. case 0x8dc8: return setValueV4ui; // _VEC4
  10825. case 0x8b5e: // SAMPLER_2D
  10826. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10827. case 0x8dca: // INT_SAMPLER_2D
  10828. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10829. case 0x8b62: // SAMPLER_2D_SHADOW
  10830. return setValueT1;
  10831. case 0x8b5f: // SAMPLER_3D
  10832. case 0x8dcb: // INT_SAMPLER_3D
  10833. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10834. return setValueT3D1;
  10835. case 0x8b60: // SAMPLER_CUBE
  10836. case 0x8dcc: // INT_SAMPLER_CUBE
  10837. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10838. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10839. return setValueT6;
  10840. case 0x8dc1: // SAMPLER_2D_ARRAY
  10841. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10842. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10843. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10844. return setValueT2DArray1;
  10845. }
  10846. }
  10847. // Array of scalars
  10848. function setValueV1fArray( gl, v ) {
  10849. gl.uniform1fv( this.addr, v );
  10850. }
  10851. // Array of vectors (from flat array or array of THREE.VectorN)
  10852. function setValueV2fArray( gl, v ) {
  10853. const data = flatten( v, this.size, 2 );
  10854. gl.uniform2fv( this.addr, data );
  10855. }
  10856. function setValueV3fArray( gl, v ) {
  10857. const data = flatten( v, this.size, 3 );
  10858. gl.uniform3fv( this.addr, data );
  10859. }
  10860. function setValueV4fArray( gl, v ) {
  10861. const data = flatten( v, this.size, 4 );
  10862. gl.uniform4fv( this.addr, data );
  10863. }
  10864. // Array of matrices (from flat array or array of THREE.MatrixN)
  10865. function setValueM2Array( gl, v ) {
  10866. const data = flatten( v, this.size, 4 );
  10867. gl.uniformMatrix2fv( this.addr, false, data );
  10868. }
  10869. function setValueM3Array( gl, v ) {
  10870. const data = flatten( v, this.size, 9 );
  10871. gl.uniformMatrix3fv( this.addr, false, data );
  10872. }
  10873. function setValueM4Array( gl, v ) {
  10874. const data = flatten( v, this.size, 16 );
  10875. gl.uniformMatrix4fv( this.addr, false, data );
  10876. }
  10877. // Array of integer / boolean
  10878. function setValueV1iArray( gl, v ) {
  10879. gl.uniform1iv( this.addr, v );
  10880. }
  10881. // Array of integer / boolean vectors (from flat array)
  10882. function setValueV2iArray( gl, v ) {
  10883. gl.uniform2iv( this.addr, v );
  10884. }
  10885. function setValueV3iArray( gl, v ) {
  10886. gl.uniform3iv( this.addr, v );
  10887. }
  10888. function setValueV4iArray( gl, v ) {
  10889. gl.uniform4iv( this.addr, v );
  10890. }
  10891. // Array of unsigned integer
  10892. function setValueV1uiArray( gl, v ) {
  10893. gl.uniform1uiv( this.addr, v );
  10894. }
  10895. // Array of unsigned integer vectors (from flat array)
  10896. function setValueV2uiArray( gl, v ) {
  10897. gl.uniform2uiv( this.addr, v );
  10898. }
  10899. function setValueV3uiArray( gl, v ) {
  10900. gl.uniform3uiv( this.addr, v );
  10901. }
  10902. function setValueV4uiArray( gl, v ) {
  10903. gl.uniform4uiv( this.addr, v );
  10904. }
  10905. // Array of textures (2D / 3D / Cube / 2DArray)
  10906. function setValueT1Array( gl, v, textures ) {
  10907. const n = v.length;
  10908. const units = allocTexUnits( textures, n );
  10909. gl.uniform1iv( this.addr, units );
  10910. for ( let i = 0; i !== n; ++ i ) {
  10911. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10912. }
  10913. }
  10914. function setValueT3DArray( gl, v, textures ) {
  10915. const n = v.length;
  10916. const units = allocTexUnits( textures, n );
  10917. gl.uniform1iv( this.addr, units );
  10918. for ( let i = 0; i !== n; ++ i ) {
  10919. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10920. }
  10921. }
  10922. function setValueT6Array( gl, v, textures ) {
  10923. const n = v.length;
  10924. const units = allocTexUnits( textures, n );
  10925. gl.uniform1iv( this.addr, units );
  10926. for ( let i = 0; i !== n; ++ i ) {
  10927. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10928. }
  10929. }
  10930. function setValueT2DArrayArray( gl, v, textures ) {
  10931. const n = v.length;
  10932. const units = allocTexUnits( textures, n );
  10933. gl.uniform1iv( this.addr, units );
  10934. for ( let i = 0; i !== n; ++ i ) {
  10935. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10936. }
  10937. }
  10938. // Helper to pick the right setter for a pure (bottom-level) array
  10939. function getPureArraySetter( type ) {
  10940. switch ( type ) {
  10941. case 0x1406: return setValueV1fArray; // FLOAT
  10942. case 0x8b50: return setValueV2fArray; // _VEC2
  10943. case 0x8b51: return setValueV3fArray; // _VEC3
  10944. case 0x8b52: return setValueV4fArray; // _VEC4
  10945. case 0x8b5a: return setValueM2Array; // _MAT2
  10946. case 0x8b5b: return setValueM3Array; // _MAT3
  10947. case 0x8b5c: return setValueM4Array; // _MAT4
  10948. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10949. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10950. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10951. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10952. case 0x1405: return setValueV1uiArray; // UINT
  10953. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10954. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10955. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10956. case 0x8b5e: // SAMPLER_2D
  10957. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10958. case 0x8dca: // INT_SAMPLER_2D
  10959. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10960. case 0x8b62: // SAMPLER_2D_SHADOW
  10961. return setValueT1Array;
  10962. case 0x8b5f: // SAMPLER_3D
  10963. case 0x8dcb: // INT_SAMPLER_3D
  10964. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10965. return setValueT3DArray;
  10966. case 0x8b60: // SAMPLER_CUBE
  10967. case 0x8dcc: // INT_SAMPLER_CUBE
  10968. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10969. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10970. return setValueT6Array;
  10971. case 0x8dc1: // SAMPLER_2D_ARRAY
  10972. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10973. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10974. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10975. return setValueT2DArrayArray;
  10976. }
  10977. }
  10978. // --- Uniform Classes ---
  10979. class SingleUniform {
  10980. constructor( id, activeInfo, addr ) {
  10981. this.id = id;
  10982. this.addr = addr;
  10983. this.cache = [];
  10984. this.setValue = getSingularSetter( activeInfo.type );
  10985. // this.path = activeInfo.name; // DEBUG
  10986. }
  10987. }
  10988. class PureArrayUniform {
  10989. constructor( id, activeInfo, addr ) {
  10990. this.id = id;
  10991. this.addr = addr;
  10992. this.cache = [];
  10993. this.size = activeInfo.size;
  10994. this.setValue = getPureArraySetter( activeInfo.type );
  10995. // this.path = activeInfo.name; // DEBUG
  10996. }
  10997. }
  10998. class StructuredUniform {
  10999. constructor( id ) {
  11000. this.id = id;
  11001. this.seq = [];
  11002. this.map = {};
  11003. }
  11004. setValue( gl, value, textures ) {
  11005. const seq = this.seq;
  11006. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11007. const u = seq[ i ];
  11008. u.setValue( gl, value[ u.id ], textures );
  11009. }
  11010. }
  11011. }
  11012. // --- Top-level ---
  11013. // Parser - builds up the property tree from the path strings
  11014. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11015. // extracts
  11016. // - the identifier (member name or array index)
  11017. // - followed by an optional right bracket (found when array index)
  11018. // - followed by an optional left bracket or dot (type of subscript)
  11019. //
  11020. // Note: These portions can be read in a non-overlapping fashion and
  11021. // allow straightforward parsing of the hierarchy that WebGL encodes
  11022. // in the uniform names.
  11023. function addUniform( container, uniformObject ) {
  11024. container.seq.push( uniformObject );
  11025. container.map[ uniformObject.id ] = uniformObject;
  11026. }
  11027. function parseUniform( activeInfo, addr, container ) {
  11028. const path = activeInfo.name,
  11029. pathLength = path.length;
  11030. // reset RegExp object, because of the early exit of a previous run
  11031. RePathPart.lastIndex = 0;
  11032. while ( true ) {
  11033. const match = RePathPart.exec( path ),
  11034. matchEnd = RePathPart.lastIndex;
  11035. let id = match[ 1 ];
  11036. const idIsIndex = match[ 2 ] === ']',
  11037. subscript = match[ 3 ];
  11038. if ( idIsIndex ) id = id | 0; // convert to integer
  11039. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11040. // bare name or "pure" bottom-level array "[0]" suffix
  11041. addUniform( container, subscript === undefined ?
  11042. new SingleUniform( id, activeInfo, addr ) :
  11043. new PureArrayUniform( id, activeInfo, addr ) );
  11044. break;
  11045. } else {
  11046. // step into inner node / create it in case it doesn't exist
  11047. const map = container.map;
  11048. let next = map[ id ];
  11049. if ( next === undefined ) {
  11050. next = new StructuredUniform( id );
  11051. addUniform( container, next );
  11052. }
  11053. container = next;
  11054. }
  11055. }
  11056. }
  11057. // Root Container
  11058. class WebGLUniforms {
  11059. constructor( gl, program ) {
  11060. this.seq = [];
  11061. this.map = {};
  11062. const n = gl.getProgramParameter( program, 35718 );
  11063. for ( let i = 0; i < n; ++ i ) {
  11064. const info = gl.getActiveUniform( program, i ),
  11065. addr = gl.getUniformLocation( program, info.name );
  11066. parseUniform( info, addr, this );
  11067. }
  11068. }
  11069. setValue( gl, name, value, textures ) {
  11070. const u = this.map[ name ];
  11071. if ( u !== undefined ) u.setValue( gl, value, textures );
  11072. }
  11073. setOptional( gl, object, name ) {
  11074. const v = object[ name ];
  11075. if ( v !== undefined ) this.setValue( gl, name, v );
  11076. }
  11077. static upload( gl, seq, values, textures ) {
  11078. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11079. const u = seq[ i ],
  11080. v = values[ u.id ];
  11081. if ( v.needsUpdate !== false ) {
  11082. // note: always updating when .needsUpdate is undefined
  11083. u.setValue( gl, v.value, textures );
  11084. }
  11085. }
  11086. }
  11087. static seqWithValue( seq, values ) {
  11088. const r = [];
  11089. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11090. const u = seq[ i ];
  11091. if ( u.id in values ) r.push( u );
  11092. }
  11093. return r;
  11094. }
  11095. }
  11096. function WebGLShader( gl, type, string ) {
  11097. const shader = gl.createShader( type );
  11098. gl.shaderSource( shader, string );
  11099. gl.compileShader( shader );
  11100. return shader;
  11101. }
  11102. let programIdCount = 0;
  11103. function handleSource( string, errorLine ) {
  11104. const lines = string.split( '\n' );
  11105. const lines2 = [];
  11106. const from = Math.max( errorLine - 6, 0 );
  11107. const to = Math.min( errorLine + 6, lines.length );
  11108. for ( let i = from; i < to; i ++ ) {
  11109. const line = i + 1;
  11110. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11111. }
  11112. return lines2.join( '\n' );
  11113. }
  11114. function getEncodingComponents( encoding ) {
  11115. switch ( encoding ) {
  11116. case LinearEncoding:
  11117. return [ 'Linear', '( value )' ];
  11118. case sRGBEncoding:
  11119. return [ 'sRGB', '( value )' ];
  11120. default:
  11121. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  11122. return [ 'Linear', '( value )' ];
  11123. }
  11124. }
  11125. function getShaderErrors( gl, shader, type ) {
  11126. const status = gl.getShaderParameter( shader, 35713 );
  11127. const errors = gl.getShaderInfoLog( shader ).trim();
  11128. if ( status && errors === '' ) return '';
  11129. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11130. if ( errorMatches ) {
  11131. // --enable-privileged-webgl-extension
  11132. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11133. const errorLine = parseInt( errorMatches[ 1 ] );
  11134. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11135. } else {
  11136. return errors;
  11137. }
  11138. }
  11139. function getTexelEncodingFunction( functionName, encoding ) {
  11140. const components = getEncodingComponents( encoding );
  11141. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11142. }
  11143. function getToneMappingFunction( functionName, toneMapping ) {
  11144. let toneMappingName;
  11145. switch ( toneMapping ) {
  11146. case LinearToneMapping:
  11147. toneMappingName = 'Linear';
  11148. break;
  11149. case ReinhardToneMapping:
  11150. toneMappingName = 'Reinhard';
  11151. break;
  11152. case CineonToneMapping:
  11153. toneMappingName = 'OptimizedCineon';
  11154. break;
  11155. case ACESFilmicToneMapping:
  11156. toneMappingName = 'ACESFilmic';
  11157. break;
  11158. case CustomToneMapping:
  11159. toneMappingName = 'Custom';
  11160. break;
  11161. default:
  11162. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11163. toneMappingName = 'Linear';
  11164. }
  11165. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11166. }
  11167. function generateExtensions( parameters ) {
  11168. const chunks = [
  11169. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11170. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11171. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11172. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11173. ];
  11174. return chunks.filter( filterEmptyLine ).join( '\n' );
  11175. }
  11176. function generateDefines( defines ) {
  11177. const chunks = [];
  11178. for ( const name in defines ) {
  11179. const value = defines[ name ];
  11180. if ( value === false ) continue;
  11181. chunks.push( '#define ' + name + ' ' + value );
  11182. }
  11183. return chunks.join( '\n' );
  11184. }
  11185. function fetchAttributeLocations( gl, program ) {
  11186. const attributes = {};
  11187. const n = gl.getProgramParameter( program, 35721 );
  11188. for ( let i = 0; i < n; i ++ ) {
  11189. const info = gl.getActiveAttrib( program, i );
  11190. const name = info.name;
  11191. let locationSize = 1;
  11192. if ( info.type === 35674 ) locationSize = 2;
  11193. if ( info.type === 35675 ) locationSize = 3;
  11194. if ( info.type === 35676 ) locationSize = 4;
  11195. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11196. attributes[ name ] = {
  11197. type: info.type,
  11198. location: gl.getAttribLocation( program, name ),
  11199. locationSize: locationSize
  11200. };
  11201. }
  11202. return attributes;
  11203. }
  11204. function filterEmptyLine( string ) {
  11205. return string !== '';
  11206. }
  11207. function replaceLightNums( string, parameters ) {
  11208. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11209. return string
  11210. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11211. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11212. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11213. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11214. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11215. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11216. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11217. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11218. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11219. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11220. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11221. }
  11222. function replaceClippingPlaneNums( string, parameters ) {
  11223. return string
  11224. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11225. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11226. }
  11227. // Resolve Includes
  11228. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11229. function resolveIncludes( string ) {
  11230. return string.replace( includePattern, includeReplacer );
  11231. }
  11232. function includeReplacer( match, include ) {
  11233. const string = ShaderChunk[ include ];
  11234. if ( string === undefined ) {
  11235. throw new Error( 'Can not resolve #include <' + include + '>' );
  11236. }
  11237. return resolveIncludes( string );
  11238. }
  11239. // Unroll Loops
  11240. 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;
  11241. function unrollLoops( string ) {
  11242. return string.replace( unrollLoopPattern, loopReplacer );
  11243. }
  11244. function loopReplacer( match, start, end, snippet ) {
  11245. let string = '';
  11246. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11247. string += snippet
  11248. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11249. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11250. }
  11251. return string;
  11252. }
  11253. //
  11254. function generatePrecision( parameters ) {
  11255. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11256. if ( parameters.precision === 'highp' ) {
  11257. precisionstring += '\n#define HIGH_PRECISION';
  11258. } else if ( parameters.precision === 'mediump' ) {
  11259. precisionstring += '\n#define MEDIUM_PRECISION';
  11260. } else if ( parameters.precision === 'lowp' ) {
  11261. precisionstring += '\n#define LOW_PRECISION';
  11262. }
  11263. return precisionstring;
  11264. }
  11265. function generateShadowMapTypeDefine( parameters ) {
  11266. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11267. if ( parameters.shadowMapType === PCFShadowMap ) {
  11268. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11269. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11270. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11271. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11272. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11273. }
  11274. return shadowMapTypeDefine;
  11275. }
  11276. function generateEnvMapTypeDefine( parameters ) {
  11277. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11278. if ( parameters.envMap ) {
  11279. switch ( parameters.envMapMode ) {
  11280. case CubeReflectionMapping:
  11281. case CubeRefractionMapping:
  11282. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11283. break;
  11284. case CubeUVReflectionMapping:
  11285. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11286. break;
  11287. }
  11288. }
  11289. return envMapTypeDefine;
  11290. }
  11291. function generateEnvMapModeDefine( parameters ) {
  11292. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11293. if ( parameters.envMap ) {
  11294. switch ( parameters.envMapMode ) {
  11295. case CubeRefractionMapping:
  11296. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11297. break;
  11298. }
  11299. }
  11300. return envMapModeDefine;
  11301. }
  11302. function generateEnvMapBlendingDefine( parameters ) {
  11303. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11304. if ( parameters.envMap ) {
  11305. switch ( parameters.combine ) {
  11306. case MultiplyOperation:
  11307. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11308. break;
  11309. case MixOperation:
  11310. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11311. break;
  11312. case AddOperation:
  11313. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11314. break;
  11315. }
  11316. }
  11317. return envMapBlendingDefine;
  11318. }
  11319. function generateCubeUVSize( parameters ) {
  11320. const imageHeight = parameters.envMapCubeUVHeight;
  11321. if ( imageHeight === null ) return null;
  11322. const maxMip = Math.log2( imageHeight ) - 2;
  11323. const texelHeight = 1.0 / imageHeight;
  11324. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11325. return { texelWidth, texelHeight, maxMip };
  11326. }
  11327. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11328. // TODO Send this event to Three.js DevTools
  11329. // console.log( 'WebGLProgram', cacheKey );
  11330. const gl = renderer.getContext();
  11331. const defines = parameters.defines;
  11332. let vertexShader = parameters.vertexShader;
  11333. let fragmentShader = parameters.fragmentShader;
  11334. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11335. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11336. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11337. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11338. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11339. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11340. const customDefines = generateDefines( defines );
  11341. const program = gl.createProgram();
  11342. let prefixVertex, prefixFragment;
  11343. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11344. if ( parameters.isRawShaderMaterial ) {
  11345. prefixVertex = [
  11346. customDefines
  11347. ].filter( filterEmptyLine ).join( '\n' );
  11348. if ( prefixVertex.length > 0 ) {
  11349. prefixVertex += '\n';
  11350. }
  11351. prefixFragment = [
  11352. customExtensions,
  11353. customDefines
  11354. ].filter( filterEmptyLine ).join( '\n' );
  11355. if ( prefixFragment.length > 0 ) {
  11356. prefixFragment += '\n';
  11357. }
  11358. } else {
  11359. prefixVertex = [
  11360. generatePrecision( parameters ),
  11361. '#define SHADER_NAME ' + parameters.shaderName,
  11362. customDefines,
  11363. parameters.instancing ? '#define USE_INSTANCING' : '',
  11364. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11365. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11366. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11367. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11368. parameters.map ? '#define USE_MAP' : '',
  11369. parameters.envMap ? '#define USE_ENVMAP' : '',
  11370. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11371. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11372. parameters.aoMap ? '#define USE_AOMAP' : '',
  11373. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11374. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11375. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11376. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11377. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11378. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11379. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11380. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11381. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11382. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11383. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11384. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11385. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11386. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11387. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11388. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11389. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11390. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11391. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11392. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11393. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11394. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11395. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11396. parameters.vertexColors ? '#define USE_COLOR' : '',
  11397. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11398. parameters.vertexUvs ? '#define USE_UV' : '',
  11399. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11400. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11401. parameters.skinning ? '#define USE_SKINNING' : '',
  11402. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11403. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11404. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11405. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11406. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11407. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11408. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11409. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11410. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11411. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11412. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11413. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11414. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11415. 'uniform mat4 modelMatrix;',
  11416. 'uniform mat4 modelViewMatrix;',
  11417. 'uniform mat4 projectionMatrix;',
  11418. 'uniform mat4 viewMatrix;',
  11419. 'uniform mat3 normalMatrix;',
  11420. 'uniform vec3 cameraPosition;',
  11421. 'uniform bool isOrthographic;',
  11422. '#ifdef USE_INSTANCING',
  11423. ' attribute mat4 instanceMatrix;',
  11424. '#endif',
  11425. '#ifdef USE_INSTANCING_COLOR',
  11426. ' attribute vec3 instanceColor;',
  11427. '#endif',
  11428. 'attribute vec3 position;',
  11429. 'attribute vec3 normal;',
  11430. 'attribute vec2 uv;',
  11431. '#ifdef USE_TANGENT',
  11432. ' attribute vec4 tangent;',
  11433. '#endif',
  11434. '#if defined( USE_COLOR_ALPHA )',
  11435. ' attribute vec4 color;',
  11436. '#elif defined( USE_COLOR )',
  11437. ' attribute vec3 color;',
  11438. '#endif',
  11439. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11440. ' attribute vec3 morphTarget0;',
  11441. ' attribute vec3 morphTarget1;',
  11442. ' attribute vec3 morphTarget2;',
  11443. ' attribute vec3 morphTarget3;',
  11444. ' #ifdef USE_MORPHNORMALS',
  11445. ' attribute vec3 morphNormal0;',
  11446. ' attribute vec3 morphNormal1;',
  11447. ' attribute vec3 morphNormal2;',
  11448. ' attribute vec3 morphNormal3;',
  11449. ' #else',
  11450. ' attribute vec3 morphTarget4;',
  11451. ' attribute vec3 morphTarget5;',
  11452. ' attribute vec3 morphTarget6;',
  11453. ' attribute vec3 morphTarget7;',
  11454. ' #endif',
  11455. '#endif',
  11456. '#ifdef USE_SKINNING',
  11457. ' attribute vec4 skinIndex;',
  11458. ' attribute vec4 skinWeight;',
  11459. '#endif',
  11460. '\n'
  11461. ].filter( filterEmptyLine ).join( '\n' );
  11462. prefixFragment = [
  11463. customExtensions,
  11464. generatePrecision( parameters ),
  11465. '#define SHADER_NAME ' + parameters.shaderName,
  11466. customDefines,
  11467. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11468. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11469. parameters.map ? '#define USE_MAP' : '',
  11470. parameters.matcap ? '#define USE_MATCAP' : '',
  11471. parameters.envMap ? '#define USE_ENVMAP' : '',
  11472. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11473. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11474. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11475. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11476. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11477. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11478. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11479. parameters.aoMap ? '#define USE_AOMAP' : '',
  11480. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11481. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11482. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11483. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11484. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11485. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11486. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11487. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11488. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11489. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11490. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11491. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11492. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11493. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11494. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11495. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11496. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11497. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11498. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11499. parameters.sheen ? '#define USE_SHEEN' : '',
  11500. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11501. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11502. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11503. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11504. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11505. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11506. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11507. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11508. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11509. parameters.vertexUvs ? '#define USE_UV' : '',
  11510. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11511. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11512. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11513. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11514. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11515. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11516. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11517. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11518. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11519. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11520. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11521. 'uniform mat4 viewMatrix;',
  11522. 'uniform vec3 cameraPosition;',
  11523. 'uniform bool isOrthographic;',
  11524. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11525. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11526. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11527. parameters.dithering ? '#define DITHERING' : '',
  11528. parameters.opaque ? '#define OPAQUE' : '',
  11529. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11530. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11531. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11532. '\n'
  11533. ].filter( filterEmptyLine ).join( '\n' );
  11534. }
  11535. vertexShader = resolveIncludes( vertexShader );
  11536. vertexShader = replaceLightNums( vertexShader, parameters );
  11537. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11538. fragmentShader = resolveIncludes( fragmentShader );
  11539. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11540. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11541. vertexShader = unrollLoops( vertexShader );
  11542. fragmentShader = unrollLoops( fragmentShader );
  11543. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11544. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11545. versionString = '#version 300 es\n';
  11546. prefixVertex = [
  11547. 'precision mediump sampler2DArray;',
  11548. '#define attribute in',
  11549. '#define varying out',
  11550. '#define texture2D texture'
  11551. ].join( '\n' ) + '\n' + prefixVertex;
  11552. prefixFragment = [
  11553. '#define varying in',
  11554. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11555. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11556. '#define gl_FragDepthEXT gl_FragDepth',
  11557. '#define texture2D texture',
  11558. '#define textureCube texture',
  11559. '#define texture2DProj textureProj',
  11560. '#define texture2DLodEXT textureLod',
  11561. '#define texture2DProjLodEXT textureProjLod',
  11562. '#define textureCubeLodEXT textureLod',
  11563. '#define texture2DGradEXT textureGrad',
  11564. '#define texture2DProjGradEXT textureProjGrad',
  11565. '#define textureCubeGradEXT textureGrad'
  11566. ].join( '\n' ) + '\n' + prefixFragment;
  11567. }
  11568. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11569. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11570. // console.log( '*VERTEX*', vertexGlsl );
  11571. // console.log( '*FRAGMENT*', fragmentGlsl );
  11572. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11573. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11574. gl.attachShader( program, glVertexShader );
  11575. gl.attachShader( program, glFragmentShader );
  11576. // Force a particular attribute to index 0.
  11577. if ( parameters.index0AttributeName !== undefined ) {
  11578. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11579. } else if ( parameters.morphTargets === true ) {
  11580. // programs with morphTargets displace position out of attribute 0
  11581. gl.bindAttribLocation( program, 0, 'position' );
  11582. }
  11583. gl.linkProgram( program );
  11584. // check for link errors
  11585. if ( renderer.debug.checkShaderErrors ) {
  11586. const programLog = gl.getProgramInfoLog( program ).trim();
  11587. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11588. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11589. let runnable = true;
  11590. let haveDiagnostics = true;
  11591. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11592. runnable = false;
  11593. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11594. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11595. console.error(
  11596. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11597. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11598. 'Program Info Log: ' + programLog + '\n' +
  11599. vertexErrors + '\n' +
  11600. fragmentErrors
  11601. );
  11602. } else if ( programLog !== '' ) {
  11603. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11604. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11605. haveDiagnostics = false;
  11606. }
  11607. if ( haveDiagnostics ) {
  11608. this.diagnostics = {
  11609. runnable: runnable,
  11610. programLog: programLog,
  11611. vertexShader: {
  11612. log: vertexLog,
  11613. prefix: prefixVertex
  11614. },
  11615. fragmentShader: {
  11616. log: fragmentLog,
  11617. prefix: prefixFragment
  11618. }
  11619. };
  11620. }
  11621. }
  11622. // Clean up
  11623. // Crashes in iOS9 and iOS10. #18402
  11624. // gl.detachShader( program, glVertexShader );
  11625. // gl.detachShader( program, glFragmentShader );
  11626. gl.deleteShader( glVertexShader );
  11627. gl.deleteShader( glFragmentShader );
  11628. // set up caching for uniform locations
  11629. let cachedUniforms;
  11630. this.getUniforms = function () {
  11631. if ( cachedUniforms === undefined ) {
  11632. cachedUniforms = new WebGLUniforms( gl, program );
  11633. }
  11634. return cachedUniforms;
  11635. };
  11636. // set up caching for attribute locations
  11637. let cachedAttributes;
  11638. this.getAttributes = function () {
  11639. if ( cachedAttributes === undefined ) {
  11640. cachedAttributes = fetchAttributeLocations( gl, program );
  11641. }
  11642. return cachedAttributes;
  11643. };
  11644. // free resource
  11645. this.destroy = function () {
  11646. bindingStates.releaseStatesOfProgram( this );
  11647. gl.deleteProgram( program );
  11648. this.program = undefined;
  11649. };
  11650. //
  11651. this.name = parameters.shaderName;
  11652. this.id = programIdCount ++;
  11653. this.cacheKey = cacheKey;
  11654. this.usedTimes = 1;
  11655. this.program = program;
  11656. this.vertexShader = glVertexShader;
  11657. this.fragmentShader = glFragmentShader;
  11658. return this;
  11659. }
  11660. let _id = 0;
  11661. class WebGLShaderCache {
  11662. constructor() {
  11663. this.shaderCache = new Map();
  11664. this.materialCache = new Map();
  11665. }
  11666. update( material ) {
  11667. const vertexShader = material.vertexShader;
  11668. const fragmentShader = material.fragmentShader;
  11669. const vertexShaderStage = this._getShaderStage( vertexShader );
  11670. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11671. const materialShaders = this._getShaderCacheForMaterial( material );
  11672. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11673. materialShaders.add( vertexShaderStage );
  11674. vertexShaderStage.usedTimes ++;
  11675. }
  11676. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11677. materialShaders.add( fragmentShaderStage );
  11678. fragmentShaderStage.usedTimes ++;
  11679. }
  11680. return this;
  11681. }
  11682. remove( material ) {
  11683. const materialShaders = this.materialCache.get( material );
  11684. for ( const shaderStage of materialShaders ) {
  11685. shaderStage.usedTimes --;
  11686. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11687. }
  11688. this.materialCache.delete( material );
  11689. return this;
  11690. }
  11691. getVertexShaderID( material ) {
  11692. return this._getShaderStage( material.vertexShader ).id;
  11693. }
  11694. getFragmentShaderID( material ) {
  11695. return this._getShaderStage( material.fragmentShader ).id;
  11696. }
  11697. dispose() {
  11698. this.shaderCache.clear();
  11699. this.materialCache.clear();
  11700. }
  11701. _getShaderCacheForMaterial( material ) {
  11702. const cache = this.materialCache;
  11703. let set = cache.get( material );
  11704. if ( set === undefined ) {
  11705. set = new Set();
  11706. cache.set( material, set );
  11707. }
  11708. return set;
  11709. }
  11710. _getShaderStage( code ) {
  11711. const cache = this.shaderCache;
  11712. let stage = cache.get( code );
  11713. if ( stage === undefined ) {
  11714. stage = new WebGLShaderStage( code );
  11715. cache.set( code, stage );
  11716. }
  11717. return stage;
  11718. }
  11719. }
  11720. class WebGLShaderStage {
  11721. constructor( code ) {
  11722. this.id = _id ++;
  11723. this.code = code;
  11724. this.usedTimes = 0;
  11725. }
  11726. }
  11727. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11728. const _programLayers = new Layers();
  11729. const _customShaders = new WebGLShaderCache();
  11730. const programs = [];
  11731. const isWebGL2 = capabilities.isWebGL2;
  11732. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11733. const vertexTextures = capabilities.vertexTextures;
  11734. let precision = capabilities.precision;
  11735. const shaderIDs = {
  11736. MeshDepthMaterial: 'depth',
  11737. MeshDistanceMaterial: 'distanceRGBA',
  11738. MeshNormalMaterial: 'normal',
  11739. MeshBasicMaterial: 'basic',
  11740. MeshLambertMaterial: 'lambert',
  11741. MeshPhongMaterial: 'phong',
  11742. MeshToonMaterial: 'toon',
  11743. MeshStandardMaterial: 'physical',
  11744. MeshPhysicalMaterial: 'physical',
  11745. MeshMatcapMaterial: 'matcap',
  11746. LineBasicMaterial: 'basic',
  11747. LineDashedMaterial: 'dashed',
  11748. PointsMaterial: 'points',
  11749. ShadowMaterial: 'shadow',
  11750. SpriteMaterial: 'sprite'
  11751. };
  11752. function getParameters( material, lights, shadows, scene, object ) {
  11753. const fog = scene.fog;
  11754. const geometry = object.geometry;
  11755. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11756. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11757. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11758. const shaderID = shaderIDs[ material.type ];
  11759. // heuristics to create shader parameters according to lights in the scene
  11760. // (not to blow over maxLights budget)
  11761. if ( material.precision !== null ) {
  11762. precision = capabilities.getMaxPrecision( material.precision );
  11763. if ( precision !== material.precision ) {
  11764. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11765. }
  11766. }
  11767. //
  11768. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11769. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11770. let morphTextureStride = 0;
  11771. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11772. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11773. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11774. //
  11775. let vertexShader, fragmentShader;
  11776. let customVertexShaderID, customFragmentShaderID;
  11777. if ( shaderID ) {
  11778. const shader = ShaderLib[ shaderID ];
  11779. vertexShader = shader.vertexShader;
  11780. fragmentShader = shader.fragmentShader;
  11781. } else {
  11782. vertexShader = material.vertexShader;
  11783. fragmentShader = material.fragmentShader;
  11784. _customShaders.update( material );
  11785. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11786. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11787. }
  11788. const currentRenderTarget = renderer.getRenderTarget();
  11789. const useAlphaTest = material.alphaTest > 0;
  11790. const useClearcoat = material.clearcoat > 0;
  11791. const useIridescence = material.iridescence > 0;
  11792. const parameters = {
  11793. isWebGL2: isWebGL2,
  11794. shaderID: shaderID,
  11795. shaderName: material.type,
  11796. vertexShader: vertexShader,
  11797. fragmentShader: fragmentShader,
  11798. defines: material.defines,
  11799. customVertexShaderID: customVertexShaderID,
  11800. customFragmentShaderID: customFragmentShaderID,
  11801. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11802. glslVersion: material.glslVersion,
  11803. precision: precision,
  11804. instancing: object.isInstancedMesh === true,
  11805. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11806. supportsVertexTextures: vertexTextures,
  11807. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11808. map: !! material.map,
  11809. matcap: !! material.matcap,
  11810. envMap: !! envMap,
  11811. envMapMode: envMap && envMap.mapping,
  11812. envMapCubeUVHeight: envMapCubeUVHeight,
  11813. lightMap: !! material.lightMap,
  11814. aoMap: !! material.aoMap,
  11815. emissiveMap: !! material.emissiveMap,
  11816. bumpMap: !! material.bumpMap,
  11817. normalMap: !! material.normalMap,
  11818. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11819. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11820. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11821. clearcoat: useClearcoat,
  11822. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11823. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11824. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11825. iridescence: useIridescence,
  11826. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11827. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11828. displacementMap: !! material.displacementMap,
  11829. roughnessMap: !! material.roughnessMap,
  11830. metalnessMap: !! material.metalnessMap,
  11831. specularMap: !! material.specularMap,
  11832. specularIntensityMap: !! material.specularIntensityMap,
  11833. specularColorMap: !! material.specularColorMap,
  11834. opaque: material.transparent === false && material.blending === NormalBlending,
  11835. alphaMap: !! material.alphaMap,
  11836. alphaTest: useAlphaTest,
  11837. gradientMap: !! material.gradientMap,
  11838. sheen: material.sheen > 0,
  11839. sheenColorMap: !! material.sheenColorMap,
  11840. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11841. transmission: material.transmission > 0,
  11842. transmissionMap: !! material.transmissionMap,
  11843. thicknessMap: !! material.thicknessMap,
  11844. combine: material.combine,
  11845. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11846. vertexColors: material.vertexColors,
  11847. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11848. 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,
  11849. 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,
  11850. fog: !! fog,
  11851. useFog: material.fog === true,
  11852. fogExp2: ( fog && fog.isFogExp2 ),
  11853. flatShading: !! material.flatShading,
  11854. sizeAttenuation: material.sizeAttenuation,
  11855. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11856. skinning: object.isSkinnedMesh === true,
  11857. morphTargets: geometry.morphAttributes.position !== undefined,
  11858. morphNormals: geometry.morphAttributes.normal !== undefined,
  11859. morphColors: geometry.morphAttributes.color !== undefined,
  11860. morphTargetsCount: morphTargetsCount,
  11861. morphTextureStride: morphTextureStride,
  11862. numDirLights: lights.directional.length,
  11863. numPointLights: lights.point.length,
  11864. numSpotLights: lights.spot.length,
  11865. numSpotLightMaps: lights.spotLightMap.length,
  11866. numRectAreaLights: lights.rectArea.length,
  11867. numHemiLights: lights.hemi.length,
  11868. numDirLightShadows: lights.directionalShadowMap.length,
  11869. numPointLightShadows: lights.pointShadowMap.length,
  11870. numSpotLightShadows: lights.spotShadowMap.length,
  11871. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11872. numClippingPlanes: clipping.numPlanes,
  11873. numClipIntersection: clipping.numIntersection,
  11874. dithering: material.dithering,
  11875. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11876. shadowMapType: renderer.shadowMap.type,
  11877. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11878. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11879. premultipliedAlpha: material.premultipliedAlpha,
  11880. doubleSided: material.side === DoubleSide,
  11881. flipSided: material.side === BackSide,
  11882. useDepthPacking: !! material.depthPacking,
  11883. depthPacking: material.depthPacking || 0,
  11884. index0AttributeName: material.index0AttributeName,
  11885. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11886. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11887. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11888. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11889. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11890. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11891. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11892. customProgramCacheKey: material.customProgramCacheKey()
  11893. };
  11894. return parameters;
  11895. }
  11896. function getProgramCacheKey( parameters ) {
  11897. const array = [];
  11898. if ( parameters.shaderID ) {
  11899. array.push( parameters.shaderID );
  11900. } else {
  11901. array.push( parameters.customVertexShaderID );
  11902. array.push( parameters.customFragmentShaderID );
  11903. }
  11904. if ( parameters.defines !== undefined ) {
  11905. for ( const name in parameters.defines ) {
  11906. array.push( name );
  11907. array.push( parameters.defines[ name ] );
  11908. }
  11909. }
  11910. if ( parameters.isRawShaderMaterial === false ) {
  11911. getProgramCacheKeyParameters( array, parameters );
  11912. getProgramCacheKeyBooleans( array, parameters );
  11913. array.push( renderer.outputEncoding );
  11914. }
  11915. array.push( parameters.customProgramCacheKey );
  11916. return array.join();
  11917. }
  11918. function getProgramCacheKeyParameters( array, parameters ) {
  11919. array.push( parameters.precision );
  11920. array.push( parameters.outputEncoding );
  11921. array.push( parameters.envMapMode );
  11922. array.push( parameters.envMapCubeUVHeight );
  11923. array.push( parameters.combine );
  11924. array.push( parameters.vertexUvs );
  11925. array.push( parameters.fogExp2 );
  11926. array.push( parameters.sizeAttenuation );
  11927. array.push( parameters.morphTargetsCount );
  11928. array.push( parameters.morphAttributeCount );
  11929. array.push( parameters.numDirLights );
  11930. array.push( parameters.numPointLights );
  11931. array.push( parameters.numSpotLights );
  11932. array.push( parameters.numSpotLightMaps );
  11933. array.push( parameters.numHemiLights );
  11934. array.push( parameters.numRectAreaLights );
  11935. array.push( parameters.numDirLightShadows );
  11936. array.push( parameters.numPointLightShadows );
  11937. array.push( parameters.numSpotLightShadows );
  11938. array.push( parameters.numSpotLightShadowsWithMaps );
  11939. array.push( parameters.shadowMapType );
  11940. array.push( parameters.toneMapping );
  11941. array.push( parameters.numClippingPlanes );
  11942. array.push( parameters.numClipIntersection );
  11943. array.push( parameters.depthPacking );
  11944. }
  11945. function getProgramCacheKeyBooleans( array, parameters ) {
  11946. _programLayers.disableAll();
  11947. if ( parameters.isWebGL2 )
  11948. _programLayers.enable( 0 );
  11949. if ( parameters.supportsVertexTextures )
  11950. _programLayers.enable( 1 );
  11951. if ( parameters.instancing )
  11952. _programLayers.enable( 2 );
  11953. if ( parameters.instancingColor )
  11954. _programLayers.enable( 3 );
  11955. if ( parameters.map )
  11956. _programLayers.enable( 4 );
  11957. if ( parameters.matcap )
  11958. _programLayers.enable( 5 );
  11959. if ( parameters.envMap )
  11960. _programLayers.enable( 6 );
  11961. if ( parameters.lightMap )
  11962. _programLayers.enable( 7 );
  11963. if ( parameters.aoMap )
  11964. _programLayers.enable( 8 );
  11965. if ( parameters.emissiveMap )
  11966. _programLayers.enable( 9 );
  11967. if ( parameters.bumpMap )
  11968. _programLayers.enable( 10 );
  11969. if ( parameters.normalMap )
  11970. _programLayers.enable( 11 );
  11971. if ( parameters.objectSpaceNormalMap )
  11972. _programLayers.enable( 12 );
  11973. if ( parameters.tangentSpaceNormalMap )
  11974. _programLayers.enable( 13 );
  11975. if ( parameters.clearcoat )
  11976. _programLayers.enable( 14 );
  11977. if ( parameters.clearcoatMap )
  11978. _programLayers.enable( 15 );
  11979. if ( parameters.clearcoatRoughnessMap )
  11980. _programLayers.enable( 16 );
  11981. if ( parameters.clearcoatNormalMap )
  11982. _programLayers.enable( 17 );
  11983. if ( parameters.iridescence )
  11984. _programLayers.enable( 18 );
  11985. if ( parameters.iridescenceMap )
  11986. _programLayers.enable( 19 );
  11987. if ( parameters.iridescenceThicknessMap )
  11988. _programLayers.enable( 20 );
  11989. if ( parameters.displacementMap )
  11990. _programLayers.enable( 21 );
  11991. if ( parameters.specularMap )
  11992. _programLayers.enable( 22 );
  11993. if ( parameters.roughnessMap )
  11994. _programLayers.enable( 23 );
  11995. if ( parameters.metalnessMap )
  11996. _programLayers.enable( 24 );
  11997. if ( parameters.gradientMap )
  11998. _programLayers.enable( 25 );
  11999. if ( parameters.alphaMap )
  12000. _programLayers.enable( 26 );
  12001. if ( parameters.alphaTest )
  12002. _programLayers.enable( 27 );
  12003. if ( parameters.vertexColors )
  12004. _programLayers.enable( 28 );
  12005. if ( parameters.vertexAlphas )
  12006. _programLayers.enable( 29 );
  12007. if ( parameters.vertexUvs )
  12008. _programLayers.enable( 30 );
  12009. if ( parameters.vertexTangents )
  12010. _programLayers.enable( 31 );
  12011. if ( parameters.uvsVertexOnly )
  12012. _programLayers.enable( 32 );
  12013. array.push( _programLayers.mask );
  12014. _programLayers.disableAll();
  12015. if ( parameters.fog )
  12016. _programLayers.enable( 0 );
  12017. if ( parameters.useFog )
  12018. _programLayers.enable( 1 );
  12019. if ( parameters.flatShading )
  12020. _programLayers.enable( 2 );
  12021. if ( parameters.logarithmicDepthBuffer )
  12022. _programLayers.enable( 3 );
  12023. if ( parameters.skinning )
  12024. _programLayers.enable( 4 );
  12025. if ( parameters.morphTargets )
  12026. _programLayers.enable( 5 );
  12027. if ( parameters.morphNormals )
  12028. _programLayers.enable( 6 );
  12029. if ( parameters.morphColors )
  12030. _programLayers.enable( 7 );
  12031. if ( parameters.premultipliedAlpha )
  12032. _programLayers.enable( 8 );
  12033. if ( parameters.shadowMapEnabled )
  12034. _programLayers.enable( 9 );
  12035. if ( parameters.physicallyCorrectLights )
  12036. _programLayers.enable( 10 );
  12037. if ( parameters.doubleSided )
  12038. _programLayers.enable( 11 );
  12039. if ( parameters.flipSided )
  12040. _programLayers.enable( 12 );
  12041. if ( parameters.useDepthPacking )
  12042. _programLayers.enable( 13 );
  12043. if ( parameters.dithering )
  12044. _programLayers.enable( 14 );
  12045. if ( parameters.specularIntensityMap )
  12046. _programLayers.enable( 15 );
  12047. if ( parameters.specularColorMap )
  12048. _programLayers.enable( 16 );
  12049. if ( parameters.transmission )
  12050. _programLayers.enable( 17 );
  12051. if ( parameters.transmissionMap )
  12052. _programLayers.enable( 18 );
  12053. if ( parameters.thicknessMap )
  12054. _programLayers.enable( 19 );
  12055. if ( parameters.sheen )
  12056. _programLayers.enable( 20 );
  12057. if ( parameters.sheenColorMap )
  12058. _programLayers.enable( 21 );
  12059. if ( parameters.sheenRoughnessMap )
  12060. _programLayers.enable( 22 );
  12061. if ( parameters.decodeVideoTexture )
  12062. _programLayers.enable( 23 );
  12063. if ( parameters.opaque )
  12064. _programLayers.enable( 24 );
  12065. array.push( _programLayers.mask );
  12066. }
  12067. function getUniforms( material ) {
  12068. const shaderID = shaderIDs[ material.type ];
  12069. let uniforms;
  12070. if ( shaderID ) {
  12071. const shader = ShaderLib[ shaderID ];
  12072. uniforms = UniformsUtils.clone( shader.uniforms );
  12073. } else {
  12074. uniforms = material.uniforms;
  12075. }
  12076. return uniforms;
  12077. }
  12078. function acquireProgram( parameters, cacheKey ) {
  12079. let program;
  12080. // Check if code has been already compiled
  12081. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12082. const preexistingProgram = programs[ p ];
  12083. if ( preexistingProgram.cacheKey === cacheKey ) {
  12084. program = preexistingProgram;
  12085. ++ program.usedTimes;
  12086. break;
  12087. }
  12088. }
  12089. if ( program === undefined ) {
  12090. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12091. programs.push( program );
  12092. }
  12093. return program;
  12094. }
  12095. function releaseProgram( program ) {
  12096. if ( -- program.usedTimes === 0 ) {
  12097. // Remove from unordered set
  12098. const i = programs.indexOf( program );
  12099. programs[ i ] = programs[ programs.length - 1 ];
  12100. programs.pop();
  12101. // Free WebGL resources
  12102. program.destroy();
  12103. }
  12104. }
  12105. function releaseShaderCache( material ) {
  12106. _customShaders.remove( material );
  12107. }
  12108. function dispose() {
  12109. _customShaders.dispose();
  12110. }
  12111. return {
  12112. getParameters: getParameters,
  12113. getProgramCacheKey: getProgramCacheKey,
  12114. getUniforms: getUniforms,
  12115. acquireProgram: acquireProgram,
  12116. releaseProgram: releaseProgram,
  12117. releaseShaderCache: releaseShaderCache,
  12118. // Exposed for resource monitoring & error feedback via renderer.info:
  12119. programs: programs,
  12120. dispose: dispose
  12121. };
  12122. }
  12123. function WebGLProperties() {
  12124. let properties = new WeakMap();
  12125. function get( object ) {
  12126. let map = properties.get( object );
  12127. if ( map === undefined ) {
  12128. map = {};
  12129. properties.set( object, map );
  12130. }
  12131. return map;
  12132. }
  12133. function remove( object ) {
  12134. properties.delete( object );
  12135. }
  12136. function update( object, key, value ) {
  12137. properties.get( object )[ key ] = value;
  12138. }
  12139. function dispose() {
  12140. properties = new WeakMap();
  12141. }
  12142. return {
  12143. get: get,
  12144. remove: remove,
  12145. update: update,
  12146. dispose: dispose
  12147. };
  12148. }
  12149. function painterSortStable( a, b ) {
  12150. if ( a.groupOrder !== b.groupOrder ) {
  12151. return a.groupOrder - b.groupOrder;
  12152. } else if ( a.renderOrder !== b.renderOrder ) {
  12153. return a.renderOrder - b.renderOrder;
  12154. } else if ( a.material.id !== b.material.id ) {
  12155. return a.material.id - b.material.id;
  12156. } else if ( a.z !== b.z ) {
  12157. return a.z - b.z;
  12158. } else {
  12159. return a.id - b.id;
  12160. }
  12161. }
  12162. function reversePainterSortStable( a, b ) {
  12163. if ( a.groupOrder !== b.groupOrder ) {
  12164. return a.groupOrder - b.groupOrder;
  12165. } else if ( a.renderOrder !== b.renderOrder ) {
  12166. return a.renderOrder - b.renderOrder;
  12167. } else if ( a.z !== b.z ) {
  12168. return b.z - a.z;
  12169. } else {
  12170. return a.id - b.id;
  12171. }
  12172. }
  12173. function WebGLRenderList() {
  12174. const renderItems = [];
  12175. let renderItemsIndex = 0;
  12176. const opaque = [];
  12177. const transmissive = [];
  12178. const transparent = [];
  12179. function init() {
  12180. renderItemsIndex = 0;
  12181. opaque.length = 0;
  12182. transmissive.length = 0;
  12183. transparent.length = 0;
  12184. }
  12185. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12186. let renderItem = renderItems[ renderItemsIndex ];
  12187. if ( renderItem === undefined ) {
  12188. renderItem = {
  12189. id: object.id,
  12190. object: object,
  12191. geometry: geometry,
  12192. material: material,
  12193. groupOrder: groupOrder,
  12194. renderOrder: object.renderOrder,
  12195. z: z,
  12196. group: group
  12197. };
  12198. renderItems[ renderItemsIndex ] = renderItem;
  12199. } else {
  12200. renderItem.id = object.id;
  12201. renderItem.object = object;
  12202. renderItem.geometry = geometry;
  12203. renderItem.material = material;
  12204. renderItem.groupOrder = groupOrder;
  12205. renderItem.renderOrder = object.renderOrder;
  12206. renderItem.z = z;
  12207. renderItem.group = group;
  12208. }
  12209. renderItemsIndex ++;
  12210. return renderItem;
  12211. }
  12212. function push( object, geometry, material, groupOrder, z, group ) {
  12213. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12214. if ( material.transmission > 0.0 ) {
  12215. transmissive.push( renderItem );
  12216. } else if ( material.transparent === true ) {
  12217. transparent.push( renderItem );
  12218. } else {
  12219. opaque.push( renderItem );
  12220. }
  12221. }
  12222. function unshift( object, geometry, material, groupOrder, z, group ) {
  12223. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12224. if ( material.transmission > 0.0 ) {
  12225. transmissive.unshift( renderItem );
  12226. } else if ( material.transparent === true ) {
  12227. transparent.unshift( renderItem );
  12228. } else {
  12229. opaque.unshift( renderItem );
  12230. }
  12231. }
  12232. function sort( customOpaqueSort, customTransparentSort ) {
  12233. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12234. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12235. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12236. }
  12237. function finish() {
  12238. // Clear references from inactive renderItems in the list
  12239. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12240. const renderItem = renderItems[ i ];
  12241. if ( renderItem.id === null ) break;
  12242. renderItem.id = null;
  12243. renderItem.object = null;
  12244. renderItem.geometry = null;
  12245. renderItem.material = null;
  12246. renderItem.group = null;
  12247. }
  12248. }
  12249. return {
  12250. opaque: opaque,
  12251. transmissive: transmissive,
  12252. transparent: transparent,
  12253. init: init,
  12254. push: push,
  12255. unshift: unshift,
  12256. finish: finish,
  12257. sort: sort
  12258. };
  12259. }
  12260. function WebGLRenderLists() {
  12261. let lists = new WeakMap();
  12262. function get( scene, renderCallDepth ) {
  12263. const listArray = lists.get( scene );
  12264. let list;
  12265. if ( listArray === undefined ) {
  12266. list = new WebGLRenderList();
  12267. lists.set( scene, [ list ] );
  12268. } else {
  12269. if ( renderCallDepth >= listArray.length ) {
  12270. list = new WebGLRenderList();
  12271. listArray.push( list );
  12272. } else {
  12273. list = listArray[ renderCallDepth ];
  12274. }
  12275. }
  12276. return list;
  12277. }
  12278. function dispose() {
  12279. lists = new WeakMap();
  12280. }
  12281. return {
  12282. get: get,
  12283. dispose: dispose
  12284. };
  12285. }
  12286. function UniformsCache() {
  12287. const lights = {};
  12288. return {
  12289. get: function ( light ) {
  12290. if ( lights[ light.id ] !== undefined ) {
  12291. return lights[ light.id ];
  12292. }
  12293. let uniforms;
  12294. switch ( light.type ) {
  12295. case 'DirectionalLight':
  12296. uniforms = {
  12297. direction: new Vector3(),
  12298. color: new Color()
  12299. };
  12300. break;
  12301. case 'SpotLight':
  12302. uniforms = {
  12303. position: new Vector3(),
  12304. direction: new Vector3(),
  12305. color: new Color(),
  12306. distance: 0,
  12307. coneCos: 0,
  12308. penumbraCos: 0,
  12309. decay: 0
  12310. };
  12311. break;
  12312. case 'PointLight':
  12313. uniforms = {
  12314. position: new Vector3(),
  12315. color: new Color(),
  12316. distance: 0,
  12317. decay: 0
  12318. };
  12319. break;
  12320. case 'HemisphereLight':
  12321. uniforms = {
  12322. direction: new Vector3(),
  12323. skyColor: new Color(),
  12324. groundColor: new Color()
  12325. };
  12326. break;
  12327. case 'RectAreaLight':
  12328. uniforms = {
  12329. color: new Color(),
  12330. position: new Vector3(),
  12331. halfWidth: new Vector3(),
  12332. halfHeight: new Vector3()
  12333. };
  12334. break;
  12335. }
  12336. lights[ light.id ] = uniforms;
  12337. return uniforms;
  12338. }
  12339. };
  12340. }
  12341. function ShadowUniformsCache() {
  12342. const lights = {};
  12343. return {
  12344. get: function ( light ) {
  12345. if ( lights[ light.id ] !== undefined ) {
  12346. return lights[ light.id ];
  12347. }
  12348. let uniforms;
  12349. switch ( light.type ) {
  12350. case 'DirectionalLight':
  12351. uniforms = {
  12352. shadowBias: 0,
  12353. shadowNormalBias: 0,
  12354. shadowRadius: 1,
  12355. shadowMapSize: new Vector2()
  12356. };
  12357. break;
  12358. case 'SpotLight':
  12359. uniforms = {
  12360. shadowBias: 0,
  12361. shadowNormalBias: 0,
  12362. shadowRadius: 1,
  12363. shadowMapSize: new Vector2()
  12364. };
  12365. break;
  12366. case 'PointLight':
  12367. uniforms = {
  12368. shadowBias: 0,
  12369. shadowNormalBias: 0,
  12370. shadowRadius: 1,
  12371. shadowMapSize: new Vector2(),
  12372. shadowCameraNear: 1,
  12373. shadowCameraFar: 1000
  12374. };
  12375. break;
  12376. // TODO (abelnation): set RectAreaLight shadow uniforms
  12377. }
  12378. lights[ light.id ] = uniforms;
  12379. return uniforms;
  12380. }
  12381. };
  12382. }
  12383. let nextVersion = 0;
  12384. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12385. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12386. }
  12387. function WebGLLights( extensions, capabilities ) {
  12388. const cache = new UniformsCache();
  12389. const shadowCache = ShadowUniformsCache();
  12390. const state = {
  12391. version: 0,
  12392. hash: {
  12393. directionalLength: - 1,
  12394. pointLength: - 1,
  12395. spotLength: - 1,
  12396. rectAreaLength: - 1,
  12397. hemiLength: - 1,
  12398. numDirectionalShadows: - 1,
  12399. numPointShadows: - 1,
  12400. numSpotShadows: - 1,
  12401. numSpotMaps: - 1
  12402. },
  12403. ambient: [ 0, 0, 0 ],
  12404. probe: [],
  12405. directional: [],
  12406. directionalShadow: [],
  12407. directionalShadowMap: [],
  12408. directionalShadowMatrix: [],
  12409. spot: [],
  12410. spotLightMap: [],
  12411. spotShadow: [],
  12412. spotShadowMap: [],
  12413. spotLightMatrix: [],
  12414. rectArea: [],
  12415. rectAreaLTC1: null,
  12416. rectAreaLTC2: null,
  12417. point: [],
  12418. pointShadow: [],
  12419. pointShadowMap: [],
  12420. pointShadowMatrix: [],
  12421. hemi: [],
  12422. numSpotLightShadowsWithMaps: 0
  12423. };
  12424. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12425. const vector3 = new Vector3();
  12426. const matrix4 = new Matrix4();
  12427. const matrix42 = new Matrix4();
  12428. function setup( lights, physicallyCorrectLights ) {
  12429. let r = 0, g = 0, b = 0;
  12430. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12431. let directionalLength = 0;
  12432. let pointLength = 0;
  12433. let spotLength = 0;
  12434. let rectAreaLength = 0;
  12435. let hemiLength = 0;
  12436. let numDirectionalShadows = 0;
  12437. let numPointShadows = 0;
  12438. let numSpotShadows = 0;
  12439. let numSpotMaps = 0;
  12440. let numSpotShadowsWithMaps = 0;
  12441. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12442. lights.sort( shadowCastingAndTexturingLightsFirst );
  12443. // artist-friendly light intensity scaling factor
  12444. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12445. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12446. const light = lights[ i ];
  12447. const color = light.color;
  12448. const intensity = light.intensity;
  12449. const distance = light.distance;
  12450. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12451. if ( light.isAmbientLight ) {
  12452. r += color.r * intensity * scaleFactor;
  12453. g += color.g * intensity * scaleFactor;
  12454. b += color.b * intensity * scaleFactor;
  12455. } else if ( light.isLightProbe ) {
  12456. for ( let j = 0; j < 9; j ++ ) {
  12457. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12458. }
  12459. } else if ( light.isDirectionalLight ) {
  12460. const uniforms = cache.get( light );
  12461. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12462. if ( light.castShadow ) {
  12463. const shadow = light.shadow;
  12464. const shadowUniforms = shadowCache.get( light );
  12465. shadowUniforms.shadowBias = shadow.bias;
  12466. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12467. shadowUniforms.shadowRadius = shadow.radius;
  12468. shadowUniforms.shadowMapSize = shadow.mapSize;
  12469. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12470. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12471. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12472. numDirectionalShadows ++;
  12473. }
  12474. state.directional[ directionalLength ] = uniforms;
  12475. directionalLength ++;
  12476. } else if ( light.isSpotLight ) {
  12477. const uniforms = cache.get( light );
  12478. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12479. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12480. uniforms.distance = distance;
  12481. uniforms.coneCos = Math.cos( light.angle );
  12482. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12483. uniforms.decay = light.decay;
  12484. state.spot[ spotLength ] = uniforms;
  12485. const shadow = light.shadow;
  12486. if ( light.map ) {
  12487. state.spotLightMap[ numSpotMaps ] = light.map;
  12488. numSpotMaps ++;
  12489. // make sure the lightMatrix is up to date
  12490. // TODO : do it if required only
  12491. shadow.updateMatrices( light );
  12492. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12493. }
  12494. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12495. if ( light.castShadow ) {
  12496. const shadowUniforms = shadowCache.get( light );
  12497. shadowUniforms.shadowBias = shadow.bias;
  12498. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12499. shadowUniforms.shadowRadius = shadow.radius;
  12500. shadowUniforms.shadowMapSize = shadow.mapSize;
  12501. state.spotShadow[ spotLength ] = shadowUniforms;
  12502. state.spotShadowMap[ spotLength ] = shadowMap;
  12503. numSpotShadows ++;
  12504. }
  12505. spotLength ++;
  12506. } else if ( light.isRectAreaLight ) {
  12507. const uniforms = cache.get( light );
  12508. // (a) intensity is the total visible light emitted
  12509. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12510. // (b) intensity is the brightness of the light
  12511. uniforms.color.copy( color ).multiplyScalar( intensity );
  12512. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12513. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12514. state.rectArea[ rectAreaLength ] = uniforms;
  12515. rectAreaLength ++;
  12516. } else if ( light.isPointLight ) {
  12517. const uniforms = cache.get( light );
  12518. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12519. uniforms.distance = light.distance;
  12520. uniforms.decay = light.decay;
  12521. if ( light.castShadow ) {
  12522. const shadow = light.shadow;
  12523. const shadowUniforms = shadowCache.get( light );
  12524. shadowUniforms.shadowBias = shadow.bias;
  12525. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12526. shadowUniforms.shadowRadius = shadow.radius;
  12527. shadowUniforms.shadowMapSize = shadow.mapSize;
  12528. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12529. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12530. state.pointShadow[ pointLength ] = shadowUniforms;
  12531. state.pointShadowMap[ pointLength ] = shadowMap;
  12532. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12533. numPointShadows ++;
  12534. }
  12535. state.point[ pointLength ] = uniforms;
  12536. pointLength ++;
  12537. } else if ( light.isHemisphereLight ) {
  12538. const uniforms = cache.get( light );
  12539. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12540. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12541. state.hemi[ hemiLength ] = uniforms;
  12542. hemiLength ++;
  12543. }
  12544. }
  12545. if ( rectAreaLength > 0 ) {
  12546. if ( capabilities.isWebGL2 ) {
  12547. // WebGL 2
  12548. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12549. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12550. } else {
  12551. // WebGL 1
  12552. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12553. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12554. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12555. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12556. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12557. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12558. } else {
  12559. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12560. }
  12561. }
  12562. }
  12563. state.ambient[ 0 ] = r;
  12564. state.ambient[ 1 ] = g;
  12565. state.ambient[ 2 ] = b;
  12566. const hash = state.hash;
  12567. if ( hash.directionalLength !== directionalLength ||
  12568. hash.pointLength !== pointLength ||
  12569. hash.spotLength !== spotLength ||
  12570. hash.rectAreaLength !== rectAreaLength ||
  12571. hash.hemiLength !== hemiLength ||
  12572. hash.numDirectionalShadows !== numDirectionalShadows ||
  12573. hash.numPointShadows !== numPointShadows ||
  12574. hash.numSpotShadows !== numSpotShadows ||
  12575. hash.numSpotMaps !== numSpotMaps ) {
  12576. state.directional.length = directionalLength;
  12577. state.spot.length = spotLength;
  12578. state.rectArea.length = rectAreaLength;
  12579. state.point.length = pointLength;
  12580. state.hemi.length = hemiLength;
  12581. state.directionalShadow.length = numDirectionalShadows;
  12582. state.directionalShadowMap.length = numDirectionalShadows;
  12583. state.pointShadow.length = numPointShadows;
  12584. state.pointShadowMap.length = numPointShadows;
  12585. state.spotShadow.length = numSpotShadows;
  12586. state.spotShadowMap.length = numSpotShadows;
  12587. state.directionalShadowMatrix.length = numDirectionalShadows;
  12588. state.pointShadowMatrix.length = numPointShadows;
  12589. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12590. state.spotLightMap.length = numSpotMaps;
  12591. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12592. hash.directionalLength = directionalLength;
  12593. hash.pointLength = pointLength;
  12594. hash.spotLength = spotLength;
  12595. hash.rectAreaLength = rectAreaLength;
  12596. hash.hemiLength = hemiLength;
  12597. hash.numDirectionalShadows = numDirectionalShadows;
  12598. hash.numPointShadows = numPointShadows;
  12599. hash.numSpotShadows = numSpotShadows;
  12600. hash.numSpotMaps = numSpotMaps;
  12601. state.version = nextVersion ++;
  12602. }
  12603. }
  12604. function setupView( lights, camera ) {
  12605. let directionalLength = 0;
  12606. let pointLength = 0;
  12607. let spotLength = 0;
  12608. let rectAreaLength = 0;
  12609. let hemiLength = 0;
  12610. const viewMatrix = camera.matrixWorldInverse;
  12611. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12612. const light = lights[ i ];
  12613. if ( light.isDirectionalLight ) {
  12614. const uniforms = state.directional[ directionalLength ];
  12615. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12616. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12617. uniforms.direction.sub( vector3 );
  12618. uniforms.direction.transformDirection( viewMatrix );
  12619. directionalLength ++;
  12620. } else if ( light.isSpotLight ) {
  12621. const uniforms = state.spot[ spotLength ];
  12622. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12623. uniforms.position.applyMatrix4( viewMatrix );
  12624. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12625. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12626. uniforms.direction.sub( vector3 );
  12627. uniforms.direction.transformDirection( viewMatrix );
  12628. spotLength ++;
  12629. } else if ( light.isRectAreaLight ) {
  12630. const uniforms = state.rectArea[ rectAreaLength ];
  12631. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12632. uniforms.position.applyMatrix4( viewMatrix );
  12633. // extract local rotation of light to derive width/height half vectors
  12634. matrix42.identity();
  12635. matrix4.copy( light.matrixWorld );
  12636. matrix4.premultiply( viewMatrix );
  12637. matrix42.extractRotation( matrix4 );
  12638. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12639. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12640. uniforms.halfWidth.applyMatrix4( matrix42 );
  12641. uniforms.halfHeight.applyMatrix4( matrix42 );
  12642. rectAreaLength ++;
  12643. } else if ( light.isPointLight ) {
  12644. const uniforms = state.point[ pointLength ];
  12645. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12646. uniforms.position.applyMatrix4( viewMatrix );
  12647. pointLength ++;
  12648. } else if ( light.isHemisphereLight ) {
  12649. const uniforms = state.hemi[ hemiLength ];
  12650. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12651. uniforms.direction.transformDirection( viewMatrix );
  12652. hemiLength ++;
  12653. }
  12654. }
  12655. }
  12656. return {
  12657. setup: setup,
  12658. setupView: setupView,
  12659. state: state
  12660. };
  12661. }
  12662. function WebGLRenderState( extensions, capabilities ) {
  12663. const lights = new WebGLLights( extensions, capabilities );
  12664. const lightsArray = [];
  12665. const shadowsArray = [];
  12666. function init() {
  12667. lightsArray.length = 0;
  12668. shadowsArray.length = 0;
  12669. }
  12670. function pushLight( light ) {
  12671. lightsArray.push( light );
  12672. }
  12673. function pushShadow( shadowLight ) {
  12674. shadowsArray.push( shadowLight );
  12675. }
  12676. function setupLights( physicallyCorrectLights ) {
  12677. lights.setup( lightsArray, physicallyCorrectLights );
  12678. }
  12679. function setupLightsView( camera ) {
  12680. lights.setupView( lightsArray, camera );
  12681. }
  12682. const state = {
  12683. lightsArray: lightsArray,
  12684. shadowsArray: shadowsArray,
  12685. lights: lights
  12686. };
  12687. return {
  12688. init: init,
  12689. state: state,
  12690. setupLights: setupLights,
  12691. setupLightsView: setupLightsView,
  12692. pushLight: pushLight,
  12693. pushShadow: pushShadow
  12694. };
  12695. }
  12696. function WebGLRenderStates( extensions, capabilities ) {
  12697. let renderStates = new WeakMap();
  12698. function get( scene, renderCallDepth = 0 ) {
  12699. const renderStateArray = renderStates.get( scene );
  12700. let renderState;
  12701. if ( renderStateArray === undefined ) {
  12702. renderState = new WebGLRenderState( extensions, capabilities );
  12703. renderStates.set( scene, [ renderState ] );
  12704. } else {
  12705. if ( renderCallDepth >= renderStateArray.length ) {
  12706. renderState = new WebGLRenderState( extensions, capabilities );
  12707. renderStateArray.push( renderState );
  12708. } else {
  12709. renderState = renderStateArray[ renderCallDepth ];
  12710. }
  12711. }
  12712. return renderState;
  12713. }
  12714. function dispose() {
  12715. renderStates = new WeakMap();
  12716. }
  12717. return {
  12718. get: get,
  12719. dispose: dispose
  12720. };
  12721. }
  12722. class MeshDepthMaterial extends Material {
  12723. constructor( parameters ) {
  12724. super();
  12725. this.isMeshDepthMaterial = true;
  12726. this.type = 'MeshDepthMaterial';
  12727. this.depthPacking = BasicDepthPacking;
  12728. this.map = null;
  12729. this.alphaMap = null;
  12730. this.displacementMap = null;
  12731. this.displacementScale = 1;
  12732. this.displacementBias = 0;
  12733. this.wireframe = false;
  12734. this.wireframeLinewidth = 1;
  12735. this.setValues( parameters );
  12736. }
  12737. copy( source ) {
  12738. super.copy( source );
  12739. this.depthPacking = source.depthPacking;
  12740. this.map = source.map;
  12741. this.alphaMap = source.alphaMap;
  12742. this.displacementMap = source.displacementMap;
  12743. this.displacementScale = source.displacementScale;
  12744. this.displacementBias = source.displacementBias;
  12745. this.wireframe = source.wireframe;
  12746. this.wireframeLinewidth = source.wireframeLinewidth;
  12747. return this;
  12748. }
  12749. }
  12750. class MeshDistanceMaterial extends Material {
  12751. constructor( parameters ) {
  12752. super();
  12753. this.isMeshDistanceMaterial = true;
  12754. this.type = 'MeshDistanceMaterial';
  12755. this.referencePosition = new Vector3();
  12756. this.nearDistance = 1;
  12757. this.farDistance = 1000;
  12758. this.map = null;
  12759. this.alphaMap = null;
  12760. this.displacementMap = null;
  12761. this.displacementScale = 1;
  12762. this.displacementBias = 0;
  12763. this.setValues( parameters );
  12764. }
  12765. copy( source ) {
  12766. super.copy( source );
  12767. this.referencePosition.copy( source.referencePosition );
  12768. this.nearDistance = source.nearDistance;
  12769. this.farDistance = source.farDistance;
  12770. this.map = source.map;
  12771. this.alphaMap = source.alphaMap;
  12772. this.displacementMap = source.displacementMap;
  12773. this.displacementScale = source.displacementScale;
  12774. this.displacementBias = source.displacementBias;
  12775. return this;
  12776. }
  12777. }
  12778. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12779. 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}";
  12780. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12781. let _frustum = new Frustum();
  12782. const _shadowMapSize = new Vector2(),
  12783. _viewportSize = new Vector2(),
  12784. _viewport = new Vector4(),
  12785. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12786. _distanceMaterial = new MeshDistanceMaterial(),
  12787. _materialCache = {},
  12788. _maxTextureSize = _capabilities.maxTextureSize;
  12789. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12790. const shadowMaterialVertical = new ShaderMaterial( {
  12791. defines: {
  12792. VSM_SAMPLES: 8
  12793. },
  12794. uniforms: {
  12795. shadow_pass: { value: null },
  12796. resolution: { value: new Vector2() },
  12797. radius: { value: 4.0 }
  12798. },
  12799. vertexShader: vertex,
  12800. fragmentShader: fragment
  12801. } );
  12802. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12803. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12804. const fullScreenTri = new BufferGeometry();
  12805. fullScreenTri.setAttribute(
  12806. 'position',
  12807. new BufferAttribute(
  12808. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12809. 3
  12810. )
  12811. );
  12812. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12813. const scope = this;
  12814. this.enabled = false;
  12815. this.autoUpdate = true;
  12816. this.needsUpdate = false;
  12817. this.type = PCFShadowMap;
  12818. this.render = function ( lights, scene, camera ) {
  12819. if ( scope.enabled === false ) return;
  12820. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12821. if ( lights.length === 0 ) return;
  12822. const currentRenderTarget = _renderer.getRenderTarget();
  12823. const activeCubeFace = _renderer.getActiveCubeFace();
  12824. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12825. const _state = _renderer.state;
  12826. // Set GL state for depth map.
  12827. _state.setBlending( NoBlending );
  12828. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12829. _state.buffers.depth.setTest( true );
  12830. _state.setScissorTest( false );
  12831. // render depth map
  12832. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12833. const light = lights[ i ];
  12834. const shadow = light.shadow;
  12835. if ( shadow === undefined ) {
  12836. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12837. continue;
  12838. }
  12839. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12840. _shadowMapSize.copy( shadow.mapSize );
  12841. const shadowFrameExtents = shadow.getFrameExtents();
  12842. _shadowMapSize.multiply( shadowFrameExtents );
  12843. _viewportSize.copy( shadow.mapSize );
  12844. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12845. if ( _shadowMapSize.x > _maxTextureSize ) {
  12846. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12847. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12848. shadow.mapSize.x = _viewportSize.x;
  12849. }
  12850. if ( _shadowMapSize.y > _maxTextureSize ) {
  12851. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12852. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12853. shadow.mapSize.y = _viewportSize.y;
  12854. }
  12855. }
  12856. if ( shadow.map === null ) {
  12857. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12858. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12859. shadow.map.texture.name = light.name + '.shadowMap';
  12860. shadow.camera.updateProjectionMatrix();
  12861. }
  12862. _renderer.setRenderTarget( shadow.map );
  12863. _renderer.clear();
  12864. const viewportCount = shadow.getViewportCount();
  12865. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12866. const viewport = shadow.getViewport( vp );
  12867. _viewport.set(
  12868. _viewportSize.x * viewport.x,
  12869. _viewportSize.y * viewport.y,
  12870. _viewportSize.x * viewport.z,
  12871. _viewportSize.y * viewport.w
  12872. );
  12873. _state.viewport( _viewport );
  12874. shadow.updateMatrices( light, vp );
  12875. _frustum = shadow.getFrustum();
  12876. renderObject( scene, camera, shadow.camera, light, this.type );
  12877. }
  12878. // do blur pass for VSM
  12879. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12880. VSMPass( shadow, camera );
  12881. }
  12882. shadow.needsUpdate = false;
  12883. }
  12884. scope.needsUpdate = false;
  12885. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12886. };
  12887. function VSMPass( shadow, camera ) {
  12888. const geometry = _objects.update( fullScreenMesh );
  12889. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12890. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12891. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12892. shadowMaterialVertical.needsUpdate = true;
  12893. shadowMaterialHorizontal.needsUpdate = true;
  12894. }
  12895. if ( shadow.mapPass === null ) {
  12896. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12897. }
  12898. // vertical pass
  12899. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12900. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12901. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12902. _renderer.setRenderTarget( shadow.mapPass );
  12903. _renderer.clear();
  12904. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12905. // horizontal pass
  12906. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12907. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12908. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12909. _renderer.setRenderTarget( shadow.map );
  12910. _renderer.clear();
  12911. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12912. }
  12913. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12914. let result = null;
  12915. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12916. if ( customMaterial !== undefined ) {
  12917. result = customMaterial;
  12918. } else {
  12919. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12920. }
  12921. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12922. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12923. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12924. // in this case we need a unique material instance reflecting the
  12925. // appropriate state
  12926. const keyA = result.uuid, keyB = material.uuid;
  12927. let materialsForVariant = _materialCache[ keyA ];
  12928. if ( materialsForVariant === undefined ) {
  12929. materialsForVariant = {};
  12930. _materialCache[ keyA ] = materialsForVariant;
  12931. }
  12932. let cachedMaterial = materialsForVariant[ keyB ];
  12933. if ( cachedMaterial === undefined ) {
  12934. cachedMaterial = result.clone();
  12935. materialsForVariant[ keyB ] = cachedMaterial;
  12936. }
  12937. result = cachedMaterial;
  12938. }
  12939. result.visible = material.visible;
  12940. result.wireframe = material.wireframe;
  12941. if ( type === VSMShadowMap ) {
  12942. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12943. } else {
  12944. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12945. }
  12946. result.alphaMap = material.alphaMap;
  12947. result.alphaTest = material.alphaTest;
  12948. result.clipShadows = material.clipShadows;
  12949. result.clippingPlanes = material.clippingPlanes;
  12950. result.clipIntersection = material.clipIntersection;
  12951. result.displacementMap = material.displacementMap;
  12952. result.displacementScale = material.displacementScale;
  12953. result.displacementBias = material.displacementBias;
  12954. result.wireframeLinewidth = material.wireframeLinewidth;
  12955. result.linewidth = material.linewidth;
  12956. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12957. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12958. result.nearDistance = shadowCameraNear;
  12959. result.farDistance = shadowCameraFar;
  12960. }
  12961. return result;
  12962. }
  12963. function renderObject( object, camera, shadowCamera, light, type ) {
  12964. if ( object.visible === false ) return;
  12965. const visible = object.layers.test( camera.layers );
  12966. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12967. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12968. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12969. const geometry = _objects.update( object );
  12970. const material = object.material;
  12971. if ( Array.isArray( material ) ) {
  12972. const groups = geometry.groups;
  12973. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12974. const group = groups[ k ];
  12975. const groupMaterial = material[ group.materialIndex ];
  12976. if ( groupMaterial && groupMaterial.visible ) {
  12977. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12978. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12979. }
  12980. }
  12981. } else if ( material.visible ) {
  12982. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12983. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12984. }
  12985. }
  12986. }
  12987. const children = object.children;
  12988. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12989. renderObject( children[ i ], camera, shadowCamera, light, type );
  12990. }
  12991. }
  12992. }
  12993. function WebGLState( gl, extensions, capabilities ) {
  12994. const isWebGL2 = capabilities.isWebGL2;
  12995. function ColorBuffer() {
  12996. let locked = false;
  12997. const color = new Vector4();
  12998. let currentColorMask = null;
  12999. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13000. return {
  13001. setMask: function ( colorMask ) {
  13002. if ( currentColorMask !== colorMask && ! locked ) {
  13003. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13004. currentColorMask = colorMask;
  13005. }
  13006. },
  13007. setLocked: function ( lock ) {
  13008. locked = lock;
  13009. },
  13010. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13011. if ( premultipliedAlpha === true ) {
  13012. r *= a; g *= a; b *= a;
  13013. }
  13014. color.set( r, g, b, a );
  13015. if ( currentColorClear.equals( color ) === false ) {
  13016. gl.clearColor( r, g, b, a );
  13017. currentColorClear.copy( color );
  13018. }
  13019. },
  13020. reset: function () {
  13021. locked = false;
  13022. currentColorMask = null;
  13023. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13024. }
  13025. };
  13026. }
  13027. function DepthBuffer() {
  13028. let locked = false;
  13029. let currentDepthMask = null;
  13030. let currentDepthFunc = null;
  13031. let currentDepthClear = null;
  13032. return {
  13033. setTest: function ( depthTest ) {
  13034. if ( depthTest ) {
  13035. enable( 2929 );
  13036. } else {
  13037. disable( 2929 );
  13038. }
  13039. },
  13040. setMask: function ( depthMask ) {
  13041. if ( currentDepthMask !== depthMask && ! locked ) {
  13042. gl.depthMask( depthMask );
  13043. currentDepthMask = depthMask;
  13044. }
  13045. },
  13046. setFunc: function ( depthFunc ) {
  13047. if ( currentDepthFunc !== depthFunc ) {
  13048. if ( depthFunc ) {
  13049. switch ( depthFunc ) {
  13050. case NeverDepth:
  13051. gl.depthFunc( 512 );
  13052. break;
  13053. case AlwaysDepth:
  13054. gl.depthFunc( 519 );
  13055. break;
  13056. case LessDepth:
  13057. gl.depthFunc( 513 );
  13058. break;
  13059. case LessEqualDepth:
  13060. gl.depthFunc( 515 );
  13061. break;
  13062. case EqualDepth:
  13063. gl.depthFunc( 514 );
  13064. break;
  13065. case GreaterEqualDepth:
  13066. gl.depthFunc( 518 );
  13067. break;
  13068. case GreaterDepth:
  13069. gl.depthFunc( 516 );
  13070. break;
  13071. case NotEqualDepth:
  13072. gl.depthFunc( 517 );
  13073. break;
  13074. default:
  13075. gl.depthFunc( 515 );
  13076. }
  13077. } else {
  13078. gl.depthFunc( 515 );
  13079. }
  13080. currentDepthFunc = depthFunc;
  13081. }
  13082. },
  13083. setLocked: function ( lock ) {
  13084. locked = lock;
  13085. },
  13086. setClear: function ( depth ) {
  13087. if ( currentDepthClear !== depth ) {
  13088. gl.clearDepth( depth );
  13089. currentDepthClear = depth;
  13090. }
  13091. },
  13092. reset: function () {
  13093. locked = false;
  13094. currentDepthMask = null;
  13095. currentDepthFunc = null;
  13096. currentDepthClear = null;
  13097. }
  13098. };
  13099. }
  13100. function StencilBuffer() {
  13101. let locked = false;
  13102. let currentStencilMask = null;
  13103. let currentStencilFunc = null;
  13104. let currentStencilRef = null;
  13105. let currentStencilFuncMask = null;
  13106. let currentStencilFail = null;
  13107. let currentStencilZFail = null;
  13108. let currentStencilZPass = null;
  13109. let currentStencilClear = null;
  13110. return {
  13111. setTest: function ( stencilTest ) {
  13112. if ( ! locked ) {
  13113. if ( stencilTest ) {
  13114. enable( 2960 );
  13115. } else {
  13116. disable( 2960 );
  13117. }
  13118. }
  13119. },
  13120. setMask: function ( stencilMask ) {
  13121. if ( currentStencilMask !== stencilMask && ! locked ) {
  13122. gl.stencilMask( stencilMask );
  13123. currentStencilMask = stencilMask;
  13124. }
  13125. },
  13126. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13127. if ( currentStencilFunc !== stencilFunc ||
  13128. currentStencilRef !== stencilRef ||
  13129. currentStencilFuncMask !== stencilMask ) {
  13130. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13131. currentStencilFunc = stencilFunc;
  13132. currentStencilRef = stencilRef;
  13133. currentStencilFuncMask = stencilMask;
  13134. }
  13135. },
  13136. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13137. if ( currentStencilFail !== stencilFail ||
  13138. currentStencilZFail !== stencilZFail ||
  13139. currentStencilZPass !== stencilZPass ) {
  13140. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13141. currentStencilFail = stencilFail;
  13142. currentStencilZFail = stencilZFail;
  13143. currentStencilZPass = stencilZPass;
  13144. }
  13145. },
  13146. setLocked: function ( lock ) {
  13147. locked = lock;
  13148. },
  13149. setClear: function ( stencil ) {
  13150. if ( currentStencilClear !== stencil ) {
  13151. gl.clearStencil( stencil );
  13152. currentStencilClear = stencil;
  13153. }
  13154. },
  13155. reset: function () {
  13156. locked = false;
  13157. currentStencilMask = null;
  13158. currentStencilFunc = null;
  13159. currentStencilRef = null;
  13160. currentStencilFuncMask = null;
  13161. currentStencilFail = null;
  13162. currentStencilZFail = null;
  13163. currentStencilZPass = null;
  13164. currentStencilClear = null;
  13165. }
  13166. };
  13167. }
  13168. //
  13169. const colorBuffer = new ColorBuffer();
  13170. const depthBuffer = new DepthBuffer();
  13171. const stencilBuffer = new StencilBuffer();
  13172. const uboBindings = new WeakMap();
  13173. const uboProgamMap = new WeakMap();
  13174. let enabledCapabilities = {};
  13175. let currentBoundFramebuffers = {};
  13176. let currentDrawbuffers = new WeakMap();
  13177. let defaultDrawbuffers = [];
  13178. let currentProgram = null;
  13179. let currentBlendingEnabled = false;
  13180. let currentBlending = null;
  13181. let currentBlendEquation = null;
  13182. let currentBlendSrc = null;
  13183. let currentBlendDst = null;
  13184. let currentBlendEquationAlpha = null;
  13185. let currentBlendSrcAlpha = null;
  13186. let currentBlendDstAlpha = null;
  13187. let currentPremultipledAlpha = false;
  13188. let currentFlipSided = null;
  13189. let currentCullFace = null;
  13190. let currentLineWidth = null;
  13191. let currentPolygonOffsetFactor = null;
  13192. let currentPolygonOffsetUnits = null;
  13193. const maxTextures = gl.getParameter( 35661 );
  13194. let lineWidthAvailable = false;
  13195. let version = 0;
  13196. const glVersion = gl.getParameter( 7938 );
  13197. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13198. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13199. lineWidthAvailable = ( version >= 1.0 );
  13200. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13201. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13202. lineWidthAvailable = ( version >= 2.0 );
  13203. }
  13204. let currentTextureSlot = null;
  13205. let currentBoundTextures = {};
  13206. const scissorParam = gl.getParameter( 3088 );
  13207. const viewportParam = gl.getParameter( 2978 );
  13208. const currentScissor = new Vector4().fromArray( scissorParam );
  13209. const currentViewport = new Vector4().fromArray( viewportParam );
  13210. function createTexture( type, target, count ) {
  13211. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13212. const texture = gl.createTexture();
  13213. gl.bindTexture( type, texture );
  13214. gl.texParameteri( type, 10241, 9728 );
  13215. gl.texParameteri( type, 10240, 9728 );
  13216. for ( let i = 0; i < count; i ++ ) {
  13217. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13218. }
  13219. return texture;
  13220. }
  13221. const emptyTextures = {};
  13222. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13223. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13224. // init
  13225. colorBuffer.setClear( 0, 0, 0, 1 );
  13226. depthBuffer.setClear( 1 );
  13227. stencilBuffer.setClear( 0 );
  13228. enable( 2929 );
  13229. depthBuffer.setFunc( LessEqualDepth );
  13230. setFlipSided( false );
  13231. setCullFace( CullFaceBack );
  13232. enable( 2884 );
  13233. setBlending( NoBlending );
  13234. //
  13235. function enable( id ) {
  13236. if ( enabledCapabilities[ id ] !== true ) {
  13237. gl.enable( id );
  13238. enabledCapabilities[ id ] = true;
  13239. }
  13240. }
  13241. function disable( id ) {
  13242. if ( enabledCapabilities[ id ] !== false ) {
  13243. gl.disable( id );
  13244. enabledCapabilities[ id ] = false;
  13245. }
  13246. }
  13247. function bindFramebuffer( target, framebuffer ) {
  13248. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13249. gl.bindFramebuffer( target, framebuffer );
  13250. currentBoundFramebuffers[ target ] = framebuffer;
  13251. if ( isWebGL2 ) {
  13252. // 36009 is equivalent to 36160
  13253. if ( target === 36009 ) {
  13254. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13255. }
  13256. if ( target === 36160 ) {
  13257. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13258. }
  13259. }
  13260. return true;
  13261. }
  13262. return false;
  13263. }
  13264. function drawBuffers( renderTarget, framebuffer ) {
  13265. let drawBuffers = defaultDrawbuffers;
  13266. let needsUpdate = false;
  13267. if ( renderTarget ) {
  13268. drawBuffers = currentDrawbuffers.get( framebuffer );
  13269. if ( drawBuffers === undefined ) {
  13270. drawBuffers = [];
  13271. currentDrawbuffers.set( framebuffer, drawBuffers );
  13272. }
  13273. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13274. const textures = renderTarget.texture;
  13275. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13276. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13277. drawBuffers[ i ] = 36064 + i;
  13278. }
  13279. drawBuffers.length = textures.length;
  13280. needsUpdate = true;
  13281. }
  13282. } else {
  13283. if ( drawBuffers[ 0 ] !== 36064 ) {
  13284. drawBuffers[ 0 ] = 36064;
  13285. needsUpdate = true;
  13286. }
  13287. }
  13288. } else {
  13289. if ( drawBuffers[ 0 ] !== 1029 ) {
  13290. drawBuffers[ 0 ] = 1029;
  13291. needsUpdate = true;
  13292. }
  13293. }
  13294. if ( needsUpdate ) {
  13295. if ( capabilities.isWebGL2 ) {
  13296. gl.drawBuffers( drawBuffers );
  13297. } else {
  13298. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13299. }
  13300. }
  13301. }
  13302. function useProgram( program ) {
  13303. if ( currentProgram !== program ) {
  13304. gl.useProgram( program );
  13305. currentProgram = program;
  13306. return true;
  13307. }
  13308. return false;
  13309. }
  13310. const equationToGL = {
  13311. [ AddEquation ]: 32774,
  13312. [ SubtractEquation ]: 32778,
  13313. [ ReverseSubtractEquation ]: 32779
  13314. };
  13315. if ( isWebGL2 ) {
  13316. equationToGL[ MinEquation ] = 32775;
  13317. equationToGL[ MaxEquation ] = 32776;
  13318. } else {
  13319. const extension = extensions.get( 'EXT_blend_minmax' );
  13320. if ( extension !== null ) {
  13321. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13322. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13323. }
  13324. }
  13325. const factorToGL = {
  13326. [ ZeroFactor ]: 0,
  13327. [ OneFactor ]: 1,
  13328. [ SrcColorFactor ]: 768,
  13329. [ SrcAlphaFactor ]: 770,
  13330. [ SrcAlphaSaturateFactor ]: 776,
  13331. [ DstColorFactor ]: 774,
  13332. [ DstAlphaFactor ]: 772,
  13333. [ OneMinusSrcColorFactor ]: 769,
  13334. [ OneMinusSrcAlphaFactor ]: 771,
  13335. [ OneMinusDstColorFactor ]: 775,
  13336. [ OneMinusDstAlphaFactor ]: 773
  13337. };
  13338. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13339. if ( blending === NoBlending ) {
  13340. if ( currentBlendingEnabled === true ) {
  13341. disable( 3042 );
  13342. currentBlendingEnabled = false;
  13343. }
  13344. return;
  13345. }
  13346. if ( currentBlendingEnabled === false ) {
  13347. enable( 3042 );
  13348. currentBlendingEnabled = true;
  13349. }
  13350. if ( blending !== CustomBlending ) {
  13351. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13352. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13353. gl.blendEquation( 32774 );
  13354. currentBlendEquation = AddEquation;
  13355. currentBlendEquationAlpha = AddEquation;
  13356. }
  13357. if ( premultipliedAlpha ) {
  13358. switch ( blending ) {
  13359. case NormalBlending:
  13360. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13361. break;
  13362. case AdditiveBlending:
  13363. gl.blendFunc( 1, 1 );
  13364. break;
  13365. case SubtractiveBlending:
  13366. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13367. break;
  13368. case MultiplyBlending:
  13369. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13370. break;
  13371. default:
  13372. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13373. break;
  13374. }
  13375. } else {
  13376. switch ( blending ) {
  13377. case NormalBlending:
  13378. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13379. break;
  13380. case AdditiveBlending:
  13381. gl.blendFunc( 770, 1 );
  13382. break;
  13383. case SubtractiveBlending:
  13384. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13385. break;
  13386. case MultiplyBlending:
  13387. gl.blendFunc( 0, 768 );
  13388. break;
  13389. default:
  13390. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13391. break;
  13392. }
  13393. }
  13394. currentBlendSrc = null;
  13395. currentBlendDst = null;
  13396. currentBlendSrcAlpha = null;
  13397. currentBlendDstAlpha = null;
  13398. currentBlending = blending;
  13399. currentPremultipledAlpha = premultipliedAlpha;
  13400. }
  13401. return;
  13402. }
  13403. // custom blending
  13404. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13405. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13406. blendDstAlpha = blendDstAlpha || blendDst;
  13407. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13408. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13409. currentBlendEquation = blendEquation;
  13410. currentBlendEquationAlpha = blendEquationAlpha;
  13411. }
  13412. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13413. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13414. currentBlendSrc = blendSrc;
  13415. currentBlendDst = blendDst;
  13416. currentBlendSrcAlpha = blendSrcAlpha;
  13417. currentBlendDstAlpha = blendDstAlpha;
  13418. }
  13419. currentBlending = blending;
  13420. currentPremultipledAlpha = null;
  13421. }
  13422. function setMaterial( material, frontFaceCW ) {
  13423. material.side === DoubleSide
  13424. ? disable( 2884 )
  13425. : enable( 2884 );
  13426. let flipSided = ( material.side === BackSide );
  13427. if ( frontFaceCW ) flipSided = ! flipSided;
  13428. setFlipSided( flipSided );
  13429. ( material.blending === NormalBlending && material.transparent === false )
  13430. ? setBlending( NoBlending )
  13431. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13432. depthBuffer.setFunc( material.depthFunc );
  13433. depthBuffer.setTest( material.depthTest );
  13434. depthBuffer.setMask( material.depthWrite );
  13435. colorBuffer.setMask( material.colorWrite );
  13436. const stencilWrite = material.stencilWrite;
  13437. stencilBuffer.setTest( stencilWrite );
  13438. if ( stencilWrite ) {
  13439. stencilBuffer.setMask( material.stencilWriteMask );
  13440. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13441. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13442. }
  13443. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13444. material.alphaToCoverage === true
  13445. ? enable( 32926 )
  13446. : disable( 32926 );
  13447. }
  13448. //
  13449. function setFlipSided( flipSided ) {
  13450. if ( currentFlipSided !== flipSided ) {
  13451. if ( flipSided ) {
  13452. gl.frontFace( 2304 );
  13453. } else {
  13454. gl.frontFace( 2305 );
  13455. }
  13456. currentFlipSided = flipSided;
  13457. }
  13458. }
  13459. function setCullFace( cullFace ) {
  13460. if ( cullFace !== CullFaceNone ) {
  13461. enable( 2884 );
  13462. if ( cullFace !== currentCullFace ) {
  13463. if ( cullFace === CullFaceBack ) {
  13464. gl.cullFace( 1029 );
  13465. } else if ( cullFace === CullFaceFront ) {
  13466. gl.cullFace( 1028 );
  13467. } else {
  13468. gl.cullFace( 1032 );
  13469. }
  13470. }
  13471. } else {
  13472. disable( 2884 );
  13473. }
  13474. currentCullFace = cullFace;
  13475. }
  13476. function setLineWidth( width ) {
  13477. if ( width !== currentLineWidth ) {
  13478. if ( lineWidthAvailable ) gl.lineWidth( width );
  13479. currentLineWidth = width;
  13480. }
  13481. }
  13482. function setPolygonOffset( polygonOffset, factor, units ) {
  13483. if ( polygonOffset ) {
  13484. enable( 32823 );
  13485. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13486. gl.polygonOffset( factor, units );
  13487. currentPolygonOffsetFactor = factor;
  13488. currentPolygonOffsetUnits = units;
  13489. }
  13490. } else {
  13491. disable( 32823 );
  13492. }
  13493. }
  13494. function setScissorTest( scissorTest ) {
  13495. if ( scissorTest ) {
  13496. enable( 3089 );
  13497. } else {
  13498. disable( 3089 );
  13499. }
  13500. }
  13501. // texture
  13502. function activeTexture( webglSlot ) {
  13503. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13504. if ( currentTextureSlot !== webglSlot ) {
  13505. gl.activeTexture( webglSlot );
  13506. currentTextureSlot = webglSlot;
  13507. }
  13508. }
  13509. function bindTexture( webglType, webglTexture ) {
  13510. if ( currentTextureSlot === null ) {
  13511. activeTexture();
  13512. }
  13513. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  13514. if ( boundTexture === undefined ) {
  13515. boundTexture = { type: undefined, texture: undefined };
  13516. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  13517. }
  13518. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13519. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13520. boundTexture.type = webglType;
  13521. boundTexture.texture = webglTexture;
  13522. }
  13523. }
  13524. function unbindTexture() {
  13525. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13526. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13527. gl.bindTexture( boundTexture.type, null );
  13528. boundTexture.type = undefined;
  13529. boundTexture.texture = undefined;
  13530. }
  13531. }
  13532. function compressedTexImage2D() {
  13533. try {
  13534. gl.compressedTexImage2D.apply( gl, arguments );
  13535. } catch ( error ) {
  13536. console.error( 'THREE.WebGLState:', error );
  13537. }
  13538. }
  13539. function texSubImage2D() {
  13540. try {
  13541. gl.texSubImage2D.apply( gl, arguments );
  13542. } catch ( error ) {
  13543. console.error( 'THREE.WebGLState:', error );
  13544. }
  13545. }
  13546. function texSubImage3D() {
  13547. try {
  13548. gl.texSubImage3D.apply( gl, arguments );
  13549. } catch ( error ) {
  13550. console.error( 'THREE.WebGLState:', error );
  13551. }
  13552. }
  13553. function compressedTexSubImage2D() {
  13554. try {
  13555. gl.compressedTexSubImage2D.apply( gl, arguments );
  13556. } catch ( error ) {
  13557. console.error( 'THREE.WebGLState:', error );
  13558. }
  13559. }
  13560. function texStorage2D() {
  13561. try {
  13562. gl.texStorage2D.apply( gl, arguments );
  13563. } catch ( error ) {
  13564. console.error( 'THREE.WebGLState:', error );
  13565. }
  13566. }
  13567. function texStorage3D() {
  13568. try {
  13569. gl.texStorage3D.apply( gl, arguments );
  13570. } catch ( error ) {
  13571. console.error( 'THREE.WebGLState:', error );
  13572. }
  13573. }
  13574. function texImage2D() {
  13575. try {
  13576. gl.texImage2D.apply( gl, arguments );
  13577. } catch ( error ) {
  13578. console.error( 'THREE.WebGLState:', error );
  13579. }
  13580. }
  13581. function texImage3D() {
  13582. try {
  13583. gl.texImage3D.apply( gl, arguments );
  13584. } catch ( error ) {
  13585. console.error( 'THREE.WebGLState:', error );
  13586. }
  13587. }
  13588. //
  13589. function scissor( scissor ) {
  13590. if ( currentScissor.equals( scissor ) === false ) {
  13591. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13592. currentScissor.copy( scissor );
  13593. }
  13594. }
  13595. function viewport( viewport ) {
  13596. if ( currentViewport.equals( viewport ) === false ) {
  13597. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13598. currentViewport.copy( viewport );
  13599. }
  13600. }
  13601. function updateUBOMapping( uniformsGroup, program ) {
  13602. let mapping = uboProgamMap.get( program );
  13603. if ( mapping === undefined ) {
  13604. mapping = new WeakMap();
  13605. uboProgamMap.set( program, mapping );
  13606. }
  13607. let blockIndex = mapping.get( uniformsGroup );
  13608. if ( blockIndex === undefined ) {
  13609. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13610. mapping.set( uniformsGroup, blockIndex );
  13611. }
  13612. }
  13613. function uniformBlockBinding( uniformsGroup, program ) {
  13614. const mapping = uboProgamMap.get( program );
  13615. const blockIndex = mapping.get( uniformsGroup );
  13616. if ( uboBindings.get( uniformsGroup ) !== blockIndex ) {
  13617. // bind shader specific block index to global block point
  13618. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13619. uboBindings.set( uniformsGroup, blockIndex );
  13620. }
  13621. }
  13622. //
  13623. function reset() {
  13624. // reset state
  13625. gl.disable( 3042 );
  13626. gl.disable( 2884 );
  13627. gl.disable( 2929 );
  13628. gl.disable( 32823 );
  13629. gl.disable( 3089 );
  13630. gl.disable( 2960 );
  13631. gl.disable( 32926 );
  13632. gl.blendEquation( 32774 );
  13633. gl.blendFunc( 1, 0 );
  13634. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13635. gl.colorMask( true, true, true, true );
  13636. gl.clearColor( 0, 0, 0, 0 );
  13637. gl.depthMask( true );
  13638. gl.depthFunc( 513 );
  13639. gl.clearDepth( 1 );
  13640. gl.stencilMask( 0xffffffff );
  13641. gl.stencilFunc( 519, 0, 0xffffffff );
  13642. gl.stencilOp( 7680, 7680, 7680 );
  13643. gl.clearStencil( 0 );
  13644. gl.cullFace( 1029 );
  13645. gl.frontFace( 2305 );
  13646. gl.polygonOffset( 0, 0 );
  13647. gl.activeTexture( 33984 );
  13648. gl.bindFramebuffer( 36160, null );
  13649. if ( isWebGL2 === true ) {
  13650. gl.bindFramebuffer( 36009, null );
  13651. gl.bindFramebuffer( 36008, null );
  13652. }
  13653. gl.useProgram( null );
  13654. gl.lineWidth( 1 );
  13655. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13656. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13657. // reset internals
  13658. enabledCapabilities = {};
  13659. currentTextureSlot = null;
  13660. currentBoundTextures = {};
  13661. currentBoundFramebuffers = {};
  13662. currentDrawbuffers = new WeakMap();
  13663. defaultDrawbuffers = [];
  13664. currentProgram = null;
  13665. currentBlendingEnabled = false;
  13666. currentBlending = null;
  13667. currentBlendEquation = null;
  13668. currentBlendSrc = null;
  13669. currentBlendDst = null;
  13670. currentBlendEquationAlpha = null;
  13671. currentBlendSrcAlpha = null;
  13672. currentBlendDstAlpha = null;
  13673. currentPremultipledAlpha = false;
  13674. currentFlipSided = null;
  13675. currentCullFace = null;
  13676. currentLineWidth = null;
  13677. currentPolygonOffsetFactor = null;
  13678. currentPolygonOffsetUnits = null;
  13679. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13680. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13681. colorBuffer.reset();
  13682. depthBuffer.reset();
  13683. stencilBuffer.reset();
  13684. }
  13685. return {
  13686. buffers: {
  13687. color: colorBuffer,
  13688. depth: depthBuffer,
  13689. stencil: stencilBuffer
  13690. },
  13691. enable: enable,
  13692. disable: disable,
  13693. bindFramebuffer: bindFramebuffer,
  13694. drawBuffers: drawBuffers,
  13695. useProgram: useProgram,
  13696. setBlending: setBlending,
  13697. setMaterial: setMaterial,
  13698. setFlipSided: setFlipSided,
  13699. setCullFace: setCullFace,
  13700. setLineWidth: setLineWidth,
  13701. setPolygonOffset: setPolygonOffset,
  13702. setScissorTest: setScissorTest,
  13703. activeTexture: activeTexture,
  13704. bindTexture: bindTexture,
  13705. unbindTexture: unbindTexture,
  13706. compressedTexImage2D: compressedTexImage2D,
  13707. texImage2D: texImage2D,
  13708. texImage3D: texImage3D,
  13709. updateUBOMapping: updateUBOMapping,
  13710. uniformBlockBinding: uniformBlockBinding,
  13711. texStorage2D: texStorage2D,
  13712. texStorage3D: texStorage3D,
  13713. texSubImage2D: texSubImage2D,
  13714. texSubImage3D: texSubImage3D,
  13715. compressedTexSubImage2D: compressedTexSubImage2D,
  13716. scissor: scissor,
  13717. viewport: viewport,
  13718. reset: reset
  13719. };
  13720. }
  13721. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13722. const isWebGL2 = capabilities.isWebGL2;
  13723. const maxTextures = capabilities.maxTextures;
  13724. const maxCubemapSize = capabilities.maxCubemapSize;
  13725. const maxTextureSize = capabilities.maxTextureSize;
  13726. const maxSamples = capabilities.maxSamples;
  13727. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13728. const supportsInvalidateFramebuffer = /OculusBrowser/g.test( navigator.userAgent );
  13729. const _videoTextures = new WeakMap();
  13730. let _canvas;
  13731. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13732. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13733. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13734. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13735. let useOffscreenCanvas = false;
  13736. try {
  13737. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13738. // eslint-disable-next-line compat/compat
  13739. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13740. } catch ( err ) {
  13741. // Ignore any errors
  13742. }
  13743. function createCanvas( width, height ) {
  13744. // Use OffscreenCanvas when available. Specially needed in web workers
  13745. return useOffscreenCanvas ?
  13746. // eslint-disable-next-line compat/compat
  13747. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13748. }
  13749. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13750. let scale = 1;
  13751. // handle case if texture exceeds max size
  13752. if ( image.width > maxSize || image.height > maxSize ) {
  13753. scale = maxSize / Math.max( image.width, image.height );
  13754. }
  13755. // only perform resize if necessary
  13756. if ( scale < 1 || needsPowerOfTwo === true ) {
  13757. // only perform resize for certain image types
  13758. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13759. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13760. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13761. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13762. const width = floor( scale * image.width );
  13763. const height = floor( scale * image.height );
  13764. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13765. // cube textures can't reuse the same canvas
  13766. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13767. canvas.width = width;
  13768. canvas.height = height;
  13769. const context = canvas.getContext( '2d' );
  13770. context.drawImage( image, 0, 0, width, height );
  13771. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13772. return canvas;
  13773. } else {
  13774. if ( 'data' in image ) {
  13775. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13776. }
  13777. return image;
  13778. }
  13779. }
  13780. return image;
  13781. }
  13782. function isPowerOfTwo$1( image ) {
  13783. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13784. }
  13785. function textureNeedsPowerOfTwo( texture ) {
  13786. if ( isWebGL2 ) return false;
  13787. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13788. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13789. }
  13790. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13791. return texture.generateMipmaps && supportsMips &&
  13792. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13793. }
  13794. function generateMipmap( target ) {
  13795. _gl.generateMipmap( target );
  13796. }
  13797. function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) {
  13798. if ( isWebGL2 === false ) return glFormat;
  13799. if ( internalFormatName !== null ) {
  13800. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13801. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13802. }
  13803. let internalFormat = glFormat;
  13804. if ( glFormat === 6403 ) {
  13805. if ( glType === 5126 ) internalFormat = 33326;
  13806. if ( glType === 5131 ) internalFormat = 33325;
  13807. if ( glType === 5121 ) internalFormat = 33321;
  13808. }
  13809. if ( glFormat === 33319 ) {
  13810. if ( glType === 5126 ) internalFormat = 33328;
  13811. if ( glType === 5131 ) internalFormat = 33327;
  13812. if ( glType === 5121 ) internalFormat = 33323;
  13813. }
  13814. if ( glFormat === 6408 ) {
  13815. if ( glType === 5126 ) internalFormat = 34836;
  13816. if ( glType === 5131 ) internalFormat = 34842;
  13817. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856;
  13818. if ( glType === 32819 ) internalFormat = 32854;
  13819. if ( glType === 32820 ) internalFormat = 32855;
  13820. }
  13821. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13822. internalFormat === 33327 || internalFormat === 33328 ||
  13823. internalFormat === 34842 || internalFormat === 34836 ) {
  13824. extensions.get( 'EXT_color_buffer_float' );
  13825. }
  13826. return internalFormat;
  13827. }
  13828. function getMipLevels( texture, image, supportsMips ) {
  13829. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13830. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13831. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13832. // user-defined mipmaps
  13833. return texture.mipmaps.length;
  13834. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13835. return image.mipmaps.length;
  13836. } else {
  13837. // texture without mipmaps (only base level)
  13838. return 1;
  13839. }
  13840. }
  13841. // Fallback filters for non-power-of-2 textures
  13842. function filterFallback( f ) {
  13843. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13844. return 9728;
  13845. }
  13846. return 9729;
  13847. }
  13848. //
  13849. function onTextureDispose( event ) {
  13850. const texture = event.target;
  13851. texture.removeEventListener( 'dispose', onTextureDispose );
  13852. deallocateTexture( texture );
  13853. if ( texture.isVideoTexture ) {
  13854. _videoTextures.delete( texture );
  13855. }
  13856. }
  13857. function onRenderTargetDispose( event ) {
  13858. const renderTarget = event.target;
  13859. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13860. deallocateRenderTarget( renderTarget );
  13861. }
  13862. //
  13863. function deallocateTexture( texture ) {
  13864. const textureProperties = properties.get( texture );
  13865. if ( textureProperties.__webglInit === undefined ) return;
  13866. // check if it's necessary to remove the WebGLTexture object
  13867. const source = texture.source;
  13868. const webglTextures = _sources.get( source );
  13869. if ( webglTextures ) {
  13870. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13871. webglTexture.usedTimes --;
  13872. // the WebGLTexture object is not used anymore, remove it
  13873. if ( webglTexture.usedTimes === 0 ) {
  13874. deleteTexture( texture );
  13875. }
  13876. // remove the weak map entry if no WebGLTexture uses the source anymore
  13877. if ( Object.keys( webglTextures ).length === 0 ) {
  13878. _sources.delete( source );
  13879. }
  13880. }
  13881. properties.remove( texture );
  13882. }
  13883. function deleteTexture( texture ) {
  13884. const textureProperties = properties.get( texture );
  13885. _gl.deleteTexture( textureProperties.__webglTexture );
  13886. const source = texture.source;
  13887. const webglTextures = _sources.get( source );
  13888. delete webglTextures[ textureProperties.__cacheKey ];
  13889. info.memory.textures --;
  13890. }
  13891. function deallocateRenderTarget( renderTarget ) {
  13892. const texture = renderTarget.texture;
  13893. const renderTargetProperties = properties.get( renderTarget );
  13894. const textureProperties = properties.get( texture );
  13895. if ( textureProperties.__webglTexture !== undefined ) {
  13896. _gl.deleteTexture( textureProperties.__webglTexture );
  13897. info.memory.textures --;
  13898. }
  13899. if ( renderTarget.depthTexture ) {
  13900. renderTarget.depthTexture.dispose();
  13901. }
  13902. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13903. for ( let i = 0; i < 6; i ++ ) {
  13904. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13905. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13906. }
  13907. } else {
  13908. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13909. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13910. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13911. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13912. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13913. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13914. }
  13915. }
  13916. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13917. }
  13918. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13919. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13920. const attachmentProperties = properties.get( texture[ i ] );
  13921. if ( attachmentProperties.__webglTexture ) {
  13922. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13923. info.memory.textures --;
  13924. }
  13925. properties.remove( texture[ i ] );
  13926. }
  13927. }
  13928. properties.remove( texture );
  13929. properties.remove( renderTarget );
  13930. }
  13931. //
  13932. let textureUnits = 0;
  13933. function resetTextureUnits() {
  13934. textureUnits = 0;
  13935. }
  13936. function allocateTextureUnit() {
  13937. const textureUnit = textureUnits;
  13938. if ( textureUnit >= maxTextures ) {
  13939. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13940. }
  13941. textureUnits += 1;
  13942. return textureUnit;
  13943. }
  13944. function getTextureCacheKey( texture ) {
  13945. const array = [];
  13946. array.push( texture.wrapS );
  13947. array.push( texture.wrapT );
  13948. array.push( texture.magFilter );
  13949. array.push( texture.minFilter );
  13950. array.push( texture.anisotropy );
  13951. array.push( texture.internalFormat );
  13952. array.push( texture.format );
  13953. array.push( texture.type );
  13954. array.push( texture.generateMipmaps );
  13955. array.push( texture.premultiplyAlpha );
  13956. array.push( texture.flipY );
  13957. array.push( texture.unpackAlignment );
  13958. array.push( texture.encoding );
  13959. return array.join();
  13960. }
  13961. //
  13962. function setTexture2D( texture, slot ) {
  13963. const textureProperties = properties.get( texture );
  13964. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13965. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13966. const image = texture.image;
  13967. if ( image === null ) {
  13968. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13969. } else if ( image.complete === false ) {
  13970. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13971. } else {
  13972. uploadTexture( textureProperties, texture, slot );
  13973. return;
  13974. }
  13975. }
  13976. state.activeTexture( 33984 + slot );
  13977. state.bindTexture( 3553, textureProperties.__webglTexture );
  13978. }
  13979. function setTexture2DArray( texture, slot ) {
  13980. const textureProperties = properties.get( texture );
  13981. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13982. uploadTexture( textureProperties, texture, slot );
  13983. return;
  13984. }
  13985. state.activeTexture( 33984 + slot );
  13986. state.bindTexture( 35866, textureProperties.__webglTexture );
  13987. }
  13988. function setTexture3D( texture, slot ) {
  13989. const textureProperties = properties.get( texture );
  13990. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13991. uploadTexture( textureProperties, texture, slot );
  13992. return;
  13993. }
  13994. state.activeTexture( 33984 + slot );
  13995. state.bindTexture( 32879, textureProperties.__webglTexture );
  13996. }
  13997. function setTextureCube( texture, slot ) {
  13998. const textureProperties = properties.get( texture );
  13999. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14000. uploadCubeTexture( textureProperties, texture, slot );
  14001. return;
  14002. }
  14003. state.activeTexture( 33984 + slot );
  14004. state.bindTexture( 34067, textureProperties.__webglTexture );
  14005. }
  14006. const wrappingToGL = {
  14007. [ RepeatWrapping ]: 10497,
  14008. [ ClampToEdgeWrapping ]: 33071,
  14009. [ MirroredRepeatWrapping ]: 33648
  14010. };
  14011. const filterToGL = {
  14012. [ NearestFilter ]: 9728,
  14013. [ NearestMipmapNearestFilter ]: 9984,
  14014. [ NearestMipmapLinearFilter ]: 9986,
  14015. [ LinearFilter ]: 9729,
  14016. [ LinearMipmapNearestFilter ]: 9985,
  14017. [ LinearMipmapLinearFilter ]: 9987
  14018. };
  14019. function setTextureParameters( textureType, texture, supportsMips ) {
  14020. if ( supportsMips ) {
  14021. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  14022. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  14023. if ( textureType === 32879 || textureType === 35866 ) {
  14024. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  14025. }
  14026. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  14027. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  14028. } else {
  14029. _gl.texParameteri( textureType, 10242, 33071 );
  14030. _gl.texParameteri( textureType, 10243, 33071 );
  14031. if ( textureType === 32879 || textureType === 35866 ) {
  14032. _gl.texParameteri( textureType, 32882, 33071 );
  14033. }
  14034. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14035. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14036. }
  14037. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  14038. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  14039. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14040. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14041. }
  14042. }
  14043. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14044. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14045. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14046. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14047. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14048. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14049. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14050. }
  14051. }
  14052. }
  14053. function initTexture( textureProperties, texture ) {
  14054. let forceUpload = false;
  14055. if ( textureProperties.__webglInit === undefined ) {
  14056. textureProperties.__webglInit = true;
  14057. texture.addEventListener( 'dispose', onTextureDispose );
  14058. }
  14059. // create Source <-> WebGLTextures mapping if necessary
  14060. const source = texture.source;
  14061. let webglTextures = _sources.get( source );
  14062. if ( webglTextures === undefined ) {
  14063. webglTextures = {};
  14064. _sources.set( source, webglTextures );
  14065. }
  14066. // check if there is already a WebGLTexture object for the given texture parameters
  14067. const textureCacheKey = getTextureCacheKey( texture );
  14068. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14069. // if not, create a new instance of WebGLTexture
  14070. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14071. // create new entry
  14072. webglTextures[ textureCacheKey ] = {
  14073. texture: _gl.createTexture(),
  14074. usedTimes: 0
  14075. };
  14076. info.memory.textures ++;
  14077. // when a new instance of WebGLTexture was created, a texture upload is required
  14078. // even if the image contents are identical
  14079. forceUpload = true;
  14080. }
  14081. webglTextures[ textureCacheKey ].usedTimes ++;
  14082. // every time the texture cache key changes, it's necessary to check if an instance of
  14083. // WebGLTexture can be deleted in order to avoid a memory leak.
  14084. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14085. if ( webglTexture !== undefined ) {
  14086. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14087. if ( webglTexture.usedTimes === 0 ) {
  14088. deleteTexture( texture );
  14089. }
  14090. }
  14091. // store references to cache key and WebGLTexture object
  14092. textureProperties.__cacheKey = textureCacheKey;
  14093. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14094. }
  14095. return forceUpload;
  14096. }
  14097. function uploadTexture( textureProperties, texture, slot ) {
  14098. let textureType = 3553;
  14099. if ( texture.isDataArrayTexture ) textureType = 35866;
  14100. if ( texture.isData3DTexture ) textureType = 32879;
  14101. const forceUpload = initTexture( textureProperties, texture );
  14102. const source = texture.source;
  14103. state.activeTexture( 33984 + slot );
  14104. state.bindTexture( textureType, textureProperties.__webglTexture );
  14105. if ( source.version !== source.__currentVersion || forceUpload === true ) {
  14106. _gl.pixelStorei( 37440, texture.flipY );
  14107. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14108. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14109. _gl.pixelStorei( 37443, 0 );
  14110. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14111. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14112. image = verifyColorSpace( texture, image );
  14113. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14114. glFormat = utils.convert( texture.format, texture.encoding );
  14115. let glType = utils.convert( texture.type ),
  14116. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  14117. setTextureParameters( textureType, texture, supportsMips );
  14118. let mipmap;
  14119. const mipmaps = texture.mipmaps;
  14120. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14121. const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true );
  14122. const levels = getMipLevels( texture, image, supportsMips );
  14123. if ( texture.isDepthTexture ) {
  14124. // populate depth texture with dummy data
  14125. glInternalFormat = 6402;
  14126. if ( isWebGL2 ) {
  14127. if ( texture.type === FloatType ) {
  14128. glInternalFormat = 36012;
  14129. } else if ( texture.type === UnsignedIntType ) {
  14130. glInternalFormat = 33190;
  14131. } else if ( texture.type === UnsignedInt248Type ) {
  14132. glInternalFormat = 35056;
  14133. } else {
  14134. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14135. }
  14136. } else {
  14137. if ( texture.type === FloatType ) {
  14138. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14139. }
  14140. }
  14141. // validation checks for WebGL 1
  14142. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14143. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14144. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14145. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14146. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14147. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14148. texture.type = UnsignedIntType;
  14149. glType = utils.convert( texture.type );
  14150. }
  14151. }
  14152. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14153. // Depth stencil textures need the DEPTH_STENCIL internal format
  14154. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14155. glInternalFormat = 34041;
  14156. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14157. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14158. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14159. if ( texture.type !== UnsignedInt248Type ) {
  14160. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14161. texture.type = UnsignedInt248Type;
  14162. glType = utils.convert( texture.type );
  14163. }
  14164. }
  14165. //
  14166. if ( allocateMemory ) {
  14167. if ( useTexStorage ) {
  14168. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  14169. } else {
  14170. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14171. }
  14172. }
  14173. } else if ( texture.isDataTexture ) {
  14174. // use manually created mipmaps if available
  14175. // if there are no manual mipmaps
  14176. // set 0 level mipmap and then use GL to generate other mipmap levels
  14177. if ( mipmaps.length > 0 && supportsMips ) {
  14178. if ( useTexStorage && allocateMemory ) {
  14179. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14180. }
  14181. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14182. mipmap = mipmaps[ i ];
  14183. if ( useTexStorage ) {
  14184. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14185. } else {
  14186. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14187. }
  14188. }
  14189. texture.generateMipmaps = false;
  14190. } else {
  14191. if ( useTexStorage ) {
  14192. if ( allocateMemory ) {
  14193. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14194. }
  14195. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14196. } else {
  14197. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14198. }
  14199. }
  14200. } else if ( texture.isCompressedTexture ) {
  14201. if ( useTexStorage && allocateMemory ) {
  14202. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14203. }
  14204. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14205. mipmap = mipmaps[ i ];
  14206. if ( texture.format !== RGBAFormat ) {
  14207. if ( glFormat !== null ) {
  14208. if ( useTexStorage ) {
  14209. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14210. } else {
  14211. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14212. }
  14213. } else {
  14214. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14215. }
  14216. } else {
  14217. if ( useTexStorage ) {
  14218. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14219. } else {
  14220. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14221. }
  14222. }
  14223. }
  14224. } else if ( texture.isDataArrayTexture ) {
  14225. if ( useTexStorage ) {
  14226. if ( allocateMemory ) {
  14227. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  14228. }
  14229. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14230. } else {
  14231. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14232. }
  14233. } else if ( texture.isData3DTexture ) {
  14234. if ( useTexStorage ) {
  14235. if ( allocateMemory ) {
  14236. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  14237. }
  14238. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14239. } else {
  14240. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14241. }
  14242. } else if ( texture.isFramebufferTexture ) {
  14243. if ( allocateMemory ) {
  14244. if ( useTexStorage ) {
  14245. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14246. } else {
  14247. let width = image.width, height = image.height;
  14248. for ( let i = 0; i < levels; i ++ ) {
  14249. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14250. width >>= 1;
  14251. height >>= 1;
  14252. }
  14253. }
  14254. }
  14255. } else {
  14256. // regular Texture (image, video, canvas)
  14257. // use manually created mipmaps if available
  14258. // if there are no manual mipmaps
  14259. // set 0 level mipmap and then use GL to generate other mipmap levels
  14260. if ( mipmaps.length > 0 && supportsMips ) {
  14261. if ( useTexStorage && allocateMemory ) {
  14262. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14263. }
  14264. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14265. mipmap = mipmaps[ i ];
  14266. if ( useTexStorage ) {
  14267. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  14268. } else {
  14269. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14270. }
  14271. }
  14272. texture.generateMipmaps = false;
  14273. } else {
  14274. if ( useTexStorage ) {
  14275. if ( allocateMemory ) {
  14276. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14277. }
  14278. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  14279. } else {
  14280. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14281. }
  14282. }
  14283. }
  14284. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14285. generateMipmap( textureType );
  14286. }
  14287. source.__currentVersion = source.version;
  14288. if ( texture.onUpdate ) texture.onUpdate( texture );
  14289. }
  14290. textureProperties.__version = texture.version;
  14291. }
  14292. function uploadCubeTexture( textureProperties, texture, slot ) {
  14293. if ( texture.image.length !== 6 ) return;
  14294. const forceUpload = initTexture( textureProperties, texture );
  14295. const source = texture.source;
  14296. state.activeTexture( 33984 + slot );
  14297. state.bindTexture( 34067, textureProperties.__webglTexture );
  14298. if ( source.version !== source.__currentVersion || forceUpload === true ) {
  14299. _gl.pixelStorei( 37440, texture.flipY );
  14300. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14301. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14302. _gl.pixelStorei( 37443, 0 );
  14303. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14304. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14305. const cubeImage = [];
  14306. for ( let i = 0; i < 6; i ++ ) {
  14307. if ( ! isCompressed && ! isDataTexture ) {
  14308. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14309. } else {
  14310. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14311. }
  14312. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14313. }
  14314. const image = cubeImage[ 0 ],
  14315. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14316. glFormat = utils.convert( texture.format, texture.encoding ),
  14317. glType = utils.convert( texture.type ),
  14318. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14319. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14320. const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true );
  14321. let levels = getMipLevels( texture, image, supportsMips );
  14322. setTextureParameters( 34067, texture, supportsMips );
  14323. let mipmaps;
  14324. if ( isCompressed ) {
  14325. if ( useTexStorage && allocateMemory ) {
  14326. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14327. }
  14328. for ( let i = 0; i < 6; i ++ ) {
  14329. mipmaps = cubeImage[ i ].mipmaps;
  14330. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14331. const mipmap = mipmaps[ j ];
  14332. if ( texture.format !== RGBAFormat ) {
  14333. if ( glFormat !== null ) {
  14334. if ( useTexStorage ) {
  14335. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14336. } else {
  14337. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14338. }
  14339. } else {
  14340. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14341. }
  14342. } else {
  14343. if ( useTexStorage ) {
  14344. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14345. } else {
  14346. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14347. }
  14348. }
  14349. }
  14350. }
  14351. } else {
  14352. mipmaps = texture.mipmaps;
  14353. if ( useTexStorage && allocateMemory ) {
  14354. // TODO: Uniformly handle mipmap definitions
  14355. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14356. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14357. if ( mipmaps.length > 0 ) levels ++;
  14358. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14359. }
  14360. for ( let i = 0; i < 6; i ++ ) {
  14361. if ( isDataTexture ) {
  14362. if ( useTexStorage ) {
  14363. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14364. } else {
  14365. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14366. }
  14367. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14368. const mipmap = mipmaps[ j ];
  14369. const mipmapImage = mipmap.image[ i ].image;
  14370. if ( useTexStorage ) {
  14371. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14372. } else {
  14373. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14374. }
  14375. }
  14376. } else {
  14377. if ( useTexStorage ) {
  14378. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14379. } else {
  14380. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14381. }
  14382. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14383. const mipmap = mipmaps[ j ];
  14384. if ( useTexStorage ) {
  14385. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14386. } else {
  14387. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14388. }
  14389. }
  14390. }
  14391. }
  14392. }
  14393. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14394. // We assume images for cube map have the same size.
  14395. generateMipmap( 34067 );
  14396. }
  14397. source.__currentVersion = source.version;
  14398. if ( texture.onUpdate ) texture.onUpdate( texture );
  14399. }
  14400. textureProperties.__version = texture.version;
  14401. }
  14402. // Render targets
  14403. // Setup storage for target texture and bind it to correct framebuffer
  14404. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14405. const glFormat = utils.convert( texture.format, texture.encoding );
  14406. const glType = utils.convert( texture.type );
  14407. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14408. const renderTargetProperties = properties.get( renderTarget );
  14409. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14410. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14411. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14412. } else {
  14413. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14414. }
  14415. }
  14416. state.bindFramebuffer( 36160, framebuffer );
  14417. if ( useMultisampledRTT( renderTarget ) ) {
  14418. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14419. } else {
  14420. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14421. }
  14422. state.bindFramebuffer( 36160, null );
  14423. }
  14424. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14425. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14426. _gl.bindRenderbuffer( 36161, renderbuffer );
  14427. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14428. let glInternalFormat = 33189;
  14429. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14430. const depthTexture = renderTarget.depthTexture;
  14431. if ( depthTexture && depthTexture.isDepthTexture ) {
  14432. if ( depthTexture.type === FloatType ) {
  14433. glInternalFormat = 36012;
  14434. } else if ( depthTexture.type === UnsignedIntType ) {
  14435. glInternalFormat = 33190;
  14436. }
  14437. }
  14438. const samples = getRenderTargetSamples( renderTarget );
  14439. if ( useMultisampledRTT( renderTarget ) ) {
  14440. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14441. } else {
  14442. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14443. }
  14444. } else {
  14445. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14446. }
  14447. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14448. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14449. const samples = getRenderTargetSamples( renderTarget );
  14450. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14451. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14452. } else if ( useMultisampledRTT( renderTarget ) ) {
  14453. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14454. } else {
  14455. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14456. }
  14457. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14458. } else {
  14459. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14460. for ( let i = 0; i < textures.length; i ++ ) {
  14461. const texture = textures[ i ];
  14462. const glFormat = utils.convert( texture.format, texture.encoding );
  14463. const glType = utils.convert( texture.type );
  14464. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14465. const samples = getRenderTargetSamples( renderTarget );
  14466. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14467. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14468. } else if ( useMultisampledRTT( renderTarget ) ) {
  14469. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14470. } else {
  14471. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14472. }
  14473. }
  14474. }
  14475. _gl.bindRenderbuffer( 36161, null );
  14476. }
  14477. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14478. function setupDepthTexture( framebuffer, renderTarget ) {
  14479. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14480. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14481. state.bindFramebuffer( 36160, framebuffer );
  14482. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14483. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14484. }
  14485. // upload an empty depth texture with framebuffer size
  14486. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14487. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14488. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14489. renderTarget.depthTexture.image.width = renderTarget.width;
  14490. renderTarget.depthTexture.image.height = renderTarget.height;
  14491. renderTarget.depthTexture.needsUpdate = true;
  14492. }
  14493. setTexture2D( renderTarget.depthTexture, 0 );
  14494. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14495. const samples = getRenderTargetSamples( renderTarget );
  14496. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14497. if ( useMultisampledRTT( renderTarget ) ) {
  14498. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14499. } else {
  14500. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14501. }
  14502. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14503. if ( useMultisampledRTT( renderTarget ) ) {
  14504. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14505. } else {
  14506. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14507. }
  14508. } else {
  14509. throw new Error( 'Unknown depthTexture format' );
  14510. }
  14511. }
  14512. // Setup GL resources for a non-texture depth buffer
  14513. function setupDepthRenderbuffer( renderTarget ) {
  14514. const renderTargetProperties = properties.get( renderTarget );
  14515. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14516. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14517. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14518. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14519. } else {
  14520. if ( isCube ) {
  14521. renderTargetProperties.__webglDepthbuffer = [];
  14522. for ( let i = 0; i < 6; i ++ ) {
  14523. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14524. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14525. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14526. }
  14527. } else {
  14528. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14529. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14530. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14531. }
  14532. }
  14533. state.bindFramebuffer( 36160, null );
  14534. }
  14535. // rebind framebuffer with external textures
  14536. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14537. const renderTargetProperties = properties.get( renderTarget );
  14538. if ( colorTexture !== undefined ) {
  14539. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14540. }
  14541. if ( depthTexture !== undefined ) {
  14542. setupDepthRenderbuffer( renderTarget );
  14543. }
  14544. }
  14545. // Set up GL resources for the render target
  14546. function setupRenderTarget( renderTarget ) {
  14547. const texture = renderTarget.texture;
  14548. const renderTargetProperties = properties.get( renderTarget );
  14549. const textureProperties = properties.get( texture );
  14550. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14551. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14552. if ( textureProperties.__webglTexture === undefined ) {
  14553. textureProperties.__webglTexture = _gl.createTexture();
  14554. }
  14555. textureProperties.__version = texture.version;
  14556. info.memory.textures ++;
  14557. }
  14558. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14559. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14560. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14561. // Setup framebuffer
  14562. if ( isCube ) {
  14563. renderTargetProperties.__webglFramebuffer = [];
  14564. for ( let i = 0; i < 6; i ++ ) {
  14565. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14566. }
  14567. } else {
  14568. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14569. if ( isMultipleRenderTargets ) {
  14570. if ( capabilities.drawBuffers ) {
  14571. const textures = renderTarget.texture;
  14572. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14573. const attachmentProperties = properties.get( textures[ i ] );
  14574. if ( attachmentProperties.__webglTexture === undefined ) {
  14575. attachmentProperties.__webglTexture = _gl.createTexture();
  14576. info.memory.textures ++;
  14577. }
  14578. }
  14579. } else {
  14580. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14581. }
  14582. }
  14583. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14584. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14585. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14586. renderTargetProperties.__webglColorRenderbuffer = [];
  14587. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14588. for ( let i = 0; i < textures.length; i ++ ) {
  14589. const texture = textures[ i ];
  14590. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14591. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14592. const glFormat = utils.convert( texture.format, texture.encoding );
  14593. const glType = utils.convert( texture.type );
  14594. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14595. const samples = getRenderTargetSamples( renderTarget );
  14596. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14597. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14598. }
  14599. _gl.bindRenderbuffer( 36161, null );
  14600. if ( renderTarget.depthBuffer ) {
  14601. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14602. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14603. }
  14604. state.bindFramebuffer( 36160, null );
  14605. }
  14606. }
  14607. // Setup color buffer
  14608. if ( isCube ) {
  14609. state.bindTexture( 34067, textureProperties.__webglTexture );
  14610. setTextureParameters( 34067, texture, supportsMips );
  14611. for ( let i = 0; i < 6; i ++ ) {
  14612. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14613. }
  14614. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14615. generateMipmap( 34067 );
  14616. }
  14617. state.unbindTexture();
  14618. } else if ( isMultipleRenderTargets ) {
  14619. const textures = renderTarget.texture;
  14620. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14621. const attachment = textures[ i ];
  14622. const attachmentProperties = properties.get( attachment );
  14623. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14624. setTextureParameters( 3553, attachment, supportsMips );
  14625. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14626. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14627. generateMipmap( 3553 );
  14628. }
  14629. }
  14630. state.unbindTexture();
  14631. } else {
  14632. let glTextureType = 3553;
  14633. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14634. if ( isWebGL2 ) {
  14635. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14636. } else {
  14637. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14638. }
  14639. }
  14640. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14641. setTextureParameters( glTextureType, texture, supportsMips );
  14642. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14643. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14644. generateMipmap( glTextureType );
  14645. }
  14646. state.unbindTexture();
  14647. }
  14648. // Setup depth and stencil buffers
  14649. if ( renderTarget.depthBuffer ) {
  14650. setupDepthRenderbuffer( renderTarget );
  14651. }
  14652. }
  14653. function updateRenderTargetMipmap( renderTarget ) {
  14654. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14655. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14656. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14657. const texture = textures[ i ];
  14658. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14659. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14660. const webglTexture = properties.get( texture ).__webglTexture;
  14661. state.bindTexture( target, webglTexture );
  14662. generateMipmap( target );
  14663. state.unbindTexture();
  14664. }
  14665. }
  14666. }
  14667. function updateMultisampleRenderTarget( renderTarget ) {
  14668. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14669. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14670. const width = renderTarget.width;
  14671. const height = renderTarget.height;
  14672. let mask = 16384;
  14673. const invalidationArray = [];
  14674. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14675. const renderTargetProperties = properties.get( renderTarget );
  14676. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14677. // If MRT we need to remove FBO attachments
  14678. if ( isMultipleRenderTargets ) {
  14679. for ( let i = 0; i < textures.length; i ++ ) {
  14680. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14681. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14682. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14683. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14684. }
  14685. }
  14686. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14687. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14688. for ( let i = 0; i < textures.length; i ++ ) {
  14689. invalidationArray.push( 36064 + i );
  14690. if ( renderTarget.depthBuffer ) {
  14691. invalidationArray.push( depthStyle );
  14692. }
  14693. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14694. if ( ignoreDepthValues === false ) {
  14695. if ( renderTarget.depthBuffer ) mask |= 256;
  14696. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14697. }
  14698. if ( isMultipleRenderTargets ) {
  14699. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14700. }
  14701. if ( ignoreDepthValues === true ) {
  14702. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14703. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14704. }
  14705. if ( isMultipleRenderTargets ) {
  14706. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14707. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14708. }
  14709. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14710. if ( supportsInvalidateFramebuffer ) {
  14711. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14712. }
  14713. }
  14714. state.bindFramebuffer( 36008, null );
  14715. state.bindFramebuffer( 36009, null );
  14716. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14717. if ( isMultipleRenderTargets ) {
  14718. for ( let i = 0; i < textures.length; i ++ ) {
  14719. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14720. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14721. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14722. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14723. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14724. }
  14725. }
  14726. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14727. }
  14728. }
  14729. function getRenderTargetSamples( renderTarget ) {
  14730. return Math.min( maxSamples, renderTarget.samples );
  14731. }
  14732. function useMultisampledRTT( renderTarget ) {
  14733. const renderTargetProperties = properties.get( renderTarget );
  14734. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14735. }
  14736. function updateVideoTexture( texture ) {
  14737. const frame = info.render.frame;
  14738. // Check the last frame we updated the VideoTexture
  14739. if ( _videoTextures.get( texture ) !== frame ) {
  14740. _videoTextures.set( texture, frame );
  14741. texture.update();
  14742. }
  14743. }
  14744. function verifyColorSpace( texture, image ) {
  14745. const encoding = texture.encoding;
  14746. const format = texture.format;
  14747. const type = texture.type;
  14748. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14749. if ( encoding !== LinearEncoding ) {
  14750. // sRGB
  14751. if ( encoding === sRGBEncoding ) {
  14752. if ( isWebGL2 === false ) {
  14753. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14754. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14755. texture.format = _SRGBAFormat;
  14756. // it's not possible to generate mips in WebGL 1 with this extension
  14757. texture.minFilter = LinearFilter;
  14758. texture.generateMipmaps = false;
  14759. } else {
  14760. // slow fallback (CPU decode)
  14761. image = ImageUtils.sRGBToLinear( image );
  14762. }
  14763. } else {
  14764. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14765. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14766. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14767. }
  14768. }
  14769. } else {
  14770. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14771. }
  14772. }
  14773. return image;
  14774. }
  14775. //
  14776. this.allocateTextureUnit = allocateTextureUnit;
  14777. this.resetTextureUnits = resetTextureUnits;
  14778. this.setTexture2D = setTexture2D;
  14779. this.setTexture2DArray = setTexture2DArray;
  14780. this.setTexture3D = setTexture3D;
  14781. this.setTextureCube = setTextureCube;
  14782. this.rebindTextures = rebindTextures;
  14783. this.setupRenderTarget = setupRenderTarget;
  14784. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14785. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14786. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14787. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14788. this.useMultisampledRTT = useMultisampledRTT;
  14789. }
  14790. function WebGLUtils( gl, extensions, capabilities ) {
  14791. const isWebGL2 = capabilities.isWebGL2;
  14792. function convert( p, encoding = null ) {
  14793. let extension;
  14794. if ( p === UnsignedByteType ) return 5121;
  14795. if ( p === UnsignedShort4444Type ) return 32819;
  14796. if ( p === UnsignedShort5551Type ) return 32820;
  14797. if ( p === ByteType ) return 5120;
  14798. if ( p === ShortType ) return 5122;
  14799. if ( p === UnsignedShortType ) return 5123;
  14800. if ( p === IntType ) return 5124;
  14801. if ( p === UnsignedIntType ) return 5125;
  14802. if ( p === FloatType ) return 5126;
  14803. if ( p === HalfFloatType ) {
  14804. if ( isWebGL2 ) return 5131;
  14805. extension = extensions.get( 'OES_texture_half_float' );
  14806. if ( extension !== null ) {
  14807. return extension.HALF_FLOAT_OES;
  14808. } else {
  14809. return null;
  14810. }
  14811. }
  14812. if ( p === AlphaFormat ) return 6406;
  14813. if ( p === RGBAFormat ) return 6408;
  14814. if ( p === LuminanceFormat ) return 6409;
  14815. if ( p === LuminanceAlphaFormat ) return 6410;
  14816. if ( p === DepthFormat ) return 6402;
  14817. if ( p === DepthStencilFormat ) return 34041;
  14818. if ( p === RedFormat ) return 6403;
  14819. // @deprecated since r137
  14820. if ( p === RGBFormat ) {
  14821. console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' );
  14822. return 6408;
  14823. }
  14824. // WebGL 1 sRGB fallback
  14825. if ( p === _SRGBAFormat ) {
  14826. extension = extensions.get( 'EXT_sRGB' );
  14827. if ( extension !== null ) {
  14828. return extension.SRGB_ALPHA_EXT;
  14829. } else {
  14830. return null;
  14831. }
  14832. }
  14833. // WebGL2 formats.
  14834. if ( p === RedIntegerFormat ) return 36244;
  14835. if ( p === RGFormat ) return 33319;
  14836. if ( p === RGIntegerFormat ) return 33320;
  14837. if ( p === RGBAIntegerFormat ) return 36249;
  14838. // S3TC
  14839. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14840. if ( encoding === sRGBEncoding ) {
  14841. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14842. if ( extension !== null ) {
  14843. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14844. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14845. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14846. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14847. } else {
  14848. return null;
  14849. }
  14850. } else {
  14851. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14852. if ( extension !== null ) {
  14853. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14854. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14855. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14856. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14857. } else {
  14858. return null;
  14859. }
  14860. }
  14861. }
  14862. // PVRTC
  14863. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14864. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14865. if ( extension !== null ) {
  14866. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14867. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14868. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14869. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14870. } else {
  14871. return null;
  14872. }
  14873. }
  14874. // ETC1
  14875. if ( p === RGB_ETC1_Format ) {
  14876. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14877. if ( extension !== null ) {
  14878. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14879. } else {
  14880. return null;
  14881. }
  14882. }
  14883. // ETC2
  14884. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14885. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14886. if ( extension !== null ) {
  14887. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14888. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14889. } else {
  14890. return null;
  14891. }
  14892. }
  14893. // ASTC
  14894. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14895. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14896. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14897. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14898. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14899. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14900. if ( extension !== null ) {
  14901. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14902. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14903. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14904. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14905. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14906. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14907. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14908. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14909. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14910. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14911. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14912. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14913. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14914. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14915. } else {
  14916. return null;
  14917. }
  14918. }
  14919. // BPTC
  14920. if ( p === RGBA_BPTC_Format ) {
  14921. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14922. if ( extension !== null ) {
  14923. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14924. } else {
  14925. return null;
  14926. }
  14927. }
  14928. //
  14929. if ( p === UnsignedInt248Type ) {
  14930. if ( isWebGL2 ) return 34042;
  14931. extension = extensions.get( 'WEBGL_depth_texture' );
  14932. if ( extension !== null ) {
  14933. return extension.UNSIGNED_INT_24_8_WEBGL;
  14934. } else {
  14935. return null;
  14936. }
  14937. }
  14938. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14939. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14940. }
  14941. return { convert: convert };
  14942. }
  14943. class ArrayCamera extends PerspectiveCamera {
  14944. constructor( array = [] ) {
  14945. super();
  14946. this.isArrayCamera = true;
  14947. this.cameras = array;
  14948. }
  14949. }
  14950. class Group extends Object3D {
  14951. constructor() {
  14952. super();
  14953. this.isGroup = true;
  14954. this.type = 'Group';
  14955. }
  14956. }
  14957. const _moveEvent = { type: 'move' };
  14958. class WebXRController {
  14959. constructor() {
  14960. this._targetRay = null;
  14961. this._grip = null;
  14962. this._hand = null;
  14963. }
  14964. getHandSpace() {
  14965. if ( this._hand === null ) {
  14966. this._hand = new Group();
  14967. this._hand.matrixAutoUpdate = false;
  14968. this._hand.visible = false;
  14969. this._hand.joints = {};
  14970. this._hand.inputState = { pinching: false };
  14971. }
  14972. return this._hand;
  14973. }
  14974. getTargetRaySpace() {
  14975. if ( this._targetRay === null ) {
  14976. this._targetRay = new Group();
  14977. this._targetRay.matrixAutoUpdate = false;
  14978. this._targetRay.visible = false;
  14979. this._targetRay.hasLinearVelocity = false;
  14980. this._targetRay.linearVelocity = new Vector3();
  14981. this._targetRay.hasAngularVelocity = false;
  14982. this._targetRay.angularVelocity = new Vector3();
  14983. }
  14984. return this._targetRay;
  14985. }
  14986. getGripSpace() {
  14987. if ( this._grip === null ) {
  14988. this._grip = new Group();
  14989. this._grip.matrixAutoUpdate = false;
  14990. this._grip.visible = false;
  14991. this._grip.hasLinearVelocity = false;
  14992. this._grip.linearVelocity = new Vector3();
  14993. this._grip.hasAngularVelocity = false;
  14994. this._grip.angularVelocity = new Vector3();
  14995. }
  14996. return this._grip;
  14997. }
  14998. dispatchEvent( event ) {
  14999. if ( this._targetRay !== null ) {
  15000. this._targetRay.dispatchEvent( event );
  15001. }
  15002. if ( this._grip !== null ) {
  15003. this._grip.dispatchEvent( event );
  15004. }
  15005. if ( this._hand !== null ) {
  15006. this._hand.dispatchEvent( event );
  15007. }
  15008. return this;
  15009. }
  15010. disconnect( inputSource ) {
  15011. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15012. if ( this._targetRay !== null ) {
  15013. this._targetRay.visible = false;
  15014. }
  15015. if ( this._grip !== null ) {
  15016. this._grip.visible = false;
  15017. }
  15018. if ( this._hand !== null ) {
  15019. this._hand.visible = false;
  15020. }
  15021. return this;
  15022. }
  15023. update( inputSource, frame, referenceSpace ) {
  15024. let inputPose = null;
  15025. let gripPose = null;
  15026. let handPose = null;
  15027. const targetRay = this._targetRay;
  15028. const grip = this._grip;
  15029. const hand = this._hand;
  15030. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15031. if ( hand && inputSource.hand ) {
  15032. handPose = true;
  15033. for ( const inputjoint of inputSource.hand.values() ) {
  15034. // Update the joints groups with the XRJoint poses
  15035. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15036. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15037. // The transform of this joint will be updated with the joint pose on each frame
  15038. const joint = new Group();
  15039. joint.matrixAutoUpdate = false;
  15040. joint.visible = false;
  15041. hand.joints[ inputjoint.jointName ] = joint;
  15042. // ??
  15043. hand.add( joint );
  15044. }
  15045. const joint = hand.joints[ inputjoint.jointName ];
  15046. if ( jointPose !== null ) {
  15047. joint.matrix.fromArray( jointPose.transform.matrix );
  15048. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15049. joint.jointRadius = jointPose.radius;
  15050. }
  15051. joint.visible = jointPose !== null;
  15052. }
  15053. // Custom events
  15054. // Check pinchz
  15055. const indexTip = hand.joints[ 'index-finger-tip' ];
  15056. const thumbTip = hand.joints[ 'thumb-tip' ];
  15057. const distance = indexTip.position.distanceTo( thumbTip.position );
  15058. const distanceToPinch = 0.02;
  15059. const threshold = 0.005;
  15060. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15061. hand.inputState.pinching = false;
  15062. this.dispatchEvent( {
  15063. type: 'pinchend',
  15064. handedness: inputSource.handedness,
  15065. target: this
  15066. } );
  15067. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15068. hand.inputState.pinching = true;
  15069. this.dispatchEvent( {
  15070. type: 'pinchstart',
  15071. handedness: inputSource.handedness,
  15072. target: this
  15073. } );
  15074. }
  15075. } else {
  15076. if ( grip !== null && inputSource.gripSpace ) {
  15077. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15078. if ( gripPose !== null ) {
  15079. grip.matrix.fromArray( gripPose.transform.matrix );
  15080. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15081. if ( gripPose.linearVelocity ) {
  15082. grip.hasLinearVelocity = true;
  15083. grip.linearVelocity.copy( gripPose.linearVelocity );
  15084. } else {
  15085. grip.hasLinearVelocity = false;
  15086. }
  15087. if ( gripPose.angularVelocity ) {
  15088. grip.hasAngularVelocity = true;
  15089. grip.angularVelocity.copy( gripPose.angularVelocity );
  15090. } else {
  15091. grip.hasAngularVelocity = false;
  15092. }
  15093. }
  15094. }
  15095. }
  15096. if ( targetRay !== null ) {
  15097. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15098. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15099. if ( inputPose === null && gripPose !== null ) {
  15100. inputPose = gripPose;
  15101. }
  15102. if ( inputPose !== null ) {
  15103. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15104. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15105. if ( inputPose.linearVelocity ) {
  15106. targetRay.hasLinearVelocity = true;
  15107. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15108. } else {
  15109. targetRay.hasLinearVelocity = false;
  15110. }
  15111. if ( inputPose.angularVelocity ) {
  15112. targetRay.hasAngularVelocity = true;
  15113. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15114. } else {
  15115. targetRay.hasAngularVelocity = false;
  15116. }
  15117. this.dispatchEvent( _moveEvent );
  15118. }
  15119. }
  15120. }
  15121. if ( targetRay !== null ) {
  15122. targetRay.visible = ( inputPose !== null );
  15123. }
  15124. if ( grip !== null ) {
  15125. grip.visible = ( gripPose !== null );
  15126. }
  15127. if ( hand !== null ) {
  15128. hand.visible = ( handPose !== null );
  15129. }
  15130. return this;
  15131. }
  15132. }
  15133. class DepthTexture extends Texture {
  15134. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15135. format = format !== undefined ? format : DepthFormat;
  15136. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15137. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15138. }
  15139. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15140. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15141. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15142. this.isDepthTexture = true;
  15143. this.image = { width: width, height: height };
  15144. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15145. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15146. this.flipY = false;
  15147. this.generateMipmaps = false;
  15148. }
  15149. }
  15150. class WebXRManager extends EventDispatcher {
  15151. constructor( renderer, gl ) {
  15152. super();
  15153. const scope = this;
  15154. let session = null;
  15155. let framebufferScaleFactor = 1.0;
  15156. let referenceSpace = null;
  15157. let referenceSpaceType = 'local-floor';
  15158. let customReferenceSpace = null;
  15159. let pose = null;
  15160. let glBinding = null;
  15161. let glProjLayer = null;
  15162. let glBaseLayer = null;
  15163. let xrFrame = null;
  15164. const attributes = gl.getContextAttributes();
  15165. let initialRenderTarget = null;
  15166. let newRenderTarget = null;
  15167. const controllers = [];
  15168. const controllerInputSources = [];
  15169. //
  15170. const cameraL = new PerspectiveCamera();
  15171. cameraL.layers.enable( 1 );
  15172. cameraL.viewport = new Vector4();
  15173. const cameraR = new PerspectiveCamera();
  15174. cameraR.layers.enable( 2 );
  15175. cameraR.viewport = new Vector4();
  15176. const cameras = [ cameraL, cameraR ];
  15177. const cameraVR = new ArrayCamera();
  15178. cameraVR.layers.enable( 1 );
  15179. cameraVR.layers.enable( 2 );
  15180. let _currentDepthNear = null;
  15181. let _currentDepthFar = null;
  15182. //
  15183. this.cameraAutoUpdate = true;
  15184. this.enabled = false;
  15185. this.isPresenting = false;
  15186. this.getController = function ( index ) {
  15187. let controller = controllers[ index ];
  15188. if ( controller === undefined ) {
  15189. controller = new WebXRController();
  15190. controllers[ index ] = controller;
  15191. }
  15192. return controller.getTargetRaySpace();
  15193. };
  15194. this.getControllerGrip = function ( index ) {
  15195. let controller = controllers[ index ];
  15196. if ( controller === undefined ) {
  15197. controller = new WebXRController();
  15198. controllers[ index ] = controller;
  15199. }
  15200. return controller.getGripSpace();
  15201. };
  15202. this.getHand = function ( index ) {
  15203. let controller = controllers[ index ];
  15204. if ( controller === undefined ) {
  15205. controller = new WebXRController();
  15206. controllers[ index ] = controller;
  15207. }
  15208. return controller.getHandSpace();
  15209. };
  15210. //
  15211. function onSessionEvent( event ) {
  15212. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15213. if ( controllerIndex === - 1 ) {
  15214. return;
  15215. }
  15216. const controller = controllers[ controllerIndex ];
  15217. if ( controller !== undefined ) {
  15218. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15219. }
  15220. }
  15221. function onSessionEnd() {
  15222. session.removeEventListener( 'select', onSessionEvent );
  15223. session.removeEventListener( 'selectstart', onSessionEvent );
  15224. session.removeEventListener( 'selectend', onSessionEvent );
  15225. session.removeEventListener( 'squeeze', onSessionEvent );
  15226. session.removeEventListener( 'squeezestart', onSessionEvent );
  15227. session.removeEventListener( 'squeezeend', onSessionEvent );
  15228. session.removeEventListener( 'end', onSessionEnd );
  15229. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15230. for ( let i = 0; i < controllers.length; i ++ ) {
  15231. const inputSource = controllerInputSources[ i ];
  15232. if ( inputSource === null ) continue;
  15233. controllerInputSources[ i ] = null;
  15234. controllers[ i ].disconnect( inputSource );
  15235. }
  15236. _currentDepthNear = null;
  15237. _currentDepthFar = null;
  15238. // restore framebuffer/rendering state
  15239. renderer.setRenderTarget( initialRenderTarget );
  15240. glBaseLayer = null;
  15241. glProjLayer = null;
  15242. glBinding = null;
  15243. session = null;
  15244. newRenderTarget = null;
  15245. //
  15246. animation.stop();
  15247. scope.isPresenting = false;
  15248. scope.dispatchEvent( { type: 'sessionend' } );
  15249. }
  15250. this.setFramebufferScaleFactor = function ( value ) {
  15251. framebufferScaleFactor = value;
  15252. if ( scope.isPresenting === true ) {
  15253. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15254. }
  15255. };
  15256. this.setReferenceSpaceType = function ( value ) {
  15257. referenceSpaceType = value;
  15258. if ( scope.isPresenting === true ) {
  15259. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15260. }
  15261. };
  15262. this.getReferenceSpace = function () {
  15263. return customReferenceSpace || referenceSpace;
  15264. };
  15265. this.setReferenceSpace = function ( space ) {
  15266. customReferenceSpace = space;
  15267. };
  15268. this.getBaseLayer = function () {
  15269. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15270. };
  15271. this.getBinding = function () {
  15272. return glBinding;
  15273. };
  15274. this.getFrame = function () {
  15275. return xrFrame;
  15276. };
  15277. this.getSession = function () {
  15278. return session;
  15279. };
  15280. this.setSession = async function ( value ) {
  15281. session = value;
  15282. if ( session !== null ) {
  15283. initialRenderTarget = renderer.getRenderTarget();
  15284. session.addEventListener( 'select', onSessionEvent );
  15285. session.addEventListener( 'selectstart', onSessionEvent );
  15286. session.addEventListener( 'selectend', onSessionEvent );
  15287. session.addEventListener( 'squeeze', onSessionEvent );
  15288. session.addEventListener( 'squeezestart', onSessionEvent );
  15289. session.addEventListener( 'squeezeend', onSessionEvent );
  15290. session.addEventListener( 'end', onSessionEnd );
  15291. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15292. if ( attributes.xrCompatible !== true ) {
  15293. await gl.makeXRCompatible();
  15294. }
  15295. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15296. const layerInit = {
  15297. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15298. alpha: attributes.alpha,
  15299. depth: attributes.depth,
  15300. stencil: attributes.stencil,
  15301. framebufferScaleFactor: framebufferScaleFactor
  15302. };
  15303. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15304. session.updateRenderState( { baseLayer: glBaseLayer } );
  15305. newRenderTarget = new WebGLRenderTarget(
  15306. glBaseLayer.framebufferWidth,
  15307. glBaseLayer.framebufferHeight,
  15308. {
  15309. format: RGBAFormat,
  15310. type: UnsignedByteType,
  15311. encoding: renderer.outputEncoding,
  15312. stencilBuffer: attributes.stencil
  15313. }
  15314. );
  15315. } else {
  15316. let depthFormat = null;
  15317. let depthType = null;
  15318. let glDepthFormat = null;
  15319. if ( attributes.depth ) {
  15320. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15321. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15322. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15323. }
  15324. const projectionlayerInit = {
  15325. colorFormat: 32856,
  15326. depthFormat: glDepthFormat,
  15327. scaleFactor: framebufferScaleFactor
  15328. };
  15329. glBinding = new XRWebGLBinding( session, gl );
  15330. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15331. session.updateRenderState( { layers: [ glProjLayer ] } );
  15332. newRenderTarget = new WebGLRenderTarget(
  15333. glProjLayer.textureWidth,
  15334. glProjLayer.textureHeight,
  15335. {
  15336. format: RGBAFormat,
  15337. type: UnsignedByteType,
  15338. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15339. stencilBuffer: attributes.stencil,
  15340. encoding: renderer.outputEncoding,
  15341. samples: attributes.antialias ? 4 : 0
  15342. } );
  15343. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15344. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15345. }
  15346. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15347. // Set foveation to maximum.
  15348. this.setFoveation( 1.0 );
  15349. customReferenceSpace = null;
  15350. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15351. animation.setContext( session );
  15352. animation.start();
  15353. scope.isPresenting = true;
  15354. scope.dispatchEvent( { type: 'sessionstart' } );
  15355. }
  15356. };
  15357. function onInputSourcesChange( event ) {
  15358. // Notify disconnected
  15359. for ( let i = 0; i < event.removed.length; i ++ ) {
  15360. const inputSource = event.removed[ i ];
  15361. const index = controllerInputSources.indexOf( inputSource );
  15362. if ( index >= 0 ) {
  15363. controllerInputSources[ index ] = null;
  15364. controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } );
  15365. }
  15366. }
  15367. // Notify connected
  15368. for ( let i = 0; i < event.added.length; i ++ ) {
  15369. const inputSource = event.added[ i ];
  15370. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15371. if ( controllerIndex === - 1 ) {
  15372. // Assign input source a controller that currently has no input source
  15373. for ( let i = 0; i < controllers.length; i ++ ) {
  15374. if ( i >= controllerInputSources.length ) {
  15375. controllerInputSources.push( inputSource );
  15376. controllerIndex = i;
  15377. break;
  15378. } else if ( controllerInputSources[ i ] === null ) {
  15379. controllerInputSources[ i ] = inputSource;
  15380. controllerIndex = i;
  15381. break;
  15382. }
  15383. }
  15384. // If all controllers do currently receive input we ignore new ones
  15385. if ( controllerIndex === - 1 ) break;
  15386. }
  15387. const controller = controllers[ controllerIndex ];
  15388. if ( controller ) {
  15389. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  15390. }
  15391. }
  15392. }
  15393. //
  15394. const cameraLPos = new Vector3();
  15395. const cameraRPos = new Vector3();
  15396. /**
  15397. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15398. * the cameras' projection and world matrices have already been set.
  15399. * And that near and far planes are identical for both cameras.
  15400. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15401. */
  15402. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15403. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15404. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15405. const ipd = cameraLPos.distanceTo( cameraRPos );
  15406. const projL = cameraL.projectionMatrix.elements;
  15407. const projR = cameraR.projectionMatrix.elements;
  15408. // VR systems will have identical far and near planes, and
  15409. // most likely identical top and bottom frustum extents.
  15410. // Use the left camera for these values.
  15411. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15412. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15413. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15414. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15415. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15416. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15417. const left = near * leftFov;
  15418. const right = near * rightFov;
  15419. // Calculate the new camera's position offset from the
  15420. // left camera. xOffset should be roughly half `ipd`.
  15421. const zOffset = ipd / ( - leftFov + rightFov );
  15422. const xOffset = zOffset * - leftFov;
  15423. // TODO: Better way to apply this offset?
  15424. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15425. camera.translateX( xOffset );
  15426. camera.translateZ( zOffset );
  15427. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15428. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15429. // Find the union of the frustum values of the cameras and scale
  15430. // the values so that the near plane's position does not change in world space,
  15431. // although must now be relative to the new union camera.
  15432. const near2 = near + zOffset;
  15433. const far2 = far + zOffset;
  15434. const left2 = left - xOffset;
  15435. const right2 = right + ( ipd - xOffset );
  15436. const top2 = topFov * far / far2 * near2;
  15437. const bottom2 = bottomFov * far / far2 * near2;
  15438. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15439. }
  15440. function updateCamera( camera, parent ) {
  15441. if ( parent === null ) {
  15442. camera.matrixWorld.copy( camera.matrix );
  15443. } else {
  15444. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15445. }
  15446. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15447. }
  15448. this.updateCamera = function ( camera ) {
  15449. if ( session === null ) return;
  15450. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15451. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15452. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15453. // Note that the new renderState won't apply until the next frame. See #18320
  15454. session.updateRenderState( {
  15455. depthNear: cameraVR.near,
  15456. depthFar: cameraVR.far
  15457. } );
  15458. _currentDepthNear = cameraVR.near;
  15459. _currentDepthFar = cameraVR.far;
  15460. }
  15461. const parent = camera.parent;
  15462. const cameras = cameraVR.cameras;
  15463. updateCamera( cameraVR, parent );
  15464. for ( let i = 0; i < cameras.length; i ++ ) {
  15465. updateCamera( cameras[ i ], parent );
  15466. }
  15467. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15468. // update user camera and its children
  15469. camera.matrix.copy( cameraVR.matrix );
  15470. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15471. const children = camera.children;
  15472. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15473. children[ i ].updateMatrixWorld( true );
  15474. }
  15475. // update projection matrix for proper view frustum culling
  15476. if ( cameras.length === 2 ) {
  15477. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15478. } else {
  15479. // assume single camera setup (AR)
  15480. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15481. }
  15482. };
  15483. this.getCamera = function () {
  15484. return cameraVR;
  15485. };
  15486. this.getFoveation = function () {
  15487. if ( glProjLayer !== null ) {
  15488. return glProjLayer.fixedFoveation;
  15489. }
  15490. if ( glBaseLayer !== null ) {
  15491. return glBaseLayer.fixedFoveation;
  15492. }
  15493. return undefined;
  15494. };
  15495. this.setFoveation = function ( foveation ) {
  15496. // 0 = no foveation = full resolution
  15497. // 1 = maximum foveation = the edges render at lower resolution
  15498. if ( glProjLayer !== null ) {
  15499. glProjLayer.fixedFoveation = foveation;
  15500. }
  15501. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15502. glBaseLayer.fixedFoveation = foveation;
  15503. }
  15504. };
  15505. // Animation Loop
  15506. let onAnimationFrameCallback = null;
  15507. function onAnimationFrame( time, frame ) {
  15508. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15509. xrFrame = frame;
  15510. if ( pose !== null ) {
  15511. const views = pose.views;
  15512. if ( glBaseLayer !== null ) {
  15513. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15514. renderer.setRenderTarget( newRenderTarget );
  15515. }
  15516. let cameraVRNeedsUpdate = false;
  15517. // check if it's necessary to rebuild cameraVR's camera list
  15518. if ( views.length !== cameraVR.cameras.length ) {
  15519. cameraVR.cameras.length = 0;
  15520. cameraVRNeedsUpdate = true;
  15521. }
  15522. for ( let i = 0; i < views.length; i ++ ) {
  15523. const view = views[ i ];
  15524. let viewport = null;
  15525. if ( glBaseLayer !== null ) {
  15526. viewport = glBaseLayer.getViewport( view );
  15527. } else {
  15528. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15529. viewport = glSubImage.viewport;
  15530. // For side-by-side projection, we only produce a single texture for both eyes.
  15531. if ( i === 0 ) {
  15532. renderer.setRenderTargetTextures(
  15533. newRenderTarget,
  15534. glSubImage.colorTexture,
  15535. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15536. renderer.setRenderTarget( newRenderTarget );
  15537. }
  15538. }
  15539. let camera = cameras[ i ];
  15540. if ( camera === undefined ) {
  15541. camera = new PerspectiveCamera();
  15542. camera.layers.enable( i );
  15543. camera.viewport = new Vector4();
  15544. cameras[ i ] = camera;
  15545. }
  15546. camera.matrix.fromArray( view.transform.matrix );
  15547. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15548. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15549. if ( i === 0 ) {
  15550. cameraVR.matrix.copy( camera.matrix );
  15551. }
  15552. if ( cameraVRNeedsUpdate === true ) {
  15553. cameraVR.cameras.push( camera );
  15554. }
  15555. }
  15556. }
  15557. //
  15558. for ( let i = 0; i < controllers.length; i ++ ) {
  15559. const inputSource = controllerInputSources[ i ];
  15560. const controller = controllers[ i ];
  15561. if ( inputSource !== null && controller !== undefined ) {
  15562. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15563. }
  15564. }
  15565. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15566. xrFrame = null;
  15567. }
  15568. const animation = new WebGLAnimation();
  15569. animation.setAnimationLoop( onAnimationFrame );
  15570. this.setAnimationLoop = function ( callback ) {
  15571. onAnimationFrameCallback = callback;
  15572. };
  15573. this.dispose = function () {};
  15574. }
  15575. }
  15576. function WebGLMaterials( renderer, properties ) {
  15577. function refreshFogUniforms( uniforms, fog ) {
  15578. uniforms.fogColor.value.copy( fog.color );
  15579. if ( fog.isFog ) {
  15580. uniforms.fogNear.value = fog.near;
  15581. uniforms.fogFar.value = fog.far;
  15582. } else if ( fog.isFogExp2 ) {
  15583. uniforms.fogDensity.value = fog.density;
  15584. }
  15585. }
  15586. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15587. if ( material.isMeshBasicMaterial ) {
  15588. refreshUniformsCommon( uniforms, material );
  15589. } else if ( material.isMeshLambertMaterial ) {
  15590. refreshUniformsCommon( uniforms, material );
  15591. } else if ( material.isMeshToonMaterial ) {
  15592. refreshUniformsCommon( uniforms, material );
  15593. refreshUniformsToon( uniforms, material );
  15594. } else if ( material.isMeshPhongMaterial ) {
  15595. refreshUniformsCommon( uniforms, material );
  15596. refreshUniformsPhong( uniforms, material );
  15597. } else if ( material.isMeshStandardMaterial ) {
  15598. refreshUniformsCommon( uniforms, material );
  15599. refreshUniformsStandard( uniforms, material );
  15600. if ( material.isMeshPhysicalMaterial ) {
  15601. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15602. }
  15603. } else if ( material.isMeshMatcapMaterial ) {
  15604. refreshUniformsCommon( uniforms, material );
  15605. refreshUniformsMatcap( uniforms, material );
  15606. } else if ( material.isMeshDepthMaterial ) {
  15607. refreshUniformsCommon( uniforms, material );
  15608. } else if ( material.isMeshDistanceMaterial ) {
  15609. refreshUniformsCommon( uniforms, material );
  15610. refreshUniformsDistance( uniforms, material );
  15611. } else if ( material.isMeshNormalMaterial ) {
  15612. refreshUniformsCommon( uniforms, material );
  15613. } else if ( material.isLineBasicMaterial ) {
  15614. refreshUniformsLine( uniforms, material );
  15615. if ( material.isLineDashedMaterial ) {
  15616. refreshUniformsDash( uniforms, material );
  15617. }
  15618. } else if ( material.isPointsMaterial ) {
  15619. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15620. } else if ( material.isSpriteMaterial ) {
  15621. refreshUniformsSprites( uniforms, material );
  15622. } else if ( material.isShadowMaterial ) {
  15623. uniforms.color.value.copy( material.color );
  15624. uniforms.opacity.value = material.opacity;
  15625. } else if ( material.isShaderMaterial ) {
  15626. material.uniformsNeedUpdate = false; // #15581
  15627. }
  15628. }
  15629. function refreshUniformsCommon( uniforms, material ) {
  15630. uniforms.opacity.value = material.opacity;
  15631. if ( material.color ) {
  15632. uniforms.diffuse.value.copy( material.color );
  15633. }
  15634. if ( material.emissive ) {
  15635. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15636. }
  15637. if ( material.map ) {
  15638. uniforms.map.value = material.map;
  15639. }
  15640. if ( material.alphaMap ) {
  15641. uniforms.alphaMap.value = material.alphaMap;
  15642. }
  15643. if ( material.bumpMap ) {
  15644. uniforms.bumpMap.value = material.bumpMap;
  15645. uniforms.bumpScale.value = material.bumpScale;
  15646. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15647. }
  15648. if ( material.displacementMap ) {
  15649. uniforms.displacementMap.value = material.displacementMap;
  15650. uniforms.displacementScale.value = material.displacementScale;
  15651. uniforms.displacementBias.value = material.displacementBias;
  15652. }
  15653. if ( material.emissiveMap ) {
  15654. uniforms.emissiveMap.value = material.emissiveMap;
  15655. }
  15656. if ( material.normalMap ) {
  15657. uniforms.normalMap.value = material.normalMap;
  15658. uniforms.normalScale.value.copy( material.normalScale );
  15659. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15660. }
  15661. if ( material.specularMap ) {
  15662. uniforms.specularMap.value = material.specularMap;
  15663. }
  15664. if ( material.alphaTest > 0 ) {
  15665. uniforms.alphaTest.value = material.alphaTest;
  15666. }
  15667. const envMap = properties.get( material ).envMap;
  15668. if ( envMap ) {
  15669. uniforms.envMap.value = envMap;
  15670. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15671. uniforms.reflectivity.value = material.reflectivity;
  15672. uniforms.ior.value = material.ior;
  15673. uniforms.refractionRatio.value = material.refractionRatio;
  15674. }
  15675. if ( material.lightMap ) {
  15676. uniforms.lightMap.value = material.lightMap;
  15677. // artist-friendly light intensity scaling factor
  15678. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15679. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15680. }
  15681. if ( material.aoMap ) {
  15682. uniforms.aoMap.value = material.aoMap;
  15683. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15684. }
  15685. // uv repeat and offset setting priorities
  15686. // 1. color map
  15687. // 2. specular map
  15688. // 3. displacementMap map
  15689. // 4. normal map
  15690. // 5. bump map
  15691. // 6. roughnessMap map
  15692. // 7. metalnessMap map
  15693. // 8. alphaMap map
  15694. // 9. emissiveMap map
  15695. // 10. clearcoat map
  15696. // 11. clearcoat normal map
  15697. // 12. clearcoat roughnessMap map
  15698. // 13. iridescence map
  15699. // 14. iridescence thickness map
  15700. // 15. specular intensity map
  15701. // 16. specular tint map
  15702. // 17. transmission map
  15703. // 18. thickness map
  15704. let uvScaleMap;
  15705. if ( material.map ) {
  15706. uvScaleMap = material.map;
  15707. } else if ( material.specularMap ) {
  15708. uvScaleMap = material.specularMap;
  15709. } else if ( material.displacementMap ) {
  15710. uvScaleMap = material.displacementMap;
  15711. } else if ( material.normalMap ) {
  15712. uvScaleMap = material.normalMap;
  15713. } else if ( material.bumpMap ) {
  15714. uvScaleMap = material.bumpMap;
  15715. } else if ( material.roughnessMap ) {
  15716. uvScaleMap = material.roughnessMap;
  15717. } else if ( material.metalnessMap ) {
  15718. uvScaleMap = material.metalnessMap;
  15719. } else if ( material.alphaMap ) {
  15720. uvScaleMap = material.alphaMap;
  15721. } else if ( material.emissiveMap ) {
  15722. uvScaleMap = material.emissiveMap;
  15723. } else if ( material.clearcoatMap ) {
  15724. uvScaleMap = material.clearcoatMap;
  15725. } else if ( material.clearcoatNormalMap ) {
  15726. uvScaleMap = material.clearcoatNormalMap;
  15727. } else if ( material.clearcoatRoughnessMap ) {
  15728. uvScaleMap = material.clearcoatRoughnessMap;
  15729. } else if ( material.iridescenceMap ) {
  15730. uvScaleMap = material.iridescenceMap;
  15731. } else if ( material.iridescenceThicknessMap ) {
  15732. uvScaleMap = material.iridescenceThicknessMap;
  15733. } else if ( material.specularIntensityMap ) {
  15734. uvScaleMap = material.specularIntensityMap;
  15735. } else if ( material.specularColorMap ) {
  15736. uvScaleMap = material.specularColorMap;
  15737. } else if ( material.transmissionMap ) {
  15738. uvScaleMap = material.transmissionMap;
  15739. } else if ( material.thicknessMap ) {
  15740. uvScaleMap = material.thicknessMap;
  15741. } else if ( material.sheenColorMap ) {
  15742. uvScaleMap = material.sheenColorMap;
  15743. } else if ( material.sheenRoughnessMap ) {
  15744. uvScaleMap = material.sheenRoughnessMap;
  15745. }
  15746. if ( uvScaleMap !== undefined ) {
  15747. // backwards compatibility
  15748. if ( uvScaleMap.isWebGLRenderTarget ) {
  15749. uvScaleMap = uvScaleMap.texture;
  15750. }
  15751. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15752. uvScaleMap.updateMatrix();
  15753. }
  15754. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15755. }
  15756. // uv repeat and offset setting priorities for uv2
  15757. // 1. ao map
  15758. // 2. light map
  15759. let uv2ScaleMap;
  15760. if ( material.aoMap ) {
  15761. uv2ScaleMap = material.aoMap;
  15762. } else if ( material.lightMap ) {
  15763. uv2ScaleMap = material.lightMap;
  15764. }
  15765. if ( uv2ScaleMap !== undefined ) {
  15766. // backwards compatibility
  15767. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15768. uv2ScaleMap = uv2ScaleMap.texture;
  15769. }
  15770. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15771. uv2ScaleMap.updateMatrix();
  15772. }
  15773. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15774. }
  15775. }
  15776. function refreshUniformsLine( uniforms, material ) {
  15777. uniforms.diffuse.value.copy( material.color );
  15778. uniforms.opacity.value = material.opacity;
  15779. }
  15780. function refreshUniformsDash( uniforms, material ) {
  15781. uniforms.dashSize.value = material.dashSize;
  15782. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15783. uniforms.scale.value = material.scale;
  15784. }
  15785. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15786. uniforms.diffuse.value.copy( material.color );
  15787. uniforms.opacity.value = material.opacity;
  15788. uniforms.size.value = material.size * pixelRatio;
  15789. uniforms.scale.value = height * 0.5;
  15790. if ( material.map ) {
  15791. uniforms.map.value = material.map;
  15792. }
  15793. if ( material.alphaMap ) {
  15794. uniforms.alphaMap.value = material.alphaMap;
  15795. }
  15796. if ( material.alphaTest > 0 ) {
  15797. uniforms.alphaTest.value = material.alphaTest;
  15798. }
  15799. // uv repeat and offset setting priorities
  15800. // 1. color map
  15801. // 2. alpha map
  15802. let uvScaleMap;
  15803. if ( material.map ) {
  15804. uvScaleMap = material.map;
  15805. } else if ( material.alphaMap ) {
  15806. uvScaleMap = material.alphaMap;
  15807. }
  15808. if ( uvScaleMap !== undefined ) {
  15809. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15810. uvScaleMap.updateMatrix();
  15811. }
  15812. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15813. }
  15814. }
  15815. function refreshUniformsSprites( uniforms, material ) {
  15816. uniforms.diffuse.value.copy( material.color );
  15817. uniforms.opacity.value = material.opacity;
  15818. uniforms.rotation.value = material.rotation;
  15819. if ( material.map ) {
  15820. uniforms.map.value = material.map;
  15821. }
  15822. if ( material.alphaMap ) {
  15823. uniforms.alphaMap.value = material.alphaMap;
  15824. }
  15825. if ( material.alphaTest > 0 ) {
  15826. uniforms.alphaTest.value = material.alphaTest;
  15827. }
  15828. // uv repeat and offset setting priorities
  15829. // 1. color map
  15830. // 2. alpha map
  15831. let uvScaleMap;
  15832. if ( material.map ) {
  15833. uvScaleMap = material.map;
  15834. } else if ( material.alphaMap ) {
  15835. uvScaleMap = material.alphaMap;
  15836. }
  15837. if ( uvScaleMap !== undefined ) {
  15838. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15839. uvScaleMap.updateMatrix();
  15840. }
  15841. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15842. }
  15843. }
  15844. function refreshUniformsPhong( uniforms, material ) {
  15845. uniforms.specular.value.copy( material.specular );
  15846. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15847. }
  15848. function refreshUniformsToon( uniforms, material ) {
  15849. if ( material.gradientMap ) {
  15850. uniforms.gradientMap.value = material.gradientMap;
  15851. }
  15852. }
  15853. function refreshUniformsStandard( uniforms, material ) {
  15854. uniforms.roughness.value = material.roughness;
  15855. uniforms.metalness.value = material.metalness;
  15856. if ( material.roughnessMap ) {
  15857. uniforms.roughnessMap.value = material.roughnessMap;
  15858. }
  15859. if ( material.metalnessMap ) {
  15860. uniforms.metalnessMap.value = material.metalnessMap;
  15861. }
  15862. const envMap = properties.get( material ).envMap;
  15863. if ( envMap ) {
  15864. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15865. uniforms.envMapIntensity.value = material.envMapIntensity;
  15866. }
  15867. }
  15868. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15869. uniforms.ior.value = material.ior; // also part of uniforms common
  15870. if ( material.sheen > 0 ) {
  15871. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15872. uniforms.sheenRoughness.value = material.sheenRoughness;
  15873. if ( material.sheenColorMap ) {
  15874. uniforms.sheenColorMap.value = material.sheenColorMap;
  15875. }
  15876. if ( material.sheenRoughnessMap ) {
  15877. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15878. }
  15879. }
  15880. if ( material.clearcoat > 0 ) {
  15881. uniforms.clearcoat.value = material.clearcoat;
  15882. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15883. if ( material.clearcoatMap ) {
  15884. uniforms.clearcoatMap.value = material.clearcoatMap;
  15885. }
  15886. if ( material.clearcoatRoughnessMap ) {
  15887. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15888. }
  15889. if ( material.clearcoatNormalMap ) {
  15890. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15891. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15892. if ( material.side === BackSide ) {
  15893. uniforms.clearcoatNormalScale.value.negate();
  15894. }
  15895. }
  15896. }
  15897. if ( material.iridescence > 0 ) {
  15898. uniforms.iridescence.value = material.iridescence;
  15899. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15900. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15901. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15902. if ( material.iridescenceMap ) {
  15903. uniforms.iridescenceMap.value = material.iridescenceMap;
  15904. }
  15905. if ( material.iridescenceThicknessMap ) {
  15906. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15907. }
  15908. }
  15909. if ( material.transmission > 0 ) {
  15910. uniforms.transmission.value = material.transmission;
  15911. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15912. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15913. if ( material.transmissionMap ) {
  15914. uniforms.transmissionMap.value = material.transmissionMap;
  15915. }
  15916. uniforms.thickness.value = material.thickness;
  15917. if ( material.thicknessMap ) {
  15918. uniforms.thicknessMap.value = material.thicknessMap;
  15919. }
  15920. uniforms.attenuationDistance.value = material.attenuationDistance;
  15921. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15922. }
  15923. uniforms.specularIntensity.value = material.specularIntensity;
  15924. uniforms.specularColor.value.copy( material.specularColor );
  15925. if ( material.specularIntensityMap ) {
  15926. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15927. }
  15928. if ( material.specularColorMap ) {
  15929. uniforms.specularColorMap.value = material.specularColorMap;
  15930. }
  15931. }
  15932. function refreshUniformsMatcap( uniforms, material ) {
  15933. if ( material.matcap ) {
  15934. uniforms.matcap.value = material.matcap;
  15935. }
  15936. }
  15937. function refreshUniformsDistance( uniforms, material ) {
  15938. uniforms.referencePosition.value.copy( material.referencePosition );
  15939. uniforms.nearDistance.value = material.nearDistance;
  15940. uniforms.farDistance.value = material.farDistance;
  15941. }
  15942. return {
  15943. refreshFogUniforms: refreshFogUniforms,
  15944. refreshMaterialUniforms: refreshMaterialUniforms
  15945. };
  15946. }
  15947. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15948. let buffers = {};
  15949. let updateList = {};
  15950. let allocatedBindingPoints = [];
  15951. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  15952. function bind( uniformsGroup, program ) {
  15953. const webglProgram = program.program;
  15954. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15955. }
  15956. function update( uniformsGroup, program ) {
  15957. let buffer = buffers[ uniformsGroup.id ];
  15958. if ( buffer === undefined ) {
  15959. prepareUniformsGroup( uniformsGroup );
  15960. buffer = createBuffer( uniformsGroup );
  15961. buffers[ uniformsGroup.id ] = buffer;
  15962. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15963. }
  15964. // ensure to update the binding points/block indices mapping for this program
  15965. const webglProgram = program.program;
  15966. state.updateUBOMapping( uniformsGroup, webglProgram );
  15967. // update UBO once per frame
  15968. const frame = info.render.frame;
  15969. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15970. updateBufferData( uniformsGroup );
  15971. updateList[ uniformsGroup.id ] = frame;
  15972. }
  15973. }
  15974. function createBuffer( uniformsGroup ) {
  15975. // the setup of an UBO is independent of a particular shader program but global
  15976. const bindingPointIndex = allocateBindingPointIndex();
  15977. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15978. const buffer = gl.createBuffer();
  15979. const size = uniformsGroup.__size;
  15980. const usage = uniformsGroup.usage;
  15981. gl.bindBuffer( 35345, buffer );
  15982. gl.bufferData( 35345, size, usage );
  15983. gl.bindBuffer( 35345, null );
  15984. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  15985. return buffer;
  15986. }
  15987. function allocateBindingPointIndex() {
  15988. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15989. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15990. allocatedBindingPoints.push( i );
  15991. return i;
  15992. }
  15993. }
  15994. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15995. return 0;
  15996. }
  15997. function updateBufferData( uniformsGroup ) {
  15998. const buffer = buffers[ uniformsGroup.id ];
  15999. const uniforms = uniformsGroup.uniforms;
  16000. const cache = uniformsGroup.__cache;
  16001. gl.bindBuffer( 35345, buffer );
  16002. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16003. const uniform = uniforms[ i ];
  16004. // partly update the buffer if necessary
  16005. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16006. const value = uniform.value;
  16007. const offset = uniform.__offset;
  16008. if ( typeof value === 'number' ) {
  16009. uniform.__data[ 0 ] = value;
  16010. gl.bufferSubData( 35345, offset, uniform.__data );
  16011. } else {
  16012. if ( uniform.value.isMatrix3 ) {
  16013. // manually converting 3x3 to 3x4
  16014. uniform.__data[ 0 ] = uniform.value.elements[ 0 ];
  16015. uniform.__data[ 1 ] = uniform.value.elements[ 1 ];
  16016. uniform.__data[ 2 ] = uniform.value.elements[ 2 ];
  16017. uniform.__data[ 3 ] = uniform.value.elements[ 0 ];
  16018. uniform.__data[ 4 ] = uniform.value.elements[ 3 ];
  16019. uniform.__data[ 5 ] = uniform.value.elements[ 4 ];
  16020. uniform.__data[ 6 ] = uniform.value.elements[ 5 ];
  16021. uniform.__data[ 7 ] = uniform.value.elements[ 0 ];
  16022. uniform.__data[ 8 ] = uniform.value.elements[ 6 ];
  16023. uniform.__data[ 9 ] = uniform.value.elements[ 7 ];
  16024. uniform.__data[ 10 ] = uniform.value.elements[ 8 ];
  16025. uniform.__data[ 11 ] = uniform.value.elements[ 0 ];
  16026. } else {
  16027. value.toArray( uniform.__data );
  16028. }
  16029. gl.bufferSubData( 35345, offset, uniform.__data );
  16030. }
  16031. }
  16032. }
  16033. gl.bindBuffer( 35345, null );
  16034. }
  16035. function hasUniformChanged( uniform, index, cache ) {
  16036. const value = uniform.value;
  16037. if ( cache[ index ] === undefined ) {
  16038. // cache entry does not exist so far
  16039. if ( typeof value === 'number' ) {
  16040. cache[ index ] = value;
  16041. } else {
  16042. cache[ index ] = value.clone();
  16043. }
  16044. return true;
  16045. } else {
  16046. // compare current value with cached entry
  16047. if ( typeof value === 'number' ) {
  16048. if ( cache[ index ] !== value ) {
  16049. cache[ index ] = value;
  16050. return true;
  16051. }
  16052. } else {
  16053. const cachedObject = cache[ index ];
  16054. if ( cachedObject.equals( value ) === false ) {
  16055. cachedObject.copy( value );
  16056. return true;
  16057. }
  16058. }
  16059. }
  16060. return false;
  16061. }
  16062. function prepareUniformsGroup( uniformsGroup ) {
  16063. // determine total buffer size according to the STD140 layout
  16064. // Hint: STD140 is the only supported layout in WebGL 2
  16065. const uniforms = uniformsGroup.uniforms;
  16066. let offset = 0; // global buffer offset in bytes
  16067. const chunkSize = 16; // size of a chunk in bytes
  16068. let chunkOffset = 0; // offset within a single chunk in bytes
  16069. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16070. const uniform = uniforms[ i ];
  16071. const info = getUniformSize( uniform );
  16072. // the following two properties will be used for partial buffer updates
  16073. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  16074. uniform.__offset = offset;
  16075. //
  16076. if ( i > 0 ) {
  16077. chunkOffset = offset % chunkSize;
  16078. const remainingSizeInChunk = chunkSize - chunkOffset;
  16079. // check for chunk overflow
  16080. if ( chunkOffset !== 0 && ( remainingSizeInChunk - info.boundary ) < 0 ) {
  16081. // add padding and adjust offset
  16082. offset += ( chunkSize - chunkOffset );
  16083. uniform.__offset = offset;
  16084. }
  16085. }
  16086. offset += info.storage;
  16087. }
  16088. // ensure correct final padding
  16089. chunkOffset = offset % chunkSize;
  16090. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16091. //
  16092. uniformsGroup.__size = offset;
  16093. uniformsGroup.__cache = {};
  16094. return this;
  16095. }
  16096. function getUniformSize( uniform ) {
  16097. const value = uniform.value;
  16098. const info = {
  16099. boundary: 0, // bytes
  16100. storage: 0 // bytes
  16101. };
  16102. // determine sizes according to STD140
  16103. if ( typeof value === 'number' ) {
  16104. // float/int
  16105. info.boundary = 4;
  16106. info.storage = 4;
  16107. } else if ( value.isVector2 ) {
  16108. // vec2
  16109. info.boundary = 8;
  16110. info.storage = 8;
  16111. } else if ( value.isVector3 || value.isColor ) {
  16112. // vec3
  16113. info.boundary = 16;
  16114. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16115. } else if ( value.isVector4 ) {
  16116. // vec4
  16117. info.boundary = 16;
  16118. info.storage = 16;
  16119. } else if ( value.isMatrix3 ) {
  16120. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16121. info.boundary = 48;
  16122. info.storage = 48;
  16123. } else if ( value.isMatrix4 ) {
  16124. // mat4
  16125. info.boundary = 64;
  16126. info.storage = 64;
  16127. } else if ( value.isTexture ) {
  16128. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16129. } else {
  16130. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16131. }
  16132. return info;
  16133. }
  16134. function onUniformsGroupsDispose( event ) {
  16135. const uniformsGroup = event.target;
  16136. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16137. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16138. allocatedBindingPoints.splice( index, 1 );
  16139. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16140. delete buffers[ uniformsGroup.id ];
  16141. delete updateList[ uniformsGroup.id ];
  16142. }
  16143. function dispose() {
  16144. for ( const id in buffers ) {
  16145. gl.deleteBuffer( buffers[ id ] );
  16146. }
  16147. allocatedBindingPoints = [];
  16148. buffers = {};
  16149. updateList = {};
  16150. }
  16151. return {
  16152. bind: bind,
  16153. update: update,
  16154. dispose: dispose
  16155. };
  16156. }
  16157. function createCanvasElement() {
  16158. const canvas = createElementNS( 'canvas' );
  16159. canvas.style.display = 'block';
  16160. return canvas;
  16161. }
  16162. function WebGLRenderer( parameters = {} ) {
  16163. this.isWebGLRenderer = true;
  16164. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16165. _context = parameters.context !== undefined ? parameters.context : null,
  16166. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16167. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16168. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16169. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16170. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16171. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16172. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16173. let _alpha;
  16174. if ( _context !== null ) {
  16175. _alpha = _context.getContextAttributes().alpha;
  16176. } else {
  16177. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16178. }
  16179. let currentRenderList = null;
  16180. let currentRenderState = null;
  16181. // render() can be called from within a callback triggered by another render.
  16182. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16183. const renderListStack = [];
  16184. const renderStateStack = [];
  16185. // public properties
  16186. this.domElement = _canvas;
  16187. // Debug configuration container
  16188. this.debug = {
  16189. /**
  16190. * Enables error checking and reporting when shader programs are being compiled
  16191. * @type {boolean}
  16192. */
  16193. checkShaderErrors: true
  16194. };
  16195. // clearing
  16196. this.autoClear = true;
  16197. this.autoClearColor = true;
  16198. this.autoClearDepth = true;
  16199. this.autoClearStencil = true;
  16200. // scene graph
  16201. this.sortObjects = true;
  16202. // user-defined clipping
  16203. this.clippingPlanes = [];
  16204. this.localClippingEnabled = false;
  16205. // physically based shading
  16206. this.outputEncoding = LinearEncoding;
  16207. // physical lights
  16208. this.physicallyCorrectLights = false;
  16209. // tone mapping
  16210. this.toneMapping = NoToneMapping;
  16211. this.toneMappingExposure = 1.0;
  16212. //
  16213. Object.defineProperties( this, {
  16214. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  16215. gammaFactor: {
  16216. get: function () {
  16217. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  16218. return 2;
  16219. },
  16220. set: function () {
  16221. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  16222. }
  16223. }
  16224. } );
  16225. // internal properties
  16226. const _this = this;
  16227. let _isContextLost = false;
  16228. // internal state cache
  16229. let _currentActiveCubeFace = 0;
  16230. let _currentActiveMipmapLevel = 0;
  16231. let _currentRenderTarget = null;
  16232. let _currentMaterialId = - 1;
  16233. let _currentCamera = null;
  16234. const _currentViewport = new Vector4();
  16235. const _currentScissor = new Vector4();
  16236. let _currentScissorTest = null;
  16237. //
  16238. let _width = _canvas.width;
  16239. let _height = _canvas.height;
  16240. let _pixelRatio = 1;
  16241. let _opaqueSort = null;
  16242. let _transparentSort = null;
  16243. const _viewport = new Vector4( 0, 0, _width, _height );
  16244. const _scissor = new Vector4( 0, 0, _width, _height );
  16245. let _scissorTest = false;
  16246. // frustum
  16247. const _frustum = new Frustum();
  16248. // clipping
  16249. let _clippingEnabled = false;
  16250. let _localClippingEnabled = false;
  16251. // transmission
  16252. let _transmissionRenderTarget = null;
  16253. // camera matrices cache
  16254. const _projScreenMatrix = new Matrix4();
  16255. const _vector2 = new Vector2();
  16256. const _vector3 = new Vector3();
  16257. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16258. function getTargetPixelRatio() {
  16259. return _currentRenderTarget === null ? _pixelRatio : 1;
  16260. }
  16261. // initialize
  16262. let _gl = _context;
  16263. function getContext( contextNames, contextAttributes ) {
  16264. for ( let i = 0; i < contextNames.length; i ++ ) {
  16265. const contextName = contextNames[ i ];
  16266. const context = _canvas.getContext( contextName, contextAttributes );
  16267. if ( context !== null ) return context;
  16268. }
  16269. return null;
  16270. }
  16271. try {
  16272. const contextAttributes = {
  16273. alpha: true,
  16274. depth: _depth,
  16275. stencil: _stencil,
  16276. antialias: _antialias,
  16277. premultipliedAlpha: _premultipliedAlpha,
  16278. preserveDrawingBuffer: _preserveDrawingBuffer,
  16279. powerPreference: _powerPreference,
  16280. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16281. };
  16282. // OffscreenCanvas does not have setAttribute, see #22811
  16283. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16284. // event listeners must be registered before WebGL context is created, see #12753
  16285. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16286. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16287. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16288. if ( _gl === null ) {
  16289. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16290. if ( _this.isWebGL1Renderer === true ) {
  16291. contextNames.shift();
  16292. }
  16293. _gl = getContext( contextNames, contextAttributes );
  16294. if ( _gl === null ) {
  16295. if ( getContext( contextNames ) ) {
  16296. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16297. } else {
  16298. throw new Error( 'Error creating WebGL context.' );
  16299. }
  16300. }
  16301. }
  16302. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16303. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16304. _gl.getShaderPrecisionFormat = function () {
  16305. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16306. };
  16307. }
  16308. } catch ( error ) {
  16309. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16310. throw error;
  16311. }
  16312. let extensions, capabilities, state, info;
  16313. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16314. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16315. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16316. let utils, bindingStates, uniformsGroups;
  16317. function initGLContext() {
  16318. extensions = new WebGLExtensions( _gl );
  16319. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16320. extensions.init( capabilities );
  16321. utils = new WebGLUtils( _gl, extensions, capabilities );
  16322. state = new WebGLState( _gl, extensions, capabilities );
  16323. info = new WebGLInfo();
  16324. properties = new WebGLProperties();
  16325. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16326. cubemaps = new WebGLCubeMaps( _this );
  16327. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16328. attributes = new WebGLAttributes( _gl, capabilities );
  16329. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16330. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16331. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16332. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16333. clipping = new WebGLClipping( properties );
  16334. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16335. materials = new WebGLMaterials( _this, properties );
  16336. renderLists = new WebGLRenderLists();
  16337. renderStates = new WebGLRenderStates( extensions, capabilities );
  16338. background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
  16339. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16340. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16341. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16342. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16343. info.programs = programCache.programs;
  16344. _this.capabilities = capabilities;
  16345. _this.extensions = extensions;
  16346. _this.properties = properties;
  16347. _this.renderLists = renderLists;
  16348. _this.shadowMap = shadowMap;
  16349. _this.state = state;
  16350. _this.info = info;
  16351. }
  16352. initGLContext();
  16353. // xr
  16354. const xr = new WebXRManager( _this, _gl );
  16355. this.xr = xr;
  16356. // API
  16357. this.getContext = function () {
  16358. return _gl;
  16359. };
  16360. this.getContextAttributes = function () {
  16361. return _gl.getContextAttributes();
  16362. };
  16363. this.forceContextLoss = function () {
  16364. const extension = extensions.get( 'WEBGL_lose_context' );
  16365. if ( extension ) extension.loseContext();
  16366. };
  16367. this.forceContextRestore = function () {
  16368. const extension = extensions.get( 'WEBGL_lose_context' );
  16369. if ( extension ) extension.restoreContext();
  16370. };
  16371. this.getPixelRatio = function () {
  16372. return _pixelRatio;
  16373. };
  16374. this.setPixelRatio = function ( value ) {
  16375. if ( value === undefined ) return;
  16376. _pixelRatio = value;
  16377. this.setSize( _width, _height, false );
  16378. };
  16379. this.getSize = function ( target ) {
  16380. return target.set( _width, _height );
  16381. };
  16382. this.setSize = function ( width, height, updateStyle ) {
  16383. if ( xr.isPresenting ) {
  16384. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16385. return;
  16386. }
  16387. _width = width;
  16388. _height = height;
  16389. _canvas.width = Math.floor( width * _pixelRatio );
  16390. _canvas.height = Math.floor( height * _pixelRatio );
  16391. if ( updateStyle !== false ) {
  16392. _canvas.style.width = width + 'px';
  16393. _canvas.style.height = height + 'px';
  16394. }
  16395. this.setViewport( 0, 0, width, height );
  16396. };
  16397. this.getDrawingBufferSize = function ( target ) {
  16398. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16399. };
  16400. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16401. _width = width;
  16402. _height = height;
  16403. _pixelRatio = pixelRatio;
  16404. _canvas.width = Math.floor( width * pixelRatio );
  16405. _canvas.height = Math.floor( height * pixelRatio );
  16406. this.setViewport( 0, 0, width, height );
  16407. };
  16408. this.getCurrentViewport = function ( target ) {
  16409. return target.copy( _currentViewport );
  16410. };
  16411. this.getViewport = function ( target ) {
  16412. return target.copy( _viewport );
  16413. };
  16414. this.setViewport = function ( x, y, width, height ) {
  16415. if ( x.isVector4 ) {
  16416. _viewport.set( x.x, x.y, x.z, x.w );
  16417. } else {
  16418. _viewport.set( x, y, width, height );
  16419. }
  16420. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16421. };
  16422. this.getScissor = function ( target ) {
  16423. return target.copy( _scissor );
  16424. };
  16425. this.setScissor = function ( x, y, width, height ) {
  16426. if ( x.isVector4 ) {
  16427. _scissor.set( x.x, x.y, x.z, x.w );
  16428. } else {
  16429. _scissor.set( x, y, width, height );
  16430. }
  16431. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16432. };
  16433. this.getScissorTest = function () {
  16434. return _scissorTest;
  16435. };
  16436. this.setScissorTest = function ( boolean ) {
  16437. state.setScissorTest( _scissorTest = boolean );
  16438. };
  16439. this.setOpaqueSort = function ( method ) {
  16440. _opaqueSort = method;
  16441. };
  16442. this.setTransparentSort = function ( method ) {
  16443. _transparentSort = method;
  16444. };
  16445. // Clearing
  16446. this.getClearColor = function ( target ) {
  16447. return target.copy( background.getClearColor() );
  16448. };
  16449. this.setClearColor = function () {
  16450. background.setClearColor.apply( background, arguments );
  16451. };
  16452. this.getClearAlpha = function () {
  16453. return background.getClearAlpha();
  16454. };
  16455. this.setClearAlpha = function () {
  16456. background.setClearAlpha.apply( background, arguments );
  16457. };
  16458. this.clear = function ( color = true, depth = true, stencil = true ) {
  16459. let bits = 0;
  16460. if ( color ) bits |= 16384;
  16461. if ( depth ) bits |= 256;
  16462. if ( stencil ) bits |= 1024;
  16463. _gl.clear( bits );
  16464. };
  16465. this.clearColor = function () {
  16466. this.clear( true, false, false );
  16467. };
  16468. this.clearDepth = function () {
  16469. this.clear( false, true, false );
  16470. };
  16471. this.clearStencil = function () {
  16472. this.clear( false, false, true );
  16473. };
  16474. //
  16475. this.dispose = function () {
  16476. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16477. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16478. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16479. renderLists.dispose();
  16480. renderStates.dispose();
  16481. properties.dispose();
  16482. cubemaps.dispose();
  16483. cubeuvmaps.dispose();
  16484. objects.dispose();
  16485. bindingStates.dispose();
  16486. uniformsGroups.dispose();
  16487. programCache.dispose();
  16488. xr.dispose();
  16489. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16490. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16491. if ( _transmissionRenderTarget ) {
  16492. _transmissionRenderTarget.dispose();
  16493. _transmissionRenderTarget = null;
  16494. }
  16495. animation.stop();
  16496. };
  16497. // Events
  16498. function onContextLost( event ) {
  16499. event.preventDefault();
  16500. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16501. _isContextLost = true;
  16502. }
  16503. function onContextRestore( /* event */ ) {
  16504. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16505. _isContextLost = false;
  16506. const infoAutoReset = info.autoReset;
  16507. const shadowMapEnabled = shadowMap.enabled;
  16508. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16509. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16510. const shadowMapType = shadowMap.type;
  16511. initGLContext();
  16512. info.autoReset = infoAutoReset;
  16513. shadowMap.enabled = shadowMapEnabled;
  16514. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16515. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16516. shadowMap.type = shadowMapType;
  16517. }
  16518. function onContextCreationError( event ) {
  16519. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16520. }
  16521. function onMaterialDispose( event ) {
  16522. const material = event.target;
  16523. material.removeEventListener( 'dispose', onMaterialDispose );
  16524. deallocateMaterial( material );
  16525. }
  16526. // Buffer deallocation
  16527. function deallocateMaterial( material ) {
  16528. releaseMaterialProgramReferences( material );
  16529. properties.remove( material );
  16530. }
  16531. function releaseMaterialProgramReferences( material ) {
  16532. const programs = properties.get( material ).programs;
  16533. if ( programs !== undefined ) {
  16534. programs.forEach( function ( program ) {
  16535. programCache.releaseProgram( program );
  16536. } );
  16537. if ( material.isShaderMaterial ) {
  16538. programCache.releaseShaderCache( material );
  16539. }
  16540. }
  16541. }
  16542. // Buffer rendering
  16543. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16544. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16545. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16546. const program = setProgram( camera, scene, geometry, material, object );
  16547. state.setMaterial( material, frontFaceCW );
  16548. //
  16549. let index = geometry.index;
  16550. const position = geometry.attributes.position;
  16551. //
  16552. if ( index === null ) {
  16553. if ( position === undefined || position.count === 0 ) return;
  16554. } else if ( index.count === 0 ) {
  16555. return;
  16556. }
  16557. //
  16558. let rangeFactor = 1;
  16559. if ( material.wireframe === true ) {
  16560. index = geometries.getWireframeAttribute( geometry );
  16561. rangeFactor = 2;
  16562. }
  16563. bindingStates.setup( object, material, program, geometry, index );
  16564. let attribute;
  16565. let renderer = bufferRenderer;
  16566. if ( index !== null ) {
  16567. attribute = attributes.get( index );
  16568. renderer = indexedBufferRenderer;
  16569. renderer.setIndex( attribute );
  16570. }
  16571. //
  16572. const dataCount = ( index !== null ) ? index.count : position.count;
  16573. const rangeStart = geometry.drawRange.start * rangeFactor;
  16574. const rangeCount = geometry.drawRange.count * rangeFactor;
  16575. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16576. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16577. const drawStart = Math.max( rangeStart, groupStart );
  16578. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16579. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16580. if ( drawCount === 0 ) return;
  16581. //
  16582. if ( object.isMesh ) {
  16583. if ( material.wireframe === true ) {
  16584. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16585. renderer.setMode( 1 );
  16586. } else {
  16587. renderer.setMode( 4 );
  16588. }
  16589. } else if ( object.isLine ) {
  16590. let lineWidth = material.linewidth;
  16591. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16592. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16593. if ( object.isLineSegments ) {
  16594. renderer.setMode( 1 );
  16595. } else if ( object.isLineLoop ) {
  16596. renderer.setMode( 2 );
  16597. } else {
  16598. renderer.setMode( 3 );
  16599. }
  16600. } else if ( object.isPoints ) {
  16601. renderer.setMode( 0 );
  16602. } else if ( object.isSprite ) {
  16603. renderer.setMode( 4 );
  16604. }
  16605. if ( object.isInstancedMesh ) {
  16606. renderer.renderInstances( drawStart, drawCount, object.count );
  16607. } else if ( geometry.isInstancedBufferGeometry ) {
  16608. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  16609. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16610. } else {
  16611. renderer.render( drawStart, drawCount );
  16612. }
  16613. };
  16614. // Compile
  16615. this.compile = function ( scene, camera ) {
  16616. function prepare( material, scene, object ) {
  16617. if ( material.transparent === true && material.side === DoubleSide ) {
  16618. material.side = BackSide;
  16619. material.needsUpdate = true;
  16620. getProgram( material, scene, object );
  16621. material.side = FrontSide;
  16622. material.needsUpdate = true;
  16623. getProgram( material, scene, object );
  16624. material.side = DoubleSide;
  16625. } else {
  16626. getProgram( material, scene, object );
  16627. }
  16628. }
  16629. currentRenderState = renderStates.get( scene );
  16630. currentRenderState.init();
  16631. renderStateStack.push( currentRenderState );
  16632. scene.traverseVisible( function ( object ) {
  16633. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16634. currentRenderState.pushLight( object );
  16635. if ( object.castShadow ) {
  16636. currentRenderState.pushShadow( object );
  16637. }
  16638. }
  16639. } );
  16640. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16641. scene.traverse( function ( object ) {
  16642. const material = object.material;
  16643. if ( material ) {
  16644. if ( Array.isArray( material ) ) {
  16645. for ( let i = 0; i < material.length; i ++ ) {
  16646. const material2 = material[ i ];
  16647. prepare( material2, scene, object );
  16648. }
  16649. } else {
  16650. prepare( material, scene, object );
  16651. }
  16652. }
  16653. } );
  16654. renderStateStack.pop();
  16655. currentRenderState = null;
  16656. };
  16657. // Animation Loop
  16658. let onAnimationFrameCallback = null;
  16659. function onAnimationFrame( time ) {
  16660. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16661. }
  16662. function onXRSessionStart() {
  16663. animation.stop();
  16664. }
  16665. function onXRSessionEnd() {
  16666. animation.start();
  16667. }
  16668. const animation = new WebGLAnimation();
  16669. animation.setAnimationLoop( onAnimationFrame );
  16670. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16671. this.setAnimationLoop = function ( callback ) {
  16672. onAnimationFrameCallback = callback;
  16673. xr.setAnimationLoop( callback );
  16674. ( callback === null ) ? animation.stop() : animation.start();
  16675. };
  16676. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16677. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16678. // Rendering
  16679. this.render = function ( scene, camera ) {
  16680. if ( camera !== undefined && camera.isCamera !== true ) {
  16681. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16682. return;
  16683. }
  16684. if ( _isContextLost === true ) return;
  16685. // update scene graph
  16686. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16687. // update camera matrices and frustum
  16688. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16689. if ( xr.enabled === true && xr.isPresenting === true ) {
  16690. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16691. camera = xr.getCamera(); // use XR camera for rendering
  16692. }
  16693. //
  16694. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16695. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16696. currentRenderState.init();
  16697. renderStateStack.push( currentRenderState );
  16698. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16699. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16700. _localClippingEnabled = this.localClippingEnabled;
  16701. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16702. currentRenderList = renderLists.get( scene, renderListStack.length );
  16703. currentRenderList.init();
  16704. renderListStack.push( currentRenderList );
  16705. projectObject( scene, camera, 0, _this.sortObjects );
  16706. currentRenderList.finish();
  16707. if ( _this.sortObjects === true ) {
  16708. currentRenderList.sort( _opaqueSort, _transparentSort );
  16709. }
  16710. //
  16711. if ( _clippingEnabled === true ) clipping.beginShadows();
  16712. const shadowsArray = currentRenderState.state.shadowsArray;
  16713. shadowMap.render( shadowsArray, scene, camera );
  16714. if ( _clippingEnabled === true ) clipping.endShadows();
  16715. //
  16716. if ( this.info.autoReset === true ) this.info.reset();
  16717. //
  16718. background.render( currentRenderList, scene );
  16719. // render scene
  16720. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16721. if ( camera.isArrayCamera ) {
  16722. const cameras = camera.cameras;
  16723. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16724. const camera2 = cameras[ i ];
  16725. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16726. }
  16727. } else {
  16728. renderScene( currentRenderList, scene, camera );
  16729. }
  16730. //
  16731. if ( _currentRenderTarget !== null ) {
  16732. // resolve multisample renderbuffers to a single-sample texture if necessary
  16733. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16734. // Generate mipmap if we're using any kind of mipmap filtering
  16735. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16736. }
  16737. //
  16738. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16739. // _gl.finish();
  16740. bindingStates.resetDefaultState();
  16741. _currentMaterialId = - 1;
  16742. _currentCamera = null;
  16743. renderStateStack.pop();
  16744. if ( renderStateStack.length > 0 ) {
  16745. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16746. } else {
  16747. currentRenderState = null;
  16748. }
  16749. renderListStack.pop();
  16750. if ( renderListStack.length > 0 ) {
  16751. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16752. } else {
  16753. currentRenderList = null;
  16754. }
  16755. };
  16756. function projectObject( object, camera, groupOrder, sortObjects ) {
  16757. if ( object.visible === false ) return;
  16758. const visible = object.layers.test( camera.layers );
  16759. if ( visible ) {
  16760. if ( object.isGroup ) {
  16761. groupOrder = object.renderOrder;
  16762. } else if ( object.isLOD ) {
  16763. if ( object.autoUpdate === true ) object.update( camera );
  16764. } else if ( object.isLight ) {
  16765. currentRenderState.pushLight( object );
  16766. if ( object.castShadow ) {
  16767. currentRenderState.pushShadow( object );
  16768. }
  16769. } else if ( object.isSprite ) {
  16770. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16771. if ( sortObjects ) {
  16772. _vector3.setFromMatrixPosition( object.matrixWorld )
  16773. .applyMatrix4( _projScreenMatrix );
  16774. }
  16775. const geometry = objects.update( object );
  16776. const material = object.material;
  16777. if ( material.visible ) {
  16778. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16779. }
  16780. }
  16781. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16782. if ( object.isSkinnedMesh ) {
  16783. // update skeleton only once in a frame
  16784. if ( object.skeleton.frame !== info.render.frame ) {
  16785. object.skeleton.update();
  16786. object.skeleton.frame = info.render.frame;
  16787. }
  16788. }
  16789. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16790. if ( sortObjects ) {
  16791. _vector3.setFromMatrixPosition( object.matrixWorld )
  16792. .applyMatrix4( _projScreenMatrix );
  16793. }
  16794. const geometry = objects.update( object );
  16795. const material = object.material;
  16796. if ( Array.isArray( material ) ) {
  16797. const groups = geometry.groups;
  16798. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16799. const group = groups[ i ];
  16800. const groupMaterial = material[ group.materialIndex ];
  16801. if ( groupMaterial && groupMaterial.visible ) {
  16802. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16803. }
  16804. }
  16805. } else if ( material.visible ) {
  16806. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16807. }
  16808. }
  16809. }
  16810. }
  16811. const children = object.children;
  16812. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16813. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16814. }
  16815. }
  16816. function renderScene( currentRenderList, scene, camera, viewport ) {
  16817. const opaqueObjects = currentRenderList.opaque;
  16818. const transmissiveObjects = currentRenderList.transmissive;
  16819. const transparentObjects = currentRenderList.transparent;
  16820. currentRenderState.setupLightsView( camera );
  16821. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16822. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16823. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16824. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16825. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16826. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16827. state.buffers.depth.setTest( true );
  16828. state.buffers.depth.setMask( true );
  16829. state.buffers.color.setMask( true );
  16830. state.setPolygonOffset( false );
  16831. }
  16832. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16833. const isWebGL2 = capabilities.isWebGL2;
  16834. if ( _transmissionRenderTarget === null ) {
  16835. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16836. generateMipmaps: true,
  16837. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16838. minFilter: LinearMipmapLinearFilter,
  16839. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16840. } );
  16841. }
  16842. _this.getDrawingBufferSize( _vector2 );
  16843. if ( isWebGL2 ) {
  16844. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16845. } else {
  16846. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16847. }
  16848. //
  16849. const currentRenderTarget = _this.getRenderTarget();
  16850. _this.setRenderTarget( _transmissionRenderTarget );
  16851. _this.clear();
  16852. // Turn off the features which can affect the frag color for opaque objects pass.
  16853. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16854. const currentToneMapping = _this.toneMapping;
  16855. _this.toneMapping = NoToneMapping;
  16856. renderObjects( opaqueObjects, scene, camera );
  16857. _this.toneMapping = currentToneMapping;
  16858. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16859. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16860. _this.setRenderTarget( currentRenderTarget );
  16861. }
  16862. function renderObjects( renderList, scene, camera ) {
  16863. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16864. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16865. const renderItem = renderList[ i ];
  16866. const object = renderItem.object;
  16867. const geometry = renderItem.geometry;
  16868. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16869. const group = renderItem.group;
  16870. if ( object.layers.test( camera.layers ) ) {
  16871. renderObject( object, scene, camera, geometry, material, group );
  16872. }
  16873. }
  16874. }
  16875. function renderObject( object, scene, camera, geometry, material, group ) {
  16876. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16877. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16878. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16879. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16880. if ( material.transparent === true && material.side === DoubleSide ) {
  16881. material.side = BackSide;
  16882. material.needsUpdate = true;
  16883. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16884. material.side = FrontSide;
  16885. material.needsUpdate = true;
  16886. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16887. material.side = DoubleSide;
  16888. } else {
  16889. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16890. }
  16891. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16892. }
  16893. function getProgram( material, scene, object ) {
  16894. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16895. const materialProperties = properties.get( material );
  16896. const lights = currentRenderState.state.lights;
  16897. const shadowsArray = currentRenderState.state.shadowsArray;
  16898. const lightsStateVersion = lights.state.version;
  16899. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16900. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16901. let programs = materialProperties.programs;
  16902. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16903. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16904. materialProperties.fog = scene.fog;
  16905. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16906. if ( programs === undefined ) {
  16907. // new material
  16908. material.addEventListener( 'dispose', onMaterialDispose );
  16909. programs = new Map();
  16910. materialProperties.programs = programs;
  16911. }
  16912. let program = programs.get( programCacheKey );
  16913. if ( program !== undefined ) {
  16914. // early out if program and light state is identical
  16915. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16916. updateCommonMaterialProperties( material, parameters );
  16917. return program;
  16918. }
  16919. } else {
  16920. parameters.uniforms = programCache.getUniforms( material );
  16921. material.onBuild( object, parameters, _this );
  16922. material.onBeforeCompile( parameters, _this );
  16923. program = programCache.acquireProgram( parameters, programCacheKey );
  16924. programs.set( programCacheKey, program );
  16925. materialProperties.uniforms = parameters.uniforms;
  16926. }
  16927. const uniforms = materialProperties.uniforms;
  16928. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16929. uniforms.clippingPlanes = clipping.uniform;
  16930. }
  16931. updateCommonMaterialProperties( material, parameters );
  16932. // store the light setup it was created for
  16933. materialProperties.needsLights = materialNeedsLights( material );
  16934. materialProperties.lightsStateVersion = lightsStateVersion;
  16935. if ( materialProperties.needsLights ) {
  16936. // wire up the material to this renderer's lighting state
  16937. uniforms.ambientLightColor.value = lights.state.ambient;
  16938. uniforms.lightProbe.value = lights.state.probe;
  16939. uniforms.directionalLights.value = lights.state.directional;
  16940. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16941. uniforms.spotLights.value = lights.state.spot;
  16942. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16943. uniforms.rectAreaLights.value = lights.state.rectArea;
  16944. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16945. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16946. uniforms.pointLights.value = lights.state.point;
  16947. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16948. uniforms.hemisphereLights.value = lights.state.hemi;
  16949. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16950. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16951. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16952. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16953. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16954. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16955. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16956. // TODO (abelnation): add area lights shadow info to uniforms
  16957. }
  16958. const progUniforms = program.getUniforms();
  16959. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16960. materialProperties.currentProgram = program;
  16961. materialProperties.uniformsList = uniformsList;
  16962. return program;
  16963. }
  16964. function updateCommonMaterialProperties( material, parameters ) {
  16965. const materialProperties = properties.get( material );
  16966. materialProperties.outputEncoding = parameters.outputEncoding;
  16967. materialProperties.instancing = parameters.instancing;
  16968. materialProperties.skinning = parameters.skinning;
  16969. materialProperties.morphTargets = parameters.morphTargets;
  16970. materialProperties.morphNormals = parameters.morphNormals;
  16971. materialProperties.morphColors = parameters.morphColors;
  16972. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16973. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16974. materialProperties.numIntersection = parameters.numClipIntersection;
  16975. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16976. materialProperties.vertexTangents = parameters.vertexTangents;
  16977. materialProperties.toneMapping = parameters.toneMapping;
  16978. }
  16979. function setProgram( camera, scene, geometry, material, object ) {
  16980. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16981. textures.resetTextureUnits();
  16982. const fog = scene.fog;
  16983. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16984. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16985. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16986. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16987. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16988. const morphTargets = !! geometry.morphAttributes.position;
  16989. const morphNormals = !! geometry.morphAttributes.normal;
  16990. const morphColors = !! geometry.morphAttributes.color;
  16991. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16992. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16993. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16994. const materialProperties = properties.get( material );
  16995. const lights = currentRenderState.state.lights;
  16996. if ( _clippingEnabled === true ) {
  16997. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16998. const useCache =
  16999. camera === _currentCamera &&
  17000. material.id === _currentMaterialId;
  17001. // we might want to call this function with some ClippingGroup
  17002. // object instead of the material, once it becomes feasible
  17003. // (#8465, #8379)
  17004. clipping.setState( material, camera, useCache );
  17005. }
  17006. }
  17007. //
  17008. let needsProgramChange = false;
  17009. if ( material.version === materialProperties.__version ) {
  17010. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17011. needsProgramChange = true;
  17012. } else if ( materialProperties.outputEncoding !== encoding ) {
  17013. needsProgramChange = true;
  17014. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17015. needsProgramChange = true;
  17016. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17017. needsProgramChange = true;
  17018. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17019. needsProgramChange = true;
  17020. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17021. needsProgramChange = true;
  17022. } else if ( materialProperties.envMap !== envMap ) {
  17023. needsProgramChange = true;
  17024. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17025. needsProgramChange = true;
  17026. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17027. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17028. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17029. needsProgramChange = true;
  17030. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17031. needsProgramChange = true;
  17032. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17033. needsProgramChange = true;
  17034. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17035. needsProgramChange = true;
  17036. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17037. needsProgramChange = true;
  17038. } else if ( materialProperties.morphColors !== morphColors ) {
  17039. needsProgramChange = true;
  17040. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17041. needsProgramChange = true;
  17042. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17043. needsProgramChange = true;
  17044. }
  17045. } else {
  17046. needsProgramChange = true;
  17047. materialProperties.__version = material.version;
  17048. }
  17049. //
  17050. let program = materialProperties.currentProgram;
  17051. if ( needsProgramChange === true ) {
  17052. program = getProgram( material, scene, object );
  17053. }
  17054. let refreshProgram = false;
  17055. let refreshMaterial = false;
  17056. let refreshLights = false;
  17057. const p_uniforms = program.getUniforms(),
  17058. m_uniforms = materialProperties.uniforms;
  17059. if ( state.useProgram( program.program ) ) {
  17060. refreshProgram = true;
  17061. refreshMaterial = true;
  17062. refreshLights = true;
  17063. }
  17064. if ( material.id !== _currentMaterialId ) {
  17065. _currentMaterialId = material.id;
  17066. refreshMaterial = true;
  17067. }
  17068. if ( refreshProgram || _currentCamera !== camera ) {
  17069. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17070. if ( capabilities.logarithmicDepthBuffer ) {
  17071. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17072. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17073. }
  17074. if ( _currentCamera !== camera ) {
  17075. _currentCamera = camera;
  17076. // lighting uniforms depend on the camera so enforce an update
  17077. // now, in case this material supports lights - or later, when
  17078. // the next material that does gets activated:
  17079. refreshMaterial = true; // set to true on material change
  17080. refreshLights = true; // remains set until update done
  17081. }
  17082. // load material specific uniforms
  17083. // (shader material also gets them for the sake of genericity)
  17084. if ( material.isShaderMaterial ||
  17085. material.isMeshPhongMaterial ||
  17086. material.isMeshToonMaterial ||
  17087. material.isMeshStandardMaterial ||
  17088. material.envMap ) {
  17089. const uCamPos = p_uniforms.map.cameraPosition;
  17090. if ( uCamPos !== undefined ) {
  17091. uCamPos.setValue( _gl,
  17092. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17093. }
  17094. }
  17095. if ( material.isMeshPhongMaterial ||
  17096. material.isMeshToonMaterial ||
  17097. material.isMeshLambertMaterial ||
  17098. material.isMeshBasicMaterial ||
  17099. material.isMeshStandardMaterial ||
  17100. material.isShaderMaterial ) {
  17101. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17102. }
  17103. if ( material.isMeshPhongMaterial ||
  17104. material.isMeshToonMaterial ||
  17105. material.isMeshLambertMaterial ||
  17106. material.isMeshBasicMaterial ||
  17107. material.isMeshStandardMaterial ||
  17108. material.isShaderMaterial ||
  17109. material.isShadowMaterial ||
  17110. object.isSkinnedMesh ) {
  17111. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17112. }
  17113. }
  17114. // skinning and morph target uniforms must be set even if material didn't change
  17115. // auto-setting of texture unit for bone and morph texture must go before other textures
  17116. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17117. if ( object.isSkinnedMesh ) {
  17118. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17119. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17120. const skeleton = object.skeleton;
  17121. if ( skeleton ) {
  17122. if ( capabilities.floatVertexTextures ) {
  17123. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17124. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17125. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17126. } else {
  17127. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17128. }
  17129. }
  17130. }
  17131. const morphAttributes = geometry.morphAttributes;
  17132. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17133. morphtargets.update( object, geometry, material, program );
  17134. }
  17135. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17136. materialProperties.receiveShadow = object.receiveShadow;
  17137. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17138. }
  17139. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17140. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17141. m_uniforms.envMap.value = envMap;
  17142. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17143. }
  17144. if ( refreshMaterial ) {
  17145. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17146. if ( materialProperties.needsLights ) {
  17147. // the current material requires lighting info
  17148. // note: all lighting uniforms are always set correctly
  17149. // they simply reference the renderer's state for their
  17150. // values
  17151. //
  17152. // use the current material's .needsUpdate flags to set
  17153. // the GL state when required
  17154. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17155. }
  17156. // refresh uniforms common to several materials
  17157. if ( fog && material.fog === true ) {
  17158. materials.refreshFogUniforms( m_uniforms, fog );
  17159. }
  17160. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17161. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17162. }
  17163. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17164. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17165. material.uniformsNeedUpdate = false;
  17166. }
  17167. if ( material.isSpriteMaterial ) {
  17168. p_uniforms.setValue( _gl, 'center', object.center );
  17169. }
  17170. // common matrices
  17171. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17172. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17173. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17174. // UBOs
  17175. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17176. const groups = material.uniformsGroups;
  17177. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17178. if ( capabilities.isWebGL2 ) {
  17179. const group = groups[ i ];
  17180. uniformsGroups.update( group, program );
  17181. uniformsGroups.bind( group, program );
  17182. } else {
  17183. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17184. }
  17185. }
  17186. }
  17187. return program;
  17188. }
  17189. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17190. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17191. uniforms.ambientLightColor.needsUpdate = value;
  17192. uniforms.lightProbe.needsUpdate = value;
  17193. uniforms.directionalLights.needsUpdate = value;
  17194. uniforms.directionalLightShadows.needsUpdate = value;
  17195. uniforms.pointLights.needsUpdate = value;
  17196. uniforms.pointLightShadows.needsUpdate = value;
  17197. uniforms.spotLights.needsUpdate = value;
  17198. uniforms.spotLightShadows.needsUpdate = value;
  17199. uniforms.rectAreaLights.needsUpdate = value;
  17200. uniforms.hemisphereLights.needsUpdate = value;
  17201. }
  17202. function materialNeedsLights( material ) {
  17203. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17204. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17205. ( material.isShaderMaterial && material.lights === true );
  17206. }
  17207. this.getActiveCubeFace = function () {
  17208. return _currentActiveCubeFace;
  17209. };
  17210. this.getActiveMipmapLevel = function () {
  17211. return _currentActiveMipmapLevel;
  17212. };
  17213. this.getRenderTarget = function () {
  17214. return _currentRenderTarget;
  17215. };
  17216. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17217. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17218. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17219. const renderTargetProperties = properties.get( renderTarget );
  17220. renderTargetProperties.__hasExternalTextures = true;
  17221. if ( renderTargetProperties.__hasExternalTextures ) {
  17222. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17223. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17224. // The multisample_render_to_texture extension doesn't work properly if there
  17225. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17226. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17227. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17228. renderTargetProperties.__useRenderToTexture = false;
  17229. }
  17230. }
  17231. }
  17232. };
  17233. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17234. const renderTargetProperties = properties.get( renderTarget );
  17235. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17236. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17237. };
  17238. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17239. _currentRenderTarget = renderTarget;
  17240. _currentActiveCubeFace = activeCubeFace;
  17241. _currentActiveMipmapLevel = activeMipmapLevel;
  17242. let useDefaultFramebuffer = true;
  17243. if ( renderTarget ) {
  17244. const renderTargetProperties = properties.get( renderTarget );
  17245. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17246. // We need to make sure to rebind the framebuffer.
  17247. state.bindFramebuffer( 36160, null );
  17248. useDefaultFramebuffer = false;
  17249. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17250. textures.setupRenderTarget( renderTarget );
  17251. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17252. // Color and depth texture must be rebound in order for the swapchain to update.
  17253. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17254. }
  17255. }
  17256. let framebuffer = null;
  17257. let isCube = false;
  17258. let isRenderTarget3D = false;
  17259. if ( renderTarget ) {
  17260. const texture = renderTarget.texture;
  17261. if ( texture.isData3DTexture || texture.isDataArrayTexture ) {
  17262. isRenderTarget3D = true;
  17263. }
  17264. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17265. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17266. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17267. isCube = true;
  17268. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17269. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17270. } else {
  17271. framebuffer = __webglFramebuffer;
  17272. }
  17273. _currentViewport.copy( renderTarget.viewport );
  17274. _currentScissor.copy( renderTarget.scissor );
  17275. _currentScissorTest = renderTarget.scissorTest;
  17276. } else {
  17277. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17278. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17279. _currentScissorTest = _scissorTest;
  17280. }
  17281. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17282. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17283. state.drawBuffers( renderTarget, framebuffer );
  17284. }
  17285. state.viewport( _currentViewport );
  17286. state.scissor( _currentScissor );
  17287. state.setScissorTest( _currentScissorTest );
  17288. if ( isCube ) {
  17289. const textureProperties = properties.get( renderTarget.texture );
  17290. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17291. } else if ( isRenderTarget3D ) {
  17292. const textureProperties = properties.get( renderTarget.texture );
  17293. const layer = activeCubeFace || 0;
  17294. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17295. }
  17296. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17297. };
  17298. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17299. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17300. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17301. return;
  17302. }
  17303. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17304. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17305. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17306. }
  17307. if ( framebuffer ) {
  17308. state.bindFramebuffer( 36160, framebuffer );
  17309. try {
  17310. const texture = renderTarget.texture;
  17311. const textureFormat = texture.format;
  17312. const textureType = texture.type;
  17313. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17314. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17315. return;
  17316. }
  17317. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17318. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17319. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17320. ! halfFloatSupportedByExt ) {
  17321. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17322. return;
  17323. }
  17324. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17325. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17326. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17327. }
  17328. } finally {
  17329. // restore framebuffer of current render target if necessary
  17330. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17331. state.bindFramebuffer( 36160, framebuffer );
  17332. }
  17333. }
  17334. };
  17335. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17336. const levelScale = Math.pow( 2, - level );
  17337. const width = Math.floor( texture.image.width * levelScale );
  17338. const height = Math.floor( texture.image.height * levelScale );
  17339. textures.setTexture2D( texture, 0 );
  17340. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17341. state.unbindTexture();
  17342. };
  17343. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17344. const width = srcTexture.image.width;
  17345. const height = srcTexture.image.height;
  17346. const glFormat = utils.convert( dstTexture.format );
  17347. const glType = utils.convert( dstTexture.type );
  17348. textures.setTexture2D( dstTexture, 0 );
  17349. // As another texture upload may have changed pixelStorei
  17350. // parameters, make sure they are correct for the dstTexture
  17351. _gl.pixelStorei( 37440, dstTexture.flipY );
  17352. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17353. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17354. if ( srcTexture.isDataTexture ) {
  17355. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17356. } else {
  17357. if ( srcTexture.isCompressedTexture ) {
  17358. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17359. } else {
  17360. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17361. }
  17362. }
  17363. // Generate mipmaps only when copying level 0
  17364. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17365. state.unbindTexture();
  17366. };
  17367. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17368. if ( _this.isWebGL1Renderer ) {
  17369. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17370. return;
  17371. }
  17372. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17373. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17374. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17375. const glFormat = utils.convert( dstTexture.format );
  17376. const glType = utils.convert( dstTexture.type );
  17377. let glTarget;
  17378. if ( dstTexture.isData3DTexture ) {
  17379. textures.setTexture3D( dstTexture, 0 );
  17380. glTarget = 32879;
  17381. } else if ( dstTexture.isDataArrayTexture ) {
  17382. textures.setTexture2DArray( dstTexture, 0 );
  17383. glTarget = 35866;
  17384. } else {
  17385. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17386. return;
  17387. }
  17388. _gl.pixelStorei( 37440, dstTexture.flipY );
  17389. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17390. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17391. const unpackRowLen = _gl.getParameter( 3314 );
  17392. const unpackImageHeight = _gl.getParameter( 32878 );
  17393. const unpackSkipPixels = _gl.getParameter( 3316 );
  17394. const unpackSkipRows = _gl.getParameter( 3315 );
  17395. const unpackSkipImages = _gl.getParameter( 32877 );
  17396. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17397. _gl.pixelStorei( 3314, image.width );
  17398. _gl.pixelStorei( 32878, image.height );
  17399. _gl.pixelStorei( 3316, sourceBox.min.x );
  17400. _gl.pixelStorei( 3315, sourceBox.min.y );
  17401. _gl.pixelStorei( 32877, sourceBox.min.z );
  17402. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17403. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17404. } else {
  17405. if ( srcTexture.isCompressedTexture ) {
  17406. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17407. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17408. } else {
  17409. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17410. }
  17411. }
  17412. _gl.pixelStorei( 3314, unpackRowLen );
  17413. _gl.pixelStorei( 32878, unpackImageHeight );
  17414. _gl.pixelStorei( 3316, unpackSkipPixels );
  17415. _gl.pixelStorei( 3315, unpackSkipRows );
  17416. _gl.pixelStorei( 32877, unpackSkipImages );
  17417. // Generate mipmaps only when copying level 0
  17418. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17419. state.unbindTexture();
  17420. };
  17421. this.initTexture = function ( texture ) {
  17422. if ( texture.isCubeTexture ) {
  17423. textures.setTextureCube( texture, 0 );
  17424. } else if ( texture.isData3DTexture ) {
  17425. textures.setTexture3D( texture, 0 );
  17426. } else if ( texture.isDataArrayTexture ) {
  17427. textures.setTexture2DArray( texture, 0 );
  17428. } else {
  17429. textures.setTexture2D( texture, 0 );
  17430. }
  17431. state.unbindTexture();
  17432. };
  17433. this.resetState = function () {
  17434. _currentActiveCubeFace = 0;
  17435. _currentActiveMipmapLevel = 0;
  17436. _currentRenderTarget = null;
  17437. state.reset();
  17438. bindingStates.reset();
  17439. };
  17440. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17441. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17442. }
  17443. }
  17444. class WebGL1Renderer extends WebGLRenderer {}
  17445. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17446. class FogExp2 {
  17447. constructor( color, density = 0.00025 ) {
  17448. this.isFogExp2 = true;
  17449. this.name = '';
  17450. this.color = new Color( color );
  17451. this.density = density;
  17452. }
  17453. clone() {
  17454. return new FogExp2( this.color, this.density );
  17455. }
  17456. toJSON( /* meta */ ) {
  17457. return {
  17458. type: 'FogExp2',
  17459. color: this.color.getHex(),
  17460. density: this.density
  17461. };
  17462. }
  17463. }
  17464. class Fog {
  17465. constructor( color, near = 1, far = 1000 ) {
  17466. this.isFog = true;
  17467. this.name = '';
  17468. this.color = new Color( color );
  17469. this.near = near;
  17470. this.far = far;
  17471. }
  17472. clone() {
  17473. return new Fog( this.color, this.near, this.far );
  17474. }
  17475. toJSON( /* meta */ ) {
  17476. return {
  17477. type: 'Fog',
  17478. color: this.color.getHex(),
  17479. near: this.near,
  17480. far: this.far
  17481. };
  17482. }
  17483. }
  17484. class Scene extends Object3D {
  17485. constructor() {
  17486. super();
  17487. this.isScene = true;
  17488. this.type = 'Scene';
  17489. this.background = null;
  17490. this.environment = null;
  17491. this.fog = null;
  17492. this.overrideMaterial = null;
  17493. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17494. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17495. }
  17496. }
  17497. copy( source, recursive ) {
  17498. super.copy( source, recursive );
  17499. if ( source.background !== null ) this.background = source.background.clone();
  17500. if ( source.environment !== null ) this.environment = source.environment.clone();
  17501. if ( source.fog !== null ) this.fog = source.fog.clone();
  17502. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17503. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17504. return this;
  17505. }
  17506. toJSON( meta ) {
  17507. const data = super.toJSON( meta );
  17508. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17509. return data;
  17510. }
  17511. // Deprecated
  17512. get autoUpdate() {
  17513. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17514. return this.matrixWorldAutoUpdate;
  17515. }
  17516. set autoUpdate( value ) {
  17517. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17518. this.matrixWorldAutoUpdate = value;
  17519. }
  17520. }
  17521. class InterleavedBuffer {
  17522. constructor( array, stride ) {
  17523. this.isInterleavedBuffer = true;
  17524. this.array = array;
  17525. this.stride = stride;
  17526. this.count = array !== undefined ? array.length / stride : 0;
  17527. this.usage = StaticDrawUsage;
  17528. this.updateRange = { offset: 0, count: - 1 };
  17529. this.version = 0;
  17530. this.uuid = generateUUID();
  17531. }
  17532. onUploadCallback() {}
  17533. set needsUpdate( value ) {
  17534. if ( value === true ) this.version ++;
  17535. }
  17536. setUsage( value ) {
  17537. this.usage = value;
  17538. return this;
  17539. }
  17540. copy( source ) {
  17541. this.array = new source.array.constructor( source.array );
  17542. this.count = source.count;
  17543. this.stride = source.stride;
  17544. this.usage = source.usage;
  17545. return this;
  17546. }
  17547. copyAt( index1, attribute, index2 ) {
  17548. index1 *= this.stride;
  17549. index2 *= attribute.stride;
  17550. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17551. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17552. }
  17553. return this;
  17554. }
  17555. set( value, offset = 0 ) {
  17556. this.array.set( value, offset );
  17557. return this;
  17558. }
  17559. clone( data ) {
  17560. if ( data.arrayBuffers === undefined ) {
  17561. data.arrayBuffers = {};
  17562. }
  17563. if ( this.array.buffer._uuid === undefined ) {
  17564. this.array.buffer._uuid = generateUUID();
  17565. }
  17566. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17567. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17568. }
  17569. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17570. const ib = new this.constructor( array, this.stride );
  17571. ib.setUsage( this.usage );
  17572. return ib;
  17573. }
  17574. onUpload( callback ) {
  17575. this.onUploadCallback = callback;
  17576. return this;
  17577. }
  17578. toJSON( data ) {
  17579. if ( data.arrayBuffers === undefined ) {
  17580. data.arrayBuffers = {};
  17581. }
  17582. // generate UUID for array buffer if necessary
  17583. if ( this.array.buffer._uuid === undefined ) {
  17584. this.array.buffer._uuid = generateUUID();
  17585. }
  17586. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17587. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17588. }
  17589. //
  17590. return {
  17591. uuid: this.uuid,
  17592. buffer: this.array.buffer._uuid,
  17593. type: this.array.constructor.name,
  17594. stride: this.stride
  17595. };
  17596. }
  17597. }
  17598. const _vector$6 = /*@__PURE__*/ new Vector3();
  17599. class InterleavedBufferAttribute {
  17600. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17601. this.isInterleavedBufferAttribute = true;
  17602. this.name = '';
  17603. this.data = interleavedBuffer;
  17604. this.itemSize = itemSize;
  17605. this.offset = offset;
  17606. this.normalized = normalized === true;
  17607. }
  17608. get count() {
  17609. return this.data.count;
  17610. }
  17611. get array() {
  17612. return this.data.array;
  17613. }
  17614. set needsUpdate( value ) {
  17615. this.data.needsUpdate = value;
  17616. }
  17617. applyMatrix4( m ) {
  17618. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17619. _vector$6.fromBufferAttribute( this, i );
  17620. _vector$6.applyMatrix4( m );
  17621. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17622. }
  17623. return this;
  17624. }
  17625. applyNormalMatrix( m ) {
  17626. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17627. _vector$6.fromBufferAttribute( this, i );
  17628. _vector$6.applyNormalMatrix( m );
  17629. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17630. }
  17631. return this;
  17632. }
  17633. transformDirection( m ) {
  17634. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17635. _vector$6.fromBufferAttribute( this, i );
  17636. _vector$6.transformDirection( m );
  17637. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17638. }
  17639. return this;
  17640. }
  17641. setX( index, x ) {
  17642. if ( this.normalized ) x = normalize( x, this.array );
  17643. this.data.array[ index * this.data.stride + this.offset ] = x;
  17644. return this;
  17645. }
  17646. setY( index, y ) {
  17647. if ( this.normalized ) y = normalize( y, this.array );
  17648. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17649. return this;
  17650. }
  17651. setZ( index, z ) {
  17652. if ( this.normalized ) z = normalize( z, this.array );
  17653. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17654. return this;
  17655. }
  17656. setW( index, w ) {
  17657. if ( this.normalized ) w = normalize( w, this.array );
  17658. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17659. return this;
  17660. }
  17661. getX( index ) {
  17662. let x = this.data.array[ index * this.data.stride + this.offset ];
  17663. if ( this.normalized ) x = denormalize( x, this.array );
  17664. return x;
  17665. }
  17666. getY( index ) {
  17667. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17668. if ( this.normalized ) y = denormalize( y, this.array );
  17669. return y;
  17670. }
  17671. getZ( index ) {
  17672. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17673. if ( this.normalized ) z = denormalize( z, this.array );
  17674. return z;
  17675. }
  17676. getW( index ) {
  17677. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17678. if ( this.normalized ) w = denormalize( w, this.array );
  17679. return w;
  17680. }
  17681. setXY( index, x, y ) {
  17682. index = index * this.data.stride + this.offset;
  17683. if ( this.normalized ) {
  17684. x = normalize( x, this.array );
  17685. y = normalize( y, this.array );
  17686. }
  17687. this.data.array[ index + 0 ] = x;
  17688. this.data.array[ index + 1 ] = y;
  17689. return this;
  17690. }
  17691. setXYZ( index, x, y, z ) {
  17692. index = index * this.data.stride + this.offset;
  17693. if ( this.normalized ) {
  17694. x = normalize( x, this.array );
  17695. y = normalize( y, this.array );
  17696. z = normalize( z, this.array );
  17697. }
  17698. this.data.array[ index + 0 ] = x;
  17699. this.data.array[ index + 1 ] = y;
  17700. this.data.array[ index + 2 ] = z;
  17701. return this;
  17702. }
  17703. setXYZW( index, x, y, z, w ) {
  17704. index = index * this.data.stride + this.offset;
  17705. if ( this.normalized ) {
  17706. x = normalize( x, this.array );
  17707. y = normalize( y, this.array );
  17708. z = normalize( z, this.array );
  17709. w = normalize( w, this.array );
  17710. }
  17711. this.data.array[ index + 0 ] = x;
  17712. this.data.array[ index + 1 ] = y;
  17713. this.data.array[ index + 2 ] = z;
  17714. this.data.array[ index + 3 ] = w;
  17715. return this;
  17716. }
  17717. clone( data ) {
  17718. if ( data === undefined ) {
  17719. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' );
  17720. const array = [];
  17721. for ( let i = 0; i < this.count; i ++ ) {
  17722. const index = i * this.data.stride + this.offset;
  17723. for ( let j = 0; j < this.itemSize; j ++ ) {
  17724. array.push( this.data.array[ index + j ] );
  17725. }
  17726. }
  17727. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17728. } else {
  17729. if ( data.interleavedBuffers === undefined ) {
  17730. data.interleavedBuffers = {};
  17731. }
  17732. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17733. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17734. }
  17735. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17736. }
  17737. }
  17738. toJSON( data ) {
  17739. if ( data === undefined ) {
  17740. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' );
  17741. const array = [];
  17742. for ( let i = 0; i < this.count; i ++ ) {
  17743. const index = i * this.data.stride + this.offset;
  17744. for ( let j = 0; j < this.itemSize; j ++ ) {
  17745. array.push( this.data.array[ index + j ] );
  17746. }
  17747. }
  17748. // deinterleave data and save it as an ordinary buffer attribute for now
  17749. return {
  17750. itemSize: this.itemSize,
  17751. type: this.array.constructor.name,
  17752. array: array,
  17753. normalized: this.normalized
  17754. };
  17755. } else {
  17756. // save as true interleaved attribtue
  17757. if ( data.interleavedBuffers === undefined ) {
  17758. data.interleavedBuffers = {};
  17759. }
  17760. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17761. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17762. }
  17763. return {
  17764. isInterleavedBufferAttribute: true,
  17765. itemSize: this.itemSize,
  17766. data: this.data.uuid,
  17767. offset: this.offset,
  17768. normalized: this.normalized
  17769. };
  17770. }
  17771. }
  17772. }
  17773. class SpriteMaterial extends Material {
  17774. constructor( parameters ) {
  17775. super();
  17776. this.isSpriteMaterial = true;
  17777. this.type = 'SpriteMaterial';
  17778. this.color = new Color( 0xffffff );
  17779. this.map = null;
  17780. this.alphaMap = null;
  17781. this.rotation = 0;
  17782. this.sizeAttenuation = true;
  17783. this.transparent = true;
  17784. this.fog = true;
  17785. this.setValues( parameters );
  17786. }
  17787. copy( source ) {
  17788. super.copy( source );
  17789. this.color.copy( source.color );
  17790. this.map = source.map;
  17791. this.alphaMap = source.alphaMap;
  17792. this.rotation = source.rotation;
  17793. this.sizeAttenuation = source.sizeAttenuation;
  17794. this.fog = source.fog;
  17795. return this;
  17796. }
  17797. }
  17798. let _geometry;
  17799. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17800. const _worldScale = /*@__PURE__*/ new Vector3();
  17801. const _mvPosition = /*@__PURE__*/ new Vector3();
  17802. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17803. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17804. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17805. const _vA = /*@__PURE__*/ new Vector3();
  17806. const _vB = /*@__PURE__*/ new Vector3();
  17807. const _vC = /*@__PURE__*/ new Vector3();
  17808. const _uvA = /*@__PURE__*/ new Vector2();
  17809. const _uvB = /*@__PURE__*/ new Vector2();
  17810. const _uvC = /*@__PURE__*/ new Vector2();
  17811. class Sprite extends Object3D {
  17812. constructor( material ) {
  17813. super();
  17814. this.isSprite = true;
  17815. this.type = 'Sprite';
  17816. if ( _geometry === undefined ) {
  17817. _geometry = new BufferGeometry();
  17818. const float32Array = new Float32Array( [
  17819. - 0.5, - 0.5, 0, 0, 0,
  17820. 0.5, - 0.5, 0, 1, 0,
  17821. 0.5, 0.5, 0, 1, 1,
  17822. - 0.5, 0.5, 0, 0, 1
  17823. ] );
  17824. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17825. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17826. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17827. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17828. }
  17829. this.geometry = _geometry;
  17830. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17831. this.center = new Vector2( 0.5, 0.5 );
  17832. }
  17833. raycast( raycaster, intersects ) {
  17834. if ( raycaster.camera === null ) {
  17835. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17836. }
  17837. _worldScale.setFromMatrixScale( this.matrixWorld );
  17838. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17839. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17840. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17841. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17842. _worldScale.multiplyScalar( - _mvPosition.z );
  17843. }
  17844. const rotation = this.material.rotation;
  17845. let sin, cos;
  17846. if ( rotation !== 0 ) {
  17847. cos = Math.cos( rotation );
  17848. sin = Math.sin( rotation );
  17849. }
  17850. const center = this.center;
  17851. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17852. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17853. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17854. _uvA.set( 0, 0 );
  17855. _uvB.set( 1, 0 );
  17856. _uvC.set( 1, 1 );
  17857. // check first triangle
  17858. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17859. if ( intersect === null ) {
  17860. // check second triangle
  17861. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17862. _uvB.set( 0, 1 );
  17863. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17864. if ( intersect === null ) {
  17865. return;
  17866. }
  17867. }
  17868. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17869. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17870. intersects.push( {
  17871. distance: distance,
  17872. point: _intersectPoint.clone(),
  17873. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17874. face: null,
  17875. object: this
  17876. } );
  17877. }
  17878. copy( source, recursive ) {
  17879. super.copy( source, recursive );
  17880. if ( source.center !== undefined ) this.center.copy( source.center );
  17881. this.material = source.material;
  17882. return this;
  17883. }
  17884. }
  17885. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17886. // compute position in camera space
  17887. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17888. // to check if rotation is not zero
  17889. if ( sin !== undefined ) {
  17890. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17891. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17892. } else {
  17893. _rotatedPosition.copy( _alignedPosition );
  17894. }
  17895. vertexPosition.copy( mvPosition );
  17896. vertexPosition.x += _rotatedPosition.x;
  17897. vertexPosition.y += _rotatedPosition.y;
  17898. // transform to world space
  17899. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17900. }
  17901. const _v1$2 = /*@__PURE__*/ new Vector3();
  17902. const _v2$1 = /*@__PURE__*/ new Vector3();
  17903. class LOD extends Object3D {
  17904. constructor() {
  17905. super();
  17906. this._currentLevel = 0;
  17907. this.type = 'LOD';
  17908. Object.defineProperties( this, {
  17909. levels: {
  17910. enumerable: true,
  17911. value: []
  17912. },
  17913. isLOD: {
  17914. value: true,
  17915. }
  17916. } );
  17917. this.autoUpdate = true;
  17918. }
  17919. copy( source ) {
  17920. super.copy( source, false );
  17921. const levels = source.levels;
  17922. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17923. const level = levels[ i ];
  17924. this.addLevel( level.object.clone(), level.distance );
  17925. }
  17926. this.autoUpdate = source.autoUpdate;
  17927. return this;
  17928. }
  17929. addLevel( object, distance = 0 ) {
  17930. distance = Math.abs( distance );
  17931. const levels = this.levels;
  17932. let l;
  17933. for ( l = 0; l < levels.length; l ++ ) {
  17934. if ( distance < levels[ l ].distance ) {
  17935. break;
  17936. }
  17937. }
  17938. levels.splice( l, 0, { distance: distance, object: object } );
  17939. this.add( object );
  17940. return this;
  17941. }
  17942. getCurrentLevel() {
  17943. return this._currentLevel;
  17944. }
  17945. getObjectForDistance( distance ) {
  17946. const levels = this.levels;
  17947. if ( levels.length > 0 ) {
  17948. let i, l;
  17949. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17950. if ( distance < levels[ i ].distance ) {
  17951. break;
  17952. }
  17953. }
  17954. return levels[ i - 1 ].object;
  17955. }
  17956. return null;
  17957. }
  17958. raycast( raycaster, intersects ) {
  17959. const levels = this.levels;
  17960. if ( levels.length > 0 ) {
  17961. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17962. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17963. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17964. }
  17965. }
  17966. update( camera ) {
  17967. const levels = this.levels;
  17968. if ( levels.length > 1 ) {
  17969. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17970. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17971. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17972. levels[ 0 ].object.visible = true;
  17973. let i, l;
  17974. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17975. if ( distance >= levels[ i ].distance ) {
  17976. levels[ i - 1 ].object.visible = false;
  17977. levels[ i ].object.visible = true;
  17978. } else {
  17979. break;
  17980. }
  17981. }
  17982. this._currentLevel = i - 1;
  17983. for ( ; i < l; i ++ ) {
  17984. levels[ i ].object.visible = false;
  17985. }
  17986. }
  17987. }
  17988. toJSON( meta ) {
  17989. const data = super.toJSON( meta );
  17990. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17991. data.object.levels = [];
  17992. const levels = this.levels;
  17993. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17994. const level = levels[ i ];
  17995. data.object.levels.push( {
  17996. object: level.object.uuid,
  17997. distance: level.distance
  17998. } );
  17999. }
  18000. return data;
  18001. }
  18002. }
  18003. const _basePosition = /*@__PURE__*/ new Vector3();
  18004. const _skinIndex = /*@__PURE__*/ new Vector4();
  18005. const _skinWeight = /*@__PURE__*/ new Vector4();
  18006. const _vector$5 = /*@__PURE__*/ new Vector3();
  18007. const _matrix = /*@__PURE__*/ new Matrix4();
  18008. class SkinnedMesh extends Mesh {
  18009. constructor( geometry, material ) {
  18010. super( geometry, material );
  18011. this.isSkinnedMesh = true;
  18012. this.type = 'SkinnedMesh';
  18013. this.bindMode = 'attached';
  18014. this.bindMatrix = new Matrix4();
  18015. this.bindMatrixInverse = new Matrix4();
  18016. }
  18017. copy( source, recursive ) {
  18018. super.copy( source, recursive );
  18019. this.bindMode = source.bindMode;
  18020. this.bindMatrix.copy( source.bindMatrix );
  18021. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18022. this.skeleton = source.skeleton;
  18023. return this;
  18024. }
  18025. bind( skeleton, bindMatrix ) {
  18026. this.skeleton = skeleton;
  18027. if ( bindMatrix === undefined ) {
  18028. this.updateMatrixWorld( true );
  18029. this.skeleton.calculateInverses();
  18030. bindMatrix = this.matrixWorld;
  18031. }
  18032. this.bindMatrix.copy( bindMatrix );
  18033. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18034. }
  18035. pose() {
  18036. this.skeleton.pose();
  18037. }
  18038. normalizeSkinWeights() {
  18039. const vector = new Vector4();
  18040. const skinWeight = this.geometry.attributes.skinWeight;
  18041. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18042. vector.fromBufferAttribute( skinWeight, i );
  18043. const scale = 1.0 / vector.manhattanLength();
  18044. if ( scale !== Infinity ) {
  18045. vector.multiplyScalar( scale );
  18046. } else {
  18047. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18048. }
  18049. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18050. }
  18051. }
  18052. updateMatrixWorld( force ) {
  18053. super.updateMatrixWorld( force );
  18054. if ( this.bindMode === 'attached' ) {
  18055. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18056. } else if ( this.bindMode === 'detached' ) {
  18057. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18058. } else {
  18059. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18060. }
  18061. }
  18062. boneTransform( index, target ) {
  18063. const skeleton = this.skeleton;
  18064. const geometry = this.geometry;
  18065. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18066. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18067. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18068. target.set( 0, 0, 0 );
  18069. for ( let i = 0; i < 4; i ++ ) {
  18070. const weight = _skinWeight.getComponent( i );
  18071. if ( weight !== 0 ) {
  18072. const boneIndex = _skinIndex.getComponent( i );
  18073. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18074. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18075. }
  18076. }
  18077. return target.applyMatrix4( this.bindMatrixInverse );
  18078. }
  18079. }
  18080. class Bone extends Object3D {
  18081. constructor() {
  18082. super();
  18083. this.isBone = true;
  18084. this.type = 'Bone';
  18085. }
  18086. }
  18087. class DataTexture extends Texture {
  18088. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18089. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18090. this.isDataTexture = true;
  18091. this.image = { data: data, width: width, height: height };
  18092. this.generateMipmaps = false;
  18093. this.flipY = false;
  18094. this.unpackAlignment = 1;
  18095. }
  18096. }
  18097. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18098. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18099. class Skeleton {
  18100. constructor( bones = [], boneInverses = [] ) {
  18101. this.uuid = generateUUID();
  18102. this.bones = bones.slice( 0 );
  18103. this.boneInverses = boneInverses;
  18104. this.boneMatrices = null;
  18105. this.boneTexture = null;
  18106. this.boneTextureSize = 0;
  18107. this.frame = - 1;
  18108. this.init();
  18109. }
  18110. init() {
  18111. const bones = this.bones;
  18112. const boneInverses = this.boneInverses;
  18113. this.boneMatrices = new Float32Array( bones.length * 16 );
  18114. // calculate inverse bone matrices if necessary
  18115. if ( boneInverses.length === 0 ) {
  18116. this.calculateInverses();
  18117. } else {
  18118. // handle special case
  18119. if ( bones.length !== boneInverses.length ) {
  18120. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18121. this.boneInverses = [];
  18122. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18123. this.boneInverses.push( new Matrix4() );
  18124. }
  18125. }
  18126. }
  18127. }
  18128. calculateInverses() {
  18129. this.boneInverses.length = 0;
  18130. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18131. const inverse = new Matrix4();
  18132. if ( this.bones[ i ] ) {
  18133. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18134. }
  18135. this.boneInverses.push( inverse );
  18136. }
  18137. }
  18138. pose() {
  18139. // recover the bind-time world matrices
  18140. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18141. const bone = this.bones[ i ];
  18142. if ( bone ) {
  18143. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18144. }
  18145. }
  18146. // compute the local matrices, positions, rotations and scales
  18147. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18148. const bone = this.bones[ i ];
  18149. if ( bone ) {
  18150. if ( bone.parent && bone.parent.isBone ) {
  18151. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18152. bone.matrix.multiply( bone.matrixWorld );
  18153. } else {
  18154. bone.matrix.copy( bone.matrixWorld );
  18155. }
  18156. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18157. }
  18158. }
  18159. }
  18160. update() {
  18161. const bones = this.bones;
  18162. const boneInverses = this.boneInverses;
  18163. const boneMatrices = this.boneMatrices;
  18164. const boneTexture = this.boneTexture;
  18165. // flatten bone matrices to array
  18166. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18167. // compute the offset between the current and the original transform
  18168. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18169. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18170. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18171. }
  18172. if ( boneTexture !== null ) {
  18173. boneTexture.needsUpdate = true;
  18174. }
  18175. }
  18176. clone() {
  18177. return new Skeleton( this.bones, this.boneInverses );
  18178. }
  18179. computeBoneTexture() {
  18180. // layout (1 matrix = 4 pixels)
  18181. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18182. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18183. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18184. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18185. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18186. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18187. size = ceilPowerOfTwo( size );
  18188. size = Math.max( size, 4 );
  18189. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18190. boneMatrices.set( this.boneMatrices ); // copy current values
  18191. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18192. boneTexture.needsUpdate = true;
  18193. this.boneMatrices = boneMatrices;
  18194. this.boneTexture = boneTexture;
  18195. this.boneTextureSize = size;
  18196. return this;
  18197. }
  18198. getBoneByName( name ) {
  18199. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18200. const bone = this.bones[ i ];
  18201. if ( bone.name === name ) {
  18202. return bone;
  18203. }
  18204. }
  18205. return undefined;
  18206. }
  18207. dispose( ) {
  18208. if ( this.boneTexture !== null ) {
  18209. this.boneTexture.dispose();
  18210. this.boneTexture = null;
  18211. }
  18212. }
  18213. fromJSON( json, bones ) {
  18214. this.uuid = json.uuid;
  18215. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18216. const uuid = json.bones[ i ];
  18217. let bone = bones[ uuid ];
  18218. if ( bone === undefined ) {
  18219. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18220. bone = new Bone();
  18221. }
  18222. this.bones.push( bone );
  18223. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18224. }
  18225. this.init();
  18226. return this;
  18227. }
  18228. toJSON() {
  18229. const data = {
  18230. metadata: {
  18231. version: 4.5,
  18232. type: 'Skeleton',
  18233. generator: 'Skeleton.toJSON'
  18234. },
  18235. bones: [],
  18236. boneInverses: []
  18237. };
  18238. data.uuid = this.uuid;
  18239. const bones = this.bones;
  18240. const boneInverses = this.boneInverses;
  18241. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18242. const bone = bones[ i ];
  18243. data.bones.push( bone.uuid );
  18244. const boneInverse = boneInverses[ i ];
  18245. data.boneInverses.push( boneInverse.toArray() );
  18246. }
  18247. return data;
  18248. }
  18249. }
  18250. class InstancedBufferAttribute extends BufferAttribute {
  18251. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18252. super( array, itemSize, normalized );
  18253. this.isInstancedBufferAttribute = true;
  18254. this.meshPerAttribute = meshPerAttribute;
  18255. }
  18256. copy( source ) {
  18257. super.copy( source );
  18258. this.meshPerAttribute = source.meshPerAttribute;
  18259. return this;
  18260. }
  18261. toJSON() {
  18262. const data = super.toJSON();
  18263. data.meshPerAttribute = this.meshPerAttribute;
  18264. data.isInstancedBufferAttribute = true;
  18265. return data;
  18266. }
  18267. }
  18268. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18269. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18270. const _instanceIntersects = [];
  18271. const _mesh = /*@__PURE__*/ new Mesh();
  18272. class InstancedMesh extends Mesh {
  18273. constructor( geometry, material, count ) {
  18274. super( geometry, material );
  18275. this.isInstancedMesh = true;
  18276. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18277. this.instanceColor = null;
  18278. this.count = count;
  18279. this.frustumCulled = false;
  18280. }
  18281. copy( source, recursive ) {
  18282. super.copy( source, recursive );
  18283. this.instanceMatrix.copy( source.instanceMatrix );
  18284. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18285. this.count = source.count;
  18286. return this;
  18287. }
  18288. getColorAt( index, color ) {
  18289. color.fromArray( this.instanceColor.array, index * 3 );
  18290. }
  18291. getMatrixAt( index, matrix ) {
  18292. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18293. }
  18294. raycast( raycaster, intersects ) {
  18295. const matrixWorld = this.matrixWorld;
  18296. const raycastTimes = this.count;
  18297. _mesh.geometry = this.geometry;
  18298. _mesh.material = this.material;
  18299. if ( _mesh.material === undefined ) return;
  18300. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18301. // calculate the world matrix for each instance
  18302. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18303. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18304. // the mesh represents this single instance
  18305. _mesh.matrixWorld = _instanceWorldMatrix;
  18306. _mesh.raycast( raycaster, _instanceIntersects );
  18307. // process the result of raycast
  18308. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18309. const intersect = _instanceIntersects[ i ];
  18310. intersect.instanceId = instanceId;
  18311. intersect.object = this;
  18312. intersects.push( intersect );
  18313. }
  18314. _instanceIntersects.length = 0;
  18315. }
  18316. }
  18317. setColorAt( index, color ) {
  18318. if ( this.instanceColor === null ) {
  18319. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18320. }
  18321. color.toArray( this.instanceColor.array, index * 3 );
  18322. }
  18323. setMatrixAt( index, matrix ) {
  18324. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18325. }
  18326. updateMorphTargets() {
  18327. }
  18328. dispose() {
  18329. this.dispatchEvent( { type: 'dispose' } );
  18330. }
  18331. }
  18332. class LineBasicMaterial extends Material {
  18333. constructor( parameters ) {
  18334. super();
  18335. this.isLineBasicMaterial = true;
  18336. this.type = 'LineBasicMaterial';
  18337. this.color = new Color( 0xffffff );
  18338. this.linewidth = 1;
  18339. this.linecap = 'round';
  18340. this.linejoin = 'round';
  18341. this.fog = true;
  18342. this.setValues( parameters );
  18343. }
  18344. copy( source ) {
  18345. super.copy( source );
  18346. this.color.copy( source.color );
  18347. this.linewidth = source.linewidth;
  18348. this.linecap = source.linecap;
  18349. this.linejoin = source.linejoin;
  18350. this.fog = source.fog;
  18351. return this;
  18352. }
  18353. }
  18354. const _start$1 = /*@__PURE__*/ new Vector3();
  18355. const _end$1 = /*@__PURE__*/ new Vector3();
  18356. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18357. const _ray$1 = /*@__PURE__*/ new Ray();
  18358. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18359. class Line extends Object3D {
  18360. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18361. super();
  18362. this.isLine = true;
  18363. this.type = 'Line';
  18364. this.geometry = geometry;
  18365. this.material = material;
  18366. this.updateMorphTargets();
  18367. }
  18368. copy( source, recursive ) {
  18369. super.copy( source, recursive );
  18370. this.material = source.material;
  18371. this.geometry = source.geometry;
  18372. return this;
  18373. }
  18374. computeLineDistances() {
  18375. const geometry = this.geometry;
  18376. // we assume non-indexed geometry
  18377. if ( geometry.index === null ) {
  18378. const positionAttribute = geometry.attributes.position;
  18379. const lineDistances = [ 0 ];
  18380. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18381. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18382. _end$1.fromBufferAttribute( positionAttribute, i );
  18383. lineDistances[ i ] = lineDistances[ i - 1 ];
  18384. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18385. }
  18386. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18387. } else {
  18388. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18389. }
  18390. return this;
  18391. }
  18392. raycast( raycaster, intersects ) {
  18393. const geometry = this.geometry;
  18394. const matrixWorld = this.matrixWorld;
  18395. const threshold = raycaster.params.Line.threshold;
  18396. const drawRange = geometry.drawRange;
  18397. // Checking boundingSphere distance to ray
  18398. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18399. _sphere$1.copy( geometry.boundingSphere );
  18400. _sphere$1.applyMatrix4( matrixWorld );
  18401. _sphere$1.radius += threshold;
  18402. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18403. //
  18404. _inverseMatrix$1.copy( matrixWorld ).invert();
  18405. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18406. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18407. const localThresholdSq = localThreshold * localThreshold;
  18408. const vStart = new Vector3();
  18409. const vEnd = new Vector3();
  18410. const interSegment = new Vector3();
  18411. const interRay = new Vector3();
  18412. const step = this.isLineSegments ? 2 : 1;
  18413. const index = geometry.index;
  18414. const attributes = geometry.attributes;
  18415. const positionAttribute = attributes.position;
  18416. if ( index !== null ) {
  18417. const start = Math.max( 0, drawRange.start );
  18418. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18419. for ( let i = start, l = end - 1; i < l; i += step ) {
  18420. const a = index.getX( i );
  18421. const b = index.getX( i + 1 );
  18422. vStart.fromBufferAttribute( positionAttribute, a );
  18423. vEnd.fromBufferAttribute( positionAttribute, b );
  18424. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18425. if ( distSq > localThresholdSq ) continue;
  18426. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18427. const distance = raycaster.ray.origin.distanceTo( interRay );
  18428. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18429. intersects.push( {
  18430. distance: distance,
  18431. // What do we want? intersection point on the ray or on the segment??
  18432. // point: raycaster.ray.at( distance ),
  18433. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18434. index: i,
  18435. face: null,
  18436. faceIndex: null,
  18437. object: this
  18438. } );
  18439. }
  18440. } else {
  18441. const start = Math.max( 0, drawRange.start );
  18442. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18443. for ( let i = start, l = end - 1; i < l; i += step ) {
  18444. vStart.fromBufferAttribute( positionAttribute, i );
  18445. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18446. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18447. if ( distSq > localThresholdSq ) continue;
  18448. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18449. const distance = raycaster.ray.origin.distanceTo( interRay );
  18450. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18451. intersects.push( {
  18452. distance: distance,
  18453. // What do we want? intersection point on the ray or on the segment??
  18454. // point: raycaster.ray.at( distance ),
  18455. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18456. index: i,
  18457. face: null,
  18458. faceIndex: null,
  18459. object: this
  18460. } );
  18461. }
  18462. }
  18463. }
  18464. updateMorphTargets() {
  18465. const geometry = this.geometry;
  18466. const morphAttributes = geometry.morphAttributes;
  18467. const keys = Object.keys( morphAttributes );
  18468. if ( keys.length > 0 ) {
  18469. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18470. if ( morphAttribute !== undefined ) {
  18471. this.morphTargetInfluences = [];
  18472. this.morphTargetDictionary = {};
  18473. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18474. const name = morphAttribute[ m ].name || String( m );
  18475. this.morphTargetInfluences.push( 0 );
  18476. this.morphTargetDictionary[ name ] = m;
  18477. }
  18478. }
  18479. }
  18480. }
  18481. }
  18482. const _start = /*@__PURE__*/ new Vector3();
  18483. const _end = /*@__PURE__*/ new Vector3();
  18484. class LineSegments extends Line {
  18485. constructor( geometry, material ) {
  18486. super( geometry, material );
  18487. this.isLineSegments = true;
  18488. this.type = 'LineSegments';
  18489. }
  18490. computeLineDistances() {
  18491. const geometry = this.geometry;
  18492. // we assume non-indexed geometry
  18493. if ( geometry.index === null ) {
  18494. const positionAttribute = geometry.attributes.position;
  18495. const lineDistances = [];
  18496. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18497. _start.fromBufferAttribute( positionAttribute, i );
  18498. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18499. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18500. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18501. }
  18502. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18503. } else {
  18504. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18505. }
  18506. return this;
  18507. }
  18508. }
  18509. class LineLoop extends Line {
  18510. constructor( geometry, material ) {
  18511. super( geometry, material );
  18512. this.isLineLoop = true;
  18513. this.type = 'LineLoop';
  18514. }
  18515. }
  18516. class PointsMaterial extends Material {
  18517. constructor( parameters ) {
  18518. super();
  18519. this.isPointsMaterial = true;
  18520. this.type = 'PointsMaterial';
  18521. this.color = new Color( 0xffffff );
  18522. this.map = null;
  18523. this.alphaMap = null;
  18524. this.size = 1;
  18525. this.sizeAttenuation = true;
  18526. this.fog = true;
  18527. this.setValues( parameters );
  18528. }
  18529. copy( source ) {
  18530. super.copy( source );
  18531. this.color.copy( source.color );
  18532. this.map = source.map;
  18533. this.alphaMap = source.alphaMap;
  18534. this.size = source.size;
  18535. this.sizeAttenuation = source.sizeAttenuation;
  18536. this.fog = source.fog;
  18537. return this;
  18538. }
  18539. }
  18540. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18541. const _ray = /*@__PURE__*/ new Ray();
  18542. const _sphere = /*@__PURE__*/ new Sphere();
  18543. const _position$2 = /*@__PURE__*/ new Vector3();
  18544. class Points extends Object3D {
  18545. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18546. super();
  18547. this.isPoints = true;
  18548. this.type = 'Points';
  18549. this.geometry = geometry;
  18550. this.material = material;
  18551. this.updateMorphTargets();
  18552. }
  18553. copy( source, recursive ) {
  18554. super.copy( source, recursive );
  18555. this.material = source.material;
  18556. this.geometry = source.geometry;
  18557. return this;
  18558. }
  18559. raycast( raycaster, intersects ) {
  18560. const geometry = this.geometry;
  18561. const matrixWorld = this.matrixWorld;
  18562. const threshold = raycaster.params.Points.threshold;
  18563. const drawRange = geometry.drawRange;
  18564. // Checking boundingSphere distance to ray
  18565. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18566. _sphere.copy( geometry.boundingSphere );
  18567. _sphere.applyMatrix4( matrixWorld );
  18568. _sphere.radius += threshold;
  18569. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18570. //
  18571. _inverseMatrix.copy( matrixWorld ).invert();
  18572. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18573. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18574. const localThresholdSq = localThreshold * localThreshold;
  18575. const index = geometry.index;
  18576. const attributes = geometry.attributes;
  18577. const positionAttribute = attributes.position;
  18578. if ( index !== null ) {
  18579. const start = Math.max( 0, drawRange.start );
  18580. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18581. for ( let i = start, il = end; i < il; i ++ ) {
  18582. const a = index.getX( i );
  18583. _position$2.fromBufferAttribute( positionAttribute, a );
  18584. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18585. }
  18586. } else {
  18587. const start = Math.max( 0, drawRange.start );
  18588. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18589. for ( let i = start, l = end; i < l; i ++ ) {
  18590. _position$2.fromBufferAttribute( positionAttribute, i );
  18591. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18592. }
  18593. }
  18594. }
  18595. updateMorphTargets() {
  18596. const geometry = this.geometry;
  18597. const morphAttributes = geometry.morphAttributes;
  18598. const keys = Object.keys( morphAttributes );
  18599. if ( keys.length > 0 ) {
  18600. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18601. if ( morphAttribute !== undefined ) {
  18602. this.morphTargetInfluences = [];
  18603. this.morphTargetDictionary = {};
  18604. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18605. const name = morphAttribute[ m ].name || String( m );
  18606. this.morphTargetInfluences.push( 0 );
  18607. this.morphTargetDictionary[ name ] = m;
  18608. }
  18609. }
  18610. }
  18611. }
  18612. }
  18613. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18614. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18615. if ( rayPointDistanceSq < localThresholdSq ) {
  18616. const intersectPoint = new Vector3();
  18617. _ray.closestPointToPoint( point, intersectPoint );
  18618. intersectPoint.applyMatrix4( matrixWorld );
  18619. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18620. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18621. intersects.push( {
  18622. distance: distance,
  18623. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18624. point: intersectPoint,
  18625. index: index,
  18626. face: null,
  18627. object: object
  18628. } );
  18629. }
  18630. }
  18631. class VideoTexture extends Texture {
  18632. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18633. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18634. this.isVideoTexture = true;
  18635. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18636. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18637. this.generateMipmaps = false;
  18638. const scope = this;
  18639. function updateVideo() {
  18640. scope.needsUpdate = true;
  18641. video.requestVideoFrameCallback( updateVideo );
  18642. }
  18643. if ( 'requestVideoFrameCallback' in video ) {
  18644. video.requestVideoFrameCallback( updateVideo );
  18645. }
  18646. }
  18647. clone() {
  18648. return new this.constructor( this.image ).copy( this );
  18649. }
  18650. update() {
  18651. const video = this.image;
  18652. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18653. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18654. this.needsUpdate = true;
  18655. }
  18656. }
  18657. }
  18658. class FramebufferTexture extends Texture {
  18659. constructor( width, height, format ) {
  18660. super( { width, height } );
  18661. this.isFramebufferTexture = true;
  18662. this.format = format;
  18663. this.magFilter = NearestFilter;
  18664. this.minFilter = NearestFilter;
  18665. this.generateMipmaps = false;
  18666. this.needsUpdate = true;
  18667. }
  18668. }
  18669. class CompressedTexture extends Texture {
  18670. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18671. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18672. this.isCompressedTexture = true;
  18673. this.image = { width: width, height: height };
  18674. this.mipmaps = mipmaps;
  18675. // no flipping for cube textures
  18676. // (also flipping doesn't work for compressed textures )
  18677. this.flipY = false;
  18678. // can't generate mipmaps for compressed textures
  18679. // mips must be embedded in DDS files
  18680. this.generateMipmaps = false;
  18681. }
  18682. }
  18683. class CanvasTexture extends Texture {
  18684. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18685. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18686. this.isCanvasTexture = true;
  18687. this.needsUpdate = true;
  18688. }
  18689. }
  18690. /**
  18691. * Extensible curve object.
  18692. *
  18693. * Some common of curve methods:
  18694. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18695. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18696. * .getPoints(), .getSpacedPoints()
  18697. * .getLength()
  18698. * .updateArcLengths()
  18699. *
  18700. * This following curves inherit from THREE.Curve:
  18701. *
  18702. * -- 2D curves --
  18703. * THREE.ArcCurve
  18704. * THREE.CubicBezierCurve
  18705. * THREE.EllipseCurve
  18706. * THREE.LineCurve
  18707. * THREE.QuadraticBezierCurve
  18708. * THREE.SplineCurve
  18709. *
  18710. * -- 3D curves --
  18711. * THREE.CatmullRomCurve3
  18712. * THREE.CubicBezierCurve3
  18713. * THREE.LineCurve3
  18714. * THREE.QuadraticBezierCurve3
  18715. *
  18716. * A series of curves can be represented as a THREE.CurvePath.
  18717. *
  18718. **/
  18719. class Curve {
  18720. constructor() {
  18721. this.type = 'Curve';
  18722. this.arcLengthDivisions = 200;
  18723. }
  18724. // Virtual base class method to overwrite and implement in subclasses
  18725. // - t [0 .. 1]
  18726. getPoint( /* t, optionalTarget */ ) {
  18727. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18728. return null;
  18729. }
  18730. // Get point at relative position in curve according to arc length
  18731. // - u [0 .. 1]
  18732. getPointAt( u, optionalTarget ) {
  18733. const t = this.getUtoTmapping( u );
  18734. return this.getPoint( t, optionalTarget );
  18735. }
  18736. // Get sequence of points using getPoint( t )
  18737. getPoints( divisions = 5 ) {
  18738. const points = [];
  18739. for ( let d = 0; d <= divisions; d ++ ) {
  18740. points.push( this.getPoint( d / divisions ) );
  18741. }
  18742. return points;
  18743. }
  18744. // Get sequence of points using getPointAt( u )
  18745. getSpacedPoints( divisions = 5 ) {
  18746. const points = [];
  18747. for ( let d = 0; d <= divisions; d ++ ) {
  18748. points.push( this.getPointAt( d / divisions ) );
  18749. }
  18750. return points;
  18751. }
  18752. // Get total curve arc length
  18753. getLength() {
  18754. const lengths = this.getLengths();
  18755. return lengths[ lengths.length - 1 ];
  18756. }
  18757. // Get list of cumulative segment lengths
  18758. getLengths( divisions = this.arcLengthDivisions ) {
  18759. if ( this.cacheArcLengths &&
  18760. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18761. ! this.needsUpdate ) {
  18762. return this.cacheArcLengths;
  18763. }
  18764. this.needsUpdate = false;
  18765. const cache = [];
  18766. let current, last = this.getPoint( 0 );
  18767. let sum = 0;
  18768. cache.push( 0 );
  18769. for ( let p = 1; p <= divisions; p ++ ) {
  18770. current = this.getPoint( p / divisions );
  18771. sum += current.distanceTo( last );
  18772. cache.push( sum );
  18773. last = current;
  18774. }
  18775. this.cacheArcLengths = cache;
  18776. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18777. }
  18778. updateArcLengths() {
  18779. this.needsUpdate = true;
  18780. this.getLengths();
  18781. }
  18782. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18783. getUtoTmapping( u, distance ) {
  18784. const arcLengths = this.getLengths();
  18785. let i = 0;
  18786. const il = arcLengths.length;
  18787. let targetArcLength; // The targeted u distance value to get
  18788. if ( distance ) {
  18789. targetArcLength = distance;
  18790. } else {
  18791. targetArcLength = u * arcLengths[ il - 1 ];
  18792. }
  18793. // binary search for the index with largest value smaller than target u distance
  18794. let low = 0, high = il - 1, comparison;
  18795. while ( low <= high ) {
  18796. 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
  18797. comparison = arcLengths[ i ] - targetArcLength;
  18798. if ( comparison < 0 ) {
  18799. low = i + 1;
  18800. } else if ( comparison > 0 ) {
  18801. high = i - 1;
  18802. } else {
  18803. high = i;
  18804. break;
  18805. // DONE
  18806. }
  18807. }
  18808. i = high;
  18809. if ( arcLengths[ i ] === targetArcLength ) {
  18810. return i / ( il - 1 );
  18811. }
  18812. // we could get finer grain at lengths, or use simple interpolation between two points
  18813. const lengthBefore = arcLengths[ i ];
  18814. const lengthAfter = arcLengths[ i + 1 ];
  18815. const segmentLength = lengthAfter - lengthBefore;
  18816. // determine where we are between the 'before' and 'after' points
  18817. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18818. // add that fractional amount to t
  18819. const t = ( i + segmentFraction ) / ( il - 1 );
  18820. return t;
  18821. }
  18822. // Returns a unit vector tangent at t
  18823. // In case any sub curve does not implement its tangent derivation,
  18824. // 2 points a small delta apart will be used to find its gradient
  18825. // which seems to give a reasonable approximation
  18826. getTangent( t, optionalTarget ) {
  18827. const delta = 0.0001;
  18828. let t1 = t - delta;
  18829. let t2 = t + delta;
  18830. // Capping in case of danger
  18831. if ( t1 < 0 ) t1 = 0;
  18832. if ( t2 > 1 ) t2 = 1;
  18833. const pt1 = this.getPoint( t1 );
  18834. const pt2 = this.getPoint( t2 );
  18835. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18836. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18837. return tangent;
  18838. }
  18839. getTangentAt( u, optionalTarget ) {
  18840. const t = this.getUtoTmapping( u );
  18841. return this.getTangent( t, optionalTarget );
  18842. }
  18843. computeFrenetFrames( segments, closed ) {
  18844. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18845. const normal = new Vector3();
  18846. const tangents = [];
  18847. const normals = [];
  18848. const binormals = [];
  18849. const vec = new Vector3();
  18850. const mat = new Matrix4();
  18851. // compute the tangent vectors for each segment on the curve
  18852. for ( let i = 0; i <= segments; i ++ ) {
  18853. const u = i / segments;
  18854. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18855. }
  18856. // select an initial normal vector perpendicular to the first tangent vector,
  18857. // and in the direction of the minimum tangent xyz component
  18858. normals[ 0 ] = new Vector3();
  18859. binormals[ 0 ] = new Vector3();
  18860. let min = Number.MAX_VALUE;
  18861. const tx = Math.abs( tangents[ 0 ].x );
  18862. const ty = Math.abs( tangents[ 0 ].y );
  18863. const tz = Math.abs( tangents[ 0 ].z );
  18864. if ( tx <= min ) {
  18865. min = tx;
  18866. normal.set( 1, 0, 0 );
  18867. }
  18868. if ( ty <= min ) {
  18869. min = ty;
  18870. normal.set( 0, 1, 0 );
  18871. }
  18872. if ( tz <= min ) {
  18873. normal.set( 0, 0, 1 );
  18874. }
  18875. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18876. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18877. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18878. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18879. for ( let i = 1; i <= segments; i ++ ) {
  18880. normals[ i ] = normals[ i - 1 ].clone();
  18881. binormals[ i ] = binormals[ i - 1 ].clone();
  18882. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18883. if ( vec.length() > Number.EPSILON ) {
  18884. vec.normalize();
  18885. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18886. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18887. }
  18888. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18889. }
  18890. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18891. if ( closed === true ) {
  18892. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18893. theta /= segments;
  18894. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18895. theta = - theta;
  18896. }
  18897. for ( let i = 1; i <= segments; i ++ ) {
  18898. // twist a little...
  18899. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18900. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18901. }
  18902. }
  18903. return {
  18904. tangents: tangents,
  18905. normals: normals,
  18906. binormals: binormals
  18907. };
  18908. }
  18909. clone() {
  18910. return new this.constructor().copy( this );
  18911. }
  18912. copy( source ) {
  18913. this.arcLengthDivisions = source.arcLengthDivisions;
  18914. return this;
  18915. }
  18916. toJSON() {
  18917. const data = {
  18918. metadata: {
  18919. version: 4.5,
  18920. type: 'Curve',
  18921. generator: 'Curve.toJSON'
  18922. }
  18923. };
  18924. data.arcLengthDivisions = this.arcLengthDivisions;
  18925. data.type = this.type;
  18926. return data;
  18927. }
  18928. fromJSON( json ) {
  18929. this.arcLengthDivisions = json.arcLengthDivisions;
  18930. return this;
  18931. }
  18932. }
  18933. class EllipseCurve extends Curve {
  18934. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18935. super();
  18936. this.isEllipseCurve = true;
  18937. this.type = 'EllipseCurve';
  18938. this.aX = aX;
  18939. this.aY = aY;
  18940. this.xRadius = xRadius;
  18941. this.yRadius = yRadius;
  18942. this.aStartAngle = aStartAngle;
  18943. this.aEndAngle = aEndAngle;
  18944. this.aClockwise = aClockwise;
  18945. this.aRotation = aRotation;
  18946. }
  18947. getPoint( t, optionalTarget ) {
  18948. const point = optionalTarget || new Vector2();
  18949. const twoPi = Math.PI * 2;
  18950. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18951. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18952. // ensures that deltaAngle is 0 .. 2 PI
  18953. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18954. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18955. if ( deltaAngle < Number.EPSILON ) {
  18956. if ( samePoints ) {
  18957. deltaAngle = 0;
  18958. } else {
  18959. deltaAngle = twoPi;
  18960. }
  18961. }
  18962. if ( this.aClockwise === true && ! samePoints ) {
  18963. if ( deltaAngle === twoPi ) {
  18964. deltaAngle = - twoPi;
  18965. } else {
  18966. deltaAngle = deltaAngle - twoPi;
  18967. }
  18968. }
  18969. const angle = this.aStartAngle + t * deltaAngle;
  18970. let x = this.aX + this.xRadius * Math.cos( angle );
  18971. let y = this.aY + this.yRadius * Math.sin( angle );
  18972. if ( this.aRotation !== 0 ) {
  18973. const cos = Math.cos( this.aRotation );
  18974. const sin = Math.sin( this.aRotation );
  18975. const tx = x - this.aX;
  18976. const ty = y - this.aY;
  18977. // Rotate the point about the center of the ellipse.
  18978. x = tx * cos - ty * sin + this.aX;
  18979. y = tx * sin + ty * cos + this.aY;
  18980. }
  18981. return point.set( x, y );
  18982. }
  18983. copy( source ) {
  18984. super.copy( source );
  18985. this.aX = source.aX;
  18986. this.aY = source.aY;
  18987. this.xRadius = source.xRadius;
  18988. this.yRadius = source.yRadius;
  18989. this.aStartAngle = source.aStartAngle;
  18990. this.aEndAngle = source.aEndAngle;
  18991. this.aClockwise = source.aClockwise;
  18992. this.aRotation = source.aRotation;
  18993. return this;
  18994. }
  18995. toJSON() {
  18996. const data = super.toJSON();
  18997. data.aX = this.aX;
  18998. data.aY = this.aY;
  18999. data.xRadius = this.xRadius;
  19000. data.yRadius = this.yRadius;
  19001. data.aStartAngle = this.aStartAngle;
  19002. data.aEndAngle = this.aEndAngle;
  19003. data.aClockwise = this.aClockwise;
  19004. data.aRotation = this.aRotation;
  19005. return data;
  19006. }
  19007. fromJSON( json ) {
  19008. super.fromJSON( json );
  19009. this.aX = json.aX;
  19010. this.aY = json.aY;
  19011. this.xRadius = json.xRadius;
  19012. this.yRadius = json.yRadius;
  19013. this.aStartAngle = json.aStartAngle;
  19014. this.aEndAngle = json.aEndAngle;
  19015. this.aClockwise = json.aClockwise;
  19016. this.aRotation = json.aRotation;
  19017. return this;
  19018. }
  19019. }
  19020. class ArcCurve extends EllipseCurve {
  19021. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19022. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19023. this.isArcCurve = true;
  19024. this.type = 'ArcCurve';
  19025. }
  19026. }
  19027. /**
  19028. * Centripetal CatmullRom Curve - which is useful for avoiding
  19029. * cusps and self-intersections in non-uniform catmull rom curves.
  19030. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19031. *
  19032. * curve.type accepts centripetal(default), chordal and catmullrom
  19033. * curve.tension is used for catmullrom which defaults to 0.5
  19034. */
  19035. /*
  19036. Based on an optimized c++ solution in
  19037. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19038. - http://ideone.com/NoEbVM
  19039. This CubicPoly class could be used for reusing some variables and calculations,
  19040. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19041. which can be placed in CurveUtils.
  19042. */
  19043. function CubicPoly() {
  19044. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19045. /*
  19046. * Compute coefficients for a cubic polynomial
  19047. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19048. * such that
  19049. * p(0) = x0, p(1) = x1
  19050. * and
  19051. * p'(0) = t0, p'(1) = t1.
  19052. */
  19053. function init( x0, x1, t0, t1 ) {
  19054. c0 = x0;
  19055. c1 = t0;
  19056. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19057. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19058. }
  19059. return {
  19060. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19061. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19062. },
  19063. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19064. // compute tangents when parameterized in [t1,t2]
  19065. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19066. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19067. // rescale tangents for parametrization in [0,1]
  19068. t1 *= dt1;
  19069. t2 *= dt1;
  19070. init( x1, x2, t1, t2 );
  19071. },
  19072. calc: function ( t ) {
  19073. const t2 = t * t;
  19074. const t3 = t2 * t;
  19075. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19076. }
  19077. };
  19078. }
  19079. //
  19080. const tmp = /*@__PURE__*/ new Vector3();
  19081. const px = /*@__PURE__*/ new CubicPoly();
  19082. const py = /*@__PURE__*/ new CubicPoly();
  19083. const pz = /*@__PURE__*/ new CubicPoly();
  19084. class CatmullRomCurve3 extends Curve {
  19085. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19086. super();
  19087. this.isCatmullRomCurve3 = true;
  19088. this.type = 'CatmullRomCurve3';
  19089. this.points = points;
  19090. this.closed = closed;
  19091. this.curveType = curveType;
  19092. this.tension = tension;
  19093. }
  19094. getPoint( t, optionalTarget = new Vector3() ) {
  19095. const point = optionalTarget;
  19096. const points = this.points;
  19097. const l = points.length;
  19098. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19099. let intPoint = Math.floor( p );
  19100. let weight = p - intPoint;
  19101. if ( this.closed ) {
  19102. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19103. } else if ( weight === 0 && intPoint === l - 1 ) {
  19104. intPoint = l - 2;
  19105. weight = 1;
  19106. }
  19107. let p0, p3; // 4 points (p1 & p2 defined below)
  19108. if ( this.closed || intPoint > 0 ) {
  19109. p0 = points[ ( intPoint - 1 ) % l ];
  19110. } else {
  19111. // extrapolate first point
  19112. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19113. p0 = tmp;
  19114. }
  19115. const p1 = points[ intPoint % l ];
  19116. const p2 = points[ ( intPoint + 1 ) % l ];
  19117. if ( this.closed || intPoint + 2 < l ) {
  19118. p3 = points[ ( intPoint + 2 ) % l ];
  19119. } else {
  19120. // extrapolate last point
  19121. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19122. p3 = tmp;
  19123. }
  19124. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19125. // init Centripetal / Chordal Catmull-Rom
  19126. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19127. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19128. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19129. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19130. // safety check for repeated points
  19131. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19132. if ( dt0 < 1e-4 ) dt0 = dt1;
  19133. if ( dt2 < 1e-4 ) dt2 = dt1;
  19134. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19135. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19136. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19137. } else if ( this.curveType === 'catmullrom' ) {
  19138. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19139. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19140. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19141. }
  19142. point.set(
  19143. px.calc( weight ),
  19144. py.calc( weight ),
  19145. pz.calc( weight )
  19146. );
  19147. return point;
  19148. }
  19149. copy( source ) {
  19150. super.copy( source );
  19151. this.points = [];
  19152. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19153. const point = source.points[ i ];
  19154. this.points.push( point.clone() );
  19155. }
  19156. this.closed = source.closed;
  19157. this.curveType = source.curveType;
  19158. this.tension = source.tension;
  19159. return this;
  19160. }
  19161. toJSON() {
  19162. const data = super.toJSON();
  19163. data.points = [];
  19164. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19165. const point = this.points[ i ];
  19166. data.points.push( point.toArray() );
  19167. }
  19168. data.closed = this.closed;
  19169. data.curveType = this.curveType;
  19170. data.tension = this.tension;
  19171. return data;
  19172. }
  19173. fromJSON( json ) {
  19174. super.fromJSON( json );
  19175. this.points = [];
  19176. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19177. const point = json.points[ i ];
  19178. this.points.push( new Vector3().fromArray( point ) );
  19179. }
  19180. this.closed = json.closed;
  19181. this.curveType = json.curveType;
  19182. this.tension = json.tension;
  19183. return this;
  19184. }
  19185. }
  19186. /**
  19187. * Bezier Curves formulas obtained from
  19188. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19189. */
  19190. function CatmullRom( t, p0, p1, p2, p3 ) {
  19191. const v0 = ( p2 - p0 ) * 0.5;
  19192. const v1 = ( p3 - p1 ) * 0.5;
  19193. const t2 = t * t;
  19194. const t3 = t * t2;
  19195. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19196. }
  19197. //
  19198. function QuadraticBezierP0( t, p ) {
  19199. const k = 1 - t;
  19200. return k * k * p;
  19201. }
  19202. function QuadraticBezierP1( t, p ) {
  19203. return 2 * ( 1 - t ) * t * p;
  19204. }
  19205. function QuadraticBezierP2( t, p ) {
  19206. return t * t * p;
  19207. }
  19208. function QuadraticBezier( t, p0, p1, p2 ) {
  19209. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19210. QuadraticBezierP2( t, p2 );
  19211. }
  19212. //
  19213. function CubicBezierP0( t, p ) {
  19214. const k = 1 - t;
  19215. return k * k * k * p;
  19216. }
  19217. function CubicBezierP1( t, p ) {
  19218. const k = 1 - t;
  19219. return 3 * k * k * t * p;
  19220. }
  19221. function CubicBezierP2( t, p ) {
  19222. return 3 * ( 1 - t ) * t * t * p;
  19223. }
  19224. function CubicBezierP3( t, p ) {
  19225. return t * t * t * p;
  19226. }
  19227. function CubicBezier( t, p0, p1, p2, p3 ) {
  19228. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19229. CubicBezierP3( t, p3 );
  19230. }
  19231. class CubicBezierCurve extends Curve {
  19232. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19233. super();
  19234. this.isCubicBezierCurve = true;
  19235. this.type = 'CubicBezierCurve';
  19236. this.v0 = v0;
  19237. this.v1 = v1;
  19238. this.v2 = v2;
  19239. this.v3 = v3;
  19240. }
  19241. getPoint( t, optionalTarget = new Vector2() ) {
  19242. const point = optionalTarget;
  19243. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19244. point.set(
  19245. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19246. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19247. );
  19248. return point;
  19249. }
  19250. copy( source ) {
  19251. super.copy( source );
  19252. this.v0.copy( source.v0 );
  19253. this.v1.copy( source.v1 );
  19254. this.v2.copy( source.v2 );
  19255. this.v3.copy( source.v3 );
  19256. return this;
  19257. }
  19258. toJSON() {
  19259. const data = super.toJSON();
  19260. data.v0 = this.v0.toArray();
  19261. data.v1 = this.v1.toArray();
  19262. data.v2 = this.v2.toArray();
  19263. data.v3 = this.v3.toArray();
  19264. return data;
  19265. }
  19266. fromJSON( json ) {
  19267. super.fromJSON( json );
  19268. this.v0.fromArray( json.v0 );
  19269. this.v1.fromArray( json.v1 );
  19270. this.v2.fromArray( json.v2 );
  19271. this.v3.fromArray( json.v3 );
  19272. return this;
  19273. }
  19274. }
  19275. class CubicBezierCurve3 extends Curve {
  19276. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19277. super();
  19278. this.isCubicBezierCurve3 = true;
  19279. this.type = 'CubicBezierCurve3';
  19280. this.v0 = v0;
  19281. this.v1 = v1;
  19282. this.v2 = v2;
  19283. this.v3 = v3;
  19284. }
  19285. getPoint( t, optionalTarget = new Vector3() ) {
  19286. const point = optionalTarget;
  19287. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19288. point.set(
  19289. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19290. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19291. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19292. );
  19293. return point;
  19294. }
  19295. copy( source ) {
  19296. super.copy( source );
  19297. this.v0.copy( source.v0 );
  19298. this.v1.copy( source.v1 );
  19299. this.v2.copy( source.v2 );
  19300. this.v3.copy( source.v3 );
  19301. return this;
  19302. }
  19303. toJSON() {
  19304. const data = super.toJSON();
  19305. data.v0 = this.v0.toArray();
  19306. data.v1 = this.v1.toArray();
  19307. data.v2 = this.v2.toArray();
  19308. data.v3 = this.v3.toArray();
  19309. return data;
  19310. }
  19311. fromJSON( json ) {
  19312. super.fromJSON( json );
  19313. this.v0.fromArray( json.v0 );
  19314. this.v1.fromArray( json.v1 );
  19315. this.v2.fromArray( json.v2 );
  19316. this.v3.fromArray( json.v3 );
  19317. return this;
  19318. }
  19319. }
  19320. class LineCurve extends Curve {
  19321. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19322. super();
  19323. this.isLineCurve = true;
  19324. this.type = 'LineCurve';
  19325. this.v1 = v1;
  19326. this.v2 = v2;
  19327. }
  19328. getPoint( t, optionalTarget = new Vector2() ) {
  19329. const point = optionalTarget;
  19330. if ( t === 1 ) {
  19331. point.copy( this.v2 );
  19332. } else {
  19333. point.copy( this.v2 ).sub( this.v1 );
  19334. point.multiplyScalar( t ).add( this.v1 );
  19335. }
  19336. return point;
  19337. }
  19338. // Line curve is linear, so we can overwrite default getPointAt
  19339. getPointAt( u, optionalTarget ) {
  19340. return this.getPoint( u, optionalTarget );
  19341. }
  19342. getTangent( t, optionalTarget ) {
  19343. const tangent = optionalTarget || new Vector2();
  19344. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19345. return tangent;
  19346. }
  19347. copy( source ) {
  19348. super.copy( source );
  19349. this.v1.copy( source.v1 );
  19350. this.v2.copy( source.v2 );
  19351. return this;
  19352. }
  19353. toJSON() {
  19354. const data = super.toJSON();
  19355. data.v1 = this.v1.toArray();
  19356. data.v2 = this.v2.toArray();
  19357. return data;
  19358. }
  19359. fromJSON( json ) {
  19360. super.fromJSON( json );
  19361. this.v1.fromArray( json.v1 );
  19362. this.v2.fromArray( json.v2 );
  19363. return this;
  19364. }
  19365. }
  19366. class LineCurve3 extends Curve {
  19367. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19368. super();
  19369. this.isLineCurve3 = true;
  19370. this.type = 'LineCurve3';
  19371. this.v1 = v1;
  19372. this.v2 = v2;
  19373. }
  19374. getPoint( t, optionalTarget = new Vector3() ) {
  19375. const point = optionalTarget;
  19376. if ( t === 1 ) {
  19377. point.copy( this.v2 );
  19378. } else {
  19379. point.copy( this.v2 ).sub( this.v1 );
  19380. point.multiplyScalar( t ).add( this.v1 );
  19381. }
  19382. return point;
  19383. }
  19384. // Line curve is linear, so we can overwrite default getPointAt
  19385. getPointAt( u, optionalTarget ) {
  19386. return this.getPoint( u, optionalTarget );
  19387. }
  19388. copy( source ) {
  19389. super.copy( source );
  19390. this.v1.copy( source.v1 );
  19391. this.v2.copy( source.v2 );
  19392. return this;
  19393. }
  19394. toJSON() {
  19395. const data = super.toJSON();
  19396. data.v1 = this.v1.toArray();
  19397. data.v2 = this.v2.toArray();
  19398. return data;
  19399. }
  19400. fromJSON( json ) {
  19401. super.fromJSON( json );
  19402. this.v1.fromArray( json.v1 );
  19403. this.v2.fromArray( json.v2 );
  19404. return this;
  19405. }
  19406. }
  19407. class QuadraticBezierCurve extends Curve {
  19408. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19409. super();
  19410. this.isQuadraticBezierCurve = true;
  19411. this.type = 'QuadraticBezierCurve';
  19412. this.v0 = v0;
  19413. this.v1 = v1;
  19414. this.v2 = v2;
  19415. }
  19416. getPoint( t, optionalTarget = new Vector2() ) {
  19417. const point = optionalTarget;
  19418. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19419. point.set(
  19420. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19421. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19422. );
  19423. return point;
  19424. }
  19425. copy( source ) {
  19426. super.copy( source );
  19427. this.v0.copy( source.v0 );
  19428. this.v1.copy( source.v1 );
  19429. this.v2.copy( source.v2 );
  19430. return this;
  19431. }
  19432. toJSON() {
  19433. const data = super.toJSON();
  19434. data.v0 = this.v0.toArray();
  19435. data.v1 = this.v1.toArray();
  19436. data.v2 = this.v2.toArray();
  19437. return data;
  19438. }
  19439. fromJSON( json ) {
  19440. super.fromJSON( json );
  19441. this.v0.fromArray( json.v0 );
  19442. this.v1.fromArray( json.v1 );
  19443. this.v2.fromArray( json.v2 );
  19444. return this;
  19445. }
  19446. }
  19447. class QuadraticBezierCurve3 extends Curve {
  19448. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19449. super();
  19450. this.isQuadraticBezierCurve3 = true;
  19451. this.type = 'QuadraticBezierCurve3';
  19452. this.v0 = v0;
  19453. this.v1 = v1;
  19454. this.v2 = v2;
  19455. }
  19456. getPoint( t, optionalTarget = new Vector3() ) {
  19457. const point = optionalTarget;
  19458. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19459. point.set(
  19460. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19461. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19462. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19463. );
  19464. return point;
  19465. }
  19466. copy( source ) {
  19467. super.copy( source );
  19468. this.v0.copy( source.v0 );
  19469. this.v1.copy( source.v1 );
  19470. this.v2.copy( source.v2 );
  19471. return this;
  19472. }
  19473. toJSON() {
  19474. const data = super.toJSON();
  19475. data.v0 = this.v0.toArray();
  19476. data.v1 = this.v1.toArray();
  19477. data.v2 = this.v2.toArray();
  19478. return data;
  19479. }
  19480. fromJSON( json ) {
  19481. super.fromJSON( json );
  19482. this.v0.fromArray( json.v0 );
  19483. this.v1.fromArray( json.v1 );
  19484. this.v2.fromArray( json.v2 );
  19485. return this;
  19486. }
  19487. }
  19488. class SplineCurve extends Curve {
  19489. constructor( points = [] ) {
  19490. super();
  19491. this.isSplineCurve = true;
  19492. this.type = 'SplineCurve';
  19493. this.points = points;
  19494. }
  19495. getPoint( t, optionalTarget = new Vector2() ) {
  19496. const point = optionalTarget;
  19497. const points = this.points;
  19498. const p = ( points.length - 1 ) * t;
  19499. const intPoint = Math.floor( p );
  19500. const weight = p - intPoint;
  19501. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19502. const p1 = points[ intPoint ];
  19503. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19504. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19505. point.set(
  19506. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19507. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19508. );
  19509. return point;
  19510. }
  19511. copy( source ) {
  19512. super.copy( source );
  19513. this.points = [];
  19514. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19515. const point = source.points[ i ];
  19516. this.points.push( point.clone() );
  19517. }
  19518. return this;
  19519. }
  19520. toJSON() {
  19521. const data = super.toJSON();
  19522. data.points = [];
  19523. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19524. const point = this.points[ i ];
  19525. data.points.push( point.toArray() );
  19526. }
  19527. return data;
  19528. }
  19529. fromJSON( json ) {
  19530. super.fromJSON( json );
  19531. this.points = [];
  19532. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19533. const point = json.points[ i ];
  19534. this.points.push( new Vector2().fromArray( point ) );
  19535. }
  19536. return this;
  19537. }
  19538. }
  19539. var Curves = /*#__PURE__*/Object.freeze({
  19540. __proto__: null,
  19541. ArcCurve: ArcCurve,
  19542. CatmullRomCurve3: CatmullRomCurve3,
  19543. CubicBezierCurve: CubicBezierCurve,
  19544. CubicBezierCurve3: CubicBezierCurve3,
  19545. EllipseCurve: EllipseCurve,
  19546. LineCurve: LineCurve,
  19547. LineCurve3: LineCurve3,
  19548. QuadraticBezierCurve: QuadraticBezierCurve,
  19549. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19550. SplineCurve: SplineCurve
  19551. });
  19552. /**************************************************************
  19553. * Curved Path - a curve path is simply a array of connected
  19554. * curves, but retains the api of a curve
  19555. **************************************************************/
  19556. class CurvePath extends Curve {
  19557. constructor() {
  19558. super();
  19559. this.type = 'CurvePath';
  19560. this.curves = [];
  19561. this.autoClose = false; // Automatically closes the path
  19562. }
  19563. add( curve ) {
  19564. this.curves.push( curve );
  19565. }
  19566. closePath() {
  19567. // Add a line curve if start and end of lines are not connected
  19568. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19569. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19570. if ( ! startPoint.equals( endPoint ) ) {
  19571. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19572. }
  19573. }
  19574. // To get accurate point with reference to
  19575. // entire path distance at time t,
  19576. // following has to be done:
  19577. // 1. Length of each sub path have to be known
  19578. // 2. Locate and identify type of curve
  19579. // 3. Get t for the curve
  19580. // 4. Return curve.getPointAt(t')
  19581. getPoint( t, optionalTarget ) {
  19582. const d = t * this.getLength();
  19583. const curveLengths = this.getCurveLengths();
  19584. let i = 0;
  19585. // To think about boundaries points.
  19586. while ( i < curveLengths.length ) {
  19587. if ( curveLengths[ i ] >= d ) {
  19588. const diff = curveLengths[ i ] - d;
  19589. const curve = this.curves[ i ];
  19590. const segmentLength = curve.getLength();
  19591. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19592. return curve.getPointAt( u, optionalTarget );
  19593. }
  19594. i ++;
  19595. }
  19596. return null;
  19597. // loop where sum != 0, sum > d , sum+1 <d
  19598. }
  19599. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19600. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19601. // getPoint() depends on getLength
  19602. getLength() {
  19603. const lens = this.getCurveLengths();
  19604. return lens[ lens.length - 1 ];
  19605. }
  19606. // cacheLengths must be recalculated.
  19607. updateArcLengths() {
  19608. this.needsUpdate = true;
  19609. this.cacheLengths = null;
  19610. this.getCurveLengths();
  19611. }
  19612. // Compute lengths and cache them
  19613. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19614. getCurveLengths() {
  19615. // We use cache values if curves and cache array are same length
  19616. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19617. return this.cacheLengths;
  19618. }
  19619. // Get length of sub-curve
  19620. // Push sums into cached array
  19621. const lengths = [];
  19622. let sums = 0;
  19623. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19624. sums += this.curves[ i ].getLength();
  19625. lengths.push( sums );
  19626. }
  19627. this.cacheLengths = lengths;
  19628. return lengths;
  19629. }
  19630. getSpacedPoints( divisions = 40 ) {
  19631. const points = [];
  19632. for ( let i = 0; i <= divisions; i ++ ) {
  19633. points.push( this.getPoint( i / divisions ) );
  19634. }
  19635. if ( this.autoClose ) {
  19636. points.push( points[ 0 ] );
  19637. }
  19638. return points;
  19639. }
  19640. getPoints( divisions = 12 ) {
  19641. const points = [];
  19642. let last;
  19643. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19644. const curve = curves[ i ];
  19645. const resolution = curve.isEllipseCurve ? divisions * 2
  19646. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19647. : curve.isSplineCurve ? divisions * curve.points.length
  19648. : divisions;
  19649. const pts = curve.getPoints( resolution );
  19650. for ( let j = 0; j < pts.length; j ++ ) {
  19651. const point = pts[ j ];
  19652. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19653. points.push( point );
  19654. last = point;
  19655. }
  19656. }
  19657. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19658. points.push( points[ 0 ] );
  19659. }
  19660. return points;
  19661. }
  19662. copy( source ) {
  19663. super.copy( source );
  19664. this.curves = [];
  19665. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19666. const curve = source.curves[ i ];
  19667. this.curves.push( curve.clone() );
  19668. }
  19669. this.autoClose = source.autoClose;
  19670. return this;
  19671. }
  19672. toJSON() {
  19673. const data = super.toJSON();
  19674. data.autoClose = this.autoClose;
  19675. data.curves = [];
  19676. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19677. const curve = this.curves[ i ];
  19678. data.curves.push( curve.toJSON() );
  19679. }
  19680. return data;
  19681. }
  19682. fromJSON( json ) {
  19683. super.fromJSON( json );
  19684. this.autoClose = json.autoClose;
  19685. this.curves = [];
  19686. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19687. const curve = json.curves[ i ];
  19688. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19689. }
  19690. return this;
  19691. }
  19692. }
  19693. class Path extends CurvePath {
  19694. constructor( points ) {
  19695. super();
  19696. this.type = 'Path';
  19697. this.currentPoint = new Vector2();
  19698. if ( points ) {
  19699. this.setFromPoints( points );
  19700. }
  19701. }
  19702. setFromPoints( points ) {
  19703. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19704. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19705. this.lineTo( points[ i ].x, points[ i ].y );
  19706. }
  19707. return this;
  19708. }
  19709. moveTo( x, y ) {
  19710. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19711. return this;
  19712. }
  19713. lineTo( x, y ) {
  19714. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19715. this.curves.push( curve );
  19716. this.currentPoint.set( x, y );
  19717. return this;
  19718. }
  19719. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19720. const curve = new QuadraticBezierCurve(
  19721. this.currentPoint.clone(),
  19722. new Vector2( aCPx, aCPy ),
  19723. new Vector2( aX, aY )
  19724. );
  19725. this.curves.push( curve );
  19726. this.currentPoint.set( aX, aY );
  19727. return this;
  19728. }
  19729. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19730. const curve = new CubicBezierCurve(
  19731. this.currentPoint.clone(),
  19732. new Vector2( aCP1x, aCP1y ),
  19733. new Vector2( aCP2x, aCP2y ),
  19734. new Vector2( aX, aY )
  19735. );
  19736. this.curves.push( curve );
  19737. this.currentPoint.set( aX, aY );
  19738. return this;
  19739. }
  19740. splineThru( pts /*Array of Vector*/ ) {
  19741. const npts = [ this.currentPoint.clone() ].concat( pts );
  19742. const curve = new SplineCurve( npts );
  19743. this.curves.push( curve );
  19744. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19745. return this;
  19746. }
  19747. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19748. const x0 = this.currentPoint.x;
  19749. const y0 = this.currentPoint.y;
  19750. this.absarc( aX + x0, aY + y0, aRadius,
  19751. aStartAngle, aEndAngle, aClockwise );
  19752. return this;
  19753. }
  19754. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19755. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19756. return this;
  19757. }
  19758. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19759. const x0 = this.currentPoint.x;
  19760. const y0 = this.currentPoint.y;
  19761. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19762. return this;
  19763. }
  19764. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19765. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19766. if ( this.curves.length > 0 ) {
  19767. // if a previous curve is present, attempt to join
  19768. const firstPoint = curve.getPoint( 0 );
  19769. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19770. this.lineTo( firstPoint.x, firstPoint.y );
  19771. }
  19772. }
  19773. this.curves.push( curve );
  19774. const lastPoint = curve.getPoint( 1 );
  19775. this.currentPoint.copy( lastPoint );
  19776. return this;
  19777. }
  19778. copy( source ) {
  19779. super.copy( source );
  19780. this.currentPoint.copy( source.currentPoint );
  19781. return this;
  19782. }
  19783. toJSON() {
  19784. const data = super.toJSON();
  19785. data.currentPoint = this.currentPoint.toArray();
  19786. return data;
  19787. }
  19788. fromJSON( json ) {
  19789. super.fromJSON( json );
  19790. this.currentPoint.fromArray( json.currentPoint );
  19791. return this;
  19792. }
  19793. }
  19794. class LatheGeometry extends BufferGeometry {
  19795. 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 ) {
  19796. super();
  19797. this.type = 'LatheGeometry';
  19798. this.parameters = {
  19799. points: points,
  19800. segments: segments,
  19801. phiStart: phiStart,
  19802. phiLength: phiLength
  19803. };
  19804. segments = Math.floor( segments );
  19805. // clamp phiLength so it's in range of [ 0, 2PI ]
  19806. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19807. // buffers
  19808. const indices = [];
  19809. const vertices = [];
  19810. const uvs = [];
  19811. const initNormals = [];
  19812. const normals = [];
  19813. // helper variables
  19814. const inverseSegments = 1.0 / segments;
  19815. const vertex = new Vector3();
  19816. const uv = new Vector2();
  19817. const normal = new Vector3();
  19818. const curNormal = new Vector3();
  19819. const prevNormal = new Vector3();
  19820. let dx = 0;
  19821. let dy = 0;
  19822. // pre-compute normals for initial "meridian"
  19823. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19824. switch ( j ) {
  19825. case 0: // special handling for 1st vertex on path
  19826. dx = points[ j + 1 ].x - points[ j ].x;
  19827. dy = points[ j + 1 ].y - points[ j ].y;
  19828. normal.x = dy * 1.0;
  19829. normal.y = - dx;
  19830. normal.z = dy * 0.0;
  19831. prevNormal.copy( normal );
  19832. normal.normalize();
  19833. initNormals.push( normal.x, normal.y, normal.z );
  19834. break;
  19835. case ( points.length - 1 ): // special handling for last Vertex on path
  19836. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19837. break;
  19838. default: // default handling for all vertices in between
  19839. dx = points[ j + 1 ].x - points[ j ].x;
  19840. dy = points[ j + 1 ].y - points[ j ].y;
  19841. normal.x = dy * 1.0;
  19842. normal.y = - dx;
  19843. normal.z = dy * 0.0;
  19844. curNormal.copy( normal );
  19845. normal.x += prevNormal.x;
  19846. normal.y += prevNormal.y;
  19847. normal.z += prevNormal.z;
  19848. normal.normalize();
  19849. initNormals.push( normal.x, normal.y, normal.z );
  19850. prevNormal.copy( curNormal );
  19851. }
  19852. }
  19853. // generate vertices, uvs and normals
  19854. for ( let i = 0; i <= segments; i ++ ) {
  19855. const phi = phiStart + i * inverseSegments * phiLength;
  19856. const sin = Math.sin( phi );
  19857. const cos = Math.cos( phi );
  19858. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19859. // vertex
  19860. vertex.x = points[ j ].x * sin;
  19861. vertex.y = points[ j ].y;
  19862. vertex.z = points[ j ].x * cos;
  19863. vertices.push( vertex.x, vertex.y, vertex.z );
  19864. // uv
  19865. uv.x = i / segments;
  19866. uv.y = j / ( points.length - 1 );
  19867. uvs.push( uv.x, uv.y );
  19868. // normal
  19869. const x = initNormals[ 3 * j + 0 ] * sin;
  19870. const y = initNormals[ 3 * j + 1 ];
  19871. const z = initNormals[ 3 * j + 0 ] * cos;
  19872. normals.push( x, y, z );
  19873. }
  19874. }
  19875. // indices
  19876. for ( let i = 0; i < segments; i ++ ) {
  19877. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19878. const base = j + i * points.length;
  19879. const a = base;
  19880. const b = base + points.length;
  19881. const c = base + points.length + 1;
  19882. const d = base + 1;
  19883. // faces
  19884. indices.push( a, b, d );
  19885. indices.push( c, d, b );
  19886. }
  19887. }
  19888. // build geometry
  19889. this.setIndex( indices );
  19890. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19891. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19892. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19893. }
  19894. static fromJSON( data ) {
  19895. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19896. }
  19897. }
  19898. class CapsuleGeometry extends LatheGeometry {
  19899. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19900. const path = new Path();
  19901. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19902. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19903. super( path.getPoints( capSegments ), radialSegments );
  19904. this.type = 'CapsuleGeometry';
  19905. this.parameters = {
  19906. radius: radius,
  19907. height: length,
  19908. capSegments: capSegments,
  19909. radialSegments: radialSegments,
  19910. };
  19911. }
  19912. static fromJSON( data ) {
  19913. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19914. }
  19915. }
  19916. class CircleGeometry extends BufferGeometry {
  19917. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19918. super();
  19919. this.type = 'CircleGeometry';
  19920. this.parameters = {
  19921. radius: radius,
  19922. segments: segments,
  19923. thetaStart: thetaStart,
  19924. thetaLength: thetaLength
  19925. };
  19926. segments = Math.max( 3, segments );
  19927. // buffers
  19928. const indices = [];
  19929. const vertices = [];
  19930. const normals = [];
  19931. const uvs = [];
  19932. // helper variables
  19933. const vertex = new Vector3();
  19934. const uv = new Vector2();
  19935. // center point
  19936. vertices.push( 0, 0, 0 );
  19937. normals.push( 0, 0, 1 );
  19938. uvs.push( 0.5, 0.5 );
  19939. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19940. const segment = thetaStart + s / segments * thetaLength;
  19941. // vertex
  19942. vertex.x = radius * Math.cos( segment );
  19943. vertex.y = radius * Math.sin( segment );
  19944. vertices.push( vertex.x, vertex.y, vertex.z );
  19945. // normal
  19946. normals.push( 0, 0, 1 );
  19947. // uvs
  19948. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19949. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19950. uvs.push( uv.x, uv.y );
  19951. }
  19952. // indices
  19953. for ( let i = 1; i <= segments; i ++ ) {
  19954. indices.push( i, i + 1, 0 );
  19955. }
  19956. // build geometry
  19957. this.setIndex( indices );
  19958. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19959. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19960. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19961. }
  19962. static fromJSON( data ) {
  19963. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19964. }
  19965. }
  19966. class CylinderGeometry extends BufferGeometry {
  19967. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19968. super();
  19969. this.type = 'CylinderGeometry';
  19970. this.parameters = {
  19971. radiusTop: radiusTop,
  19972. radiusBottom: radiusBottom,
  19973. height: height,
  19974. radialSegments: radialSegments,
  19975. heightSegments: heightSegments,
  19976. openEnded: openEnded,
  19977. thetaStart: thetaStart,
  19978. thetaLength: thetaLength
  19979. };
  19980. const scope = this;
  19981. radialSegments = Math.floor( radialSegments );
  19982. heightSegments = Math.floor( heightSegments );
  19983. // buffers
  19984. const indices = [];
  19985. const vertices = [];
  19986. const normals = [];
  19987. const uvs = [];
  19988. // helper variables
  19989. let index = 0;
  19990. const indexArray = [];
  19991. const halfHeight = height / 2;
  19992. let groupStart = 0;
  19993. // generate geometry
  19994. generateTorso();
  19995. if ( openEnded === false ) {
  19996. if ( radiusTop > 0 ) generateCap( true );
  19997. if ( radiusBottom > 0 ) generateCap( false );
  19998. }
  19999. // build geometry
  20000. this.setIndex( indices );
  20001. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20002. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20003. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20004. function generateTorso() {
  20005. const normal = new Vector3();
  20006. const vertex = new Vector3();
  20007. let groupCount = 0;
  20008. // this will be used to calculate the normal
  20009. const slope = ( radiusBottom - radiusTop ) / height;
  20010. // generate vertices, normals and uvs
  20011. for ( let y = 0; y <= heightSegments; y ++ ) {
  20012. const indexRow = [];
  20013. const v = y / heightSegments;
  20014. // calculate the radius of the current row
  20015. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20016. for ( let x = 0; x <= radialSegments; x ++ ) {
  20017. const u = x / radialSegments;
  20018. const theta = u * thetaLength + thetaStart;
  20019. const sinTheta = Math.sin( theta );
  20020. const cosTheta = Math.cos( theta );
  20021. // vertex
  20022. vertex.x = radius * sinTheta;
  20023. vertex.y = - v * height + halfHeight;
  20024. vertex.z = radius * cosTheta;
  20025. vertices.push( vertex.x, vertex.y, vertex.z );
  20026. // normal
  20027. normal.set( sinTheta, slope, cosTheta ).normalize();
  20028. normals.push( normal.x, normal.y, normal.z );
  20029. // uv
  20030. uvs.push( u, 1 - v );
  20031. // save index of vertex in respective row
  20032. indexRow.push( index ++ );
  20033. }
  20034. // now save vertices of the row in our index array
  20035. indexArray.push( indexRow );
  20036. }
  20037. // generate indices
  20038. for ( let x = 0; x < radialSegments; x ++ ) {
  20039. for ( let y = 0; y < heightSegments; y ++ ) {
  20040. // we use the index array to access the correct indices
  20041. const a = indexArray[ y ][ x ];
  20042. const b = indexArray[ y + 1 ][ x ];
  20043. const c = indexArray[ y + 1 ][ x + 1 ];
  20044. const d = indexArray[ y ][ x + 1 ];
  20045. // faces
  20046. indices.push( a, b, d );
  20047. indices.push( b, c, d );
  20048. // update group counter
  20049. groupCount += 6;
  20050. }
  20051. }
  20052. // add a group to the geometry. this will ensure multi material support
  20053. scope.addGroup( groupStart, groupCount, 0 );
  20054. // calculate new start value for groups
  20055. groupStart += groupCount;
  20056. }
  20057. function generateCap( top ) {
  20058. // save the index of the first center vertex
  20059. const centerIndexStart = index;
  20060. const uv = new Vector2();
  20061. const vertex = new Vector3();
  20062. let groupCount = 0;
  20063. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20064. const sign = ( top === true ) ? 1 : - 1;
  20065. // first we generate the center vertex data of the cap.
  20066. // because the geometry needs one set of uvs per face,
  20067. // we must generate a center vertex per face/segment
  20068. for ( let x = 1; x <= radialSegments; x ++ ) {
  20069. // vertex
  20070. vertices.push( 0, halfHeight * sign, 0 );
  20071. // normal
  20072. normals.push( 0, sign, 0 );
  20073. // uv
  20074. uvs.push( 0.5, 0.5 );
  20075. // increase index
  20076. index ++;
  20077. }
  20078. // save the index of the last center vertex
  20079. const centerIndexEnd = index;
  20080. // now we generate the surrounding vertices, normals and uvs
  20081. for ( let x = 0; x <= radialSegments; x ++ ) {
  20082. const u = x / radialSegments;
  20083. const theta = u * thetaLength + thetaStart;
  20084. const cosTheta = Math.cos( theta );
  20085. const sinTheta = Math.sin( theta );
  20086. // vertex
  20087. vertex.x = radius * sinTheta;
  20088. vertex.y = halfHeight * sign;
  20089. vertex.z = radius * cosTheta;
  20090. vertices.push( vertex.x, vertex.y, vertex.z );
  20091. // normal
  20092. normals.push( 0, sign, 0 );
  20093. // uv
  20094. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20095. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20096. uvs.push( uv.x, uv.y );
  20097. // increase index
  20098. index ++;
  20099. }
  20100. // generate indices
  20101. for ( let x = 0; x < radialSegments; x ++ ) {
  20102. const c = centerIndexStart + x;
  20103. const i = centerIndexEnd + x;
  20104. if ( top === true ) {
  20105. // face top
  20106. indices.push( i, i + 1, c );
  20107. } else {
  20108. // face bottom
  20109. indices.push( i + 1, i, c );
  20110. }
  20111. groupCount += 3;
  20112. }
  20113. // add a group to the geometry. this will ensure multi material support
  20114. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20115. // calculate new start value for groups
  20116. groupStart += groupCount;
  20117. }
  20118. }
  20119. static fromJSON( data ) {
  20120. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20121. }
  20122. }
  20123. class ConeGeometry extends CylinderGeometry {
  20124. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20125. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20126. this.type = 'ConeGeometry';
  20127. this.parameters = {
  20128. radius: radius,
  20129. height: height,
  20130. radialSegments: radialSegments,
  20131. heightSegments: heightSegments,
  20132. openEnded: openEnded,
  20133. thetaStart: thetaStart,
  20134. thetaLength: thetaLength
  20135. };
  20136. }
  20137. static fromJSON( data ) {
  20138. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20139. }
  20140. }
  20141. class PolyhedronGeometry extends BufferGeometry {
  20142. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20143. super();
  20144. this.type = 'PolyhedronGeometry';
  20145. this.parameters = {
  20146. vertices: vertices,
  20147. indices: indices,
  20148. radius: radius,
  20149. detail: detail
  20150. };
  20151. // default buffer data
  20152. const vertexBuffer = [];
  20153. const uvBuffer = [];
  20154. // the subdivision creates the vertex buffer data
  20155. subdivide( detail );
  20156. // all vertices should lie on a conceptual sphere with a given radius
  20157. applyRadius( radius );
  20158. // finally, create the uv data
  20159. generateUVs();
  20160. // build non-indexed geometry
  20161. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20162. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20163. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20164. if ( detail === 0 ) {
  20165. this.computeVertexNormals(); // flat normals
  20166. } else {
  20167. this.normalizeNormals(); // smooth normals
  20168. }
  20169. // helper functions
  20170. function subdivide( detail ) {
  20171. const a = new Vector3();
  20172. const b = new Vector3();
  20173. const c = new Vector3();
  20174. // iterate over all faces and apply a subdivison with the given detail value
  20175. for ( let i = 0; i < indices.length; i += 3 ) {
  20176. // get the vertices of the face
  20177. getVertexByIndex( indices[ i + 0 ], a );
  20178. getVertexByIndex( indices[ i + 1 ], b );
  20179. getVertexByIndex( indices[ i + 2 ], c );
  20180. // perform subdivision
  20181. subdivideFace( a, b, c, detail );
  20182. }
  20183. }
  20184. function subdivideFace( a, b, c, detail ) {
  20185. const cols = detail + 1;
  20186. // we use this multidimensional array as a data structure for creating the subdivision
  20187. const v = [];
  20188. // construct all of the vertices for this subdivision
  20189. for ( let i = 0; i <= cols; i ++ ) {
  20190. v[ i ] = [];
  20191. const aj = a.clone().lerp( c, i / cols );
  20192. const bj = b.clone().lerp( c, i / cols );
  20193. const rows = cols - i;
  20194. for ( let j = 0; j <= rows; j ++ ) {
  20195. if ( j === 0 && i === cols ) {
  20196. v[ i ][ j ] = aj;
  20197. } else {
  20198. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20199. }
  20200. }
  20201. }
  20202. // construct all of the faces
  20203. for ( let i = 0; i < cols; i ++ ) {
  20204. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20205. const k = Math.floor( j / 2 );
  20206. if ( j % 2 === 0 ) {
  20207. pushVertex( v[ i ][ k + 1 ] );
  20208. pushVertex( v[ i + 1 ][ k ] );
  20209. pushVertex( v[ i ][ k ] );
  20210. } else {
  20211. pushVertex( v[ i ][ k + 1 ] );
  20212. pushVertex( v[ i + 1 ][ k + 1 ] );
  20213. pushVertex( v[ i + 1 ][ k ] );
  20214. }
  20215. }
  20216. }
  20217. }
  20218. function applyRadius( radius ) {
  20219. const vertex = new Vector3();
  20220. // iterate over the entire buffer and apply the radius to each vertex
  20221. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20222. vertex.x = vertexBuffer[ i + 0 ];
  20223. vertex.y = vertexBuffer[ i + 1 ];
  20224. vertex.z = vertexBuffer[ i + 2 ];
  20225. vertex.normalize().multiplyScalar( radius );
  20226. vertexBuffer[ i + 0 ] = vertex.x;
  20227. vertexBuffer[ i + 1 ] = vertex.y;
  20228. vertexBuffer[ i + 2 ] = vertex.z;
  20229. }
  20230. }
  20231. function generateUVs() {
  20232. const vertex = new Vector3();
  20233. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20234. vertex.x = vertexBuffer[ i + 0 ];
  20235. vertex.y = vertexBuffer[ i + 1 ];
  20236. vertex.z = vertexBuffer[ i + 2 ];
  20237. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20238. const v = inclination( vertex ) / Math.PI + 0.5;
  20239. uvBuffer.push( u, 1 - v );
  20240. }
  20241. correctUVs();
  20242. correctSeam();
  20243. }
  20244. function correctSeam() {
  20245. // handle case when face straddles the seam, see #3269
  20246. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20247. // uv data of a single face
  20248. const x0 = uvBuffer[ i + 0 ];
  20249. const x1 = uvBuffer[ i + 2 ];
  20250. const x2 = uvBuffer[ i + 4 ];
  20251. const max = Math.max( x0, x1, x2 );
  20252. const min = Math.min( x0, x1, x2 );
  20253. // 0.9 is somewhat arbitrary
  20254. if ( max > 0.9 && min < 0.1 ) {
  20255. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20256. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20257. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20258. }
  20259. }
  20260. }
  20261. function pushVertex( vertex ) {
  20262. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20263. }
  20264. function getVertexByIndex( index, vertex ) {
  20265. const stride = index * 3;
  20266. vertex.x = vertices[ stride + 0 ];
  20267. vertex.y = vertices[ stride + 1 ];
  20268. vertex.z = vertices[ stride + 2 ];
  20269. }
  20270. function correctUVs() {
  20271. const a = new Vector3();
  20272. const b = new Vector3();
  20273. const c = new Vector3();
  20274. const centroid = new Vector3();
  20275. const uvA = new Vector2();
  20276. const uvB = new Vector2();
  20277. const uvC = new Vector2();
  20278. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20279. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20280. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20281. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20282. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20283. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20284. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20285. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20286. const azi = azimuth( centroid );
  20287. correctUV( uvA, j + 0, a, azi );
  20288. correctUV( uvB, j + 2, b, azi );
  20289. correctUV( uvC, j + 4, c, azi );
  20290. }
  20291. }
  20292. function correctUV( uv, stride, vector, azimuth ) {
  20293. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20294. uvBuffer[ stride ] = uv.x - 1;
  20295. }
  20296. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20297. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20298. }
  20299. }
  20300. // Angle around the Y axis, counter-clockwise when looking from above.
  20301. function azimuth( vector ) {
  20302. return Math.atan2( vector.z, - vector.x );
  20303. }
  20304. // Angle above the XZ plane.
  20305. function inclination( vector ) {
  20306. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20307. }
  20308. }
  20309. static fromJSON( data ) {
  20310. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20311. }
  20312. }
  20313. class DodecahedronGeometry extends PolyhedronGeometry {
  20314. constructor( radius = 1, detail = 0 ) {
  20315. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20316. const r = 1 / t;
  20317. const vertices = [
  20318. // (±1, ±1, ±1)
  20319. - 1, - 1, - 1, - 1, - 1, 1,
  20320. - 1, 1, - 1, - 1, 1, 1,
  20321. 1, - 1, - 1, 1, - 1, 1,
  20322. 1, 1, - 1, 1, 1, 1,
  20323. // (0, ±1/φ, ±φ)
  20324. 0, - r, - t, 0, - r, t,
  20325. 0, r, - t, 0, r, t,
  20326. // (±1/φ, ±φ, 0)
  20327. - r, - t, 0, - r, t, 0,
  20328. r, - t, 0, r, t, 0,
  20329. // (±φ, 0, ±1/φ)
  20330. - t, 0, - r, t, 0, - r,
  20331. - t, 0, r, t, 0, r
  20332. ];
  20333. const indices = [
  20334. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20335. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20336. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20337. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20338. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20339. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20340. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20341. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20342. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20343. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20344. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20345. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20346. ];
  20347. super( vertices, indices, radius, detail );
  20348. this.type = 'DodecahedronGeometry';
  20349. this.parameters = {
  20350. radius: radius,
  20351. detail: detail
  20352. };
  20353. }
  20354. static fromJSON( data ) {
  20355. return new DodecahedronGeometry( data.radius, data.detail );
  20356. }
  20357. }
  20358. const _v0 = /*@__PURE__*/ new Vector3();
  20359. const _v1$1 = /*@__PURE__*/ new Vector3();
  20360. const _normal = /*@__PURE__*/ new Vector3();
  20361. const _triangle = /*@__PURE__*/ new Triangle();
  20362. class EdgesGeometry extends BufferGeometry {
  20363. constructor( geometry = null, thresholdAngle = 1 ) {
  20364. super();
  20365. this.type = 'EdgesGeometry';
  20366. this.parameters = {
  20367. geometry: geometry,
  20368. thresholdAngle: thresholdAngle
  20369. };
  20370. if ( geometry !== null ) {
  20371. const precisionPoints = 4;
  20372. const precision = Math.pow( 10, precisionPoints );
  20373. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20374. const indexAttr = geometry.getIndex();
  20375. const positionAttr = geometry.getAttribute( 'position' );
  20376. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20377. const indexArr = [ 0, 0, 0 ];
  20378. const vertKeys = [ 'a', 'b', 'c' ];
  20379. const hashes = new Array( 3 );
  20380. const edgeData = {};
  20381. const vertices = [];
  20382. for ( let i = 0; i < indexCount; i += 3 ) {
  20383. if ( indexAttr ) {
  20384. indexArr[ 0 ] = indexAttr.getX( i );
  20385. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20386. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20387. } else {
  20388. indexArr[ 0 ] = i;
  20389. indexArr[ 1 ] = i + 1;
  20390. indexArr[ 2 ] = i + 2;
  20391. }
  20392. const { a, b, c } = _triangle;
  20393. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20394. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20395. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20396. _triangle.getNormal( _normal );
  20397. // create hashes for the edge from the vertices
  20398. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20399. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20400. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20401. // skip degenerate triangles
  20402. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20403. continue;
  20404. }
  20405. // iterate over every edge
  20406. for ( let j = 0; j < 3; j ++ ) {
  20407. // get the first and next vertex making up the edge
  20408. const jNext = ( j + 1 ) % 3;
  20409. const vecHash0 = hashes[ j ];
  20410. const vecHash1 = hashes[ jNext ];
  20411. const v0 = _triangle[ vertKeys[ j ] ];
  20412. const v1 = _triangle[ vertKeys[ jNext ] ];
  20413. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20414. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20415. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20416. // if we found a sibling edge add it into the vertex array if
  20417. // it meets the angle threshold and delete the edge from the map.
  20418. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20419. vertices.push( v0.x, v0.y, v0.z );
  20420. vertices.push( v1.x, v1.y, v1.z );
  20421. }
  20422. edgeData[ reverseHash ] = null;
  20423. } else if ( ! ( hash in edgeData ) ) {
  20424. // if we've already got an edge here then skip adding a new one
  20425. edgeData[ hash ] = {
  20426. index0: indexArr[ j ],
  20427. index1: indexArr[ jNext ],
  20428. normal: _normal.clone(),
  20429. };
  20430. }
  20431. }
  20432. }
  20433. // iterate over all remaining, unmatched edges and add them to the vertex array
  20434. for ( const key in edgeData ) {
  20435. if ( edgeData[ key ] ) {
  20436. const { index0, index1 } = edgeData[ key ];
  20437. _v0.fromBufferAttribute( positionAttr, index0 );
  20438. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20439. vertices.push( _v0.x, _v0.y, _v0.z );
  20440. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20441. }
  20442. }
  20443. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20444. }
  20445. }
  20446. }
  20447. class Shape extends Path {
  20448. constructor( points ) {
  20449. super( points );
  20450. this.uuid = generateUUID();
  20451. this.type = 'Shape';
  20452. this.holes = [];
  20453. }
  20454. getPointsHoles( divisions ) {
  20455. const holesPts = [];
  20456. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20457. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20458. }
  20459. return holesPts;
  20460. }
  20461. // get points of shape and holes (keypoints based on segments parameter)
  20462. extractPoints( divisions ) {
  20463. return {
  20464. shape: this.getPoints( divisions ),
  20465. holes: this.getPointsHoles( divisions )
  20466. };
  20467. }
  20468. copy( source ) {
  20469. super.copy( source );
  20470. this.holes = [];
  20471. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20472. const hole = source.holes[ i ];
  20473. this.holes.push( hole.clone() );
  20474. }
  20475. return this;
  20476. }
  20477. toJSON() {
  20478. const data = super.toJSON();
  20479. data.uuid = this.uuid;
  20480. data.holes = [];
  20481. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20482. const hole = this.holes[ i ];
  20483. data.holes.push( hole.toJSON() );
  20484. }
  20485. return data;
  20486. }
  20487. fromJSON( json ) {
  20488. super.fromJSON( json );
  20489. this.uuid = json.uuid;
  20490. this.holes = [];
  20491. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20492. const hole = json.holes[ i ];
  20493. this.holes.push( new Path().fromJSON( hole ) );
  20494. }
  20495. return this;
  20496. }
  20497. }
  20498. /**
  20499. * Port from https://github.com/mapbox/earcut (v2.2.2)
  20500. */
  20501. const Earcut = {
  20502. triangulate: function ( data, holeIndices, dim = 2 ) {
  20503. const hasHoles = holeIndices && holeIndices.length;
  20504. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20505. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20506. const triangles = [];
  20507. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20508. let minX, minY, maxX, maxY, x, y, invSize;
  20509. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20510. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20511. if ( data.length > 80 * dim ) {
  20512. minX = maxX = data[ 0 ];
  20513. minY = maxY = data[ 1 ];
  20514. for ( let i = dim; i < outerLen; i += dim ) {
  20515. x = data[ i ];
  20516. y = data[ i + 1 ];
  20517. if ( x < minX ) minX = x;
  20518. if ( y < minY ) minY = y;
  20519. if ( x > maxX ) maxX = x;
  20520. if ( y > maxY ) maxY = y;
  20521. }
  20522. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20523. invSize = Math.max( maxX - minX, maxY - minY );
  20524. invSize = invSize !== 0 ? 1 / invSize : 0;
  20525. }
  20526. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20527. return triangles;
  20528. }
  20529. };
  20530. // create a circular doubly linked list from polygon points in the specified winding order
  20531. function linkedList( data, start, end, dim, clockwise ) {
  20532. let i, last;
  20533. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20534. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20535. } else {
  20536. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20537. }
  20538. if ( last && equals( last, last.next ) ) {
  20539. removeNode( last );
  20540. last = last.next;
  20541. }
  20542. return last;
  20543. }
  20544. // eliminate colinear or duplicate points
  20545. function filterPoints( start, end ) {
  20546. if ( ! start ) return start;
  20547. if ( ! end ) end = start;
  20548. let p = start,
  20549. again;
  20550. do {
  20551. again = false;
  20552. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20553. removeNode( p );
  20554. p = end = p.prev;
  20555. if ( p === p.next ) break;
  20556. again = true;
  20557. } else {
  20558. p = p.next;
  20559. }
  20560. } while ( again || p !== end );
  20561. return end;
  20562. }
  20563. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20564. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20565. if ( ! ear ) return;
  20566. // interlink polygon nodes in z-order
  20567. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20568. let stop = ear,
  20569. prev, next;
  20570. // iterate through ears, slicing them one by one
  20571. while ( ear.prev !== ear.next ) {
  20572. prev = ear.prev;
  20573. next = ear.next;
  20574. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20575. // cut off the triangle
  20576. triangles.push( prev.i / dim );
  20577. triangles.push( ear.i / dim );
  20578. triangles.push( next.i / dim );
  20579. removeNode( ear );
  20580. // skipping the next vertex leads to less sliver triangles
  20581. ear = next.next;
  20582. stop = next.next;
  20583. continue;
  20584. }
  20585. ear = next;
  20586. // if we looped through the whole remaining polygon and can't find any more ears
  20587. if ( ear === stop ) {
  20588. // try filtering points and slicing again
  20589. if ( ! pass ) {
  20590. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20591. // if this didn't work, try curing all small self-intersections locally
  20592. } else if ( pass === 1 ) {
  20593. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20594. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20595. // as a last resort, try splitting the remaining polygon into two
  20596. } else if ( pass === 2 ) {
  20597. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20598. }
  20599. break;
  20600. }
  20601. }
  20602. }
  20603. // check whether a polygon node forms a valid ear with adjacent nodes
  20604. function isEar( ear ) {
  20605. const a = ear.prev,
  20606. b = ear,
  20607. c = ear.next;
  20608. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20609. // now make sure we don't have other points inside the potential ear
  20610. let p = ear.next.next;
  20611. while ( p !== ear.prev ) {
  20612. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20613. area( p.prev, p, p.next ) >= 0 ) return false;
  20614. p = p.next;
  20615. }
  20616. return true;
  20617. }
  20618. function isEarHashed( ear, minX, minY, invSize ) {
  20619. const a = ear.prev,
  20620. b = ear,
  20621. c = ear.next;
  20622. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20623. // triangle bbox; min & max are calculated like this for speed
  20624. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20625. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20626. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20627. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20628. // z-order range for the current triangle bbox;
  20629. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20630. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20631. let p = ear.prevZ,
  20632. n = ear.nextZ;
  20633. // look for points inside the triangle in both directions
  20634. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20635. if ( p !== ear.prev && p !== ear.next &&
  20636. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20637. area( p.prev, p, p.next ) >= 0 ) return false;
  20638. p = p.prevZ;
  20639. if ( n !== ear.prev && n !== ear.next &&
  20640. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20641. area( n.prev, n, n.next ) >= 0 ) return false;
  20642. n = n.nextZ;
  20643. }
  20644. // look for remaining points in decreasing z-order
  20645. while ( p && p.z >= minZ ) {
  20646. if ( p !== ear.prev && p !== ear.next &&
  20647. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20648. area( p.prev, p, p.next ) >= 0 ) return false;
  20649. p = p.prevZ;
  20650. }
  20651. // look for remaining points in increasing z-order
  20652. while ( n && n.z <= maxZ ) {
  20653. if ( n !== ear.prev && n !== ear.next &&
  20654. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20655. area( n.prev, n, n.next ) >= 0 ) return false;
  20656. n = n.nextZ;
  20657. }
  20658. return true;
  20659. }
  20660. // go through all polygon nodes and cure small local self-intersections
  20661. function cureLocalIntersections( start, triangles, dim ) {
  20662. let p = start;
  20663. do {
  20664. const a = p.prev,
  20665. b = p.next.next;
  20666. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20667. triangles.push( a.i / dim );
  20668. triangles.push( p.i / dim );
  20669. triangles.push( b.i / dim );
  20670. // remove two nodes involved
  20671. removeNode( p );
  20672. removeNode( p.next );
  20673. p = start = b;
  20674. }
  20675. p = p.next;
  20676. } while ( p !== start );
  20677. return filterPoints( p );
  20678. }
  20679. // try splitting polygon into two and triangulate them independently
  20680. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20681. // look for a valid diagonal that divides the polygon into two
  20682. let a = start;
  20683. do {
  20684. let b = a.next.next;
  20685. while ( b !== a.prev ) {
  20686. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20687. // split the polygon in two by the diagonal
  20688. let c = splitPolygon( a, b );
  20689. // filter colinear points around the cuts
  20690. a = filterPoints( a, a.next );
  20691. c = filterPoints( c, c.next );
  20692. // run earcut on each half
  20693. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20694. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20695. return;
  20696. }
  20697. b = b.next;
  20698. }
  20699. a = a.next;
  20700. } while ( a !== start );
  20701. }
  20702. // link every hole into the outer loop, producing a single-ring polygon without holes
  20703. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20704. const queue = [];
  20705. let i, len, start, end, list;
  20706. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20707. start = holeIndices[ i ] * dim;
  20708. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20709. list = linkedList( data, start, end, dim, false );
  20710. if ( list === list.next ) list.steiner = true;
  20711. queue.push( getLeftmost( list ) );
  20712. }
  20713. queue.sort( compareX );
  20714. // process holes from left to right
  20715. for ( i = 0; i < queue.length; i ++ ) {
  20716. eliminateHole( queue[ i ], outerNode );
  20717. outerNode = filterPoints( outerNode, outerNode.next );
  20718. }
  20719. return outerNode;
  20720. }
  20721. function compareX( a, b ) {
  20722. return a.x - b.x;
  20723. }
  20724. // find a bridge between vertices that connects hole with an outer ring and link it
  20725. function eliminateHole( hole, outerNode ) {
  20726. outerNode = findHoleBridge( hole, outerNode );
  20727. if ( outerNode ) {
  20728. const b = splitPolygon( outerNode, hole );
  20729. // filter collinear points around the cuts
  20730. filterPoints( outerNode, outerNode.next );
  20731. filterPoints( b, b.next );
  20732. }
  20733. }
  20734. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20735. function findHoleBridge( hole, outerNode ) {
  20736. let p = outerNode;
  20737. const hx = hole.x;
  20738. const hy = hole.y;
  20739. let qx = - Infinity, m;
  20740. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20741. // segment's endpoint with lesser x will be potential connection point
  20742. do {
  20743. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20744. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20745. if ( x <= hx && x > qx ) {
  20746. qx = x;
  20747. if ( x === hx ) {
  20748. if ( hy === p.y ) return p;
  20749. if ( hy === p.next.y ) return p.next;
  20750. }
  20751. m = p.x < p.next.x ? p : p.next;
  20752. }
  20753. }
  20754. p = p.next;
  20755. } while ( p !== outerNode );
  20756. if ( ! m ) return null;
  20757. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  20758. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20759. // if there are no points found, we have a valid connection;
  20760. // otherwise choose the point of the minimum angle with the ray as connection point
  20761. const stop = m,
  20762. mx = m.x,
  20763. my = m.y;
  20764. let tanMin = Infinity, tan;
  20765. p = m;
  20766. do {
  20767. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20768. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20769. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20770. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20771. m = p;
  20772. tanMin = tan;
  20773. }
  20774. }
  20775. p = p.next;
  20776. } while ( p !== stop );
  20777. return m;
  20778. }
  20779. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20780. function sectorContainsSector( m, p ) {
  20781. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20782. }
  20783. // interlink polygon nodes in z-order
  20784. function indexCurve( start, minX, minY, invSize ) {
  20785. let p = start;
  20786. do {
  20787. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20788. p.prevZ = p.prev;
  20789. p.nextZ = p.next;
  20790. p = p.next;
  20791. } while ( p !== start );
  20792. p.prevZ.nextZ = null;
  20793. p.prevZ = null;
  20794. sortLinked( p );
  20795. }
  20796. // Simon Tatham's linked list merge sort algorithm
  20797. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20798. function sortLinked( list ) {
  20799. let i, p, q, e, tail, numMerges, pSize, qSize,
  20800. inSize = 1;
  20801. do {
  20802. p = list;
  20803. list = null;
  20804. tail = null;
  20805. numMerges = 0;
  20806. while ( p ) {
  20807. numMerges ++;
  20808. q = p;
  20809. pSize = 0;
  20810. for ( i = 0; i < inSize; i ++ ) {
  20811. pSize ++;
  20812. q = q.nextZ;
  20813. if ( ! q ) break;
  20814. }
  20815. qSize = inSize;
  20816. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20817. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20818. e = p;
  20819. p = p.nextZ;
  20820. pSize --;
  20821. } else {
  20822. e = q;
  20823. q = q.nextZ;
  20824. qSize --;
  20825. }
  20826. if ( tail ) tail.nextZ = e;
  20827. else list = e;
  20828. e.prevZ = tail;
  20829. tail = e;
  20830. }
  20831. p = q;
  20832. }
  20833. tail.nextZ = null;
  20834. inSize *= 2;
  20835. } while ( numMerges > 1 );
  20836. return list;
  20837. }
  20838. // z-order of a point given coords and inverse of the longer side of data bbox
  20839. function zOrder( x, y, minX, minY, invSize ) {
  20840. // coords are transformed into non-negative 15-bit integer range
  20841. x = 32767 * ( x - minX ) * invSize;
  20842. y = 32767 * ( y - minY ) * invSize;
  20843. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20844. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20845. x = ( x | ( x << 2 ) ) & 0x33333333;
  20846. x = ( x | ( x << 1 ) ) & 0x55555555;
  20847. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20848. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20849. y = ( y | ( y << 2 ) ) & 0x33333333;
  20850. y = ( y | ( y << 1 ) ) & 0x55555555;
  20851. return x | ( y << 1 );
  20852. }
  20853. // find the leftmost node of a polygon ring
  20854. function getLeftmost( start ) {
  20855. let p = start,
  20856. leftmost = start;
  20857. do {
  20858. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20859. p = p.next;
  20860. } while ( p !== start );
  20861. return leftmost;
  20862. }
  20863. // check if a point lies within a convex triangle
  20864. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20865. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20866. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20867. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20868. }
  20869. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20870. function isValidDiagonal( a, b ) {
  20871. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  20872. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20873. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20874. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20875. }
  20876. // signed area of a triangle
  20877. function area( p, q, r ) {
  20878. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20879. }
  20880. // check if two points are equal
  20881. function equals( p1, p2 ) {
  20882. return p1.x === p2.x && p1.y === p2.y;
  20883. }
  20884. // check if two segments intersect
  20885. function intersects( p1, q1, p2, q2 ) {
  20886. const o1 = sign( area( p1, q1, p2 ) );
  20887. const o2 = sign( area( p1, q1, q2 ) );
  20888. const o3 = sign( area( p2, q2, p1 ) );
  20889. const o4 = sign( area( p2, q2, q1 ) );
  20890. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20891. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20892. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20893. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20894. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20895. return false;
  20896. }
  20897. // for collinear points p, q, r, check if point q lies on segment pr
  20898. function onSegment( p, q, r ) {
  20899. 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 );
  20900. }
  20901. function sign( num ) {
  20902. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20903. }
  20904. // check if a polygon diagonal intersects any polygon segments
  20905. function intersectsPolygon( a, b ) {
  20906. let p = a;
  20907. do {
  20908. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20909. intersects( p, p.next, a, b ) ) return true;
  20910. p = p.next;
  20911. } while ( p !== a );
  20912. return false;
  20913. }
  20914. // check if a polygon diagonal is locally inside the polygon
  20915. function locallyInside( a, b ) {
  20916. return area( a.prev, a, a.next ) < 0 ?
  20917. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20918. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20919. }
  20920. // check if the middle point of a polygon diagonal is inside the polygon
  20921. function middleInside( a, b ) {
  20922. let p = a,
  20923. inside = false;
  20924. const px = ( a.x + b.x ) / 2,
  20925. py = ( a.y + b.y ) / 2;
  20926. do {
  20927. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20928. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20929. inside = ! inside;
  20930. p = p.next;
  20931. } while ( p !== a );
  20932. return inside;
  20933. }
  20934. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20935. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20936. function splitPolygon( a, b ) {
  20937. const a2 = new Node( a.i, a.x, a.y ),
  20938. b2 = new Node( b.i, b.x, b.y ),
  20939. an = a.next,
  20940. bp = b.prev;
  20941. a.next = b;
  20942. b.prev = a;
  20943. a2.next = an;
  20944. an.prev = a2;
  20945. b2.next = a2;
  20946. a2.prev = b2;
  20947. bp.next = b2;
  20948. b2.prev = bp;
  20949. return b2;
  20950. }
  20951. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20952. function insertNode( i, x, y, last ) {
  20953. const p = new Node( i, x, y );
  20954. if ( ! last ) {
  20955. p.prev = p;
  20956. p.next = p;
  20957. } else {
  20958. p.next = last.next;
  20959. p.prev = last;
  20960. last.next.prev = p;
  20961. last.next = p;
  20962. }
  20963. return p;
  20964. }
  20965. function removeNode( p ) {
  20966. p.next.prev = p.prev;
  20967. p.prev.next = p.next;
  20968. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20969. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20970. }
  20971. function Node( i, x, y ) {
  20972. // vertex index in coordinates array
  20973. this.i = i;
  20974. // vertex coordinates
  20975. this.x = x;
  20976. this.y = y;
  20977. // previous and next vertex nodes in a polygon ring
  20978. this.prev = null;
  20979. this.next = null;
  20980. // z-order curve value
  20981. this.z = null;
  20982. // previous and next nodes in z-order
  20983. this.prevZ = null;
  20984. this.nextZ = null;
  20985. // indicates whether this is a steiner point
  20986. this.steiner = false;
  20987. }
  20988. function signedArea( data, start, end, dim ) {
  20989. let sum = 0;
  20990. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20991. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20992. j = i;
  20993. }
  20994. return sum;
  20995. }
  20996. class ShapeUtils {
  20997. // calculate area of the contour polygon
  20998. static area( contour ) {
  20999. const n = contour.length;
  21000. let a = 0.0;
  21001. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21002. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21003. }
  21004. return a * 0.5;
  21005. }
  21006. static isClockWise( pts ) {
  21007. return ShapeUtils.area( pts ) < 0;
  21008. }
  21009. static triangulateShape( contour, holes ) {
  21010. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21011. const holeIndices = []; // array of hole indices
  21012. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21013. removeDupEndPts( contour );
  21014. addContour( vertices, contour );
  21015. //
  21016. let holeIndex = contour.length;
  21017. holes.forEach( removeDupEndPts );
  21018. for ( let i = 0; i < holes.length; i ++ ) {
  21019. holeIndices.push( holeIndex );
  21020. holeIndex += holes[ i ].length;
  21021. addContour( vertices, holes[ i ] );
  21022. }
  21023. //
  21024. const triangles = Earcut.triangulate( vertices, holeIndices );
  21025. //
  21026. for ( let i = 0; i < triangles.length; i += 3 ) {
  21027. faces.push( triangles.slice( i, i + 3 ) );
  21028. }
  21029. return faces;
  21030. }
  21031. }
  21032. function removeDupEndPts( points ) {
  21033. const l = points.length;
  21034. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21035. points.pop();
  21036. }
  21037. }
  21038. function addContour( vertices, contour ) {
  21039. for ( let i = 0; i < contour.length; i ++ ) {
  21040. vertices.push( contour[ i ].x );
  21041. vertices.push( contour[ i ].y );
  21042. }
  21043. }
  21044. /**
  21045. * Creates extruded geometry from a path shape.
  21046. *
  21047. * parameters = {
  21048. *
  21049. * curveSegments: <int>, // number of points on the curves
  21050. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21051. * depth: <float>, // Depth to extrude the shape
  21052. *
  21053. * bevelEnabled: <bool>, // turn on bevel
  21054. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21055. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21056. * bevelOffset: <float>, // how far from shape outline does bevel start
  21057. * bevelSegments: <int>, // number of bevel layers
  21058. *
  21059. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21060. *
  21061. * UVGenerator: <Object> // object that provides UV generator functions
  21062. *
  21063. * }
  21064. */
  21065. class ExtrudeGeometry extends BufferGeometry {
  21066. 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 = {} ) {
  21067. super();
  21068. this.type = 'ExtrudeGeometry';
  21069. this.parameters = {
  21070. shapes: shapes,
  21071. options: options
  21072. };
  21073. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21074. const scope = this;
  21075. const verticesArray = [];
  21076. const uvArray = [];
  21077. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21078. const shape = shapes[ i ];
  21079. addShape( shape );
  21080. }
  21081. // build geometry
  21082. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21083. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21084. this.computeVertexNormals();
  21085. // functions
  21086. function addShape( shape ) {
  21087. const placeholder = [];
  21088. // options
  21089. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21090. const steps = options.steps !== undefined ? options.steps : 1;
  21091. const depth = options.depth !== undefined ? options.depth : 1;
  21092. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21093. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21094. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21095. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21096. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21097. const extrudePath = options.extrudePath;
  21098. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21099. //
  21100. let extrudePts, extrudeByPath = false;
  21101. let splineTube, binormal, normal, position2;
  21102. if ( extrudePath ) {
  21103. extrudePts = extrudePath.getSpacedPoints( steps );
  21104. extrudeByPath = true;
  21105. bevelEnabled = false; // bevels not supported for path extrusion
  21106. // SETUP TNB variables
  21107. // TODO1 - have a .isClosed in spline?
  21108. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21109. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21110. binormal = new Vector3();
  21111. normal = new Vector3();
  21112. position2 = new Vector3();
  21113. }
  21114. // Safeguards if bevels are not enabled
  21115. if ( ! bevelEnabled ) {
  21116. bevelSegments = 0;
  21117. bevelThickness = 0;
  21118. bevelSize = 0;
  21119. bevelOffset = 0;
  21120. }
  21121. // Variables initialization
  21122. const shapePoints = shape.extractPoints( curveSegments );
  21123. let vertices = shapePoints.shape;
  21124. const holes = shapePoints.holes;
  21125. const reverse = ! ShapeUtils.isClockWise( vertices );
  21126. if ( reverse ) {
  21127. vertices = vertices.reverse();
  21128. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21129. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21130. const ahole = holes[ h ];
  21131. if ( ShapeUtils.isClockWise( ahole ) ) {
  21132. holes[ h ] = ahole.reverse();
  21133. }
  21134. }
  21135. }
  21136. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21137. /* Vertices */
  21138. const contour = vertices; // vertices has all points but contour has only points of circumference
  21139. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21140. const ahole = holes[ h ];
  21141. vertices = vertices.concat( ahole );
  21142. }
  21143. function scalePt2( pt, vec, size ) {
  21144. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21145. return vec.clone().multiplyScalar( size ).add( pt );
  21146. }
  21147. const vlen = vertices.length, flen = faces.length;
  21148. // Find directions for point movement
  21149. function getBevelVec( inPt, inPrev, inNext ) {
  21150. // computes for inPt the corresponding point inPt' on a new contour
  21151. // shifted by 1 unit (length of normalized vector) to the left
  21152. // if we walk along contour clockwise, this new contour is outside the old one
  21153. //
  21154. // inPt' is the intersection of the two lines parallel to the two
  21155. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21156. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21157. // good reading for geometry algorithms (here: line-line intersection)
  21158. // http://geomalgorithms.com/a05-_intersect-1.html
  21159. const v_prev_x = inPt.x - inPrev.x,
  21160. v_prev_y = inPt.y - inPrev.y;
  21161. const v_next_x = inNext.x - inPt.x,
  21162. v_next_y = inNext.y - inPt.y;
  21163. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21164. // check for collinear edges
  21165. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21166. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21167. // not collinear
  21168. // length of vectors for normalizing
  21169. const v_prev_len = Math.sqrt( v_prev_lensq );
  21170. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21171. // shift adjacent points by unit vectors to the left
  21172. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21173. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21174. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21175. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21176. // scaling factor for v_prev to intersection point
  21177. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21178. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21179. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21180. // vector from inPt to intersection point
  21181. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21182. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21183. // Don't normalize!, otherwise sharp corners become ugly
  21184. // but prevent crazy spikes
  21185. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21186. if ( v_trans_lensq <= 2 ) {
  21187. return new Vector2( v_trans_x, v_trans_y );
  21188. } else {
  21189. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21190. }
  21191. } else {
  21192. // handle special case of collinear edges
  21193. let direction_eq = false; // assumes: opposite
  21194. if ( v_prev_x > Number.EPSILON ) {
  21195. if ( v_next_x > Number.EPSILON ) {
  21196. direction_eq = true;
  21197. }
  21198. } else {
  21199. if ( v_prev_x < - Number.EPSILON ) {
  21200. if ( v_next_x < - Number.EPSILON ) {
  21201. direction_eq = true;
  21202. }
  21203. } else {
  21204. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21205. direction_eq = true;
  21206. }
  21207. }
  21208. }
  21209. if ( direction_eq ) {
  21210. // console.log("Warning: lines are a straight sequence");
  21211. v_trans_x = - v_prev_y;
  21212. v_trans_y = v_prev_x;
  21213. shrink_by = Math.sqrt( v_prev_lensq );
  21214. } else {
  21215. // console.log("Warning: lines are a straight spike");
  21216. v_trans_x = v_prev_x;
  21217. v_trans_y = v_prev_y;
  21218. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21219. }
  21220. }
  21221. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21222. }
  21223. const contourMovements = [];
  21224. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21225. if ( j === il ) j = 0;
  21226. if ( k === il ) k = 0;
  21227. // (j)---(i)---(k)
  21228. // console.log('i,j,k', i, j , k)
  21229. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21230. }
  21231. const holesMovements = [];
  21232. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21233. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21234. const ahole = holes[ h ];
  21235. oneHoleMovements = [];
  21236. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21237. if ( j === il ) j = 0;
  21238. if ( k === il ) k = 0;
  21239. // (j)---(i)---(k)
  21240. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21241. }
  21242. holesMovements.push( oneHoleMovements );
  21243. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21244. }
  21245. // Loop bevelSegments, 1 for the front, 1 for the back
  21246. for ( let b = 0; b < bevelSegments; b ++ ) {
  21247. //for ( b = bevelSegments; b > 0; b -- ) {
  21248. const t = b / bevelSegments;
  21249. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21250. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21251. // contract shape
  21252. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21253. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21254. v( vert.x, vert.y, - z );
  21255. }
  21256. // expand holes
  21257. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21258. const ahole = holes[ h ];
  21259. oneHoleMovements = holesMovements[ h ];
  21260. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21261. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21262. v( vert.x, vert.y, - z );
  21263. }
  21264. }
  21265. }
  21266. const bs = bevelSize + bevelOffset;
  21267. // Back facing vertices
  21268. for ( let i = 0; i < vlen; i ++ ) {
  21269. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21270. if ( ! extrudeByPath ) {
  21271. v( vert.x, vert.y, 0 );
  21272. } else {
  21273. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21274. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21275. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21276. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21277. v( position2.x, position2.y, position2.z );
  21278. }
  21279. }
  21280. // Add stepped vertices...
  21281. // Including front facing vertices
  21282. for ( let s = 1; s <= steps; s ++ ) {
  21283. for ( let i = 0; i < vlen; i ++ ) {
  21284. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21285. if ( ! extrudeByPath ) {
  21286. v( vert.x, vert.y, depth / steps * s );
  21287. } else {
  21288. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21289. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21290. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21291. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21292. v( position2.x, position2.y, position2.z );
  21293. }
  21294. }
  21295. }
  21296. // Add bevel segments planes
  21297. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21298. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21299. const t = b / bevelSegments;
  21300. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21301. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21302. // contract shape
  21303. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21304. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21305. v( vert.x, vert.y, depth + z );
  21306. }
  21307. // expand holes
  21308. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21309. const ahole = holes[ h ];
  21310. oneHoleMovements = holesMovements[ h ];
  21311. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21312. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21313. if ( ! extrudeByPath ) {
  21314. v( vert.x, vert.y, depth + z );
  21315. } else {
  21316. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21317. }
  21318. }
  21319. }
  21320. }
  21321. /* Faces */
  21322. // Top and bottom faces
  21323. buildLidFaces();
  21324. // Sides faces
  21325. buildSideFaces();
  21326. ///// Internal functions
  21327. function buildLidFaces() {
  21328. const start = verticesArray.length / 3;
  21329. if ( bevelEnabled ) {
  21330. let layer = 0; // steps + 1
  21331. let offset = vlen * layer;
  21332. // Bottom faces
  21333. for ( let i = 0; i < flen; i ++ ) {
  21334. const face = faces[ i ];
  21335. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21336. }
  21337. layer = steps + bevelSegments * 2;
  21338. offset = vlen * layer;
  21339. // Top faces
  21340. for ( let i = 0; i < flen; i ++ ) {
  21341. const face = faces[ i ];
  21342. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21343. }
  21344. } else {
  21345. // Bottom faces
  21346. for ( let i = 0; i < flen; i ++ ) {
  21347. const face = faces[ i ];
  21348. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21349. }
  21350. // Top faces
  21351. for ( let i = 0; i < flen; i ++ ) {
  21352. const face = faces[ i ];
  21353. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21354. }
  21355. }
  21356. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21357. }
  21358. // Create faces for the z-sides of the shape
  21359. function buildSideFaces() {
  21360. const start = verticesArray.length / 3;
  21361. let layeroffset = 0;
  21362. sidewalls( contour, layeroffset );
  21363. layeroffset += contour.length;
  21364. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21365. const ahole = holes[ h ];
  21366. sidewalls( ahole, layeroffset );
  21367. //, true
  21368. layeroffset += ahole.length;
  21369. }
  21370. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21371. }
  21372. function sidewalls( contour, layeroffset ) {
  21373. let i = contour.length;
  21374. while ( -- i >= 0 ) {
  21375. const j = i;
  21376. let k = i - 1;
  21377. if ( k < 0 ) k = contour.length - 1;
  21378. //console.log('b', i,j, i-1, k,vertices.length);
  21379. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21380. const slen1 = vlen * s;
  21381. const slen2 = vlen * ( s + 1 );
  21382. const a = layeroffset + j + slen1,
  21383. b = layeroffset + k + slen1,
  21384. c = layeroffset + k + slen2,
  21385. d = layeroffset + j + slen2;
  21386. f4( a, b, c, d );
  21387. }
  21388. }
  21389. }
  21390. function v( x, y, z ) {
  21391. placeholder.push( x );
  21392. placeholder.push( y );
  21393. placeholder.push( z );
  21394. }
  21395. function f3( a, b, c ) {
  21396. addVertex( a );
  21397. addVertex( b );
  21398. addVertex( c );
  21399. const nextIndex = verticesArray.length / 3;
  21400. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21401. addUV( uvs[ 0 ] );
  21402. addUV( uvs[ 1 ] );
  21403. addUV( uvs[ 2 ] );
  21404. }
  21405. function f4( a, b, c, d ) {
  21406. addVertex( a );
  21407. addVertex( b );
  21408. addVertex( d );
  21409. addVertex( b );
  21410. addVertex( c );
  21411. addVertex( d );
  21412. const nextIndex = verticesArray.length / 3;
  21413. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21414. addUV( uvs[ 0 ] );
  21415. addUV( uvs[ 1 ] );
  21416. addUV( uvs[ 3 ] );
  21417. addUV( uvs[ 1 ] );
  21418. addUV( uvs[ 2 ] );
  21419. addUV( uvs[ 3 ] );
  21420. }
  21421. function addVertex( index ) {
  21422. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21423. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21424. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21425. }
  21426. function addUV( vector2 ) {
  21427. uvArray.push( vector2.x );
  21428. uvArray.push( vector2.y );
  21429. }
  21430. }
  21431. }
  21432. toJSON() {
  21433. const data = super.toJSON();
  21434. const shapes = this.parameters.shapes;
  21435. const options = this.parameters.options;
  21436. return toJSON$1( shapes, options, data );
  21437. }
  21438. static fromJSON( data, shapes ) {
  21439. const geometryShapes = [];
  21440. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21441. const shape = shapes[ data.shapes[ j ] ];
  21442. geometryShapes.push( shape );
  21443. }
  21444. const extrudePath = data.options.extrudePath;
  21445. if ( extrudePath !== undefined ) {
  21446. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21447. }
  21448. return new ExtrudeGeometry( geometryShapes, data.options );
  21449. }
  21450. }
  21451. const WorldUVGenerator = {
  21452. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21453. const a_x = vertices[ indexA * 3 ];
  21454. const a_y = vertices[ indexA * 3 + 1 ];
  21455. const b_x = vertices[ indexB * 3 ];
  21456. const b_y = vertices[ indexB * 3 + 1 ];
  21457. const c_x = vertices[ indexC * 3 ];
  21458. const c_y = vertices[ indexC * 3 + 1 ];
  21459. return [
  21460. new Vector2( a_x, a_y ),
  21461. new Vector2( b_x, b_y ),
  21462. new Vector2( c_x, c_y )
  21463. ];
  21464. },
  21465. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21466. const a_x = vertices[ indexA * 3 ];
  21467. const a_y = vertices[ indexA * 3 + 1 ];
  21468. const a_z = vertices[ indexA * 3 + 2 ];
  21469. const b_x = vertices[ indexB * 3 ];
  21470. const b_y = vertices[ indexB * 3 + 1 ];
  21471. const b_z = vertices[ indexB * 3 + 2 ];
  21472. const c_x = vertices[ indexC * 3 ];
  21473. const c_y = vertices[ indexC * 3 + 1 ];
  21474. const c_z = vertices[ indexC * 3 + 2 ];
  21475. const d_x = vertices[ indexD * 3 ];
  21476. const d_y = vertices[ indexD * 3 + 1 ];
  21477. const d_z = vertices[ indexD * 3 + 2 ];
  21478. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21479. return [
  21480. new Vector2( a_x, 1 - a_z ),
  21481. new Vector2( b_x, 1 - b_z ),
  21482. new Vector2( c_x, 1 - c_z ),
  21483. new Vector2( d_x, 1 - d_z )
  21484. ];
  21485. } else {
  21486. return [
  21487. new Vector2( a_y, 1 - a_z ),
  21488. new Vector2( b_y, 1 - b_z ),
  21489. new Vector2( c_y, 1 - c_z ),
  21490. new Vector2( d_y, 1 - d_z )
  21491. ];
  21492. }
  21493. }
  21494. };
  21495. function toJSON$1( shapes, options, data ) {
  21496. data.shapes = [];
  21497. if ( Array.isArray( shapes ) ) {
  21498. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21499. const shape = shapes[ i ];
  21500. data.shapes.push( shape.uuid );
  21501. }
  21502. } else {
  21503. data.shapes.push( shapes.uuid );
  21504. }
  21505. data.options = Object.assign( {}, options );
  21506. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21507. return data;
  21508. }
  21509. class IcosahedronGeometry extends PolyhedronGeometry {
  21510. constructor( radius = 1, detail = 0 ) {
  21511. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21512. const vertices = [
  21513. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21514. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21515. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21516. ];
  21517. const indices = [
  21518. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21519. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21520. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21521. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21522. ];
  21523. super( vertices, indices, radius, detail );
  21524. this.type = 'IcosahedronGeometry';
  21525. this.parameters = {
  21526. radius: radius,
  21527. detail: detail
  21528. };
  21529. }
  21530. static fromJSON( data ) {
  21531. return new IcosahedronGeometry( data.radius, data.detail );
  21532. }
  21533. }
  21534. class OctahedronGeometry extends PolyhedronGeometry {
  21535. constructor( radius = 1, detail = 0 ) {
  21536. const vertices = [
  21537. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21538. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21539. ];
  21540. const indices = [
  21541. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21542. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21543. 1, 3, 4, 1, 4, 2
  21544. ];
  21545. super( vertices, indices, radius, detail );
  21546. this.type = 'OctahedronGeometry';
  21547. this.parameters = {
  21548. radius: radius,
  21549. detail: detail
  21550. };
  21551. }
  21552. static fromJSON( data ) {
  21553. return new OctahedronGeometry( data.radius, data.detail );
  21554. }
  21555. }
  21556. class RingGeometry extends BufferGeometry {
  21557. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21558. super();
  21559. this.type = 'RingGeometry';
  21560. this.parameters = {
  21561. innerRadius: innerRadius,
  21562. outerRadius: outerRadius,
  21563. thetaSegments: thetaSegments,
  21564. phiSegments: phiSegments,
  21565. thetaStart: thetaStart,
  21566. thetaLength: thetaLength
  21567. };
  21568. thetaSegments = Math.max( 3, thetaSegments );
  21569. phiSegments = Math.max( 1, phiSegments );
  21570. // buffers
  21571. const indices = [];
  21572. const vertices = [];
  21573. const normals = [];
  21574. const uvs = [];
  21575. // some helper variables
  21576. let radius = innerRadius;
  21577. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21578. const vertex = new Vector3();
  21579. const uv = new Vector2();
  21580. // generate vertices, normals and uvs
  21581. for ( let j = 0; j <= phiSegments; j ++ ) {
  21582. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21583. // values are generate from the inside of the ring to the outside
  21584. const segment = thetaStart + i / thetaSegments * thetaLength;
  21585. // vertex
  21586. vertex.x = radius * Math.cos( segment );
  21587. vertex.y = radius * Math.sin( segment );
  21588. vertices.push( vertex.x, vertex.y, vertex.z );
  21589. // normal
  21590. normals.push( 0, 0, 1 );
  21591. // uv
  21592. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21593. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21594. uvs.push( uv.x, uv.y );
  21595. }
  21596. // increase the radius for next row of vertices
  21597. radius += radiusStep;
  21598. }
  21599. // indices
  21600. for ( let j = 0; j < phiSegments; j ++ ) {
  21601. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21602. for ( let i = 0; i < thetaSegments; i ++ ) {
  21603. const segment = i + thetaSegmentLevel;
  21604. const a = segment;
  21605. const b = segment + thetaSegments + 1;
  21606. const c = segment + thetaSegments + 2;
  21607. const d = segment + 1;
  21608. // faces
  21609. indices.push( a, b, d );
  21610. indices.push( b, c, d );
  21611. }
  21612. }
  21613. // build geometry
  21614. this.setIndex( indices );
  21615. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21616. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21617. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21618. }
  21619. static fromJSON( data ) {
  21620. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21621. }
  21622. }
  21623. class ShapeGeometry extends BufferGeometry {
  21624. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21625. super();
  21626. this.type = 'ShapeGeometry';
  21627. this.parameters = {
  21628. shapes: shapes,
  21629. curveSegments: curveSegments
  21630. };
  21631. // buffers
  21632. const indices = [];
  21633. const vertices = [];
  21634. const normals = [];
  21635. const uvs = [];
  21636. // helper variables
  21637. let groupStart = 0;
  21638. let groupCount = 0;
  21639. // allow single and array values for "shapes" parameter
  21640. if ( Array.isArray( shapes ) === false ) {
  21641. addShape( shapes );
  21642. } else {
  21643. for ( let i = 0; i < shapes.length; i ++ ) {
  21644. addShape( shapes[ i ] );
  21645. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21646. groupStart += groupCount;
  21647. groupCount = 0;
  21648. }
  21649. }
  21650. // build geometry
  21651. this.setIndex( indices );
  21652. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21653. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21654. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21655. // helper functions
  21656. function addShape( shape ) {
  21657. const indexOffset = vertices.length / 3;
  21658. const points = shape.extractPoints( curveSegments );
  21659. let shapeVertices = points.shape;
  21660. const shapeHoles = points.holes;
  21661. // check direction of vertices
  21662. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21663. shapeVertices = shapeVertices.reverse();
  21664. }
  21665. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21666. const shapeHole = shapeHoles[ i ];
  21667. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21668. shapeHoles[ i ] = shapeHole.reverse();
  21669. }
  21670. }
  21671. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21672. // join vertices of inner and outer paths to a single array
  21673. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21674. const shapeHole = shapeHoles[ i ];
  21675. shapeVertices = shapeVertices.concat( shapeHole );
  21676. }
  21677. // vertices, normals, uvs
  21678. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21679. const vertex = shapeVertices[ i ];
  21680. vertices.push( vertex.x, vertex.y, 0 );
  21681. normals.push( 0, 0, 1 );
  21682. uvs.push( vertex.x, vertex.y ); // world uvs
  21683. }
  21684. // incides
  21685. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21686. const face = faces[ i ];
  21687. const a = face[ 0 ] + indexOffset;
  21688. const b = face[ 1 ] + indexOffset;
  21689. const c = face[ 2 ] + indexOffset;
  21690. indices.push( a, b, c );
  21691. groupCount += 3;
  21692. }
  21693. }
  21694. }
  21695. toJSON() {
  21696. const data = super.toJSON();
  21697. const shapes = this.parameters.shapes;
  21698. return toJSON( shapes, data );
  21699. }
  21700. static fromJSON( data, shapes ) {
  21701. const geometryShapes = [];
  21702. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21703. const shape = shapes[ data.shapes[ j ] ];
  21704. geometryShapes.push( shape );
  21705. }
  21706. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21707. }
  21708. }
  21709. function toJSON( shapes, data ) {
  21710. data.shapes = [];
  21711. if ( Array.isArray( shapes ) ) {
  21712. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21713. const shape = shapes[ i ];
  21714. data.shapes.push( shape.uuid );
  21715. }
  21716. } else {
  21717. data.shapes.push( shapes.uuid );
  21718. }
  21719. return data;
  21720. }
  21721. class SphereGeometry extends BufferGeometry {
  21722. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21723. super();
  21724. this.type = 'SphereGeometry';
  21725. this.parameters = {
  21726. radius: radius,
  21727. widthSegments: widthSegments,
  21728. heightSegments: heightSegments,
  21729. phiStart: phiStart,
  21730. phiLength: phiLength,
  21731. thetaStart: thetaStart,
  21732. thetaLength: thetaLength
  21733. };
  21734. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21735. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21736. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21737. let index = 0;
  21738. const grid = [];
  21739. const vertex = new Vector3();
  21740. const normal = new Vector3();
  21741. // buffers
  21742. const indices = [];
  21743. const vertices = [];
  21744. const normals = [];
  21745. const uvs = [];
  21746. // generate vertices, normals and uvs
  21747. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21748. const verticesRow = [];
  21749. const v = iy / heightSegments;
  21750. // special case for the poles
  21751. let uOffset = 0;
  21752. if ( iy == 0 && thetaStart == 0 ) {
  21753. uOffset = 0.5 / widthSegments;
  21754. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21755. uOffset = - 0.5 / widthSegments;
  21756. }
  21757. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21758. const u = ix / widthSegments;
  21759. // vertex
  21760. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21761. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21762. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21763. vertices.push( vertex.x, vertex.y, vertex.z );
  21764. // normal
  21765. normal.copy( vertex ).normalize();
  21766. normals.push( normal.x, normal.y, normal.z );
  21767. // uv
  21768. uvs.push( u + uOffset, 1 - v );
  21769. verticesRow.push( index ++ );
  21770. }
  21771. grid.push( verticesRow );
  21772. }
  21773. // indices
  21774. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21775. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21776. const a = grid[ iy ][ ix + 1 ];
  21777. const b = grid[ iy ][ ix ];
  21778. const c = grid[ iy + 1 ][ ix ];
  21779. const d = grid[ iy + 1 ][ ix + 1 ];
  21780. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21781. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21782. }
  21783. }
  21784. // build geometry
  21785. this.setIndex( indices );
  21786. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21787. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21788. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21789. }
  21790. static fromJSON( data ) {
  21791. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21792. }
  21793. }
  21794. class TetrahedronGeometry extends PolyhedronGeometry {
  21795. constructor( radius = 1, detail = 0 ) {
  21796. const vertices = [
  21797. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21798. ];
  21799. const indices = [
  21800. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21801. ];
  21802. super( vertices, indices, radius, detail );
  21803. this.type = 'TetrahedronGeometry';
  21804. this.parameters = {
  21805. radius: radius,
  21806. detail: detail
  21807. };
  21808. }
  21809. static fromJSON( data ) {
  21810. return new TetrahedronGeometry( data.radius, data.detail );
  21811. }
  21812. }
  21813. class TorusGeometry extends BufferGeometry {
  21814. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21815. super();
  21816. this.type = 'TorusGeometry';
  21817. this.parameters = {
  21818. radius: radius,
  21819. tube: tube,
  21820. radialSegments: radialSegments,
  21821. tubularSegments: tubularSegments,
  21822. arc: arc
  21823. };
  21824. radialSegments = Math.floor( radialSegments );
  21825. tubularSegments = Math.floor( tubularSegments );
  21826. // buffers
  21827. const indices = [];
  21828. const vertices = [];
  21829. const normals = [];
  21830. const uvs = [];
  21831. // helper variables
  21832. const center = new Vector3();
  21833. const vertex = new Vector3();
  21834. const normal = new Vector3();
  21835. // generate vertices, normals and uvs
  21836. for ( let j = 0; j <= radialSegments; j ++ ) {
  21837. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21838. const u = i / tubularSegments * arc;
  21839. const v = j / radialSegments * Math.PI * 2;
  21840. // vertex
  21841. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21842. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21843. vertex.z = tube * Math.sin( v );
  21844. vertices.push( vertex.x, vertex.y, vertex.z );
  21845. // normal
  21846. center.x = radius * Math.cos( u );
  21847. center.y = radius * Math.sin( u );
  21848. normal.subVectors( vertex, center ).normalize();
  21849. normals.push( normal.x, normal.y, normal.z );
  21850. // uv
  21851. uvs.push( i / tubularSegments );
  21852. uvs.push( j / radialSegments );
  21853. }
  21854. }
  21855. // generate indices
  21856. for ( let j = 1; j <= radialSegments; j ++ ) {
  21857. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21858. // indices
  21859. const a = ( tubularSegments + 1 ) * j + i - 1;
  21860. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21861. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21862. const d = ( tubularSegments + 1 ) * j + i;
  21863. // faces
  21864. indices.push( a, b, d );
  21865. indices.push( b, c, d );
  21866. }
  21867. }
  21868. // build geometry
  21869. this.setIndex( indices );
  21870. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21871. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21872. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21873. }
  21874. static fromJSON( data ) {
  21875. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21876. }
  21877. }
  21878. class TorusKnotGeometry extends BufferGeometry {
  21879. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21880. super();
  21881. this.type = 'TorusKnotGeometry';
  21882. this.parameters = {
  21883. radius: radius,
  21884. tube: tube,
  21885. tubularSegments: tubularSegments,
  21886. radialSegments: radialSegments,
  21887. p: p,
  21888. q: q
  21889. };
  21890. tubularSegments = Math.floor( tubularSegments );
  21891. radialSegments = Math.floor( radialSegments );
  21892. // buffers
  21893. const indices = [];
  21894. const vertices = [];
  21895. const normals = [];
  21896. const uvs = [];
  21897. // helper variables
  21898. const vertex = new Vector3();
  21899. const normal = new Vector3();
  21900. const P1 = new Vector3();
  21901. const P2 = new Vector3();
  21902. const B = new Vector3();
  21903. const T = new Vector3();
  21904. const N = new Vector3();
  21905. // generate vertices, normals and uvs
  21906. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21907. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21908. const u = i / tubularSegments * p * Math.PI * 2;
  21909. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21910. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21911. calculatePositionOnCurve( u, p, q, radius, P1 );
  21912. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21913. // calculate orthonormal basis
  21914. T.subVectors( P2, P1 );
  21915. N.addVectors( P2, P1 );
  21916. B.crossVectors( T, N );
  21917. N.crossVectors( B, T );
  21918. // normalize B, N. T can be ignored, we don't use it
  21919. B.normalize();
  21920. N.normalize();
  21921. for ( let j = 0; j <= radialSegments; ++ j ) {
  21922. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21923. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21924. const v = j / radialSegments * Math.PI * 2;
  21925. const cx = - tube * Math.cos( v );
  21926. const cy = tube * Math.sin( v );
  21927. // now calculate the final vertex position.
  21928. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21929. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21930. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21931. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21932. vertices.push( vertex.x, vertex.y, vertex.z );
  21933. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21934. normal.subVectors( vertex, P1 ).normalize();
  21935. normals.push( normal.x, normal.y, normal.z );
  21936. // uv
  21937. uvs.push( i / tubularSegments );
  21938. uvs.push( j / radialSegments );
  21939. }
  21940. }
  21941. // generate indices
  21942. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21943. for ( let i = 1; i <= radialSegments; i ++ ) {
  21944. // indices
  21945. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21946. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21947. const c = ( radialSegments + 1 ) * j + i;
  21948. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21949. // faces
  21950. indices.push( a, b, d );
  21951. indices.push( b, c, d );
  21952. }
  21953. }
  21954. // build geometry
  21955. this.setIndex( indices );
  21956. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21957. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21958. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21959. // this function calculates the current position on the torus curve
  21960. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21961. const cu = Math.cos( u );
  21962. const su = Math.sin( u );
  21963. const quOverP = q / p * u;
  21964. const cs = Math.cos( quOverP );
  21965. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21966. position.y = radius * ( 2 + cs ) * su * 0.5;
  21967. position.z = radius * Math.sin( quOverP ) * 0.5;
  21968. }
  21969. }
  21970. static fromJSON( data ) {
  21971. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21972. }
  21973. }
  21974. class TubeGeometry extends BufferGeometry {
  21975. 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 ) {
  21976. super();
  21977. this.type = 'TubeGeometry';
  21978. this.parameters = {
  21979. path: path,
  21980. tubularSegments: tubularSegments,
  21981. radius: radius,
  21982. radialSegments: radialSegments,
  21983. closed: closed
  21984. };
  21985. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21986. // expose internals
  21987. this.tangents = frames.tangents;
  21988. this.normals = frames.normals;
  21989. this.binormals = frames.binormals;
  21990. // helper variables
  21991. const vertex = new Vector3();
  21992. const normal = new Vector3();
  21993. const uv = new Vector2();
  21994. let P = new Vector3();
  21995. // buffer
  21996. const vertices = [];
  21997. const normals = [];
  21998. const uvs = [];
  21999. const indices = [];
  22000. // create buffer data
  22001. generateBufferData();
  22002. // build geometry
  22003. this.setIndex( indices );
  22004. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22005. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22006. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22007. // functions
  22008. function generateBufferData() {
  22009. for ( let i = 0; i < tubularSegments; i ++ ) {
  22010. generateSegment( i );
  22011. }
  22012. // if the geometry is not closed, generate the last row of vertices and normals
  22013. // at the regular position on the given path
  22014. //
  22015. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22016. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22017. // uvs are generated in a separate function.
  22018. // this makes it easy compute correct values for closed geometries
  22019. generateUVs();
  22020. // finally create faces
  22021. generateIndices();
  22022. }
  22023. function generateSegment( i ) {
  22024. // we use getPointAt to sample evenly distributed points from the given path
  22025. P = path.getPointAt( i / tubularSegments, P );
  22026. // retrieve corresponding normal and binormal
  22027. const N = frames.normals[ i ];
  22028. const B = frames.binormals[ i ];
  22029. // generate normals and vertices for the current segment
  22030. for ( let j = 0; j <= radialSegments; j ++ ) {
  22031. const v = j / radialSegments * Math.PI * 2;
  22032. const sin = Math.sin( v );
  22033. const cos = - Math.cos( v );
  22034. // normal
  22035. normal.x = ( cos * N.x + sin * B.x );
  22036. normal.y = ( cos * N.y + sin * B.y );
  22037. normal.z = ( cos * N.z + sin * B.z );
  22038. normal.normalize();
  22039. normals.push( normal.x, normal.y, normal.z );
  22040. // vertex
  22041. vertex.x = P.x + radius * normal.x;
  22042. vertex.y = P.y + radius * normal.y;
  22043. vertex.z = P.z + radius * normal.z;
  22044. vertices.push( vertex.x, vertex.y, vertex.z );
  22045. }
  22046. }
  22047. function generateIndices() {
  22048. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22049. for ( let i = 1; i <= radialSegments; i ++ ) {
  22050. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22051. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22052. const c = ( radialSegments + 1 ) * j + i;
  22053. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22054. // faces
  22055. indices.push( a, b, d );
  22056. indices.push( b, c, d );
  22057. }
  22058. }
  22059. }
  22060. function generateUVs() {
  22061. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22062. for ( let j = 0; j <= radialSegments; j ++ ) {
  22063. uv.x = i / tubularSegments;
  22064. uv.y = j / radialSegments;
  22065. uvs.push( uv.x, uv.y );
  22066. }
  22067. }
  22068. }
  22069. }
  22070. toJSON() {
  22071. const data = super.toJSON();
  22072. data.path = this.parameters.path.toJSON();
  22073. return data;
  22074. }
  22075. static fromJSON( data ) {
  22076. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22077. // User defined curves or instances of CurvePath will not be deserialized.
  22078. return new TubeGeometry(
  22079. new Curves[ data.path.type ]().fromJSON( data.path ),
  22080. data.tubularSegments,
  22081. data.radius,
  22082. data.radialSegments,
  22083. data.closed
  22084. );
  22085. }
  22086. }
  22087. class WireframeGeometry extends BufferGeometry {
  22088. constructor( geometry = null ) {
  22089. super();
  22090. this.type = 'WireframeGeometry';
  22091. this.parameters = {
  22092. geometry: geometry
  22093. };
  22094. if ( geometry !== null ) {
  22095. // buffer
  22096. const vertices = [];
  22097. const edges = new Set();
  22098. // helper variables
  22099. const start = new Vector3();
  22100. const end = new Vector3();
  22101. if ( geometry.index !== null ) {
  22102. // indexed BufferGeometry
  22103. const position = geometry.attributes.position;
  22104. const indices = geometry.index;
  22105. let groups = geometry.groups;
  22106. if ( groups.length === 0 ) {
  22107. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22108. }
  22109. // create a data structure that contains all edges without duplicates
  22110. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22111. const group = groups[ o ];
  22112. const groupStart = group.start;
  22113. const groupCount = group.count;
  22114. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22115. for ( let j = 0; j < 3; j ++ ) {
  22116. const index1 = indices.getX( i + j );
  22117. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22118. start.fromBufferAttribute( position, index1 );
  22119. end.fromBufferAttribute( position, index2 );
  22120. if ( isUniqueEdge( start, end, edges ) === true ) {
  22121. vertices.push( start.x, start.y, start.z );
  22122. vertices.push( end.x, end.y, end.z );
  22123. }
  22124. }
  22125. }
  22126. }
  22127. } else {
  22128. // non-indexed BufferGeometry
  22129. const position = geometry.attributes.position;
  22130. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22131. for ( let j = 0; j < 3; j ++ ) {
  22132. // three edges per triangle, an edge is represented as (index1, index2)
  22133. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22134. const index1 = 3 * i + j;
  22135. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22136. start.fromBufferAttribute( position, index1 );
  22137. end.fromBufferAttribute( position, index2 );
  22138. if ( isUniqueEdge( start, end, edges ) === true ) {
  22139. vertices.push( start.x, start.y, start.z );
  22140. vertices.push( end.x, end.y, end.z );
  22141. }
  22142. }
  22143. }
  22144. }
  22145. // build geometry
  22146. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22147. }
  22148. }
  22149. }
  22150. function isUniqueEdge( start, end, edges ) {
  22151. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22152. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22153. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22154. return false;
  22155. } else {
  22156. edges.add( hash1 );
  22157. edges.add( hash2 );
  22158. return true;
  22159. }
  22160. }
  22161. var Geometries = /*#__PURE__*/Object.freeze({
  22162. __proto__: null,
  22163. BoxGeometry: BoxGeometry,
  22164. CapsuleGeometry: CapsuleGeometry,
  22165. CircleGeometry: CircleGeometry,
  22166. ConeGeometry: ConeGeometry,
  22167. CylinderGeometry: CylinderGeometry,
  22168. DodecahedronGeometry: DodecahedronGeometry,
  22169. EdgesGeometry: EdgesGeometry,
  22170. ExtrudeGeometry: ExtrudeGeometry,
  22171. IcosahedronGeometry: IcosahedronGeometry,
  22172. LatheGeometry: LatheGeometry,
  22173. OctahedronGeometry: OctahedronGeometry,
  22174. PlaneGeometry: PlaneGeometry,
  22175. PolyhedronGeometry: PolyhedronGeometry,
  22176. RingGeometry: RingGeometry,
  22177. ShapeGeometry: ShapeGeometry,
  22178. SphereGeometry: SphereGeometry,
  22179. TetrahedronGeometry: TetrahedronGeometry,
  22180. TorusGeometry: TorusGeometry,
  22181. TorusKnotGeometry: TorusKnotGeometry,
  22182. TubeGeometry: TubeGeometry,
  22183. WireframeGeometry: WireframeGeometry
  22184. });
  22185. class ShadowMaterial extends Material {
  22186. constructor( parameters ) {
  22187. super();
  22188. this.isShadowMaterial = true;
  22189. this.type = 'ShadowMaterial';
  22190. this.color = new Color( 0x000000 );
  22191. this.transparent = true;
  22192. this.fog = true;
  22193. this.setValues( parameters );
  22194. }
  22195. copy( source ) {
  22196. super.copy( source );
  22197. this.color.copy( source.color );
  22198. this.fog = source.fog;
  22199. return this;
  22200. }
  22201. }
  22202. class RawShaderMaterial extends ShaderMaterial {
  22203. constructor( parameters ) {
  22204. super( parameters );
  22205. this.isRawShaderMaterial = true;
  22206. this.type = 'RawShaderMaterial';
  22207. }
  22208. }
  22209. class MeshStandardMaterial extends Material {
  22210. constructor( parameters ) {
  22211. super();
  22212. this.isMeshStandardMaterial = true;
  22213. this.defines = { 'STANDARD': '' };
  22214. this.type = 'MeshStandardMaterial';
  22215. this.color = new Color( 0xffffff ); // diffuse
  22216. this.roughness = 1.0;
  22217. this.metalness = 0.0;
  22218. this.map = null;
  22219. this.lightMap = null;
  22220. this.lightMapIntensity = 1.0;
  22221. this.aoMap = null;
  22222. this.aoMapIntensity = 1.0;
  22223. this.emissive = new Color( 0x000000 );
  22224. this.emissiveIntensity = 1.0;
  22225. this.emissiveMap = null;
  22226. this.bumpMap = null;
  22227. this.bumpScale = 1;
  22228. this.normalMap = null;
  22229. this.normalMapType = TangentSpaceNormalMap;
  22230. this.normalScale = new Vector2( 1, 1 );
  22231. this.displacementMap = null;
  22232. this.displacementScale = 1;
  22233. this.displacementBias = 0;
  22234. this.roughnessMap = null;
  22235. this.metalnessMap = null;
  22236. this.alphaMap = null;
  22237. this.envMap = null;
  22238. this.envMapIntensity = 1.0;
  22239. this.wireframe = false;
  22240. this.wireframeLinewidth = 1;
  22241. this.wireframeLinecap = 'round';
  22242. this.wireframeLinejoin = 'round';
  22243. this.flatShading = false;
  22244. this.fog = true;
  22245. this.setValues( parameters );
  22246. }
  22247. copy( source ) {
  22248. super.copy( source );
  22249. this.defines = { 'STANDARD': '' };
  22250. this.color.copy( source.color );
  22251. this.roughness = source.roughness;
  22252. this.metalness = source.metalness;
  22253. this.map = source.map;
  22254. this.lightMap = source.lightMap;
  22255. this.lightMapIntensity = source.lightMapIntensity;
  22256. this.aoMap = source.aoMap;
  22257. this.aoMapIntensity = source.aoMapIntensity;
  22258. this.emissive.copy( source.emissive );
  22259. this.emissiveMap = source.emissiveMap;
  22260. this.emissiveIntensity = source.emissiveIntensity;
  22261. this.bumpMap = source.bumpMap;
  22262. this.bumpScale = source.bumpScale;
  22263. this.normalMap = source.normalMap;
  22264. this.normalMapType = source.normalMapType;
  22265. this.normalScale.copy( source.normalScale );
  22266. this.displacementMap = source.displacementMap;
  22267. this.displacementScale = source.displacementScale;
  22268. this.displacementBias = source.displacementBias;
  22269. this.roughnessMap = source.roughnessMap;
  22270. this.metalnessMap = source.metalnessMap;
  22271. this.alphaMap = source.alphaMap;
  22272. this.envMap = source.envMap;
  22273. this.envMapIntensity = source.envMapIntensity;
  22274. this.wireframe = source.wireframe;
  22275. this.wireframeLinewidth = source.wireframeLinewidth;
  22276. this.wireframeLinecap = source.wireframeLinecap;
  22277. this.wireframeLinejoin = source.wireframeLinejoin;
  22278. this.flatShading = source.flatShading;
  22279. this.fog = source.fog;
  22280. return this;
  22281. }
  22282. }
  22283. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22284. constructor( parameters ) {
  22285. super();
  22286. this.isMeshPhysicalMaterial = true;
  22287. this.defines = {
  22288. 'STANDARD': '',
  22289. 'PHYSICAL': ''
  22290. };
  22291. this.type = 'MeshPhysicalMaterial';
  22292. this.clearcoatMap = null;
  22293. this.clearcoatRoughness = 0.0;
  22294. this.clearcoatRoughnessMap = null;
  22295. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22296. this.clearcoatNormalMap = null;
  22297. this.ior = 1.5;
  22298. Object.defineProperty( this, 'reflectivity', {
  22299. get: function () {
  22300. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22301. },
  22302. set: function ( reflectivity ) {
  22303. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22304. }
  22305. } );
  22306. this.iridescenceMap = null;
  22307. this.iridescenceIOR = 1.3;
  22308. this.iridescenceThicknessRange = [ 100, 400 ];
  22309. this.iridescenceThicknessMap = null;
  22310. this.sheenColor = new Color( 0x000000 );
  22311. this.sheenColorMap = null;
  22312. this.sheenRoughness = 1.0;
  22313. this.sheenRoughnessMap = null;
  22314. this.transmissionMap = null;
  22315. this.thickness = 0;
  22316. this.thicknessMap = null;
  22317. this.attenuationDistance = 0.0;
  22318. this.attenuationColor = new Color( 1, 1, 1 );
  22319. this.specularIntensity = 1.0;
  22320. this.specularIntensityMap = null;
  22321. this.specularColor = new Color( 1, 1, 1 );
  22322. this.specularColorMap = null;
  22323. this._sheen = 0.0;
  22324. this._clearcoat = 0;
  22325. this._iridescence = 0;
  22326. this._transmission = 0;
  22327. this.setValues( parameters );
  22328. }
  22329. get sheen() {
  22330. return this._sheen;
  22331. }
  22332. set sheen( value ) {
  22333. if ( this._sheen > 0 !== value > 0 ) {
  22334. this.version ++;
  22335. }
  22336. this._sheen = value;
  22337. }
  22338. get clearcoat() {
  22339. return this._clearcoat;
  22340. }
  22341. set clearcoat( value ) {
  22342. if ( this._clearcoat > 0 !== value > 0 ) {
  22343. this.version ++;
  22344. }
  22345. this._clearcoat = value;
  22346. }
  22347. get iridescence() {
  22348. return this._iridescence;
  22349. }
  22350. set iridescence( value ) {
  22351. if ( this._iridescence > 0 !== value > 0 ) {
  22352. this.version ++;
  22353. }
  22354. this._iridescence = value;
  22355. }
  22356. get transmission() {
  22357. return this._transmission;
  22358. }
  22359. set transmission( value ) {
  22360. if ( this._transmission > 0 !== value > 0 ) {
  22361. this.version ++;
  22362. }
  22363. this._transmission = value;
  22364. }
  22365. copy( source ) {
  22366. super.copy( source );
  22367. this.defines = {
  22368. 'STANDARD': '',
  22369. 'PHYSICAL': ''
  22370. };
  22371. this.clearcoat = source.clearcoat;
  22372. this.clearcoatMap = source.clearcoatMap;
  22373. this.clearcoatRoughness = source.clearcoatRoughness;
  22374. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22375. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22376. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22377. this.ior = source.ior;
  22378. this.iridescence = source.iridescence;
  22379. this.iridescenceMap = source.iridescenceMap;
  22380. this.iridescenceIOR = source.iridescenceIOR;
  22381. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22382. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22383. this.sheen = source.sheen;
  22384. this.sheenColor.copy( source.sheenColor );
  22385. this.sheenColorMap = source.sheenColorMap;
  22386. this.sheenRoughness = source.sheenRoughness;
  22387. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22388. this.transmission = source.transmission;
  22389. this.transmissionMap = source.transmissionMap;
  22390. this.thickness = source.thickness;
  22391. this.thicknessMap = source.thicknessMap;
  22392. this.attenuationDistance = source.attenuationDistance;
  22393. this.attenuationColor.copy( source.attenuationColor );
  22394. this.specularIntensity = source.specularIntensity;
  22395. this.specularIntensityMap = source.specularIntensityMap;
  22396. this.specularColor.copy( source.specularColor );
  22397. this.specularColorMap = source.specularColorMap;
  22398. return this;
  22399. }
  22400. }
  22401. class MeshPhongMaterial extends Material {
  22402. constructor( parameters ) {
  22403. super();
  22404. this.isMeshPhongMaterial = true;
  22405. this.type = 'MeshPhongMaterial';
  22406. this.color = new Color( 0xffffff ); // diffuse
  22407. this.specular = new Color( 0x111111 );
  22408. this.shininess = 30;
  22409. this.map = null;
  22410. this.lightMap = null;
  22411. this.lightMapIntensity = 1.0;
  22412. this.aoMap = null;
  22413. this.aoMapIntensity = 1.0;
  22414. this.emissive = new Color( 0x000000 );
  22415. this.emissiveIntensity = 1.0;
  22416. this.emissiveMap = null;
  22417. this.bumpMap = null;
  22418. this.bumpScale = 1;
  22419. this.normalMap = null;
  22420. this.normalMapType = TangentSpaceNormalMap;
  22421. this.normalScale = new Vector2( 1, 1 );
  22422. this.displacementMap = null;
  22423. this.displacementScale = 1;
  22424. this.displacementBias = 0;
  22425. this.specularMap = null;
  22426. this.alphaMap = null;
  22427. this.envMap = null;
  22428. this.combine = MultiplyOperation;
  22429. this.reflectivity = 1;
  22430. this.refractionRatio = 0.98;
  22431. this.wireframe = false;
  22432. this.wireframeLinewidth = 1;
  22433. this.wireframeLinecap = 'round';
  22434. this.wireframeLinejoin = 'round';
  22435. this.flatShading = false;
  22436. this.fog = true;
  22437. this.setValues( parameters );
  22438. }
  22439. copy( source ) {
  22440. super.copy( source );
  22441. this.color.copy( source.color );
  22442. this.specular.copy( source.specular );
  22443. this.shininess = source.shininess;
  22444. this.map = source.map;
  22445. this.lightMap = source.lightMap;
  22446. this.lightMapIntensity = source.lightMapIntensity;
  22447. this.aoMap = source.aoMap;
  22448. this.aoMapIntensity = source.aoMapIntensity;
  22449. this.emissive.copy( source.emissive );
  22450. this.emissiveMap = source.emissiveMap;
  22451. this.emissiveIntensity = source.emissiveIntensity;
  22452. this.bumpMap = source.bumpMap;
  22453. this.bumpScale = source.bumpScale;
  22454. this.normalMap = source.normalMap;
  22455. this.normalMapType = source.normalMapType;
  22456. this.normalScale.copy( source.normalScale );
  22457. this.displacementMap = source.displacementMap;
  22458. this.displacementScale = source.displacementScale;
  22459. this.displacementBias = source.displacementBias;
  22460. this.specularMap = source.specularMap;
  22461. this.alphaMap = source.alphaMap;
  22462. this.envMap = source.envMap;
  22463. this.combine = source.combine;
  22464. this.reflectivity = source.reflectivity;
  22465. this.refractionRatio = source.refractionRatio;
  22466. this.wireframe = source.wireframe;
  22467. this.wireframeLinewidth = source.wireframeLinewidth;
  22468. this.wireframeLinecap = source.wireframeLinecap;
  22469. this.wireframeLinejoin = source.wireframeLinejoin;
  22470. this.flatShading = source.flatShading;
  22471. this.fog = source.fog;
  22472. return this;
  22473. }
  22474. }
  22475. class MeshToonMaterial extends Material {
  22476. constructor( parameters ) {
  22477. super();
  22478. this.isMeshToonMaterial = true;
  22479. this.defines = { 'TOON': '' };
  22480. this.type = 'MeshToonMaterial';
  22481. this.color = new Color( 0xffffff );
  22482. this.map = null;
  22483. this.gradientMap = null;
  22484. this.lightMap = null;
  22485. this.lightMapIntensity = 1.0;
  22486. this.aoMap = null;
  22487. this.aoMapIntensity = 1.0;
  22488. this.emissive = new Color( 0x000000 );
  22489. this.emissiveIntensity = 1.0;
  22490. this.emissiveMap = null;
  22491. this.bumpMap = null;
  22492. this.bumpScale = 1;
  22493. this.normalMap = null;
  22494. this.normalMapType = TangentSpaceNormalMap;
  22495. this.normalScale = new Vector2( 1, 1 );
  22496. this.displacementMap = null;
  22497. this.displacementScale = 1;
  22498. this.displacementBias = 0;
  22499. this.alphaMap = null;
  22500. this.wireframe = false;
  22501. this.wireframeLinewidth = 1;
  22502. this.wireframeLinecap = 'round';
  22503. this.wireframeLinejoin = 'round';
  22504. this.fog = true;
  22505. this.setValues( parameters );
  22506. }
  22507. copy( source ) {
  22508. super.copy( source );
  22509. this.color.copy( source.color );
  22510. this.map = source.map;
  22511. this.gradientMap = source.gradientMap;
  22512. this.lightMap = source.lightMap;
  22513. this.lightMapIntensity = source.lightMapIntensity;
  22514. this.aoMap = source.aoMap;
  22515. this.aoMapIntensity = source.aoMapIntensity;
  22516. this.emissive.copy( source.emissive );
  22517. this.emissiveMap = source.emissiveMap;
  22518. this.emissiveIntensity = source.emissiveIntensity;
  22519. this.bumpMap = source.bumpMap;
  22520. this.bumpScale = source.bumpScale;
  22521. this.normalMap = source.normalMap;
  22522. this.normalMapType = source.normalMapType;
  22523. this.normalScale.copy( source.normalScale );
  22524. this.displacementMap = source.displacementMap;
  22525. this.displacementScale = source.displacementScale;
  22526. this.displacementBias = source.displacementBias;
  22527. this.alphaMap = source.alphaMap;
  22528. this.wireframe = source.wireframe;
  22529. this.wireframeLinewidth = source.wireframeLinewidth;
  22530. this.wireframeLinecap = source.wireframeLinecap;
  22531. this.wireframeLinejoin = source.wireframeLinejoin;
  22532. this.fog = source.fog;
  22533. return this;
  22534. }
  22535. }
  22536. class MeshNormalMaterial extends Material {
  22537. constructor( parameters ) {
  22538. super();
  22539. this.isMeshNormalMaterial = true;
  22540. this.type = 'MeshNormalMaterial';
  22541. this.bumpMap = null;
  22542. this.bumpScale = 1;
  22543. this.normalMap = null;
  22544. this.normalMapType = TangentSpaceNormalMap;
  22545. this.normalScale = new Vector2( 1, 1 );
  22546. this.displacementMap = null;
  22547. this.displacementScale = 1;
  22548. this.displacementBias = 0;
  22549. this.wireframe = false;
  22550. this.wireframeLinewidth = 1;
  22551. this.flatShading = false;
  22552. this.setValues( parameters );
  22553. }
  22554. copy( source ) {
  22555. super.copy( source );
  22556. this.bumpMap = source.bumpMap;
  22557. this.bumpScale = source.bumpScale;
  22558. this.normalMap = source.normalMap;
  22559. this.normalMapType = source.normalMapType;
  22560. this.normalScale.copy( source.normalScale );
  22561. this.displacementMap = source.displacementMap;
  22562. this.displacementScale = source.displacementScale;
  22563. this.displacementBias = source.displacementBias;
  22564. this.wireframe = source.wireframe;
  22565. this.wireframeLinewidth = source.wireframeLinewidth;
  22566. this.flatShading = source.flatShading;
  22567. return this;
  22568. }
  22569. }
  22570. class MeshLambertMaterial extends Material {
  22571. constructor( parameters ) {
  22572. super();
  22573. this.isMeshLambertMaterial = true;
  22574. this.type = 'MeshLambertMaterial';
  22575. this.color = new Color( 0xffffff ); // diffuse
  22576. this.map = null;
  22577. this.lightMap = null;
  22578. this.lightMapIntensity = 1.0;
  22579. this.aoMap = null;
  22580. this.aoMapIntensity = 1.0;
  22581. this.emissive = new Color( 0x000000 );
  22582. this.emissiveIntensity = 1.0;
  22583. this.emissiveMap = null;
  22584. this.bumpMap = null;
  22585. this.bumpScale = 1;
  22586. this.normalMap = null;
  22587. this.normalMapType = TangentSpaceNormalMap;
  22588. this.normalScale = new Vector2( 1, 1 );
  22589. this.displacementMap = null;
  22590. this.displacementScale = 1;
  22591. this.displacementBias = 0;
  22592. this.specularMap = null;
  22593. this.alphaMap = null;
  22594. this.envMap = null;
  22595. this.combine = MultiplyOperation;
  22596. this.reflectivity = 1;
  22597. this.refractionRatio = 0.98;
  22598. this.wireframe = false;
  22599. this.wireframeLinewidth = 1;
  22600. this.wireframeLinecap = 'round';
  22601. this.wireframeLinejoin = 'round';
  22602. this.flatShading = false;
  22603. this.fog = true;
  22604. this.setValues( parameters );
  22605. }
  22606. copy( source ) {
  22607. super.copy( source );
  22608. this.color.copy( source.color );
  22609. this.map = source.map;
  22610. this.lightMap = source.lightMap;
  22611. this.lightMapIntensity = source.lightMapIntensity;
  22612. this.aoMap = source.aoMap;
  22613. this.aoMapIntensity = source.aoMapIntensity;
  22614. this.emissive.copy( source.emissive );
  22615. this.emissiveMap = source.emissiveMap;
  22616. this.emissiveIntensity = source.emissiveIntensity;
  22617. this.bumpMap = source.bumpMap;
  22618. this.bumpScale = source.bumpScale;
  22619. this.normalMap = source.normalMap;
  22620. this.normalMapType = source.normalMapType;
  22621. this.normalScale.copy( source.normalScale );
  22622. this.displacementMap = source.displacementMap;
  22623. this.displacementScale = source.displacementScale;
  22624. this.displacementBias = source.displacementBias;
  22625. this.specularMap = source.specularMap;
  22626. this.alphaMap = source.alphaMap;
  22627. this.envMap = source.envMap;
  22628. this.combine = source.combine;
  22629. this.reflectivity = source.reflectivity;
  22630. this.refractionRatio = source.refractionRatio;
  22631. this.wireframe = source.wireframe;
  22632. this.wireframeLinewidth = source.wireframeLinewidth;
  22633. this.wireframeLinecap = source.wireframeLinecap;
  22634. this.wireframeLinejoin = source.wireframeLinejoin;
  22635. this.flatShading = source.flatShading;
  22636. this.fog = source.fog;
  22637. return this;
  22638. }
  22639. }
  22640. class MeshMatcapMaterial extends Material {
  22641. constructor( parameters ) {
  22642. super();
  22643. this.isMeshMatcapMaterial = true;
  22644. this.defines = { 'MATCAP': '' };
  22645. this.type = 'MeshMatcapMaterial';
  22646. this.color = new Color( 0xffffff ); // diffuse
  22647. this.matcap = null;
  22648. this.map = null;
  22649. this.bumpMap = null;
  22650. this.bumpScale = 1;
  22651. this.normalMap = null;
  22652. this.normalMapType = TangentSpaceNormalMap;
  22653. this.normalScale = new Vector2( 1, 1 );
  22654. this.displacementMap = null;
  22655. this.displacementScale = 1;
  22656. this.displacementBias = 0;
  22657. this.alphaMap = null;
  22658. this.flatShading = false;
  22659. this.fog = true;
  22660. this.setValues( parameters );
  22661. }
  22662. copy( source ) {
  22663. super.copy( source );
  22664. this.defines = { 'MATCAP': '' };
  22665. this.color.copy( source.color );
  22666. this.matcap = source.matcap;
  22667. this.map = source.map;
  22668. this.bumpMap = source.bumpMap;
  22669. this.bumpScale = source.bumpScale;
  22670. this.normalMap = source.normalMap;
  22671. this.normalMapType = source.normalMapType;
  22672. this.normalScale.copy( source.normalScale );
  22673. this.displacementMap = source.displacementMap;
  22674. this.displacementScale = source.displacementScale;
  22675. this.displacementBias = source.displacementBias;
  22676. this.alphaMap = source.alphaMap;
  22677. this.flatShading = source.flatShading;
  22678. this.fog = source.fog;
  22679. return this;
  22680. }
  22681. }
  22682. class LineDashedMaterial extends LineBasicMaterial {
  22683. constructor( parameters ) {
  22684. super();
  22685. this.isLineDashedMaterial = true;
  22686. this.type = 'LineDashedMaterial';
  22687. this.scale = 1;
  22688. this.dashSize = 3;
  22689. this.gapSize = 1;
  22690. this.setValues( parameters );
  22691. }
  22692. copy( source ) {
  22693. super.copy( source );
  22694. this.scale = source.scale;
  22695. this.dashSize = source.dashSize;
  22696. this.gapSize = source.gapSize;
  22697. return this;
  22698. }
  22699. }
  22700. // same as Array.prototype.slice, but also works on typed arrays
  22701. function arraySlice( array, from, to ) {
  22702. if ( isTypedArray( array ) ) {
  22703. // in ios9 array.subarray(from, undefined) will return empty array
  22704. // but array.subarray(from) or array.subarray(from, len) is correct
  22705. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22706. }
  22707. return array.slice( from, to );
  22708. }
  22709. // converts an array to a specific type
  22710. function convertArray( array, type, forceClone ) {
  22711. if ( ! array || // let 'undefined' and 'null' pass
  22712. ! forceClone && array.constructor === type ) return array;
  22713. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22714. return new type( array ); // create typed array
  22715. }
  22716. return Array.prototype.slice.call( array ); // create Array
  22717. }
  22718. function isTypedArray( object ) {
  22719. return ArrayBuffer.isView( object ) &&
  22720. ! ( object instanceof DataView );
  22721. }
  22722. // returns an array by which times and values can be sorted
  22723. function getKeyframeOrder( times ) {
  22724. function compareTime( i, j ) {
  22725. return times[ i ] - times[ j ];
  22726. }
  22727. const n = times.length;
  22728. const result = new Array( n );
  22729. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22730. result.sort( compareTime );
  22731. return result;
  22732. }
  22733. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22734. function sortedArray( values, stride, order ) {
  22735. const nValues = values.length;
  22736. const result = new values.constructor( nValues );
  22737. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22738. const srcOffset = order[ i ] * stride;
  22739. for ( let j = 0; j !== stride; ++ j ) {
  22740. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22741. }
  22742. }
  22743. return result;
  22744. }
  22745. // function for parsing AOS keyframe formats
  22746. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22747. let i = 1, key = jsonKeys[ 0 ];
  22748. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22749. key = jsonKeys[ i ++ ];
  22750. }
  22751. if ( key === undefined ) return; // no data
  22752. let value = key[ valuePropertyName ];
  22753. if ( value === undefined ) return; // no data
  22754. if ( Array.isArray( value ) ) {
  22755. do {
  22756. value = key[ valuePropertyName ];
  22757. if ( value !== undefined ) {
  22758. times.push( key.time );
  22759. values.push.apply( values, value ); // push all elements
  22760. }
  22761. key = jsonKeys[ i ++ ];
  22762. } while ( key !== undefined );
  22763. } else if ( value.toArray !== undefined ) {
  22764. // ...assume THREE.Math-ish
  22765. do {
  22766. value = key[ valuePropertyName ];
  22767. if ( value !== undefined ) {
  22768. times.push( key.time );
  22769. value.toArray( values, values.length );
  22770. }
  22771. key = jsonKeys[ i ++ ];
  22772. } while ( key !== undefined );
  22773. } else {
  22774. // otherwise push as-is
  22775. do {
  22776. value = key[ valuePropertyName ];
  22777. if ( value !== undefined ) {
  22778. times.push( key.time );
  22779. values.push( value );
  22780. }
  22781. key = jsonKeys[ i ++ ];
  22782. } while ( key !== undefined );
  22783. }
  22784. }
  22785. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22786. const clip = sourceClip.clone();
  22787. clip.name = name;
  22788. const tracks = [];
  22789. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22790. const track = clip.tracks[ i ];
  22791. const valueSize = track.getValueSize();
  22792. const times = [];
  22793. const values = [];
  22794. for ( let j = 0; j < track.times.length; ++ j ) {
  22795. const frame = track.times[ j ] * fps;
  22796. if ( frame < startFrame || frame >= endFrame ) continue;
  22797. times.push( track.times[ j ] );
  22798. for ( let k = 0; k < valueSize; ++ k ) {
  22799. values.push( track.values[ j * valueSize + k ] );
  22800. }
  22801. }
  22802. if ( times.length === 0 ) continue;
  22803. track.times = convertArray( times, track.times.constructor );
  22804. track.values = convertArray( values, track.values.constructor );
  22805. tracks.push( track );
  22806. }
  22807. clip.tracks = tracks;
  22808. // find minimum .times value across all tracks in the trimmed clip
  22809. let minStartTime = Infinity;
  22810. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22811. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22812. minStartTime = clip.tracks[ i ].times[ 0 ];
  22813. }
  22814. }
  22815. // shift all tracks such that clip begins at t=0
  22816. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22817. clip.tracks[ i ].shift( - 1 * minStartTime );
  22818. }
  22819. clip.resetDuration();
  22820. return clip;
  22821. }
  22822. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22823. if ( fps <= 0 ) fps = 30;
  22824. const numTracks = referenceClip.tracks.length;
  22825. const referenceTime = referenceFrame / fps;
  22826. // Make each track's values relative to the values at the reference frame
  22827. for ( let i = 0; i < numTracks; ++ i ) {
  22828. const referenceTrack = referenceClip.tracks[ i ];
  22829. const referenceTrackType = referenceTrack.ValueTypeName;
  22830. // Skip this track if it's non-numeric
  22831. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22832. // Find the track in the target clip whose name and type matches the reference track
  22833. const targetTrack = targetClip.tracks.find( function ( track ) {
  22834. return track.name === referenceTrack.name
  22835. && track.ValueTypeName === referenceTrackType;
  22836. } );
  22837. if ( targetTrack === undefined ) continue;
  22838. let referenceOffset = 0;
  22839. const referenceValueSize = referenceTrack.getValueSize();
  22840. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22841. referenceOffset = referenceValueSize / 3;
  22842. }
  22843. let targetOffset = 0;
  22844. const targetValueSize = targetTrack.getValueSize();
  22845. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22846. targetOffset = targetValueSize / 3;
  22847. }
  22848. const lastIndex = referenceTrack.times.length - 1;
  22849. let referenceValue;
  22850. // Find the value to subtract out of the track
  22851. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22852. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22853. const startIndex = referenceOffset;
  22854. const endIndex = referenceValueSize - referenceOffset;
  22855. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22856. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22857. // Reference frame is after the last keyframe, so just use the last keyframe
  22858. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22859. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22860. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22861. } else {
  22862. // Interpolate to the reference value
  22863. const interpolant = referenceTrack.createInterpolant();
  22864. const startIndex = referenceOffset;
  22865. const endIndex = referenceValueSize - referenceOffset;
  22866. interpolant.evaluate( referenceTime );
  22867. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22868. }
  22869. // Conjugate the quaternion
  22870. if ( referenceTrackType === 'quaternion' ) {
  22871. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22872. referenceQuat.toArray( referenceValue );
  22873. }
  22874. // Subtract the reference value from all of the track values
  22875. const numTimes = targetTrack.times.length;
  22876. for ( let j = 0; j < numTimes; ++ j ) {
  22877. const valueStart = j * targetValueSize + targetOffset;
  22878. if ( referenceTrackType === 'quaternion' ) {
  22879. // Multiply the conjugate for quaternion track types
  22880. Quaternion.multiplyQuaternionsFlat(
  22881. targetTrack.values,
  22882. valueStart,
  22883. referenceValue,
  22884. 0,
  22885. targetTrack.values,
  22886. valueStart
  22887. );
  22888. } else {
  22889. const valueEnd = targetValueSize - targetOffset * 2;
  22890. // Subtract each value for all other numeric track types
  22891. for ( let k = 0; k < valueEnd; ++ k ) {
  22892. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22893. }
  22894. }
  22895. }
  22896. }
  22897. targetClip.blendMode = AdditiveAnimationBlendMode;
  22898. return targetClip;
  22899. }
  22900. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22901. __proto__: null,
  22902. arraySlice: arraySlice,
  22903. convertArray: convertArray,
  22904. isTypedArray: isTypedArray,
  22905. getKeyframeOrder: getKeyframeOrder,
  22906. sortedArray: sortedArray,
  22907. flattenJSON: flattenJSON,
  22908. subclip: subclip,
  22909. makeClipAdditive: makeClipAdditive
  22910. });
  22911. /**
  22912. * Abstract base class of interpolants over parametric samples.
  22913. *
  22914. * The parameter domain is one dimensional, typically the time or a path
  22915. * along a curve defined by the data.
  22916. *
  22917. * The sample values can have any dimensionality and derived classes may
  22918. * apply special interpretations to the data.
  22919. *
  22920. * This class provides the interval seek in a Template Method, deferring
  22921. * the actual interpolation to derived classes.
  22922. *
  22923. * Time complexity is O(1) for linear access crossing at most two points
  22924. * and O(log N) for random access, where N is the number of positions.
  22925. *
  22926. * References:
  22927. *
  22928. * http://www.oodesign.com/template-method-pattern.html
  22929. *
  22930. */
  22931. class Interpolant {
  22932. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22933. this.parameterPositions = parameterPositions;
  22934. this._cachedIndex = 0;
  22935. this.resultBuffer = resultBuffer !== undefined ?
  22936. resultBuffer : new sampleValues.constructor( sampleSize );
  22937. this.sampleValues = sampleValues;
  22938. this.valueSize = sampleSize;
  22939. this.settings = null;
  22940. this.DefaultSettings_ = {};
  22941. }
  22942. evaluate( t ) {
  22943. const pp = this.parameterPositions;
  22944. let i1 = this._cachedIndex,
  22945. t1 = pp[ i1 ],
  22946. t0 = pp[ i1 - 1 ];
  22947. validate_interval: {
  22948. seek: {
  22949. let right;
  22950. linear_scan: {
  22951. //- See http://jsperf.com/comparison-to-undefined/3
  22952. //- slower code:
  22953. //-
  22954. //- if ( t >= t1 || t1 === undefined ) {
  22955. forward_scan: if ( ! ( t < t1 ) ) {
  22956. for ( let giveUpAt = i1 + 2; ; ) {
  22957. if ( t1 === undefined ) {
  22958. if ( t < t0 ) break forward_scan;
  22959. // after end
  22960. i1 = pp.length;
  22961. this._cachedIndex = i1;
  22962. return this.copySampleValue_( i1 - 1 );
  22963. }
  22964. if ( i1 === giveUpAt ) break; // this loop
  22965. t0 = t1;
  22966. t1 = pp[ ++ i1 ];
  22967. if ( t < t1 ) {
  22968. // we have arrived at the sought interval
  22969. break seek;
  22970. }
  22971. }
  22972. // prepare binary search on the right side of the index
  22973. right = pp.length;
  22974. break linear_scan;
  22975. }
  22976. //- slower code:
  22977. //- if ( t < t0 || t0 === undefined ) {
  22978. if ( ! ( t >= t0 ) ) {
  22979. // looping?
  22980. const t1global = pp[ 1 ];
  22981. if ( t < t1global ) {
  22982. i1 = 2; // + 1, using the scan for the details
  22983. t0 = t1global;
  22984. }
  22985. // linear reverse scan
  22986. for ( let giveUpAt = i1 - 2; ; ) {
  22987. if ( t0 === undefined ) {
  22988. // before start
  22989. this._cachedIndex = 0;
  22990. return this.copySampleValue_( 0 );
  22991. }
  22992. if ( i1 === giveUpAt ) break; // this loop
  22993. t1 = t0;
  22994. t0 = pp[ -- i1 - 1 ];
  22995. if ( t >= t0 ) {
  22996. // we have arrived at the sought interval
  22997. break seek;
  22998. }
  22999. }
  23000. // prepare binary search on the left side of the index
  23001. right = i1;
  23002. i1 = 0;
  23003. break linear_scan;
  23004. }
  23005. // the interval is valid
  23006. break validate_interval;
  23007. } // linear scan
  23008. // binary search
  23009. while ( i1 < right ) {
  23010. const mid = ( i1 + right ) >>> 1;
  23011. if ( t < pp[ mid ] ) {
  23012. right = mid;
  23013. } else {
  23014. i1 = mid + 1;
  23015. }
  23016. }
  23017. t1 = pp[ i1 ];
  23018. t0 = pp[ i1 - 1 ];
  23019. // check boundary cases, again
  23020. if ( t0 === undefined ) {
  23021. this._cachedIndex = 0;
  23022. return this.copySampleValue_( 0 );
  23023. }
  23024. if ( t1 === undefined ) {
  23025. i1 = pp.length;
  23026. this._cachedIndex = i1;
  23027. return this.copySampleValue_( i1 - 1 );
  23028. }
  23029. } // seek
  23030. this._cachedIndex = i1;
  23031. this.intervalChanged_( i1, t0, t1 );
  23032. } // validate_interval
  23033. return this.interpolate_( i1, t0, t, t1 );
  23034. }
  23035. getSettings_() {
  23036. return this.settings || this.DefaultSettings_;
  23037. }
  23038. copySampleValue_( index ) {
  23039. // copies a sample value to the result buffer
  23040. const result = this.resultBuffer,
  23041. values = this.sampleValues,
  23042. stride = this.valueSize,
  23043. offset = index * stride;
  23044. for ( let i = 0; i !== stride; ++ i ) {
  23045. result[ i ] = values[ offset + i ];
  23046. }
  23047. return result;
  23048. }
  23049. // Template methods for derived classes:
  23050. interpolate_( /* i1, t0, t, t1 */ ) {
  23051. throw new Error( 'call to abstract method' );
  23052. // implementations shall return this.resultBuffer
  23053. }
  23054. intervalChanged_( /* i1, t0, t1 */ ) {
  23055. // empty
  23056. }
  23057. }
  23058. /**
  23059. * Fast and simple cubic spline interpolant.
  23060. *
  23061. * It was derived from a Hermitian construction setting the first derivative
  23062. * at each sample position to the linear slope between neighboring positions
  23063. * over their parameter interval.
  23064. */
  23065. class CubicInterpolant extends Interpolant {
  23066. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23067. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23068. this._weightPrev = - 0;
  23069. this._offsetPrev = - 0;
  23070. this._weightNext = - 0;
  23071. this._offsetNext = - 0;
  23072. this.DefaultSettings_ = {
  23073. endingStart: ZeroCurvatureEnding,
  23074. endingEnd: ZeroCurvatureEnding
  23075. };
  23076. }
  23077. intervalChanged_( i1, t0, t1 ) {
  23078. const pp = this.parameterPositions;
  23079. let iPrev = i1 - 2,
  23080. iNext = i1 + 1,
  23081. tPrev = pp[ iPrev ],
  23082. tNext = pp[ iNext ];
  23083. if ( tPrev === undefined ) {
  23084. switch ( this.getSettings_().endingStart ) {
  23085. case ZeroSlopeEnding:
  23086. // f'(t0) = 0
  23087. iPrev = i1;
  23088. tPrev = 2 * t0 - t1;
  23089. break;
  23090. case WrapAroundEnding:
  23091. // use the other end of the curve
  23092. iPrev = pp.length - 2;
  23093. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23094. break;
  23095. default: // ZeroCurvatureEnding
  23096. // f''(t0) = 0 a.k.a. Natural Spline
  23097. iPrev = i1;
  23098. tPrev = t1;
  23099. }
  23100. }
  23101. if ( tNext === undefined ) {
  23102. switch ( this.getSettings_().endingEnd ) {
  23103. case ZeroSlopeEnding:
  23104. // f'(tN) = 0
  23105. iNext = i1;
  23106. tNext = 2 * t1 - t0;
  23107. break;
  23108. case WrapAroundEnding:
  23109. // use the other end of the curve
  23110. iNext = 1;
  23111. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23112. break;
  23113. default: // ZeroCurvatureEnding
  23114. // f''(tN) = 0, a.k.a. Natural Spline
  23115. iNext = i1 - 1;
  23116. tNext = t0;
  23117. }
  23118. }
  23119. const halfDt = ( t1 - t0 ) * 0.5,
  23120. stride = this.valueSize;
  23121. this._weightPrev = halfDt / ( t0 - tPrev );
  23122. this._weightNext = halfDt / ( tNext - t1 );
  23123. this._offsetPrev = iPrev * stride;
  23124. this._offsetNext = iNext * stride;
  23125. }
  23126. interpolate_( i1, t0, t, t1 ) {
  23127. const result = this.resultBuffer,
  23128. values = this.sampleValues,
  23129. stride = this.valueSize,
  23130. o1 = i1 * stride, o0 = o1 - stride,
  23131. oP = this._offsetPrev, oN = this._offsetNext,
  23132. wP = this._weightPrev, wN = this._weightNext,
  23133. p = ( t - t0 ) / ( t1 - t0 ),
  23134. pp = p * p,
  23135. ppp = pp * p;
  23136. // evaluate polynomials
  23137. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23138. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23139. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23140. const sN = wN * ppp - wN * pp;
  23141. // combine data linearly
  23142. for ( let i = 0; i !== stride; ++ i ) {
  23143. result[ i ] =
  23144. sP * values[ oP + i ] +
  23145. s0 * values[ o0 + i ] +
  23146. s1 * values[ o1 + i ] +
  23147. sN * values[ oN + i ];
  23148. }
  23149. return result;
  23150. }
  23151. }
  23152. class LinearInterpolant extends Interpolant {
  23153. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23154. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23155. }
  23156. interpolate_( i1, t0, t, t1 ) {
  23157. const result = this.resultBuffer,
  23158. values = this.sampleValues,
  23159. stride = this.valueSize,
  23160. offset1 = i1 * stride,
  23161. offset0 = offset1 - stride,
  23162. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23163. weight0 = 1 - weight1;
  23164. for ( let i = 0; i !== stride; ++ i ) {
  23165. result[ i ] =
  23166. values[ offset0 + i ] * weight0 +
  23167. values[ offset1 + i ] * weight1;
  23168. }
  23169. return result;
  23170. }
  23171. }
  23172. /**
  23173. *
  23174. * Interpolant that evaluates to the sample value at the position preceding
  23175. * the parameter.
  23176. */
  23177. class DiscreteInterpolant extends Interpolant {
  23178. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23179. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23180. }
  23181. interpolate_( i1 /*, t0, t, t1 */ ) {
  23182. return this.copySampleValue_( i1 - 1 );
  23183. }
  23184. }
  23185. class KeyframeTrack {
  23186. constructor( name, times, values, interpolation ) {
  23187. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23188. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23189. this.name = name;
  23190. this.times = convertArray( times, this.TimeBufferType );
  23191. this.values = convertArray( values, this.ValueBufferType );
  23192. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23193. }
  23194. // Serialization (in static context, because of constructor invocation
  23195. // and automatic invocation of .toJSON):
  23196. static toJSON( track ) {
  23197. const trackType = track.constructor;
  23198. let json;
  23199. // derived classes can define a static toJSON method
  23200. if ( trackType.toJSON !== this.toJSON ) {
  23201. json = trackType.toJSON( track );
  23202. } else {
  23203. // by default, we assume the data can be serialized as-is
  23204. json = {
  23205. 'name': track.name,
  23206. 'times': convertArray( track.times, Array ),
  23207. 'values': convertArray( track.values, Array )
  23208. };
  23209. const interpolation = track.getInterpolation();
  23210. if ( interpolation !== track.DefaultInterpolation ) {
  23211. json.interpolation = interpolation;
  23212. }
  23213. }
  23214. json.type = track.ValueTypeName; // mandatory
  23215. return json;
  23216. }
  23217. InterpolantFactoryMethodDiscrete( result ) {
  23218. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23219. }
  23220. InterpolantFactoryMethodLinear( result ) {
  23221. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23222. }
  23223. InterpolantFactoryMethodSmooth( result ) {
  23224. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23225. }
  23226. setInterpolation( interpolation ) {
  23227. let factoryMethod;
  23228. switch ( interpolation ) {
  23229. case InterpolateDiscrete:
  23230. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23231. break;
  23232. case InterpolateLinear:
  23233. factoryMethod = this.InterpolantFactoryMethodLinear;
  23234. break;
  23235. case InterpolateSmooth:
  23236. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23237. break;
  23238. }
  23239. if ( factoryMethod === undefined ) {
  23240. const message = 'unsupported interpolation for ' +
  23241. this.ValueTypeName + ' keyframe track named ' + this.name;
  23242. if ( this.createInterpolant === undefined ) {
  23243. // fall back to default, unless the default itself is messed up
  23244. if ( interpolation !== this.DefaultInterpolation ) {
  23245. this.setInterpolation( this.DefaultInterpolation );
  23246. } else {
  23247. throw new Error( message ); // fatal, in this case
  23248. }
  23249. }
  23250. console.warn( 'THREE.KeyframeTrack:', message );
  23251. return this;
  23252. }
  23253. this.createInterpolant = factoryMethod;
  23254. return this;
  23255. }
  23256. getInterpolation() {
  23257. switch ( this.createInterpolant ) {
  23258. case this.InterpolantFactoryMethodDiscrete:
  23259. return InterpolateDiscrete;
  23260. case this.InterpolantFactoryMethodLinear:
  23261. return InterpolateLinear;
  23262. case this.InterpolantFactoryMethodSmooth:
  23263. return InterpolateSmooth;
  23264. }
  23265. }
  23266. getValueSize() {
  23267. return this.values.length / this.times.length;
  23268. }
  23269. // move all keyframes either forwards or backwards in time
  23270. shift( timeOffset ) {
  23271. if ( timeOffset !== 0.0 ) {
  23272. const times = this.times;
  23273. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23274. times[ i ] += timeOffset;
  23275. }
  23276. }
  23277. return this;
  23278. }
  23279. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23280. scale( timeScale ) {
  23281. if ( timeScale !== 1.0 ) {
  23282. const times = this.times;
  23283. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23284. times[ i ] *= timeScale;
  23285. }
  23286. }
  23287. return this;
  23288. }
  23289. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23290. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23291. trim( startTime, endTime ) {
  23292. const times = this.times,
  23293. nKeys = times.length;
  23294. let from = 0,
  23295. to = nKeys - 1;
  23296. while ( from !== nKeys && times[ from ] < startTime ) {
  23297. ++ from;
  23298. }
  23299. while ( to !== - 1 && times[ to ] > endTime ) {
  23300. -- to;
  23301. }
  23302. ++ to; // inclusive -> exclusive bound
  23303. if ( from !== 0 || to !== nKeys ) {
  23304. // empty tracks are forbidden, so keep at least one keyframe
  23305. if ( from >= to ) {
  23306. to = Math.max( to, 1 );
  23307. from = to - 1;
  23308. }
  23309. const stride = this.getValueSize();
  23310. this.times = arraySlice( times, from, to );
  23311. this.values = arraySlice( this.values, from * stride, to * stride );
  23312. }
  23313. return this;
  23314. }
  23315. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23316. validate() {
  23317. let valid = true;
  23318. const valueSize = this.getValueSize();
  23319. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23320. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23321. valid = false;
  23322. }
  23323. const times = this.times,
  23324. values = this.values,
  23325. nKeys = times.length;
  23326. if ( nKeys === 0 ) {
  23327. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23328. valid = false;
  23329. }
  23330. let prevTime = null;
  23331. for ( let i = 0; i !== nKeys; i ++ ) {
  23332. const currTime = times[ i ];
  23333. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23334. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23335. valid = false;
  23336. break;
  23337. }
  23338. if ( prevTime !== null && prevTime > currTime ) {
  23339. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23340. valid = false;
  23341. break;
  23342. }
  23343. prevTime = currTime;
  23344. }
  23345. if ( values !== undefined ) {
  23346. if ( isTypedArray( values ) ) {
  23347. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23348. const value = values[ i ];
  23349. if ( isNaN( value ) ) {
  23350. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23351. valid = false;
  23352. break;
  23353. }
  23354. }
  23355. }
  23356. }
  23357. return valid;
  23358. }
  23359. // removes equivalent sequential keys as common in morph target sequences
  23360. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23361. optimize() {
  23362. // times or values may be shared with other tracks, so overwriting is unsafe
  23363. const times = arraySlice( this.times ),
  23364. values = arraySlice( this.values ),
  23365. stride = this.getValueSize(),
  23366. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23367. lastIndex = times.length - 1;
  23368. let writeIndex = 1;
  23369. for ( let i = 1; i < lastIndex; ++ i ) {
  23370. let keep = false;
  23371. const time = times[ i ];
  23372. const timeNext = times[ i + 1 ];
  23373. // remove adjacent keyframes scheduled at the same time
  23374. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23375. if ( ! smoothInterpolation ) {
  23376. // remove unnecessary keyframes same as their neighbors
  23377. const offset = i * stride,
  23378. offsetP = offset - stride,
  23379. offsetN = offset + stride;
  23380. for ( let j = 0; j !== stride; ++ j ) {
  23381. const value = values[ offset + j ];
  23382. if ( value !== values[ offsetP + j ] ||
  23383. value !== values[ offsetN + j ] ) {
  23384. keep = true;
  23385. break;
  23386. }
  23387. }
  23388. } else {
  23389. keep = true;
  23390. }
  23391. }
  23392. // in-place compaction
  23393. if ( keep ) {
  23394. if ( i !== writeIndex ) {
  23395. times[ writeIndex ] = times[ i ];
  23396. const readOffset = i * stride,
  23397. writeOffset = writeIndex * stride;
  23398. for ( let j = 0; j !== stride; ++ j ) {
  23399. values[ writeOffset + j ] = values[ readOffset + j ];
  23400. }
  23401. }
  23402. ++ writeIndex;
  23403. }
  23404. }
  23405. // flush last keyframe (compaction looks ahead)
  23406. if ( lastIndex > 0 ) {
  23407. times[ writeIndex ] = times[ lastIndex ];
  23408. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23409. values[ writeOffset + j ] = values[ readOffset + j ];
  23410. }
  23411. ++ writeIndex;
  23412. }
  23413. if ( writeIndex !== times.length ) {
  23414. this.times = arraySlice( times, 0, writeIndex );
  23415. this.values = arraySlice( values, 0, writeIndex * stride );
  23416. } else {
  23417. this.times = times;
  23418. this.values = values;
  23419. }
  23420. return this;
  23421. }
  23422. clone() {
  23423. const times = arraySlice( this.times, 0 );
  23424. const values = arraySlice( this.values, 0 );
  23425. const TypedKeyframeTrack = this.constructor;
  23426. const track = new TypedKeyframeTrack( this.name, times, values );
  23427. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23428. track.createInterpolant = this.createInterpolant;
  23429. return track;
  23430. }
  23431. }
  23432. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23433. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23434. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23435. /**
  23436. * A Track of Boolean keyframe values.
  23437. */
  23438. class BooleanKeyframeTrack extends KeyframeTrack {}
  23439. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23440. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23441. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23442. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23443. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23444. /**
  23445. * A Track of keyframe values that represent color.
  23446. */
  23447. class ColorKeyframeTrack extends KeyframeTrack {}
  23448. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23449. /**
  23450. * A Track of numeric keyframe values.
  23451. */
  23452. class NumberKeyframeTrack extends KeyframeTrack {}
  23453. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23454. /**
  23455. * Spherical linear unit quaternion interpolant.
  23456. */
  23457. class QuaternionLinearInterpolant extends Interpolant {
  23458. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23459. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23460. }
  23461. interpolate_( i1, t0, t, t1 ) {
  23462. const result = this.resultBuffer,
  23463. values = this.sampleValues,
  23464. stride = this.valueSize,
  23465. alpha = ( t - t0 ) / ( t1 - t0 );
  23466. let offset = i1 * stride;
  23467. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23468. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23469. }
  23470. return result;
  23471. }
  23472. }
  23473. /**
  23474. * A Track of quaternion keyframe values.
  23475. */
  23476. class QuaternionKeyframeTrack extends KeyframeTrack {
  23477. InterpolantFactoryMethodLinear( result ) {
  23478. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23479. }
  23480. }
  23481. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23482. // ValueBufferType is inherited
  23483. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23484. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23485. /**
  23486. * A Track that interpolates Strings
  23487. */
  23488. class StringKeyframeTrack extends KeyframeTrack {}
  23489. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23490. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23491. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23492. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23493. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23494. /**
  23495. * A Track of vectored keyframe values.
  23496. */
  23497. class VectorKeyframeTrack extends KeyframeTrack {}
  23498. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23499. class AnimationClip {
  23500. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23501. this.name = name;
  23502. this.tracks = tracks;
  23503. this.duration = duration;
  23504. this.blendMode = blendMode;
  23505. this.uuid = generateUUID();
  23506. // this means it should figure out its duration by scanning the tracks
  23507. if ( this.duration < 0 ) {
  23508. this.resetDuration();
  23509. }
  23510. }
  23511. static parse( json ) {
  23512. const tracks = [],
  23513. jsonTracks = json.tracks,
  23514. frameTime = 1.0 / ( json.fps || 1.0 );
  23515. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23516. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23517. }
  23518. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23519. clip.uuid = json.uuid;
  23520. return clip;
  23521. }
  23522. static toJSON( clip ) {
  23523. const tracks = [],
  23524. clipTracks = clip.tracks;
  23525. const json = {
  23526. 'name': clip.name,
  23527. 'duration': clip.duration,
  23528. 'tracks': tracks,
  23529. 'uuid': clip.uuid,
  23530. 'blendMode': clip.blendMode
  23531. };
  23532. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23533. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23534. }
  23535. return json;
  23536. }
  23537. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23538. const numMorphTargets = morphTargetSequence.length;
  23539. const tracks = [];
  23540. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23541. let times = [];
  23542. let values = [];
  23543. times.push(
  23544. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23545. i,
  23546. ( i + 1 ) % numMorphTargets );
  23547. values.push( 0, 1, 0 );
  23548. const order = getKeyframeOrder( times );
  23549. times = sortedArray( times, 1, order );
  23550. values = sortedArray( values, 1, order );
  23551. // if there is a key at the first frame, duplicate it as the
  23552. // last frame as well for perfect loop.
  23553. if ( ! noLoop && times[ 0 ] === 0 ) {
  23554. times.push( numMorphTargets );
  23555. values.push( values[ 0 ] );
  23556. }
  23557. tracks.push(
  23558. new NumberKeyframeTrack(
  23559. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23560. times, values
  23561. ).scale( 1.0 / fps ) );
  23562. }
  23563. return new this( name, - 1, tracks );
  23564. }
  23565. static findByName( objectOrClipArray, name ) {
  23566. let clipArray = objectOrClipArray;
  23567. if ( ! Array.isArray( objectOrClipArray ) ) {
  23568. const o = objectOrClipArray;
  23569. clipArray = o.geometry && o.geometry.animations || o.animations;
  23570. }
  23571. for ( let i = 0; i < clipArray.length; i ++ ) {
  23572. if ( clipArray[ i ].name === name ) {
  23573. return clipArray[ i ];
  23574. }
  23575. }
  23576. return null;
  23577. }
  23578. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23579. const animationToMorphTargets = {};
  23580. // tested with https://regex101.com/ on trick sequences
  23581. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23582. const pattern = /^([\w-]*?)([\d]+)$/;
  23583. // sort morph target names into animation groups based
  23584. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23585. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23586. const morphTarget = morphTargets[ i ];
  23587. const parts = morphTarget.name.match( pattern );
  23588. if ( parts && parts.length > 1 ) {
  23589. const name = parts[ 1 ];
  23590. let animationMorphTargets = animationToMorphTargets[ name ];
  23591. if ( ! animationMorphTargets ) {
  23592. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23593. }
  23594. animationMorphTargets.push( morphTarget );
  23595. }
  23596. }
  23597. const clips = [];
  23598. for ( const name in animationToMorphTargets ) {
  23599. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23600. }
  23601. return clips;
  23602. }
  23603. // parse the animation.hierarchy format
  23604. static parseAnimation( animation, bones ) {
  23605. if ( ! animation ) {
  23606. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23607. return null;
  23608. }
  23609. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23610. // only return track if there are actually keys.
  23611. if ( animationKeys.length !== 0 ) {
  23612. const times = [];
  23613. const values = [];
  23614. flattenJSON( animationKeys, times, values, propertyName );
  23615. // empty keys are filtered out, so check again
  23616. if ( times.length !== 0 ) {
  23617. destTracks.push( new trackType( trackName, times, values ) );
  23618. }
  23619. }
  23620. };
  23621. const tracks = [];
  23622. const clipName = animation.name || 'default';
  23623. const fps = animation.fps || 30;
  23624. const blendMode = animation.blendMode;
  23625. // automatic length determination in AnimationClip.
  23626. let duration = animation.length || - 1;
  23627. const hierarchyTracks = animation.hierarchy || [];
  23628. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23629. const animationKeys = hierarchyTracks[ h ].keys;
  23630. // skip empty tracks
  23631. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23632. // process morph targets
  23633. if ( animationKeys[ 0 ].morphTargets ) {
  23634. // figure out all morph targets used in this track
  23635. const morphTargetNames = {};
  23636. let k;
  23637. for ( k = 0; k < animationKeys.length; k ++ ) {
  23638. if ( animationKeys[ k ].morphTargets ) {
  23639. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23640. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23641. }
  23642. }
  23643. }
  23644. // create a track for each morph target with all zero
  23645. // morphTargetInfluences except for the keys in which
  23646. // the morphTarget is named.
  23647. for ( const morphTargetName in morphTargetNames ) {
  23648. const times = [];
  23649. const values = [];
  23650. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23651. const animationKey = animationKeys[ k ];
  23652. times.push( animationKey.time );
  23653. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23654. }
  23655. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23656. }
  23657. duration = morphTargetNames.length * fps;
  23658. } else {
  23659. // ...assume skeletal animation
  23660. const boneName = '.bones[' + bones[ h ].name + ']';
  23661. addNonemptyTrack(
  23662. VectorKeyframeTrack, boneName + '.position',
  23663. animationKeys, 'pos', tracks );
  23664. addNonemptyTrack(
  23665. QuaternionKeyframeTrack, boneName + '.quaternion',
  23666. animationKeys, 'rot', tracks );
  23667. addNonemptyTrack(
  23668. VectorKeyframeTrack, boneName + '.scale',
  23669. animationKeys, 'scl', tracks );
  23670. }
  23671. }
  23672. if ( tracks.length === 0 ) {
  23673. return null;
  23674. }
  23675. const clip = new this( clipName, duration, tracks, blendMode );
  23676. return clip;
  23677. }
  23678. resetDuration() {
  23679. const tracks = this.tracks;
  23680. let duration = 0;
  23681. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23682. const track = this.tracks[ i ];
  23683. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23684. }
  23685. this.duration = duration;
  23686. return this;
  23687. }
  23688. trim() {
  23689. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23690. this.tracks[ i ].trim( 0, this.duration );
  23691. }
  23692. return this;
  23693. }
  23694. validate() {
  23695. let valid = true;
  23696. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23697. valid = valid && this.tracks[ i ].validate();
  23698. }
  23699. return valid;
  23700. }
  23701. optimize() {
  23702. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23703. this.tracks[ i ].optimize();
  23704. }
  23705. return this;
  23706. }
  23707. clone() {
  23708. const tracks = [];
  23709. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23710. tracks.push( this.tracks[ i ].clone() );
  23711. }
  23712. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23713. }
  23714. toJSON() {
  23715. return this.constructor.toJSON( this );
  23716. }
  23717. }
  23718. function getTrackTypeForValueTypeName( typeName ) {
  23719. switch ( typeName.toLowerCase() ) {
  23720. case 'scalar':
  23721. case 'double':
  23722. case 'float':
  23723. case 'number':
  23724. case 'integer':
  23725. return NumberKeyframeTrack;
  23726. case 'vector':
  23727. case 'vector2':
  23728. case 'vector3':
  23729. case 'vector4':
  23730. return VectorKeyframeTrack;
  23731. case 'color':
  23732. return ColorKeyframeTrack;
  23733. case 'quaternion':
  23734. return QuaternionKeyframeTrack;
  23735. case 'bool':
  23736. case 'boolean':
  23737. return BooleanKeyframeTrack;
  23738. case 'string':
  23739. return StringKeyframeTrack;
  23740. }
  23741. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23742. }
  23743. function parseKeyframeTrack( json ) {
  23744. if ( json.type === undefined ) {
  23745. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23746. }
  23747. const trackType = getTrackTypeForValueTypeName( json.type );
  23748. if ( json.times === undefined ) {
  23749. const times = [], values = [];
  23750. flattenJSON( json.keys, times, values, 'value' );
  23751. json.times = times;
  23752. json.values = values;
  23753. }
  23754. // derived classes can define a static parse method
  23755. if ( trackType.parse !== undefined ) {
  23756. return trackType.parse( json );
  23757. } else {
  23758. // by default, we assume a constructor compatible with the base
  23759. return new trackType( json.name, json.times, json.values, json.interpolation );
  23760. }
  23761. }
  23762. const Cache = {
  23763. enabled: false,
  23764. files: {},
  23765. add: function ( key, file ) {
  23766. if ( this.enabled === false ) return;
  23767. // console.log( 'THREE.Cache', 'Adding key:', key );
  23768. this.files[ key ] = file;
  23769. },
  23770. get: function ( key ) {
  23771. if ( this.enabled === false ) return;
  23772. // console.log( 'THREE.Cache', 'Checking key:', key );
  23773. return this.files[ key ];
  23774. },
  23775. remove: function ( key ) {
  23776. delete this.files[ key ];
  23777. },
  23778. clear: function () {
  23779. this.files = {};
  23780. }
  23781. };
  23782. class LoadingManager {
  23783. constructor( onLoad, onProgress, onError ) {
  23784. const scope = this;
  23785. let isLoading = false;
  23786. let itemsLoaded = 0;
  23787. let itemsTotal = 0;
  23788. let urlModifier = undefined;
  23789. const handlers = [];
  23790. // Refer to #5689 for the reason why we don't set .onStart
  23791. // in the constructor
  23792. this.onStart = undefined;
  23793. this.onLoad = onLoad;
  23794. this.onProgress = onProgress;
  23795. this.onError = onError;
  23796. this.itemStart = function ( url ) {
  23797. itemsTotal ++;
  23798. if ( isLoading === false ) {
  23799. if ( scope.onStart !== undefined ) {
  23800. scope.onStart( url, itemsLoaded, itemsTotal );
  23801. }
  23802. }
  23803. isLoading = true;
  23804. };
  23805. this.itemEnd = function ( url ) {
  23806. itemsLoaded ++;
  23807. if ( scope.onProgress !== undefined ) {
  23808. scope.onProgress( url, itemsLoaded, itemsTotal );
  23809. }
  23810. if ( itemsLoaded === itemsTotal ) {
  23811. isLoading = false;
  23812. if ( scope.onLoad !== undefined ) {
  23813. scope.onLoad();
  23814. }
  23815. }
  23816. };
  23817. this.itemError = function ( url ) {
  23818. if ( scope.onError !== undefined ) {
  23819. scope.onError( url );
  23820. }
  23821. };
  23822. this.resolveURL = function ( url ) {
  23823. if ( urlModifier ) {
  23824. return urlModifier( url );
  23825. }
  23826. return url;
  23827. };
  23828. this.setURLModifier = function ( transform ) {
  23829. urlModifier = transform;
  23830. return this;
  23831. };
  23832. this.addHandler = function ( regex, loader ) {
  23833. handlers.push( regex, loader );
  23834. return this;
  23835. };
  23836. this.removeHandler = function ( regex ) {
  23837. const index = handlers.indexOf( regex );
  23838. if ( index !== - 1 ) {
  23839. handlers.splice( index, 2 );
  23840. }
  23841. return this;
  23842. };
  23843. this.getHandler = function ( file ) {
  23844. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23845. const regex = handlers[ i ];
  23846. const loader = handlers[ i + 1 ];
  23847. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23848. if ( regex.test( file ) ) {
  23849. return loader;
  23850. }
  23851. }
  23852. return null;
  23853. };
  23854. }
  23855. }
  23856. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23857. class Loader {
  23858. constructor( manager ) {
  23859. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23860. this.crossOrigin = 'anonymous';
  23861. this.withCredentials = false;
  23862. this.path = '';
  23863. this.resourcePath = '';
  23864. this.requestHeader = {};
  23865. }
  23866. load( /* url, onLoad, onProgress, onError */ ) {}
  23867. loadAsync( url, onProgress ) {
  23868. const scope = this;
  23869. return new Promise( function ( resolve, reject ) {
  23870. scope.load( url, resolve, onProgress, reject );
  23871. } );
  23872. }
  23873. parse( /* data */ ) {}
  23874. setCrossOrigin( crossOrigin ) {
  23875. this.crossOrigin = crossOrigin;
  23876. return this;
  23877. }
  23878. setWithCredentials( value ) {
  23879. this.withCredentials = value;
  23880. return this;
  23881. }
  23882. setPath( path ) {
  23883. this.path = path;
  23884. return this;
  23885. }
  23886. setResourcePath( resourcePath ) {
  23887. this.resourcePath = resourcePath;
  23888. return this;
  23889. }
  23890. setRequestHeader( requestHeader ) {
  23891. this.requestHeader = requestHeader;
  23892. return this;
  23893. }
  23894. }
  23895. const loading = {};
  23896. class HttpError extends Error {
  23897. constructor( message, response ) {
  23898. super( message );
  23899. this.response = response;
  23900. }
  23901. }
  23902. class FontLoader extends Loader {
  23903. constructor( manager ) {
  23904. super( manager );
  23905. }
  23906. load( url, onLoad, onProgress, onError ) {
  23907. const scope = this;
  23908. const loader = new FileLoader( this.manager );
  23909. loader.setPath( this.path );
  23910. loader.setRequestHeader( this.requestHeader );
  23911. loader.setWithCredentials( this.withCredentials );
  23912. loader.load( url, function ( text ) {
  23913. const font = scope.parse( JSON.parse( text ) );
  23914. if ( onLoad ) onLoad( font );
  23915. }, onProgress, onError );
  23916. }
  23917. parse( json ) {
  23918. return new Font( json );
  23919. }
  23920. }
  23921. // // 加载 字体
  23922. // class FontLoaderLoad {
  23923. //
  23924. // constructor( ) {
  23925. //
  23926. //
  23927. //
  23928. // }
  23929. //
  23930. //
  23931. //
  23932. // }
  23933. //
  23934. class Font {
  23935. constructor( data ) {
  23936. this.isFont = true;
  23937. this.type = 'Font';
  23938. this.data = data;
  23939. }
  23940. generateShapes( text, size = 100 ) {
  23941. const shapes = [];
  23942. const paths = createPaths( text, size, this.data );
  23943. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  23944. shapes.push( ...paths[ p ].toShapes() );
  23945. }
  23946. return shapes;
  23947. }
  23948. }
  23949. function createPaths( text, size, data ) {
  23950. const chars = Array.from( text );
  23951. const scale = size / data.resolution;
  23952. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  23953. const paths = [];
  23954. let offsetX = 0, offsetY = 0;
  23955. for ( let i = 0; i < chars.length; i ++ ) {
  23956. const char = chars[ i ];
  23957. if ( char === '\n' ) {
  23958. offsetX = 0;
  23959. offsetY -= line_height;
  23960. } else {
  23961. const ret = createPath( char, scale, offsetX, offsetY, data );
  23962. offsetX += ret.offsetX;
  23963. paths.push( ret.path );
  23964. }
  23965. }
  23966. return paths;
  23967. }
  23968. function createPath( char, scale, offsetX, offsetY, data ) {
  23969. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  23970. if ( ! glyph ) {
  23971. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  23972. return;
  23973. }
  23974. const path = new ShapePath();
  23975. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23976. if ( glyph.o ) {
  23977. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  23978. for ( let i = 0, l = outline.length; i < l; ) {
  23979. const action = outline[ i ++ ];
  23980. switch ( action ) {
  23981. case 'm': // moveTo
  23982. x = outline[ i ++ ] * scale + offsetX;
  23983. y = outline[ i ++ ] * scale + offsetY;
  23984. path.moveTo( x, y );
  23985. break;
  23986. case 'l': // lineTo
  23987. x = outline[ i ++ ] * scale + offsetX;
  23988. y = outline[ i ++ ] * scale + offsetY;
  23989. path.lineTo( x, y );
  23990. break;
  23991. case 'q': // quadraticCurveTo
  23992. cpx = outline[ i ++ ] * scale + offsetX;
  23993. cpy = outline[ i ++ ] * scale + offsetY;
  23994. cpx1 = outline[ i ++ ] * scale + offsetX;
  23995. cpy1 = outline[ i ++ ] * scale + offsetY;
  23996. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  23997. break;
  23998. case 'b': // bezierCurveTo
  23999. cpx = outline[ i ++ ] * scale + offsetX;
  24000. cpy = outline[ i ++ ] * scale + offsetY;
  24001. cpx1 = outline[ i ++ ] * scale + offsetX;
  24002. cpy1 = outline[ i ++ ] * scale + offsetY;
  24003. cpx2 = outline[ i ++ ] * scale + offsetX;
  24004. cpy2 = outline[ i ++ ] * scale + offsetY;
  24005. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  24006. break;
  24007. }
  24008. }
  24009. }
  24010. return { offsetX: glyph.ha * scale, path: path };
  24011. }
  24012. class FileLoader extends Loader {
  24013. constructor( manager ) {
  24014. super( manager );
  24015. }
  24016. load( url, onLoad, onProgress, onError ) {
  24017. if ( url === undefined ) url = '';
  24018. if ( this.path !== undefined ) url = this.path + url;
  24019. url = this.manager.resolveURL( url );
  24020. const cached = Cache.get( url );
  24021. if ( cached !== undefined ) {
  24022. this.manager.itemStart( url );
  24023. setTimeout( () => {
  24024. if ( onLoad ) onLoad( cached );
  24025. this.manager.itemEnd( url );
  24026. }, 0 );
  24027. return cached;
  24028. }
  24029. // Check if request is duplicate
  24030. if ( loading[ url ] !== undefined ) {
  24031. loading[ url ].push( {
  24032. onLoad: onLoad,
  24033. onProgress: onProgress,
  24034. onError: onError
  24035. } );
  24036. return;
  24037. }
  24038. // Initialise array for duplicate requests
  24039. loading[ url ] = [];
  24040. loading[ url ].push( {
  24041. onLoad: onLoad,
  24042. onProgress: onProgress,
  24043. onError: onError,
  24044. } );
  24045. // create request
  24046. const req = new Request( url, {
  24047. headers: new Headers( this.requestHeader ),
  24048. credentials: this.withCredentials ? 'include' : 'same-origin',
  24049. // An abort controller could be added within a future PR
  24050. } );
  24051. // record states ( avoid data race )
  24052. const mimeType = this.mimeType;
  24053. const responseType = this.responseType;
  24054. // start the fetch
  24055. fetch( req )
  24056. .then( response => {
  24057. if ( response.status === 200 || response.status === 0 ) {
  24058. // Some browsers return HTTP Status 0 when using non-http protocol
  24059. // e.g. 'file://' or 'data://'. Handle as success.
  24060. if ( response.status === 0 ) {
  24061. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24062. }
  24063. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24064. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24065. return response;
  24066. }
  24067. const callbacks = loading[ url ];
  24068. const reader = response.body.getReader();
  24069. const contentLength = response.headers.get( 'Content-Length' );
  24070. const total = contentLength ? parseInt( contentLength ) : 0;
  24071. const lengthComputable = total !== 0;
  24072. let loaded = 0;
  24073. console.log("callbacks:",callbacks,loading)
  24074. if(callbacks === undefined){ return response; }
  24075. // periodically read data into the new stream tracking while download progress
  24076. const stream = new ReadableStream( {
  24077. start( controller ) {
  24078. readData();
  24079. function readData() {
  24080. reader.read().then( ( { done, value } ) => {
  24081. if ( done ) {
  24082. controller.close();
  24083. } else {
  24084. loaded += value.byteLength;
  24085. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24086. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24087. const callback = callbacks[ i ];
  24088. if ( callback.onProgress ) callback.onProgress( event );
  24089. }
  24090. controller.enqueue( value );
  24091. readData();
  24092. }
  24093. } );
  24094. }
  24095. }
  24096. } );
  24097. return new Response( stream );
  24098. } else {
  24099. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24100. }
  24101. } )
  24102. .then( response => {
  24103. switch ( responseType ) {
  24104. case 'arraybuffer':
  24105. return response.arrayBuffer();
  24106. case 'blob':
  24107. return response.blob();
  24108. case 'document':
  24109. return response.text()
  24110. .then( text => {
  24111. const parser = new DOMParser();
  24112. return parser.parseFromString( text, mimeType );
  24113. } );
  24114. case 'json':
  24115. return response.json();
  24116. default:
  24117. if ( mimeType === undefined ) {
  24118. return response.text();
  24119. } else {
  24120. // sniff encoding
  24121. const re = /charset="?([^;"\s]*)"?/i;
  24122. const exec = re.exec( mimeType );
  24123. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24124. const decoder = new TextDecoder( label );
  24125. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24126. }
  24127. }
  24128. } )
  24129. .then( data => {
  24130. // Add to cache only on HTTP success, so that we do not cache
  24131. // error response bodies as proper responses to requests.
  24132. Cache.add( url, data );
  24133. const callbacks = loading[ url ];
  24134. delete loading[ url ];
  24135. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24136. const callback = callbacks[ i ];
  24137. if ( callback.onLoad ) callback.onLoad( data );
  24138. }
  24139. } )
  24140. .catch( err => {
  24141. // Abort errors and other errors are handled the same
  24142. const callbacks = loading[ url ];
  24143. if ( callbacks === undefined ) {
  24144. // When onLoad was called and url was deleted in `loading`
  24145. this.manager.itemError( url );
  24146. throw err;
  24147. }
  24148. delete loading[ url ];
  24149. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24150. const callback = callbacks[ i ];
  24151. if ( callback.onError ) callback.onError( err );
  24152. }
  24153. this.manager.itemError( url );
  24154. } )
  24155. .finally( () => {
  24156. this.manager.itemEnd( url );
  24157. } );
  24158. this.manager.itemStart( url );
  24159. }
  24160. setResponseType( value ) {
  24161. this.responseType = value;
  24162. return this;
  24163. }
  24164. setMimeType( value ) {
  24165. this.mimeType = value;
  24166. return this;
  24167. }
  24168. }
  24169. class AnimationLoader extends Loader {
  24170. constructor( manager ) {
  24171. super( manager );
  24172. }
  24173. load( url, onLoad, onProgress, onError ) {
  24174. const scope = this;
  24175. const loader = new FileLoader( this.manager );
  24176. loader.setPath( this.path );
  24177. loader.setRequestHeader( this.requestHeader );
  24178. loader.setWithCredentials( this.withCredentials );
  24179. loader.load( url, function ( text ) {
  24180. try {
  24181. onLoad( scope.parse( JSON.parse( text ) ) );
  24182. } catch ( e ) {
  24183. if ( onError ) {
  24184. onError( e );
  24185. } else {
  24186. console.error( e );
  24187. }
  24188. scope.manager.itemError( url );
  24189. }
  24190. }, onProgress, onError );
  24191. }
  24192. parse( json ) {
  24193. const animations = [];
  24194. for ( let i = 0; i < json.length; i ++ ) {
  24195. const clip = AnimationClip.parse( json[ i ] );
  24196. animations.push( clip );
  24197. }
  24198. return animations;
  24199. }
  24200. }
  24201. /**
  24202. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24203. *
  24204. * Sub classes have to implement the parse() method which will be used in load().
  24205. */
  24206. class CompressedTextureLoader extends Loader {
  24207. constructor( manager ) {
  24208. super( manager );
  24209. }
  24210. load( url, onLoad, onProgress, onError ) {
  24211. const scope = this;
  24212. const images = [];
  24213. const texture = new CompressedTexture();
  24214. const loader = new FileLoader( this.manager );
  24215. loader.setPath( this.path );
  24216. loader.setResponseType( 'arraybuffer' );
  24217. loader.setRequestHeader( this.requestHeader );
  24218. loader.setWithCredentials( scope.withCredentials );
  24219. let loaded = 0;
  24220. function loadTexture( i ) {
  24221. loader.load( url[ i ], function ( buffer ) {
  24222. const texDatas = scope.parse( buffer, true );
  24223. images[ i ] = {
  24224. width: texDatas.width,
  24225. height: texDatas.height,
  24226. format: texDatas.format,
  24227. mipmaps: texDatas.mipmaps
  24228. };
  24229. loaded += 1;
  24230. if ( loaded === 6 ) {
  24231. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24232. texture.image = images;
  24233. texture.format = texDatas.format;
  24234. texture.needsUpdate = true;
  24235. if ( onLoad ) onLoad( texture );
  24236. }
  24237. }, onProgress, onError );
  24238. }
  24239. if ( Array.isArray( url ) ) {
  24240. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24241. loadTexture( i );
  24242. }
  24243. } else {
  24244. // compressed cubemap texture stored in a single DDS file
  24245. loader.load( url, function ( buffer ) {
  24246. const texDatas = scope.parse( buffer, true );
  24247. if ( texDatas.isCubemap ) {
  24248. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24249. for ( let f = 0; f < faces; f ++ ) {
  24250. images[ f ] = { mipmaps: [] };
  24251. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24252. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24253. images[ f ].format = texDatas.format;
  24254. images[ f ].width = texDatas.width;
  24255. images[ f ].height = texDatas.height;
  24256. }
  24257. }
  24258. texture.image = images;
  24259. } else {
  24260. texture.image.width = texDatas.width;
  24261. texture.image.height = texDatas.height;
  24262. texture.mipmaps = texDatas.mipmaps;
  24263. }
  24264. if ( texDatas.mipmapCount === 1 ) {
  24265. texture.minFilter = LinearFilter;
  24266. }
  24267. texture.format = texDatas.format;
  24268. texture.needsUpdate = true;
  24269. if ( onLoad ) onLoad( texture );
  24270. }, onProgress, onError );
  24271. }
  24272. return texture;
  24273. }
  24274. }
  24275. class ImageLoader extends Loader {
  24276. constructor( manager ) {
  24277. super( manager );
  24278. }
  24279. load( url, onLoad, onProgress, onError ) {
  24280. if ( this.path !== undefined ) url = this.path + url;
  24281. url = this.manager.resolveURL( url );
  24282. const scope = this;
  24283. const cached = Cache.get( url );
  24284. if ( cached !== undefined ) {
  24285. scope.manager.itemStart( url );
  24286. setTimeout( function () {
  24287. if ( onLoad ) onLoad( cached );
  24288. scope.manager.itemEnd( url );
  24289. }, 0 );
  24290. return cached;
  24291. }
  24292. const image = createElementNS( 'img' );
  24293. function onImageLoad() {
  24294. removeEventListeners();
  24295. Cache.add( url, this );
  24296. if ( onLoad ) onLoad( this );
  24297. scope.manager.itemEnd( url );
  24298. }
  24299. function onImageError( event ) {
  24300. removeEventListeners();
  24301. if ( onError ) onError( event );
  24302. scope.manager.itemError( url );
  24303. scope.manager.itemEnd( url );
  24304. }
  24305. function removeEventListeners() {
  24306. image.removeEventListener( 'load', onImageLoad, false );
  24307. image.removeEventListener( 'error', onImageError, false );
  24308. }
  24309. image.addEventListener( 'load', onImageLoad, false );
  24310. image.addEventListener( 'error', onImageError, false );
  24311. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24312. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24313. }
  24314. scope.manager.itemStart( url );
  24315. image.src = url;
  24316. return image;
  24317. }
  24318. }
  24319. class CubeTextureLoader extends Loader {
  24320. constructor( manager ) {
  24321. super( manager );
  24322. }
  24323. load( urls, onLoad, onProgress, onError ) {
  24324. const texture = new CubeTexture();
  24325. const loader = new ImageLoader( this.manager );
  24326. loader.setCrossOrigin( this.crossOrigin );
  24327. loader.setPath( this.path );
  24328. let loaded = 0;
  24329. function loadTexture( i ) {
  24330. loader.load( urls[ i ], function ( image ) {
  24331. texture.images[ i ] = image;
  24332. loaded ++;
  24333. if ( loaded === 6 ) {
  24334. texture.needsUpdate = true;
  24335. if ( onLoad ) onLoad( texture );
  24336. }
  24337. }, undefined, onError );
  24338. }
  24339. for ( let i = 0; i < urls.length; ++ i ) {
  24340. loadTexture( i );
  24341. }
  24342. return texture;
  24343. }
  24344. }
  24345. /**
  24346. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24347. *
  24348. * Sub classes have to implement the parse() method which will be used in load().
  24349. */
  24350. class DataTextureLoader extends Loader {
  24351. constructor( manager ) {
  24352. super( manager );
  24353. }
  24354. load( url, onLoad, onProgress, onError ) {
  24355. const scope = this;
  24356. const texture = new DataTexture();
  24357. const loader = new FileLoader( this.manager );
  24358. loader.setResponseType( 'arraybuffer' );
  24359. loader.setRequestHeader( this.requestHeader );
  24360. loader.setPath( this.path );
  24361. loader.setWithCredentials( scope.withCredentials );
  24362. loader.load( url, function ( buffer ) {
  24363. const texData = scope.parse( buffer );
  24364. if ( ! texData ) return;
  24365. if ( texData.image !== undefined ) {
  24366. texture.image = texData.image;
  24367. } else if ( texData.data !== undefined ) {
  24368. texture.image.width = texData.width;
  24369. texture.image.height = texData.height;
  24370. texture.image.data = texData.data;
  24371. }
  24372. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24373. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24374. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24375. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24376. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24377. if ( texData.encoding !== undefined ) {
  24378. texture.encoding = texData.encoding;
  24379. }
  24380. if ( texData.flipY !== undefined ) {
  24381. texture.flipY = texData.flipY;
  24382. }
  24383. if ( texData.format !== undefined ) {
  24384. texture.format = texData.format;
  24385. }
  24386. if ( texData.type !== undefined ) {
  24387. texture.type = texData.type;
  24388. }
  24389. if ( texData.mipmaps !== undefined ) {
  24390. texture.mipmaps = texData.mipmaps;
  24391. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24392. }
  24393. if ( texData.mipmapCount === 1 ) {
  24394. texture.minFilter = LinearFilter;
  24395. }
  24396. if ( texData.generateMipmaps !== undefined ) {
  24397. texture.generateMipmaps = texData.generateMipmaps;
  24398. }
  24399. texture.needsUpdate = true;
  24400. if ( onLoad ) onLoad( texture, texData );
  24401. }, onProgress, onError );
  24402. return texture;
  24403. }
  24404. }
  24405. class TextureLoader extends Loader {
  24406. constructor( manager ) {
  24407. super( manager );
  24408. }
  24409. load( url, onLoad, onProgress, onError ) {
  24410. const texture = new Texture();
  24411. const loader = new ImageLoader( this.manager );
  24412. loader.setCrossOrigin( this.crossOrigin );
  24413. loader.setPath( this.path );
  24414. loader.load( url, function ( image ) {
  24415. texture.image = image;
  24416. texture.needsUpdate = true;
  24417. if ( onLoad !== undefined ) {
  24418. onLoad( texture );
  24419. }
  24420. }, onProgress, onError );
  24421. return texture;
  24422. }
  24423. }
  24424. class Light extends Object3D {
  24425. constructor( color, intensity = 1 ) {
  24426. super();
  24427. this.isLight = true;
  24428. this.type = 'Light';
  24429. this.color = new Color( color );
  24430. this.intensity = intensity;
  24431. }
  24432. dispose() {
  24433. // Empty here in base class; some subclasses override.
  24434. }
  24435. copy( source, recursive ) {
  24436. super.copy( source, recursive );
  24437. this.color.copy( source.color );
  24438. this.intensity = source.intensity;
  24439. return this;
  24440. }
  24441. toJSON( meta ) {
  24442. const data = super.toJSON( meta );
  24443. data.object.color = this.color.getHex();
  24444. data.object.intensity = this.intensity;
  24445. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24446. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24447. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24448. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24449. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24450. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24451. return data;
  24452. }
  24453. }
  24454. class HemisphereLight extends Light {
  24455. constructor( skyColor, groundColor, intensity ) {
  24456. super( skyColor, intensity );
  24457. this.isHemisphereLight = true;
  24458. this.type = 'HemisphereLight';
  24459. this.position.copy( Object3D.DefaultUp );
  24460. this.updateMatrix();
  24461. this.groundColor = new Color( groundColor );
  24462. }
  24463. copy( source, recursive ) {
  24464. super.copy( source, recursive );
  24465. this.groundColor.copy( source.groundColor );
  24466. return this;
  24467. }
  24468. }
  24469. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24470. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24471. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24472. class LightShadow {
  24473. constructor( camera ) {
  24474. this.camera = camera;
  24475. this.bias = 0;
  24476. this.normalBias = 0;
  24477. this.radius = 1;
  24478. this.blurSamples = 8;
  24479. this.mapSize = new Vector2( 512, 512 );
  24480. this.map = null;
  24481. this.mapPass = null;
  24482. this.matrix = new Matrix4();
  24483. this.autoUpdate = true;
  24484. this.needsUpdate = false;
  24485. this._frustum = new Frustum();
  24486. this._frameExtents = new Vector2( 1, 1 );
  24487. this._viewportCount = 1;
  24488. this._viewports = [
  24489. new Vector4( 0, 0, 1, 1 )
  24490. ];
  24491. }
  24492. getViewportCount() {
  24493. return this._viewportCount;
  24494. }
  24495. getFrustum() {
  24496. return this._frustum;
  24497. }
  24498. updateMatrices( light ) {
  24499. const shadowCamera = this.camera;
  24500. const shadowMatrix = this.matrix;
  24501. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24502. shadowCamera.position.copy( _lightPositionWorld$1 );
  24503. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24504. shadowCamera.lookAt( _lookTarget$1 );
  24505. shadowCamera.updateMatrixWorld();
  24506. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24507. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24508. shadowMatrix.set(
  24509. 0.5, 0.0, 0.0, 0.5,
  24510. 0.0, 0.5, 0.0, 0.5,
  24511. 0.0, 0.0, 0.5, 0.5,
  24512. 0.0, 0.0, 0.0, 1.0
  24513. );
  24514. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24515. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24516. }
  24517. getViewport( viewportIndex ) {
  24518. return this._viewports[ viewportIndex ];
  24519. }
  24520. getFrameExtents() {
  24521. return this._frameExtents;
  24522. }
  24523. dispose() {
  24524. if ( this.map ) {
  24525. this.map.dispose();
  24526. }
  24527. if ( this.mapPass ) {
  24528. this.mapPass.dispose();
  24529. }
  24530. }
  24531. copy( source ) {
  24532. this.camera = source.camera.clone();
  24533. this.bias = source.bias;
  24534. this.radius = source.radius;
  24535. this.mapSize.copy( source.mapSize );
  24536. return this;
  24537. }
  24538. clone() {
  24539. return new this.constructor().copy( this );
  24540. }
  24541. toJSON() {
  24542. const object = {};
  24543. if ( this.bias !== 0 ) object.bias = this.bias;
  24544. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24545. if ( this.radius !== 1 ) object.radius = this.radius;
  24546. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24547. object.camera = this.camera.toJSON( false ).object;
  24548. delete object.camera.matrix;
  24549. return object;
  24550. }
  24551. }
  24552. class SpotLightShadow extends LightShadow {
  24553. constructor() {
  24554. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24555. this.isSpotLightShadow = true;
  24556. this.focus = 1;
  24557. }
  24558. updateMatrices( light ) {
  24559. const camera = this.camera;
  24560. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24561. const aspect = this.mapSize.width / this.mapSize.height;
  24562. const far = light.distance || camera.far;
  24563. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24564. camera.fov = fov;
  24565. camera.aspect = aspect;
  24566. camera.far = far;
  24567. camera.updateProjectionMatrix();
  24568. }
  24569. super.updateMatrices( light );
  24570. }
  24571. copy( source ) {
  24572. super.copy( source );
  24573. this.focus = source.focus;
  24574. return this;
  24575. }
  24576. }
  24577. class SpotLight extends Light {
  24578. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  24579. super( color, intensity );
  24580. this.isSpotLight = true;
  24581. this.type = 'SpotLight';
  24582. this.position.copy( Object3D.DefaultUp );
  24583. this.updateMatrix();
  24584. this.target = new Object3D();
  24585. this.distance = distance;
  24586. this.angle = angle;
  24587. this.penumbra = penumbra;
  24588. this.decay = decay; // for physically correct lights, should be 2.
  24589. this.map = null;
  24590. this.shadow = new SpotLightShadow();
  24591. }
  24592. get power() {
  24593. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24594. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24595. return this.intensity * Math.PI;
  24596. }
  24597. set power( power ) {
  24598. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24599. this.intensity = power / Math.PI;
  24600. }
  24601. dispose() {
  24602. this.shadow.dispose();
  24603. }
  24604. copy( source, recursive ) {
  24605. super.copy( source, recursive );
  24606. this.distance = source.distance;
  24607. this.angle = source.angle;
  24608. this.penumbra = source.penumbra;
  24609. this.decay = source.decay;
  24610. this.target = source.target.clone();
  24611. this.shadow = source.shadow.clone();
  24612. return this;
  24613. }
  24614. }
  24615. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24616. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24617. const _lookTarget = /*@__PURE__*/ new Vector3();
  24618. class PointLightShadow extends LightShadow {
  24619. constructor() {
  24620. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24621. this.isPointLightShadow = true;
  24622. this._frameExtents = new Vector2( 4, 2 );
  24623. this._viewportCount = 6;
  24624. this._viewports = [
  24625. // These viewports map a cube-map onto a 2D texture with the
  24626. // following orientation:
  24627. //
  24628. // xzXZ
  24629. // y Y
  24630. //
  24631. // X - Positive x direction
  24632. // x - Negative x direction
  24633. // Y - Positive y direction
  24634. // y - Negative y direction
  24635. // Z - Positive z direction
  24636. // z - Negative z direction
  24637. // positive X
  24638. new Vector4( 2, 1, 1, 1 ),
  24639. // negative X
  24640. new Vector4( 0, 1, 1, 1 ),
  24641. // positive Z
  24642. new Vector4( 3, 1, 1, 1 ),
  24643. // negative Z
  24644. new Vector4( 1, 1, 1, 1 ),
  24645. // positive Y
  24646. new Vector4( 3, 0, 1, 1 ),
  24647. // negative Y
  24648. new Vector4( 1, 0, 1, 1 )
  24649. ];
  24650. this._cubeDirections = [
  24651. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24652. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24653. ];
  24654. this._cubeUps = [
  24655. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24656. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24657. ];
  24658. }
  24659. updateMatrices( light, viewportIndex = 0 ) {
  24660. const camera = this.camera;
  24661. const shadowMatrix = this.matrix;
  24662. const far = light.distance || camera.far;
  24663. if ( far !== camera.far ) {
  24664. camera.far = far;
  24665. camera.updateProjectionMatrix();
  24666. }
  24667. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24668. camera.position.copy( _lightPositionWorld );
  24669. _lookTarget.copy( camera.position );
  24670. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24671. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24672. camera.lookAt( _lookTarget );
  24673. camera.updateMatrixWorld();
  24674. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24675. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24676. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24677. }
  24678. }
  24679. class PointLight extends Light {
  24680. constructor( color, intensity, distance = 0, decay = 1 ) {
  24681. super( color, intensity );
  24682. this.isPointLight = true;
  24683. this.type = 'PointLight';
  24684. this.distance = distance;
  24685. this.decay = decay; // for physically correct lights, should be 2.
  24686. this.shadow = new PointLightShadow();
  24687. }
  24688. get power() {
  24689. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24690. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24691. return this.intensity * 4 * Math.PI;
  24692. }
  24693. set power( power ) {
  24694. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24695. this.intensity = power / ( 4 * Math.PI );
  24696. }
  24697. dispose() {
  24698. this.shadow.dispose();
  24699. }
  24700. copy( source, recursive ) {
  24701. super.copy( source, recursive );
  24702. this.distance = source.distance;
  24703. this.decay = source.decay;
  24704. this.shadow = source.shadow.clone();
  24705. return this;
  24706. }
  24707. }
  24708. class DirectionalLightShadow extends LightShadow {
  24709. constructor() {
  24710. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24711. this.isDirectionalLightShadow = true;
  24712. }
  24713. }
  24714. class DirectionalLight extends Light {
  24715. constructor( color, intensity ) {
  24716. super( color, intensity );
  24717. this.isDirectionalLight = true;
  24718. this.type = 'DirectionalLight';
  24719. this.position.copy( Object3D.DefaultUp );
  24720. this.updateMatrix();
  24721. this.target = new Object3D();
  24722. this.shadow = new DirectionalLightShadow();
  24723. }
  24724. dispose() {
  24725. this.shadow.dispose();
  24726. }
  24727. copy( source ) {
  24728. super.copy( source );
  24729. this.target = source.target.clone();
  24730. this.shadow = source.shadow.clone();
  24731. return this;
  24732. }
  24733. }
  24734. class AmbientLight extends Light {
  24735. constructor( color, intensity ) {
  24736. super( color, intensity );
  24737. this.isAmbientLight = true;
  24738. this.type = 'AmbientLight';
  24739. }
  24740. }
  24741. class RectAreaLight extends Light {
  24742. constructor( color, intensity, width = 10, height = 10 ) {
  24743. super( color, intensity );
  24744. this.isRectAreaLight = true;
  24745. this.type = 'RectAreaLight';
  24746. this.width = width;
  24747. this.height = height;
  24748. }
  24749. get power() {
  24750. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24751. return this.intensity * this.width * this.height * Math.PI;
  24752. }
  24753. set power( power ) {
  24754. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24755. this.intensity = power / ( this.width * this.height * Math.PI );
  24756. }
  24757. copy( source ) {
  24758. super.copy( source );
  24759. this.width = source.width;
  24760. this.height = source.height;
  24761. return this;
  24762. }
  24763. toJSON( meta ) {
  24764. const data = super.toJSON( meta );
  24765. data.object.width = this.width;
  24766. data.object.height = this.height;
  24767. return data;
  24768. }
  24769. }
  24770. /**
  24771. * Primary reference:
  24772. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24773. *
  24774. * Secondary reference:
  24775. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24776. */
  24777. // 3-band SH defined by 9 coefficients
  24778. class SphericalHarmonics3 {
  24779. constructor() {
  24780. this.isSphericalHarmonics3 = true;
  24781. this.coefficients = [];
  24782. for ( let i = 0; i < 9; i ++ ) {
  24783. this.coefficients.push( new Vector3() );
  24784. }
  24785. }
  24786. set( coefficients ) {
  24787. for ( let i = 0; i < 9; i ++ ) {
  24788. this.coefficients[ i ].copy( coefficients[ i ] );
  24789. }
  24790. return this;
  24791. }
  24792. zero() {
  24793. for ( let i = 0; i < 9; i ++ ) {
  24794. this.coefficients[ i ].set( 0, 0, 0 );
  24795. }
  24796. return this;
  24797. }
  24798. // get the radiance in the direction of the normal
  24799. // target is a Vector3
  24800. getAt( normal, target ) {
  24801. // normal is assumed to be unit length
  24802. const x = normal.x, y = normal.y, z = normal.z;
  24803. const coeff = this.coefficients;
  24804. // band 0
  24805. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24806. // band 1
  24807. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24808. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24809. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24810. // band 2
  24811. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24812. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24813. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24814. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24815. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24816. return target;
  24817. }
  24818. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24819. // target is a Vector3
  24820. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24821. getIrradianceAt( normal, target ) {
  24822. // normal is assumed to be unit length
  24823. const x = normal.x, y = normal.y, z = normal.z;
  24824. const coeff = this.coefficients;
  24825. // band 0
  24826. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24827. // band 1
  24828. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24829. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24830. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24831. // band 2
  24832. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24833. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24834. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24835. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24836. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24837. return target;
  24838. }
  24839. add( sh ) {
  24840. for ( let i = 0; i < 9; i ++ ) {
  24841. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24842. }
  24843. return this;
  24844. }
  24845. addScaledSH( sh, s ) {
  24846. for ( let i = 0; i < 9; i ++ ) {
  24847. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24848. }
  24849. return this;
  24850. }
  24851. scale( s ) {
  24852. for ( let i = 0; i < 9; i ++ ) {
  24853. this.coefficients[ i ].multiplyScalar( s );
  24854. }
  24855. return this;
  24856. }
  24857. lerp( sh, alpha ) {
  24858. for ( let i = 0; i < 9; i ++ ) {
  24859. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24860. }
  24861. return this;
  24862. }
  24863. equals( sh ) {
  24864. for ( let i = 0; i < 9; i ++ ) {
  24865. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24866. return false;
  24867. }
  24868. }
  24869. return true;
  24870. }
  24871. copy( sh ) {
  24872. return this.set( sh.coefficients );
  24873. }
  24874. clone() {
  24875. return new this.constructor().copy( this );
  24876. }
  24877. fromArray( array, offset = 0 ) {
  24878. const coefficients = this.coefficients;
  24879. for ( let i = 0; i < 9; i ++ ) {
  24880. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24881. }
  24882. return this;
  24883. }
  24884. toArray( array = [], offset = 0 ) {
  24885. const coefficients = this.coefficients;
  24886. for ( let i = 0; i < 9; i ++ ) {
  24887. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24888. }
  24889. return array;
  24890. }
  24891. // evaluate the basis functions
  24892. // shBasis is an Array[ 9 ]
  24893. static getBasisAt( normal, shBasis ) {
  24894. // normal is assumed to be unit length
  24895. const x = normal.x, y = normal.y, z = normal.z;
  24896. // band 0
  24897. shBasis[ 0 ] = 0.282095;
  24898. // band 1
  24899. shBasis[ 1 ] = 0.488603 * y;
  24900. shBasis[ 2 ] = 0.488603 * z;
  24901. shBasis[ 3 ] = 0.488603 * x;
  24902. // band 2
  24903. shBasis[ 4 ] = 1.092548 * x * y;
  24904. shBasis[ 5 ] = 1.092548 * y * z;
  24905. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24906. shBasis[ 7 ] = 1.092548 * x * z;
  24907. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24908. }
  24909. }
  24910. class LightProbe extends Light {
  24911. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24912. super( undefined, intensity );
  24913. this.isLightProbe = true;
  24914. this.sh = sh;
  24915. }
  24916. copy( source ) {
  24917. super.copy( source );
  24918. this.sh.copy( source.sh );
  24919. return this;
  24920. }
  24921. fromJSON( json ) {
  24922. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24923. this.sh.fromArray( json.sh );
  24924. return this;
  24925. }
  24926. toJSON( meta ) {
  24927. const data = super.toJSON( meta );
  24928. data.object.sh = this.sh.toArray();
  24929. return data;
  24930. }
  24931. }
  24932. class MaterialLoader extends Loader {
  24933. constructor( manager ) {
  24934. super( manager );
  24935. this.textures = {};
  24936. }
  24937. load( url, onLoad, onProgress, onError ) {
  24938. const scope = this;
  24939. const loader = new FileLoader( scope.manager );
  24940. loader.setPath( scope.path );
  24941. loader.setRequestHeader( scope.requestHeader );
  24942. loader.setWithCredentials( scope.withCredentials );
  24943. loader.load( url, function ( text ) {
  24944. try {
  24945. onLoad( scope.parse( JSON.parse( text ) ) );
  24946. } catch ( e ) {
  24947. if ( onError ) {
  24948. onError( e );
  24949. } else {
  24950. console.error( e );
  24951. }
  24952. scope.manager.itemError( url );
  24953. }
  24954. }, onProgress, onError );
  24955. }
  24956. parse( json ) {
  24957. const textures = this.textures;
  24958. function getTexture( name ) {
  24959. if ( textures[ name ] === undefined ) {
  24960. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24961. }
  24962. return textures[ name ];
  24963. }
  24964. const material = MaterialLoader.createMaterialFromType( json.type );
  24965. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24966. if ( json.name !== undefined ) material.name = json.name;
  24967. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24968. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24969. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24970. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24971. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24972. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24973. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24974. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24975. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24976. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24977. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24978. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24979. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24980. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24981. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24982. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24983. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24984. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24985. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24986. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24987. if ( json.fog !== undefined ) material.fog = json.fog;
  24988. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24989. if ( json.blending !== undefined ) material.blending = json.blending;
  24990. if ( json.combine !== undefined ) material.combine = json.combine;
  24991. if ( json.side !== undefined ) material.side = json.side;
  24992. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24993. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24994. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24995. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24996. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24997. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24998. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24999. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25000. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25001. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25002. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25003. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25004. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25005. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25006. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25007. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25008. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25009. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25010. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25011. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25012. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25013. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25014. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25015. if ( json.scale !== undefined ) material.scale = json.scale;
  25016. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25017. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25018. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25019. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25020. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25021. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25022. if ( json.visible !== undefined ) material.visible = json.visible;
  25023. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25024. if ( json.userData !== undefined ) material.userData = json.userData;
  25025. if ( json.vertexColors !== undefined ) {
  25026. if ( typeof json.vertexColors === 'number' ) {
  25027. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25028. } else {
  25029. material.vertexColors = json.vertexColors;
  25030. }
  25031. }
  25032. // Shader Material
  25033. if ( json.uniforms !== undefined ) {
  25034. for ( const name in json.uniforms ) {
  25035. const uniform = json.uniforms[ name ];
  25036. material.uniforms[ name ] = {};
  25037. switch ( uniform.type ) {
  25038. case 't':
  25039. material.uniforms[ name ].value = getTexture( uniform.value );
  25040. break;
  25041. case 'c':
  25042. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25043. break;
  25044. case 'v2':
  25045. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25046. break;
  25047. case 'v3':
  25048. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25049. break;
  25050. case 'v4':
  25051. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25052. break;
  25053. case 'm3':
  25054. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25055. break;
  25056. case 'm4':
  25057. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25058. break;
  25059. default:
  25060. material.uniforms[ name ].value = uniform.value;
  25061. }
  25062. }
  25063. }
  25064. if ( json.defines !== undefined ) material.defines = json.defines;
  25065. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25066. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25067. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25068. if ( json.extensions !== undefined ) {
  25069. for ( const key in json.extensions ) {
  25070. material.extensions[ key ] = json.extensions[ key ];
  25071. }
  25072. }
  25073. // for PointsMaterial
  25074. if ( json.size !== undefined ) material.size = json.size;
  25075. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25076. // maps
  25077. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25078. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25079. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25080. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25081. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25082. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25083. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25084. if ( json.normalScale !== undefined ) {
  25085. let normalScale = json.normalScale;
  25086. if ( Array.isArray( normalScale ) === false ) {
  25087. // Blender exporter used to export a scalar. See #7459
  25088. normalScale = [ normalScale, normalScale ];
  25089. }
  25090. material.normalScale = new Vector2().fromArray( normalScale );
  25091. }
  25092. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25093. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25094. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25095. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25096. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25097. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25098. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25099. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25100. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25101. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25102. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25103. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25104. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25105. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25106. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25107. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25108. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25109. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25110. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25111. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25112. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25113. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25114. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25115. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25116. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25117. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25118. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25119. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25120. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25121. return material;
  25122. }
  25123. setTextures( value ) {
  25124. this.textures = value;
  25125. return this;
  25126. }
  25127. static createMaterialFromType( type ) {
  25128. const materialLib = {
  25129. ShadowMaterial,
  25130. SpriteMaterial,
  25131. RawShaderMaterial,
  25132. ShaderMaterial,
  25133. PointsMaterial,
  25134. MeshPhysicalMaterial,
  25135. MeshStandardMaterial,
  25136. MeshPhongMaterial,
  25137. MeshToonMaterial,
  25138. MeshNormalMaterial,
  25139. MeshLambertMaterial,
  25140. MeshDepthMaterial,
  25141. MeshDistanceMaterial,
  25142. MeshBasicMaterial,
  25143. MeshMatcapMaterial,
  25144. LineDashedMaterial,
  25145. LineBasicMaterial,
  25146. Material
  25147. };
  25148. return new materialLib[ type ]();
  25149. }
  25150. }
  25151. class LoaderUtils {
  25152. static decodeText( array ) {
  25153. if ( typeof TextDecoder !== 'undefined' ) {
  25154. return new TextDecoder().decode( array );
  25155. }
  25156. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25157. // throws a "maximum call stack size exceeded" error for large arrays.
  25158. let s = '';
  25159. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25160. // Implicitly assumes little-endian.
  25161. s += String.fromCharCode( array[ i ] );
  25162. }
  25163. try {
  25164. // merges multi-byte utf-8 characters.
  25165. return decodeURIComponent( escape( s ) );
  25166. } catch ( e ) { // see #16358
  25167. return s;
  25168. }
  25169. }
  25170. static extractUrlBase( url ) {
  25171. const index = url.lastIndexOf( '/' );
  25172. if ( index === - 1 ) return './';
  25173. return url.slice( 0, index + 1 );
  25174. }
  25175. static resolveURL( url, path ) {
  25176. // Invalid URL
  25177. if ( typeof url !== 'string' || url === '' ) return '';
  25178. // Host Relative URL
  25179. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25180. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25181. }
  25182. // Absolute URL http://,https://,//
  25183. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25184. // Data URI
  25185. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25186. // Blob URL
  25187. if ( /^blob:.*$/i.test( url ) ) return url;
  25188. // Relative URL
  25189. return path + url;
  25190. }
  25191. }
  25192. class InstancedBufferGeometry extends BufferGeometry {
  25193. constructor() {
  25194. super();
  25195. this.isInstancedBufferGeometry = true;
  25196. this.type = 'InstancedBufferGeometry';
  25197. this.instanceCount = Infinity;
  25198. }
  25199. copy( source ) {
  25200. super.copy( source );
  25201. this.instanceCount = source.instanceCount;
  25202. return this;
  25203. }
  25204. clone() {
  25205. return new this.constructor().copy( this );
  25206. }
  25207. toJSON() {
  25208. const data = super.toJSON( this );
  25209. data.instanceCount = this.instanceCount;
  25210. data.isInstancedBufferGeometry = true;
  25211. return data;
  25212. }
  25213. }
  25214. class BufferGeometryLoader extends Loader {
  25215. constructor( manager ) {
  25216. super( manager );
  25217. }
  25218. load( url, onLoad, onProgress, onError ) {
  25219. const scope = this;
  25220. const loader = new FileLoader( scope.manager );
  25221. loader.setPath( scope.path );
  25222. loader.setRequestHeader( scope.requestHeader );
  25223. loader.setWithCredentials( scope.withCredentials );
  25224. loader.load( url, function ( text ) {
  25225. try {
  25226. onLoad( scope.parse( JSON.parse( text ) ) );
  25227. } catch ( e ) {
  25228. if ( onError ) {
  25229. onError( e );
  25230. } else {
  25231. console.error( e );
  25232. }
  25233. scope.manager.itemError( url );
  25234. }
  25235. }, onProgress, onError );
  25236. }
  25237. parse( json ) {
  25238. const interleavedBufferMap = {};
  25239. const arrayBufferMap = {};
  25240. function getInterleavedBuffer( json, uuid ) {
  25241. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25242. const interleavedBuffers = json.interleavedBuffers;
  25243. const interleavedBuffer = interleavedBuffers[ uuid ];
  25244. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25245. const array = getTypedArray( interleavedBuffer.type, buffer );
  25246. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25247. ib.uuid = interleavedBuffer.uuid;
  25248. interleavedBufferMap[ uuid ] = ib;
  25249. return ib;
  25250. }
  25251. function getArrayBuffer( json, uuid ) {
  25252. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25253. const arrayBuffers = json.arrayBuffers;
  25254. const arrayBuffer = arrayBuffers[ uuid ];
  25255. const ab = new Uint32Array( arrayBuffer ).buffer;
  25256. arrayBufferMap[ uuid ] = ab;
  25257. return ab;
  25258. }
  25259. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25260. const index = json.data.index;
  25261. if ( index !== undefined ) {
  25262. const typedArray = getTypedArray( index.type, index.array );
  25263. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25264. }
  25265. const attributes = json.data.attributes;
  25266. for ( const key in attributes ) {
  25267. const attribute = attributes[ key ];
  25268. let bufferAttribute;
  25269. if ( attribute.isInterleavedBufferAttribute ) {
  25270. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25271. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25272. } else {
  25273. const typedArray = getTypedArray( attribute.type, attribute.array );
  25274. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25275. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25276. }
  25277. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25278. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25279. if ( attribute.updateRange !== undefined ) {
  25280. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25281. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25282. }
  25283. geometry.setAttribute( key, bufferAttribute );
  25284. }
  25285. const morphAttributes = json.data.morphAttributes;
  25286. if ( morphAttributes ) {
  25287. for ( const key in morphAttributes ) {
  25288. const attributeArray = morphAttributes[ key ];
  25289. const array = [];
  25290. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25291. const attribute = attributeArray[ i ];
  25292. let bufferAttribute;
  25293. if ( attribute.isInterleavedBufferAttribute ) {
  25294. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25295. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25296. } else {
  25297. const typedArray = getTypedArray( attribute.type, attribute.array );
  25298. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25299. }
  25300. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25301. array.push( bufferAttribute );
  25302. }
  25303. geometry.morphAttributes[ key ] = array;
  25304. }
  25305. }
  25306. const morphTargetsRelative = json.data.morphTargetsRelative;
  25307. if ( morphTargetsRelative ) {
  25308. geometry.morphTargetsRelative = true;
  25309. }
  25310. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25311. if ( groups !== undefined ) {
  25312. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25313. const group = groups[ i ];
  25314. geometry.addGroup( group.start, group.count, group.materialIndex );
  25315. }
  25316. }
  25317. const boundingSphere = json.data.boundingSphere;
  25318. if ( boundingSphere !== undefined ) {
  25319. const center = new Vector3();
  25320. if ( boundingSphere.center !== undefined ) {
  25321. center.fromArray( boundingSphere.center );
  25322. }
  25323. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25324. }
  25325. if ( json.name ) geometry.name = json.name;
  25326. if ( json.userData ) geometry.userData = json.userData;
  25327. return geometry;
  25328. }
  25329. }
  25330. class ObjectLoader extends Loader {
  25331. constructor( manager ) {
  25332. super( manager );
  25333. }
  25334. load( url, onLoad, onProgress, onError ) {
  25335. const scope = this;
  25336. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25337. this.resourcePath = this.resourcePath || path;
  25338. const loader = new FileLoader( this.manager );
  25339. loader.setPath( this.path );
  25340. loader.setRequestHeader( this.requestHeader );
  25341. loader.setWithCredentials( this.withCredentials );
  25342. loader.load( url, function ( text ) {
  25343. let json = null;
  25344. try {
  25345. json = JSON.parse( text );
  25346. } catch ( error ) {
  25347. if ( onError !== undefined ) onError( error );
  25348. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25349. return;
  25350. }
  25351. const metadata = json.metadata;
  25352. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25353. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25354. return;
  25355. }
  25356. scope.parse( json, onLoad );
  25357. }, onProgress, onError );
  25358. }
  25359. async loadAsync( url, onProgress ) {
  25360. const scope = this;
  25361. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25362. this.resourcePath = this.resourcePath || path;
  25363. const loader = new FileLoader( this.manager );
  25364. loader.setPath( this.path );
  25365. loader.setRequestHeader( this.requestHeader );
  25366. loader.setWithCredentials( this.withCredentials );
  25367. const text = await loader.loadAsync( url, onProgress );
  25368. const json = JSON.parse( text );
  25369. const metadata = json.metadata;
  25370. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25371. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25372. }
  25373. return await scope.parseAsync( json );
  25374. }
  25375. parse( json, onLoad ) {
  25376. const animations = this.parseAnimations( json.animations );
  25377. const shapes = this.parseShapes( json.shapes );
  25378. const geometries = this.parseGeometries( json.geometries, shapes );
  25379. const images = this.parseImages( json.images, function () {
  25380. if ( onLoad !== undefined ) onLoad( object );
  25381. } );
  25382. const textures = this.parseTextures( json.textures, images );
  25383. const materials = this.parseMaterials( json.materials, textures );
  25384. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25385. const skeletons = this.parseSkeletons( json.skeletons, object );
  25386. this.bindSkeletons( object, skeletons );
  25387. //
  25388. if ( onLoad !== undefined ) {
  25389. let hasImages = false;
  25390. for ( const uuid in images ) {
  25391. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25392. hasImages = true;
  25393. break;
  25394. }
  25395. }
  25396. if ( hasImages === false ) onLoad( object );
  25397. }
  25398. return object;
  25399. }
  25400. async parseAsync( json ) {
  25401. const animations = this.parseAnimations( json.animations );
  25402. const shapes = this.parseShapes( json.shapes );
  25403. const geometries = this.parseGeometries( json.geometries, shapes );
  25404. const images = await this.parseImagesAsync( json.images );
  25405. const textures = this.parseTextures( json.textures, images );
  25406. const materials = this.parseMaterials( json.materials, textures );
  25407. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25408. const skeletons = this.parseSkeletons( json.skeletons, object );
  25409. this.bindSkeletons( object, skeletons );
  25410. return object;
  25411. }
  25412. parseShapes( json ) {
  25413. const shapes = {};
  25414. if ( json !== undefined ) {
  25415. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25416. const shape = new Shape().fromJSON( json[ i ] );
  25417. shapes[ shape.uuid ] = shape;
  25418. }
  25419. }
  25420. return shapes;
  25421. }
  25422. parseSkeletons( json, object ) {
  25423. const skeletons = {};
  25424. const bones = {};
  25425. // generate bone lookup table
  25426. object.traverse( function ( child ) {
  25427. if ( child.isBone ) bones[ child.uuid ] = child;
  25428. } );
  25429. // create skeletons
  25430. if ( json !== undefined ) {
  25431. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25432. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25433. skeletons[ skeleton.uuid ] = skeleton;
  25434. }
  25435. }
  25436. return skeletons;
  25437. }
  25438. parseGeometries( json, shapes ) {
  25439. const geometries = {};
  25440. if ( json !== undefined ) {
  25441. const bufferGeometryLoader = new BufferGeometryLoader();
  25442. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25443. let geometry;
  25444. const data = json[ i ];
  25445. switch ( data.type ) {
  25446. case 'BufferGeometry':
  25447. case 'InstancedBufferGeometry':
  25448. geometry = bufferGeometryLoader.parse( data );
  25449. break;
  25450. default:
  25451. if ( data.type in Geometries ) {
  25452. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25453. } else {
  25454. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25455. }
  25456. }
  25457. geometry.uuid = data.uuid;
  25458. if ( data.name !== undefined ) geometry.name = data.name;
  25459. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25460. geometries[ data.uuid ] = geometry;
  25461. }
  25462. }
  25463. return geometries;
  25464. }
  25465. parseMaterials( json, textures ) {
  25466. const cache = {}; // MultiMaterial
  25467. const materials = {};
  25468. if ( json !== undefined ) {
  25469. const loader = new MaterialLoader();
  25470. loader.setTextures( textures );
  25471. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25472. const data = json[ i ];
  25473. if ( cache[ data.uuid ] === undefined ) {
  25474. cache[ data.uuid ] = loader.parse( data );
  25475. }
  25476. materials[ data.uuid ] = cache[ data.uuid ];
  25477. }
  25478. }
  25479. return materials;
  25480. }
  25481. parseAnimations( json ) {
  25482. const animations = {};
  25483. if ( json !== undefined ) {
  25484. for ( let i = 0; i < json.length; i ++ ) {
  25485. const data = json[ i ];
  25486. const clip = AnimationClip.parse( data );
  25487. animations[ clip.uuid ] = clip;
  25488. }
  25489. }
  25490. return animations;
  25491. }
  25492. parseImages( json, onLoad ) {
  25493. const scope = this;
  25494. const images = {};
  25495. let loader;
  25496. function loadImage( url ) {
  25497. scope.manager.itemStart( url );
  25498. return loader.load( url, function () {
  25499. scope.manager.itemEnd( url );
  25500. }, undefined, function () {
  25501. scope.manager.itemError( url );
  25502. scope.manager.itemEnd( url );
  25503. } );
  25504. }
  25505. function deserializeImage( image ) {
  25506. if ( typeof image === 'string' ) {
  25507. const url = image;
  25508. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25509. return loadImage( path );
  25510. } else {
  25511. if ( image.data ) {
  25512. return {
  25513. data: getTypedArray( image.type, image.data ),
  25514. width: image.width,
  25515. height: image.height
  25516. };
  25517. } else {
  25518. return null;
  25519. }
  25520. }
  25521. }
  25522. if ( json !== undefined && json.length > 0 ) {
  25523. const manager = new LoadingManager( onLoad );
  25524. loader = new ImageLoader( manager );
  25525. loader.setCrossOrigin( this.crossOrigin );
  25526. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25527. const image = json[ i ];
  25528. const url = image.url;
  25529. if ( Array.isArray( url ) ) {
  25530. // load array of images e.g CubeTexture
  25531. const imageArray = [];
  25532. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25533. const currentUrl = url[ j ];
  25534. const deserializedImage = deserializeImage( currentUrl );
  25535. if ( deserializedImage !== null ) {
  25536. if ( deserializedImage instanceof HTMLImageElement ) {
  25537. imageArray.push( deserializedImage );
  25538. } else {
  25539. // special case: handle array of data textures for cube textures
  25540. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25541. }
  25542. }
  25543. }
  25544. images[ image.uuid ] = new Source( imageArray );
  25545. } else {
  25546. // load single image
  25547. const deserializedImage = deserializeImage( image.url );
  25548. images[ image.uuid ] = new Source( deserializedImage );
  25549. }
  25550. }
  25551. }
  25552. return images;
  25553. }
  25554. async parseImagesAsync( json ) {
  25555. const scope = this;
  25556. const images = {};
  25557. let loader;
  25558. async function deserializeImage( image ) {
  25559. if ( typeof image === 'string' ) {
  25560. const url = image;
  25561. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25562. return await loader.loadAsync( path );
  25563. } else {
  25564. if ( image.data ) {
  25565. return {
  25566. data: getTypedArray( image.type, image.data ),
  25567. width: image.width,
  25568. height: image.height
  25569. };
  25570. } else {
  25571. return null;
  25572. }
  25573. }
  25574. }
  25575. if ( json !== undefined && json.length > 0 ) {
  25576. loader = new ImageLoader( this.manager );
  25577. loader.setCrossOrigin( this.crossOrigin );
  25578. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25579. const image = json[ i ];
  25580. const url = image.url;
  25581. if ( Array.isArray( url ) ) {
  25582. // load array of images e.g CubeTexture
  25583. const imageArray = [];
  25584. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25585. const currentUrl = url[ j ];
  25586. const deserializedImage = await deserializeImage( currentUrl );
  25587. if ( deserializedImage !== null ) {
  25588. if ( deserializedImage instanceof HTMLImageElement ) {
  25589. imageArray.push( deserializedImage );
  25590. } else {
  25591. // special case: handle array of data textures for cube textures
  25592. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25593. }
  25594. }
  25595. }
  25596. images[ image.uuid ] = new Source( imageArray );
  25597. } else {
  25598. // load single image
  25599. const deserializedImage = await deserializeImage( image.url );
  25600. images[ image.uuid ] = new Source( deserializedImage );
  25601. }
  25602. }
  25603. }
  25604. return images;
  25605. }
  25606. parseTextures( json, images ) {
  25607. function parseConstant( value, type ) {
  25608. if ( typeof value === 'number' ) return value;
  25609. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25610. return type[ value ];
  25611. }
  25612. const textures = {};
  25613. if ( json !== undefined ) {
  25614. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25615. const data = json[ i ];
  25616. if ( data.image === undefined ) {
  25617. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25618. }
  25619. if ( images[ data.image ] === undefined ) {
  25620. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25621. }
  25622. const source = images[ data.image ];
  25623. const image = source.data;
  25624. let texture;
  25625. if ( Array.isArray( image ) ) {
  25626. texture = new CubeTexture();
  25627. if ( image.length === 6 ) texture.needsUpdate = true;
  25628. } else {
  25629. if ( image && image.data ) {
  25630. texture = new DataTexture();
  25631. } else {
  25632. texture = new Texture();
  25633. }
  25634. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25635. }
  25636. texture.source = source;
  25637. texture.uuid = data.uuid;
  25638. if ( data.name !== undefined ) texture.name = data.name;
  25639. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25640. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25641. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25642. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25643. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25644. if ( data.wrap !== undefined ) {
  25645. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25646. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25647. }
  25648. if ( data.format !== undefined ) texture.format = data.format;
  25649. if ( data.type !== undefined ) texture.type = data.type;
  25650. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25651. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25652. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25653. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25654. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25655. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25656. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25657. if ( data.userData !== undefined ) texture.userData = data.userData;
  25658. textures[ data.uuid ] = texture;
  25659. }
  25660. }
  25661. return textures;
  25662. }
  25663. // 导入模型时 创建对象 -----------------------
  25664. parseObject( data, geometries, materials, textures, animations ) {
  25665. let object;
  25666. // 获取 几何
  25667. function getGeometry( name ) {
  25668. if ( geometries[ name ] === undefined ) {
  25669. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25670. }
  25671. return geometries[ name ];
  25672. }
  25673. // 获取 布料
  25674. function getMaterial( name ) {
  25675. if ( name === undefined ) return undefined;
  25676. if ( Array.isArray( name ) ) {
  25677. const array = [];
  25678. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25679. const uuid = name[ i ];
  25680. if ( materials[ uuid ] === undefined ) {
  25681. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25682. }
  25683. array.push( materials[ uuid ] );
  25684. }
  25685. return array;
  25686. }
  25687. if ( materials[ name ] === undefined ) {
  25688. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25689. }
  25690. return materials[ name ];
  25691. }
  25692. // 纹理
  25693. function getTexture( uuid ) {
  25694. if ( textures[ uuid ] === undefined ) {
  25695. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25696. }
  25697. return textures[ uuid ];
  25698. }
  25699. let geometry, material;
  25700. // console.log("new :",data)
  25701. // 模型类型渲染 -
  25702. switch ( data.type ) {
  25703. case 'Scene':
  25704. object = new Scene();
  25705. if ( data.background !== undefined ) {
  25706. console.log("data.background 渲染",data.background)
  25707. switch (data.background) {
  25708. case "Sky":
  25709. var urls = [
  25710. './static/js/img/bk/Sky/posx.jpg',
  25711. './static/js/img/bk/Sky/negx.jpg',
  25712. './static/js/img/bk/Sky/posy.jpg',
  25713. './static/js/img/bk/Sky/negy.jpg',
  25714. './static/js/img/bk/Sky/posz.jpg',
  25715. './static/js/img/bk/Sky/negz.jpg'
  25716. ];
  25717. var cubeLoader = new THREE.CubeTextureLoader();
  25718. object.background = cubeLoader.load(urls);
  25719. break;
  25720. case 'Dusk': //黄昏
  25721. var urls = [
  25722. './static/js/img/bk/Dusk/px.png',
  25723. './static/js/img/bk/Dusk/nx.png',
  25724. './static/js/img/bk/Dusk/py.png',
  25725. './static/js/img/bk/Dusk/ny.png',
  25726. './static/js/img/bk/Dusk/pz.png',
  25727. './static/js/img/bk/Dusk/nz.png'
  25728. ];
  25729. var cubeLoader = new THREE.CubeTextureLoader();
  25730. object.background = cubeLoader.load(urls);
  25731. break;
  25732. case 'Starry': //星空
  25733. var urls = [
  25734. './static/js/img/bk/Starry/px.jpg',
  25735. './static/js/img/bk/Starry/nx.jpg',
  25736. './static/js/img/bk/Starry/py.jpg',
  25737. './static/js/img/bk/Starry/ny.jpg',
  25738. './static/js/img/bk/Starry/pz.jpg',
  25739. './static/js/img/bk/Starry/nz.jpg'
  25740. ];
  25741. var cubeLoader = new THREE.CubeTextureLoader();
  25742. object.background = cubeLoader.load(urls);
  25743. break;
  25744. default:
  25745. if ( Number.isInteger( data.background ) ) {
  25746. object.background = new Color( data.background );
  25747. } else {
  25748. object.background = getTexture( data.background );
  25749. }
  25750. }
  25751. }
  25752. if ( data.environment !== undefined ) {
  25753. object.environment = getTexture( data.environment );
  25754. }
  25755. if ( data.fog !== undefined ) {
  25756. if ( data.fog.type === 'Fog' ) {
  25757. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25758. } else if ( data.fog.type === 'FogExp2' ) {
  25759. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25760. }
  25761. }
  25762. break;
  25763. case 'PerspectiveCamera':
  25764. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25765. if ( data.focus !== undefined ) object.focus = data.focus;
  25766. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25767. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25768. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25769. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25770. break;
  25771. case 'OrthographicCamera':
  25772. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25773. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25774. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25775. break;
  25776. case 'AmbientLight':
  25777. object = new AmbientLight( data.color, data.intensity );
  25778. break;
  25779. case 'DirectionalLight':
  25780. object = new DirectionalLight( data.color, data.intensity );
  25781. break;
  25782. case 'PointLight':
  25783. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25784. break;
  25785. case 'RectAreaLight':
  25786. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25787. break;
  25788. case 'SpotLight':
  25789. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25790. break;
  25791. case 'HemisphereLight':
  25792. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25793. break;
  25794. case 'LightProbe':
  25795. object = new LightProbe().fromJSON( data );
  25796. break;
  25797. case 'SkinnedMesh':
  25798. geometry = getGeometry( data.geometry );
  25799. material = getMaterial( data.material );
  25800. object = new SkinnedMesh( geometry, material );
  25801. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25802. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25803. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25804. break;
  25805. case 'Mesh':
  25806. geometry = getGeometry( data.geometry );
  25807. material = getMaterial( data.material );
  25808. object = new Mesh( geometry, material );
  25809. break;
  25810. case 'Text':
  25811. geometry = getGeometry( data.geometry );
  25812. material = getMaterial( data.material );
  25813. object = new Text( geometry, material );
  25814. // setTimeout(function(){
  25815. // object.geometry = new THREE.ShapeGeometry(TextFont.generateShapes(object.Text, object.font_size));
  25816. // object.geometry.computeBoundingBox();
  25817. // },1000);
  25818. break;
  25819. case 'InstancedMesh':
  25820. geometry = getGeometry( data.geometry );
  25821. material = getMaterial( data.material );
  25822. const count = data.count;
  25823. const instanceMatrix = data.instanceMatrix;
  25824. const instanceColor = data.instanceColor;
  25825. object = new InstancedMesh( geometry, material, count );
  25826. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25827. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25828. break;
  25829. case 'LOD':
  25830. object = new LOD();
  25831. break;
  25832. case 'Line':
  25833. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25834. break;
  25835. case 'LineLoop':
  25836. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25837. break;
  25838. case 'LineSegments':
  25839. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25840. break;
  25841. case 'PointCloud':
  25842. case 'Points':
  25843. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25844. break;
  25845. case 'Sprite':
  25846. object = new Sprite( getMaterial( data.material ) );
  25847. break;
  25848. case 'Group':
  25849. object = new Group();
  25850. break;
  25851. case 'Bone':
  25852. object = new Bone();
  25853. break;
  25854. case 'CSS3D':
  25855. // console.log("data.userData:",data.userData)
  25856. object = new CSS3DObject();
  25857. if(data.userData != undefined) if(data.userData.HTML != undefined) object.Up_Html(data.userData.HTML)
  25858. break;
  25859. case 'CSS2D':
  25860. // console.log("data.userData:",data.userData)
  25861. object = new CSS2DObject();
  25862. if(data.userData != undefined) if(data.userData.HTML != undefined) object.Up_Html(data.userData.HTML)
  25863. break;
  25864. default:
  25865. object = new Object3D();
  25866. }
  25867. // ----------------- 补全内容
  25868. object.uuid = data.uuid;
  25869. object.scripts = data.scripts;
  25870. if ( data.name !== undefined ) object.name = data.name;
  25871. if ( data.matrix !== undefined ) {
  25872. object.matrix.fromArray( data.matrix );
  25873. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25874. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25875. } else {
  25876. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25877. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25878. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25879. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25880. }
  25881. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25882. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25883. if ( data.shadow ) {
  25884. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25885. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25886. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25887. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25888. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25889. }
  25890. if ( data.visible !== undefined ) object.visible = data.visible;
  25891. if ( data.choice !== undefined ) object.choice = data.choice;
  25892. if ( data.play !== undefined ) object.play = data.play;
  25893. if ( data.whole !== undefined ) object.whole = data.whole;
  25894. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25895. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25896. if ( data.userData !== undefined ) object.userData = data.userData;
  25897. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25898. if ( data.children !== undefined ) {
  25899. const children = data.children;
  25900. for ( let i = 0; i < children.length; i ++ ) {
  25901. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25902. }
  25903. }
  25904. if ( data.animations !== undefined ) {
  25905. const objectAnimations = data.animations;
  25906. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25907. const uuid = objectAnimations[ i ];
  25908. object.animations.push( animations[ uuid ] );
  25909. }
  25910. }
  25911. if ( data.type === 'LOD' ) {
  25912. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25913. const levels = data.levels;
  25914. for ( let l = 0; l < levels.length; l ++ ) {
  25915. const level = levels[ l ];
  25916. const child = object.getObjectByProperty( 'uuid', level.object );
  25917. if ( child !== undefined ) {
  25918. object.addLevel( child, level.distance );
  25919. }
  25920. }
  25921. }
  25922. if (object !== null && object.animations.length > 0 ) {
  25923. if(window.mixer === undefined){
  25924. // 编辑模式
  25925. for ( const animation of object.animations ) {
  25926. object.clipAction = editor.mixer.clipAction(animation,object)
  25927. if(object.play){
  25928. object.clipAction.play(); // 自动播放
  25929. }
  25930. }
  25931. }else {
  25932. // 浏览模式
  25933. for ( const animation of object.animations ) {
  25934. object.clipAction = window.mixer.clipAction(animation,object)
  25935. if(object.play){
  25936. object.clipAction.play(); // 自动播放
  25937. }
  25938. }
  25939. }
  25940. }
  25941. return object;
  25942. }
  25943. bindSkeletons( object, skeletons ) {
  25944. if ( Object.keys( skeletons ).length === 0 ) return;
  25945. object.traverse( function ( child ) {
  25946. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25947. const skeleton = skeletons[ child.skeleton ];
  25948. if ( skeleton === undefined ) {
  25949. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25950. } else {
  25951. child.bind( skeleton, child.bindMatrix );
  25952. }
  25953. }
  25954. } );
  25955. }
  25956. }
  25957. const TEXTURE_MAPPING = {
  25958. UVMapping: UVMapping,
  25959. CubeReflectionMapping: CubeReflectionMapping,
  25960. CubeRefractionMapping: CubeRefractionMapping,
  25961. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25962. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25963. CubeUVReflectionMapping: CubeUVReflectionMapping
  25964. };
  25965. const TEXTURE_WRAPPING = {
  25966. RepeatWrapping: RepeatWrapping,
  25967. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25968. MirroredRepeatWrapping: MirroredRepeatWrapping
  25969. };
  25970. const TEXTURE_FILTER = {
  25971. NearestFilter: NearestFilter,
  25972. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25973. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25974. LinearFilter: LinearFilter,
  25975. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25976. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25977. };
  25978. class ImageBitmapLoader extends Loader {
  25979. constructor( manager ) {
  25980. super( manager );
  25981. this.isImageBitmapLoader = true;
  25982. if ( typeof createImageBitmap === 'undefined' ) {
  25983. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25984. }
  25985. if ( typeof fetch === 'undefined' ) {
  25986. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25987. }
  25988. this.options = { premultiplyAlpha: 'none' };
  25989. }
  25990. setOptions( options ) {
  25991. this.options = options;
  25992. return this;
  25993. }
  25994. load( url, onLoad, onProgress, onError ) {
  25995. if ( url === undefined ) url = '';
  25996. if ( this.path !== undefined ) url = this.path + url;
  25997. url = this.manager.resolveURL( url );
  25998. const scope = this;
  25999. const cached = Cache.get( url );
  26000. if ( cached !== undefined ) {
  26001. scope.manager.itemStart( url );
  26002. setTimeout( function () {
  26003. if ( onLoad ) onLoad( cached );
  26004. scope.manager.itemEnd( url );
  26005. }, 0 );
  26006. return cached;
  26007. }
  26008. const fetchOptions = {};
  26009. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26010. fetchOptions.headers = this.requestHeader;
  26011. fetch( url, fetchOptions ).then( function ( res ) {
  26012. return res.blob();
  26013. } ).then( function ( blob ) {
  26014. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26015. } ).then( function ( imageBitmap ) {
  26016. Cache.add( url, imageBitmap );
  26017. if ( onLoad ) onLoad( imageBitmap );
  26018. scope.manager.itemEnd( url );
  26019. } ).catch( function ( e ) {
  26020. if ( onError ) onError( e );
  26021. scope.manager.itemError( url );
  26022. scope.manager.itemEnd( url );
  26023. } );
  26024. scope.manager.itemStart( url );
  26025. }
  26026. }
  26027. let _context;
  26028. const AudioContext = {
  26029. getContext: function () {
  26030. if ( _context === undefined ) {
  26031. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26032. }
  26033. return _context;
  26034. },
  26035. setContext: function ( value ) {
  26036. _context = value;
  26037. }
  26038. };
  26039. class AudioLoader extends Loader {
  26040. constructor( manager ) {
  26041. super( manager );
  26042. }
  26043. load( url, onLoad, onProgress, onError ) {
  26044. const scope = this;
  26045. const loader = new FileLoader( this.manager );
  26046. loader.setResponseType( 'arraybuffer' );
  26047. loader.setPath( this.path );
  26048. loader.setRequestHeader( this.requestHeader );
  26049. loader.setWithCredentials( this.withCredentials );
  26050. loader.load( url, function ( buffer ) {
  26051. try {
  26052. // Create a copy of the buffer. The `decodeAudioData` method
  26053. // detaches the buffer when complete, preventing reuse.
  26054. const bufferCopy = buffer.slice( 0 );
  26055. const context = AudioContext.getContext();
  26056. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26057. onLoad( audioBuffer );
  26058. } );
  26059. } catch ( e ) {
  26060. if ( onError ) {
  26061. onError( e );
  26062. } else {
  26063. console.error( e );
  26064. }
  26065. scope.manager.itemError( url );
  26066. }
  26067. }, onProgress, onError );
  26068. }
  26069. }
  26070. class HemisphereLightProbe extends LightProbe {
  26071. constructor( skyColor, groundColor, intensity = 1 ) {
  26072. super( undefined, intensity );
  26073. this.isHemisphereLightProbe = true;
  26074. const color1 = new Color().set( skyColor );
  26075. const color2 = new Color().set( groundColor );
  26076. const sky = new Vector3( color1.r, color1.g, color1.b );
  26077. const ground = new Vector3( color2.r, color2.g, color2.b );
  26078. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26079. const c0 = Math.sqrt( Math.PI );
  26080. const c1 = c0 * Math.sqrt( 0.75 );
  26081. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26082. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26083. }
  26084. }
  26085. class AmbientLightProbe extends LightProbe {
  26086. constructor( color, intensity = 1 ) {
  26087. super( undefined, intensity );
  26088. this.isAmbientLightProbe = true;
  26089. const color1 = new Color().set( color );
  26090. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26091. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26092. }
  26093. }
  26094. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26095. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26096. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26097. class StereoCamera {
  26098. constructor() {
  26099. this.type = 'StereoCamera';
  26100. this.aspect = 1;
  26101. this.eyeSep = 0.064;
  26102. this.cameraL = new PerspectiveCamera();
  26103. this.cameraL.layers.enable( 1 );
  26104. this.cameraL.matrixAutoUpdate = false;
  26105. this.cameraR = new PerspectiveCamera();
  26106. this.cameraR.layers.enable( 2 );
  26107. this.cameraR.matrixAutoUpdate = false;
  26108. this._cache = {
  26109. focus: null,
  26110. fov: null,
  26111. aspect: null,
  26112. near: null,
  26113. far: null,
  26114. zoom: null,
  26115. eyeSep: null
  26116. };
  26117. }
  26118. update( camera ) {
  26119. const cache = this._cache;
  26120. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26121. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26122. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26123. if ( needsUpdate ) {
  26124. cache.focus = camera.focus;
  26125. cache.fov = camera.fov;
  26126. cache.aspect = camera.aspect * this.aspect;
  26127. cache.near = camera.near;
  26128. cache.far = camera.far;
  26129. cache.zoom = camera.zoom;
  26130. cache.eyeSep = this.eyeSep;
  26131. // Off-axis stereoscopic effect based on
  26132. // http://paulbourke.net/stereographics/stereorender/
  26133. _projectionMatrix.copy( camera.projectionMatrix );
  26134. const eyeSepHalf = cache.eyeSep / 2;
  26135. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26136. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26137. let xmin, xmax;
  26138. // translate xOffset
  26139. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26140. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26141. // for left eye
  26142. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26143. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26144. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26145. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26146. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26147. // for right eye
  26148. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26149. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26150. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26151. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26152. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26153. }
  26154. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26155. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26156. }
  26157. }
  26158. class Clock {
  26159. constructor( autoStart = true ) {
  26160. this.autoStart = autoStart;
  26161. this.startTime = 0;
  26162. this.oldTime = 0;
  26163. this.elapsedTime = 0;
  26164. this.running = false;
  26165. }
  26166. start() {
  26167. this.startTime = now();
  26168. this.oldTime = this.startTime;
  26169. this.elapsedTime = 0;
  26170. this.running = true;
  26171. }
  26172. stop() {
  26173. this.getElapsedTime();
  26174. this.running = false;
  26175. this.autoStart = false;
  26176. }
  26177. getElapsedTime() {
  26178. this.getDelta();
  26179. return this.elapsedTime;
  26180. }
  26181. getDelta() {
  26182. let diff = 0;
  26183. if ( this.autoStart && ! this.running ) {
  26184. this.start();
  26185. return 0;
  26186. }
  26187. if ( this.running ) {
  26188. const newTime = now();
  26189. diff = ( newTime - this.oldTime ) / 1000;
  26190. this.oldTime = newTime;
  26191. this.elapsedTime += diff;
  26192. }
  26193. return diff;
  26194. }
  26195. }
  26196. function now() {
  26197. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26198. }
  26199. const _position$1 = /*@__PURE__*/ new Vector3();
  26200. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26201. const _scale$1 = /*@__PURE__*/ new Vector3();
  26202. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26203. class AudioListener extends Object3D {
  26204. constructor() {
  26205. super();
  26206. this.type = 'AudioListener';
  26207. this.context = AudioContext.getContext();
  26208. this.gain = this.context.createGain();
  26209. this.gain.connect( this.context.destination );
  26210. this.filter = null;
  26211. this.timeDelta = 0;
  26212. // private
  26213. this._clock = new Clock();
  26214. }
  26215. getInput() {
  26216. return this.gain;
  26217. }
  26218. removeFilter() {
  26219. if ( this.filter !== null ) {
  26220. this.gain.disconnect( this.filter );
  26221. this.filter.disconnect( this.context.destination );
  26222. this.gain.connect( this.context.destination );
  26223. this.filter = null;
  26224. }
  26225. return this;
  26226. }
  26227. getFilter() {
  26228. return this.filter;
  26229. }
  26230. setFilter( value ) {
  26231. if ( this.filter !== null ) {
  26232. this.gain.disconnect( this.filter );
  26233. this.filter.disconnect( this.context.destination );
  26234. } else {
  26235. this.gain.disconnect( this.context.destination );
  26236. }
  26237. this.filter = value;
  26238. this.gain.connect( this.filter );
  26239. this.filter.connect( this.context.destination );
  26240. return this;
  26241. }
  26242. getMasterVolume() {
  26243. return this.gain.gain.value;
  26244. }
  26245. setMasterVolume( value ) {
  26246. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26247. return this;
  26248. }
  26249. updateMatrixWorld( force ) {
  26250. super.updateMatrixWorld( force );
  26251. const listener = this.context.listener;
  26252. const up = this.up;
  26253. this.timeDelta = this._clock.getDelta();
  26254. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26255. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26256. if ( listener.positionX ) {
  26257. // code path for Chrome (see #14393)
  26258. const endTime = this.context.currentTime + this.timeDelta;
  26259. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26260. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26261. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26262. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26263. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26264. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26265. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26266. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26267. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26268. } else {
  26269. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26270. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26271. }
  26272. }
  26273. }
  26274. class Audio extends Object3D {
  26275. constructor( listener ) {
  26276. super();
  26277. this.type = 'Audio';
  26278. this.listener = listener;
  26279. this.context = listener.context;
  26280. this.gain = this.context.createGain();
  26281. this.gain.connect( listener.getInput() );
  26282. this.autoplay = false;
  26283. this.buffer = null;
  26284. this.detune = 0;
  26285. this.loop = false;
  26286. this.loopStart = 0;
  26287. this.loopEnd = 0;
  26288. this.offset = 0;
  26289. this.duration = undefined;
  26290. this.playbackRate = 1;
  26291. this.isPlaying = false;
  26292. this.hasPlaybackControl = true;
  26293. this.source = null;
  26294. this.sourceType = 'empty';
  26295. this._startedAt = 0;
  26296. this._progress = 0;
  26297. this._connected = false;
  26298. this.filters = [];
  26299. }
  26300. getOutput() {
  26301. return this.gain;
  26302. }
  26303. setNodeSource( audioNode ) {
  26304. this.hasPlaybackControl = false;
  26305. this.sourceType = 'audioNode';
  26306. this.source = audioNode;
  26307. this.connect();
  26308. return this;
  26309. }
  26310. setMediaElementSource( mediaElement ) {
  26311. this.hasPlaybackControl = false;
  26312. this.sourceType = 'mediaNode';
  26313. this.source = this.context.createMediaElementSource( mediaElement );
  26314. this.connect();
  26315. return this;
  26316. }
  26317. setMediaStreamSource( mediaStream ) {
  26318. this.hasPlaybackControl = false;
  26319. this.sourceType = 'mediaStreamNode';
  26320. this.source = this.context.createMediaStreamSource( mediaStream );
  26321. this.connect();
  26322. return this;
  26323. }
  26324. setBuffer( audioBuffer ) {
  26325. this.buffer = audioBuffer;
  26326. this.sourceType = 'buffer';
  26327. if ( this.autoplay ) this.play();
  26328. return this;
  26329. }
  26330. play( delay = 0 ) {
  26331. if ( this.isPlaying === true ) {
  26332. console.warn( 'THREE.Audio: Audio is already playing.' );
  26333. return;
  26334. }
  26335. if ( this.hasPlaybackControl === false ) {
  26336. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26337. return;
  26338. }
  26339. this._startedAt = this.context.currentTime + delay;
  26340. const source = this.context.createBufferSource();
  26341. source.buffer = this.buffer;
  26342. source.loop = this.loop;
  26343. source.loopStart = this.loopStart;
  26344. source.loopEnd = this.loopEnd;
  26345. source.onended = this.onEnded.bind( this );
  26346. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26347. this.isPlaying = true;
  26348. this.source = source;
  26349. this.setDetune( this.detune );
  26350. this.setPlaybackRate( this.playbackRate );
  26351. return this.connect();
  26352. }
  26353. pause() {
  26354. if ( this.hasPlaybackControl === false ) {
  26355. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26356. return;
  26357. }
  26358. if ( this.isPlaying === true ) {
  26359. // update current progress
  26360. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26361. if ( this.loop === true ) {
  26362. // ensure _progress does not exceed duration with looped audios
  26363. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26364. }
  26365. this.source.stop();
  26366. this.source.onended = null;
  26367. this.isPlaying = false;
  26368. }
  26369. return this;
  26370. }
  26371. stop() {
  26372. if ( this.hasPlaybackControl === false ) {
  26373. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26374. return;
  26375. }
  26376. this._progress = 0;
  26377. this.source.stop();
  26378. this.source.onended = null;
  26379. this.isPlaying = false;
  26380. return this;
  26381. }
  26382. connect() {
  26383. if ( this.filters.length > 0 ) {
  26384. this.source.connect( this.filters[ 0 ] );
  26385. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26386. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26387. }
  26388. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26389. } else {
  26390. this.source.connect( this.getOutput() );
  26391. }
  26392. this._connected = true;
  26393. return this;
  26394. }
  26395. disconnect() {
  26396. if ( this.filters.length > 0 ) {
  26397. this.source.disconnect( this.filters[ 0 ] );
  26398. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26399. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26400. }
  26401. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26402. } else {
  26403. this.source.disconnect( this.getOutput() );
  26404. }
  26405. this._connected = false;
  26406. return this;
  26407. }
  26408. getFilters() {
  26409. return this.filters;
  26410. }
  26411. setFilters( value ) {
  26412. if ( ! value ) value = [];
  26413. if ( this._connected === true ) {
  26414. this.disconnect();
  26415. this.filters = value.slice();
  26416. this.connect();
  26417. } else {
  26418. this.filters = value.slice();
  26419. }
  26420. return this;
  26421. }
  26422. setDetune( value ) {
  26423. this.detune = value;
  26424. if ( this.source.detune === undefined ) return; // only set detune when available
  26425. if ( this.isPlaying === true ) {
  26426. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26427. }
  26428. return this;
  26429. }
  26430. getDetune() {
  26431. return this.detune;
  26432. }
  26433. getFilter() {
  26434. return this.getFilters()[ 0 ];
  26435. }
  26436. setFilter( filter ) {
  26437. return this.setFilters( filter ? [ filter ] : [] );
  26438. }
  26439. setPlaybackRate( value ) {
  26440. if ( this.hasPlaybackControl === false ) {
  26441. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26442. return;
  26443. }
  26444. this.playbackRate = value;
  26445. if ( this.isPlaying === true ) {
  26446. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26447. }
  26448. return this;
  26449. }
  26450. getPlaybackRate() {
  26451. return this.playbackRate;
  26452. }
  26453. onEnded() {
  26454. this.isPlaying = false;
  26455. }
  26456. getLoop() {
  26457. if ( this.hasPlaybackControl === false ) {
  26458. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26459. return false;
  26460. }
  26461. return this.loop;
  26462. }
  26463. setLoop( value ) {
  26464. if ( this.hasPlaybackControl === false ) {
  26465. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26466. return;
  26467. }
  26468. this.loop = value;
  26469. if ( this.isPlaying === true ) {
  26470. this.source.loop = this.loop;
  26471. }
  26472. return this;
  26473. }
  26474. setLoopStart( value ) {
  26475. this.loopStart = value;
  26476. return this;
  26477. }
  26478. setLoopEnd( value ) {
  26479. this.loopEnd = value;
  26480. return this;
  26481. }
  26482. getVolume() {
  26483. return this.gain.gain.value;
  26484. }
  26485. setVolume( value ) {
  26486. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26487. return this;
  26488. }
  26489. }
  26490. const _position = /*@__PURE__*/ new Vector3();
  26491. const _quaternion = /*@__PURE__*/ new Quaternion();
  26492. const _scale = /*@__PURE__*/ new Vector3();
  26493. const _orientation = /*@__PURE__*/ new Vector3();
  26494. class PositionalAudio extends Audio {
  26495. constructor( listener ) {
  26496. super( listener );
  26497. this.panner = this.context.createPanner();
  26498. this.panner.panningModel = 'HRTF';
  26499. this.panner.connect( this.gain );
  26500. }
  26501. disconnect() {
  26502. super.disconnect();
  26503. this.panner.disconnect( this.gain );
  26504. }
  26505. getOutput() {
  26506. return this.panner;
  26507. }
  26508. getRefDistance() {
  26509. return this.panner.refDistance;
  26510. }
  26511. setRefDistance( value ) {
  26512. this.panner.refDistance = value;
  26513. return this;
  26514. }
  26515. getRolloffFactor() {
  26516. return this.panner.rolloffFactor;
  26517. }
  26518. setRolloffFactor( value ) {
  26519. this.panner.rolloffFactor = value;
  26520. return this;
  26521. }
  26522. getDistanceModel() {
  26523. return this.panner.distanceModel;
  26524. }
  26525. setDistanceModel( value ) {
  26526. this.panner.distanceModel = value;
  26527. return this;
  26528. }
  26529. getMaxDistance() {
  26530. return this.panner.maxDistance;
  26531. }
  26532. setMaxDistance( value ) {
  26533. this.panner.maxDistance = value;
  26534. return this;
  26535. }
  26536. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26537. this.panner.coneInnerAngle = coneInnerAngle;
  26538. this.panner.coneOuterAngle = coneOuterAngle;
  26539. this.panner.coneOuterGain = coneOuterGain;
  26540. return this;
  26541. }
  26542. updateMatrixWorld( force ) {
  26543. super.updateMatrixWorld( force );
  26544. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26545. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26546. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26547. const panner = this.panner;
  26548. if ( panner.positionX ) {
  26549. // code path for Chrome and Firefox (see #14393)
  26550. const endTime = this.context.currentTime + this.listener.timeDelta;
  26551. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26552. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26553. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26554. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26555. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26556. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26557. } else {
  26558. panner.setPosition( _position.x, _position.y, _position.z );
  26559. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26560. }
  26561. }
  26562. }
  26563. class AudioAnalyser {
  26564. constructor( audio, fftSize = 2048 ) {
  26565. this.analyser = audio.context.createAnalyser();
  26566. this.analyser.fftSize = fftSize;
  26567. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26568. audio.getOutput().connect( this.analyser );
  26569. }
  26570. getFrequencyData() {
  26571. this.analyser.getByteFrequencyData( this.data );
  26572. return this.data;
  26573. }
  26574. getAverageFrequency() {
  26575. let value = 0;
  26576. const data = this.getFrequencyData();
  26577. for ( let i = 0; i < data.length; i ++ ) {
  26578. value += data[ i ];
  26579. }
  26580. return value / data.length;
  26581. }
  26582. }
  26583. class PropertyMixer {
  26584. constructor( binding, typeName, valueSize ) {
  26585. this.binding = binding;
  26586. this.valueSize = valueSize;
  26587. let mixFunction,
  26588. mixFunctionAdditive,
  26589. setIdentity;
  26590. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26591. //
  26592. // interpolators can use .buffer as their .result
  26593. // the data then goes to 'incoming'
  26594. //
  26595. // 'accu0' and 'accu1' are used frame-interleaved for
  26596. // the cumulative result and are compared to detect
  26597. // changes
  26598. //
  26599. // 'orig' stores the original state of the property
  26600. //
  26601. // 'add' is used for additive cumulative results
  26602. //
  26603. // 'work' is optional and is only present for quaternion types. It is used
  26604. // to store intermediate quaternion multiplication results
  26605. switch ( typeName ) {
  26606. case 'quaternion':
  26607. mixFunction = this._slerp;
  26608. mixFunctionAdditive = this._slerpAdditive;
  26609. setIdentity = this._setAdditiveIdentityQuaternion;
  26610. this.buffer = new Float64Array( valueSize * 6 );
  26611. this._workIndex = 5;
  26612. break;
  26613. case 'string':
  26614. case 'bool':
  26615. mixFunction = this._select;
  26616. // Use the regular mix function and for additive on these types,
  26617. // additive is not relevant for non-numeric types
  26618. mixFunctionAdditive = this._select;
  26619. setIdentity = this._setAdditiveIdentityOther;
  26620. this.buffer = new Array( valueSize * 5 );
  26621. break;
  26622. default:
  26623. mixFunction = this._lerp;
  26624. mixFunctionAdditive = this._lerpAdditive;
  26625. setIdentity = this._setAdditiveIdentityNumeric;
  26626. this.buffer = new Float64Array( valueSize * 5 );
  26627. }
  26628. this._mixBufferRegion = mixFunction;
  26629. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26630. this._setIdentity = setIdentity;
  26631. this._origIndex = 3;
  26632. this._addIndex = 4;
  26633. this.cumulativeWeight = 0;
  26634. this.cumulativeWeightAdditive = 0;
  26635. this.useCount = 0;
  26636. this.referenceCount = 0;
  26637. }
  26638. // accumulate data in the 'incoming' region into 'accu<i>'
  26639. accumulate( accuIndex, weight ) {
  26640. // note: happily accumulating nothing when weight = 0, the caller knows
  26641. // the weight and shouldn't have made the call in the first place
  26642. const buffer = this.buffer,
  26643. stride = this.valueSize,
  26644. offset = accuIndex * stride + stride;
  26645. let currentWeight = this.cumulativeWeight;
  26646. if ( currentWeight === 0 ) {
  26647. // accuN := incoming * weight
  26648. for ( let i = 0; i !== stride; ++ i ) {
  26649. buffer[ offset + i ] = buffer[ i ];
  26650. }
  26651. currentWeight = weight;
  26652. } else {
  26653. // accuN := accuN + incoming * weight
  26654. currentWeight += weight;
  26655. const mix = weight / currentWeight;
  26656. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26657. }
  26658. this.cumulativeWeight = currentWeight;
  26659. }
  26660. // accumulate data in the 'incoming' region into 'add'
  26661. accumulateAdditive( weight ) {
  26662. const buffer = this.buffer,
  26663. stride = this.valueSize,
  26664. offset = stride * this._addIndex;
  26665. if ( this.cumulativeWeightAdditive === 0 ) {
  26666. // add = identity
  26667. this._setIdentity();
  26668. }
  26669. // add := add + incoming * weight
  26670. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26671. this.cumulativeWeightAdditive += weight;
  26672. }
  26673. // apply the state of 'accu<i>' to the binding when accus differ
  26674. apply( accuIndex ) {
  26675. const stride = this.valueSize,
  26676. buffer = this.buffer,
  26677. offset = accuIndex * stride + stride,
  26678. weight = this.cumulativeWeight,
  26679. weightAdditive = this.cumulativeWeightAdditive,
  26680. binding = this.binding;
  26681. this.cumulativeWeight = 0;
  26682. this.cumulativeWeightAdditive = 0;
  26683. if ( weight < 1 ) {
  26684. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26685. const originalValueOffset = stride * this._origIndex;
  26686. this._mixBufferRegion(
  26687. buffer, offset, originalValueOffset, 1 - weight, stride );
  26688. }
  26689. if ( weightAdditive > 0 ) {
  26690. // accuN := accuN + additive accuN
  26691. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26692. }
  26693. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26694. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26695. // value has changed -> update scene graph
  26696. binding.setValue( buffer, offset );
  26697. break;
  26698. }
  26699. }
  26700. }
  26701. // remember the state of the bound property and copy it to both accus
  26702. saveOriginalState() {
  26703. const binding = this.binding;
  26704. const buffer = this.buffer,
  26705. stride = this.valueSize,
  26706. originalValueOffset = stride * this._origIndex;
  26707. binding.getValue( buffer, originalValueOffset );
  26708. // accu[0..1] := orig -- initially detect changes against the original
  26709. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26710. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26711. }
  26712. // Add to identity for additive
  26713. this._setIdentity();
  26714. this.cumulativeWeight = 0;
  26715. this.cumulativeWeightAdditive = 0;
  26716. }
  26717. // apply the state previously taken via 'saveOriginalState' to the binding
  26718. restoreOriginalState() {
  26719. const originalValueOffset = this.valueSize * 3;
  26720. this.binding.setValue( this.buffer, originalValueOffset );
  26721. }
  26722. _setAdditiveIdentityNumeric() {
  26723. const startIndex = this._addIndex * this.valueSize;
  26724. const endIndex = startIndex + this.valueSize;
  26725. for ( let i = startIndex; i < endIndex; i ++ ) {
  26726. this.buffer[ i ] = 0;
  26727. }
  26728. }
  26729. _setAdditiveIdentityQuaternion() {
  26730. this._setAdditiveIdentityNumeric();
  26731. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26732. }
  26733. _setAdditiveIdentityOther() {
  26734. const startIndex = this._origIndex * this.valueSize;
  26735. const targetIndex = this._addIndex * this.valueSize;
  26736. for ( let i = 0; i < this.valueSize; i ++ ) {
  26737. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26738. }
  26739. }
  26740. // mix functions
  26741. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26742. if ( t >= 0.5 ) {
  26743. for ( let i = 0; i !== stride; ++ i ) {
  26744. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26745. }
  26746. }
  26747. }
  26748. _slerp( buffer, dstOffset, srcOffset, t ) {
  26749. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26750. }
  26751. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26752. const workOffset = this._workIndex * stride;
  26753. // Store result in intermediate buffer offset
  26754. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26755. // Slerp to the intermediate result
  26756. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26757. }
  26758. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26759. const s = 1 - t;
  26760. for ( let i = 0; i !== stride; ++ i ) {
  26761. const j = dstOffset + i;
  26762. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26763. }
  26764. }
  26765. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26766. for ( let i = 0; i !== stride; ++ i ) {
  26767. const j = dstOffset + i;
  26768. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26769. }
  26770. }
  26771. }
  26772. // Characters [].:/ are reserved for track binding syntax.
  26773. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26774. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26775. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26776. // only latin characters, and the unicode \p{L} is not yet supported. So
  26777. // instead, we exclude reserved characters and match everything else.
  26778. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26779. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26780. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26781. // be matched to parse the rest of the track name.
  26782. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26783. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26784. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26785. // Object on target node, and accessor. May not contain reserved
  26786. // characters. Accessor may contain any character except closing bracket.
  26787. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26788. // Property and accessor. May not contain reserved characters. Accessor may
  26789. // contain any non-bracket characters.
  26790. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26791. const _trackRe = new RegExp( ''
  26792. + '^'
  26793. + _directoryRe
  26794. + _nodeRe
  26795. + _objectRe
  26796. + _propertyRe
  26797. + '$'
  26798. );
  26799. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26800. class Composite {
  26801. constructor( targetGroup, path, optionalParsedPath ) {
  26802. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26803. this._targetGroup = targetGroup;
  26804. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26805. }
  26806. getValue( array, offset ) {
  26807. this.bind(); // bind all binding
  26808. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26809. binding = this._bindings[ firstValidIndex ];
  26810. // and only call .getValue on the first
  26811. if ( binding !== undefined ) binding.getValue( array, offset );
  26812. }
  26813. setValue( array, offset ) {
  26814. const bindings = this._bindings;
  26815. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26816. bindings[ i ].setValue( array, offset );
  26817. }
  26818. }
  26819. bind() {
  26820. const bindings = this._bindings;
  26821. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26822. bindings[ i ].bind();
  26823. }
  26824. }
  26825. unbind() {
  26826. const bindings = this._bindings;
  26827. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26828. bindings[ i ].unbind();
  26829. }
  26830. }
  26831. }
  26832. // Note: This class uses a State pattern on a per-method basis:
  26833. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26834. // prototype version of these methods with one that represents
  26835. // the bound state. When the property is not found, the methods
  26836. // become no-ops.
  26837. class PropertyBinding {
  26838. constructor( rootNode, path, parsedPath ) {
  26839. this.path = path;
  26840. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26841. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26842. this.rootNode = rootNode;
  26843. // initial state of these methods that calls 'bind'
  26844. this.getValue = this._getValue_unbound;
  26845. this.setValue = this._setValue_unbound;
  26846. }
  26847. static create( root, path, parsedPath ) {
  26848. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26849. return new PropertyBinding( root, path, parsedPath );
  26850. } else {
  26851. return new PropertyBinding.Composite( root, path, parsedPath );
  26852. }
  26853. }
  26854. /**
  26855. * Replaces spaces with underscores and removes unsupported characters from
  26856. * node names, to ensure compatibility with parseTrackName().
  26857. *
  26858. * @param {string} name Node name to be sanitized.
  26859. * @return {string}
  26860. */
  26861. static sanitizeNodeName( name ) {
  26862. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26863. }
  26864. static parseTrackName( trackName ) {
  26865. const matches = _trackRe.exec( trackName );
  26866. if ( matches === null ) {
  26867. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26868. }
  26869. const results = {
  26870. // directoryName: matches[ 1 ], // (tschw) currently unused
  26871. nodeName: matches[ 2 ],
  26872. objectName: matches[ 3 ],
  26873. objectIndex: matches[ 4 ],
  26874. propertyName: matches[ 5 ], // required
  26875. propertyIndex: matches[ 6 ]
  26876. };
  26877. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26878. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26879. const objectName = results.nodeName.substring( lastDot + 1 );
  26880. // Object names must be checked against an allowlist. Otherwise, there
  26881. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26882. // 'bar' could be the objectName, or part of a nodeName (which can
  26883. // include '.' characters).
  26884. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26885. results.nodeName = results.nodeName.substring( 0, lastDot );
  26886. results.objectName = objectName;
  26887. }
  26888. }
  26889. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26890. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26891. }
  26892. return results;
  26893. }
  26894. static findNode( root, nodeName ) {
  26895. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26896. return root;
  26897. }
  26898. // search into skeleton bones.
  26899. if ( root.skeleton ) {
  26900. const bone = root.skeleton.getBoneByName( nodeName );
  26901. if ( bone !== undefined ) {
  26902. return bone;
  26903. }
  26904. }
  26905. // search into node subtree.
  26906. if ( root.children ) {
  26907. const searchNodeSubtree = function ( children ) {
  26908. for ( let i = 0; i < children.length; i ++ ) {
  26909. const childNode = children[ i ];
  26910. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26911. return childNode;
  26912. }
  26913. const result = searchNodeSubtree( childNode.children );
  26914. if ( result ) return result;
  26915. }
  26916. return null;
  26917. };
  26918. const subTreeNode = searchNodeSubtree( root.children );
  26919. if ( subTreeNode ) {
  26920. return subTreeNode;
  26921. }
  26922. }
  26923. return null;
  26924. }
  26925. // these are used to "bind" a nonexistent property
  26926. _getValue_unavailable() {}
  26927. _setValue_unavailable() {}
  26928. // Getters
  26929. _getValue_direct( buffer, offset ) {
  26930. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26931. }
  26932. _getValue_array( buffer, offset ) {
  26933. const source = this.resolvedProperty;
  26934. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26935. buffer[ offset ++ ] = source[ i ];
  26936. }
  26937. }
  26938. _getValue_arrayElement( buffer, offset ) {
  26939. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26940. }
  26941. _getValue_toArray( buffer, offset ) {
  26942. this.resolvedProperty.toArray( buffer, offset );
  26943. }
  26944. // Direct
  26945. _setValue_direct( buffer, offset ) {
  26946. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26947. }
  26948. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26949. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26950. this.targetObject.needsUpdate = true;
  26951. }
  26952. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26953. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26954. this.targetObject.matrixWorldNeedsUpdate = true;
  26955. }
  26956. // EntireArray
  26957. _setValue_array( buffer, offset ) {
  26958. const dest = this.resolvedProperty;
  26959. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26960. dest[ i ] = buffer[ offset ++ ];
  26961. }
  26962. }
  26963. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26964. const dest = this.resolvedProperty;
  26965. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26966. dest[ i ] = buffer[ offset ++ ];
  26967. }
  26968. this.targetObject.needsUpdate = true;
  26969. }
  26970. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26971. const dest = this.resolvedProperty;
  26972. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26973. dest[ i ] = buffer[ offset ++ ];
  26974. }
  26975. this.targetObject.matrixWorldNeedsUpdate = true;
  26976. }
  26977. // ArrayElement
  26978. _setValue_arrayElement( buffer, offset ) {
  26979. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26980. }
  26981. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26982. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26983. this.targetObject.needsUpdate = true;
  26984. }
  26985. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26986. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26987. this.targetObject.matrixWorldNeedsUpdate = true;
  26988. }
  26989. // HasToFromArray
  26990. _setValue_fromArray( buffer, offset ) {
  26991. this.resolvedProperty.fromArray( buffer, offset );
  26992. }
  26993. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26994. this.resolvedProperty.fromArray( buffer, offset );
  26995. this.targetObject.needsUpdate = true;
  26996. }
  26997. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26998. this.resolvedProperty.fromArray( buffer, offset );
  26999. this.targetObject.matrixWorldNeedsUpdate = true;
  27000. }
  27001. _getValue_unbound( targetArray, offset ) {
  27002. this.bind();
  27003. this.getValue( targetArray, offset );
  27004. }
  27005. _setValue_unbound( sourceArray, offset ) {
  27006. this.bind();
  27007. this.setValue( sourceArray, offset );
  27008. }
  27009. // create getter / setter pair for a property in the scene graph
  27010. bind() {
  27011. let targetObject = this.node;
  27012. const parsedPath = this.parsedPath;
  27013. const objectName = parsedPath.objectName;
  27014. const propertyName = parsedPath.propertyName;
  27015. let propertyIndex = parsedPath.propertyIndex;
  27016. if ( ! targetObject ) {
  27017. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27018. this.node = targetObject;
  27019. }
  27020. // set fail state so we can just 'return' on error
  27021. this.getValue = this._getValue_unavailable;
  27022. this.setValue = this._setValue_unavailable;
  27023. // ensure there is a value node
  27024. if ( ! targetObject ) {
  27025. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27026. return;
  27027. }
  27028. if ( objectName ) {
  27029. let objectIndex = parsedPath.objectIndex;
  27030. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27031. switch ( objectName ) {
  27032. case 'materials':
  27033. if ( ! targetObject.material ) {
  27034. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27035. return;
  27036. }
  27037. if ( ! targetObject.material.materials ) {
  27038. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27039. return;
  27040. }
  27041. targetObject = targetObject.material.materials;
  27042. break;
  27043. case 'bones':
  27044. if ( ! targetObject.skeleton ) {
  27045. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27046. return;
  27047. }
  27048. // potential future optimization: skip this if propertyIndex is already an integer
  27049. // and convert the integer string to a true integer.
  27050. targetObject = targetObject.skeleton.bones;
  27051. // support resolving morphTarget names into indices.
  27052. for ( let i = 0; i < targetObject.length; i ++ ) {
  27053. if ( targetObject[ i ].name === objectIndex ) {
  27054. objectIndex = i;
  27055. break;
  27056. }
  27057. }
  27058. break;
  27059. case 'map':
  27060. if ( ! targetObject.material ) {
  27061. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27062. return;
  27063. }
  27064. if ( ! targetObject.material.map ) {
  27065. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27066. return;
  27067. }
  27068. targetObject = targetObject.material.map;
  27069. break;
  27070. default:
  27071. if ( targetObject[ objectName ] === undefined ) {
  27072. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27073. return;
  27074. }
  27075. targetObject = targetObject[ objectName ];
  27076. }
  27077. if ( objectIndex !== undefined ) {
  27078. if ( targetObject[ objectIndex ] === undefined ) {
  27079. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27080. return;
  27081. }
  27082. targetObject = targetObject[ objectIndex ];
  27083. }
  27084. }
  27085. // resolve property
  27086. const nodeProperty = targetObject[ propertyName ];
  27087. if ( nodeProperty === undefined ) {
  27088. const nodeName = parsedPath.nodeName;
  27089. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27090. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27091. return;
  27092. }
  27093. // determine versioning scheme
  27094. let versioning = this.Versioning.None;
  27095. this.targetObject = targetObject;
  27096. if ( targetObject.needsUpdate !== undefined ) { // material
  27097. versioning = this.Versioning.NeedsUpdate;
  27098. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27099. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27100. }
  27101. // determine how the property gets bound
  27102. let bindingType = this.BindingType.Direct;
  27103. if ( propertyIndex !== undefined ) {
  27104. // access a sub element of the property array (only primitives are supported right now)
  27105. if ( propertyName === 'morphTargetInfluences' ) {
  27106. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27107. // support resolving morphTarget names into indices.
  27108. if ( ! targetObject.geometry ) {
  27109. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27110. return;
  27111. }
  27112. if ( ! targetObject.geometry.morphAttributes ) {
  27113. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27114. return;
  27115. }
  27116. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27117. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27118. }
  27119. }
  27120. bindingType = this.BindingType.ArrayElement;
  27121. this.resolvedProperty = nodeProperty;
  27122. this.propertyIndex = propertyIndex;
  27123. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27124. // must use copy for Object3D.Euler/Quaternion
  27125. bindingType = this.BindingType.HasFromToArray;
  27126. this.resolvedProperty = nodeProperty;
  27127. } else if ( Array.isArray( nodeProperty ) ) {
  27128. bindingType = this.BindingType.EntireArray;
  27129. this.resolvedProperty = nodeProperty;
  27130. } else {
  27131. this.propertyName = propertyName;
  27132. }
  27133. // select getter / setter
  27134. this.getValue = this.GetterByBindingType[ bindingType ];
  27135. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27136. }
  27137. unbind() {
  27138. this.node = null;
  27139. // back to the prototype version of getValue / setValue
  27140. // note: avoiding to mutate the shape of 'this' via 'delete'
  27141. this.getValue = this._getValue_unbound;
  27142. this.setValue = this._setValue_unbound;
  27143. }
  27144. }
  27145. PropertyBinding.Composite = Composite;
  27146. PropertyBinding.prototype.BindingType = {
  27147. Direct: 0,
  27148. EntireArray: 1,
  27149. ArrayElement: 2,
  27150. HasFromToArray: 3
  27151. };
  27152. PropertyBinding.prototype.Versioning = {
  27153. None: 0,
  27154. NeedsUpdate: 1,
  27155. MatrixWorldNeedsUpdate: 2
  27156. };
  27157. PropertyBinding.prototype.GetterByBindingType = [
  27158. PropertyBinding.prototype._getValue_direct,
  27159. PropertyBinding.prototype._getValue_array,
  27160. PropertyBinding.prototype._getValue_arrayElement,
  27161. PropertyBinding.prototype._getValue_toArray,
  27162. ];
  27163. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27164. [
  27165. // Direct
  27166. PropertyBinding.prototype._setValue_direct,
  27167. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27168. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27169. ], [
  27170. // EntireArray
  27171. PropertyBinding.prototype._setValue_array,
  27172. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27173. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27174. ], [
  27175. // ArrayElement
  27176. PropertyBinding.prototype._setValue_arrayElement,
  27177. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27178. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27179. ], [
  27180. // HasToFromArray
  27181. PropertyBinding.prototype._setValue_fromArray,
  27182. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27183. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27184. ]
  27185. ];
  27186. /**
  27187. *
  27188. * A group of objects that receives a shared animation state.
  27189. *
  27190. * Usage:
  27191. *
  27192. * - Add objects you would otherwise pass as 'root' to the
  27193. * constructor or the .clipAction method of AnimationMixer.
  27194. *
  27195. * - Instead pass this object as 'root'.
  27196. *
  27197. * - You can also add and remove objects later when the mixer
  27198. * is running.
  27199. *
  27200. * Note:
  27201. *
  27202. * Objects of this class appear as one object to the mixer,
  27203. * so cache control of the individual objects must be done
  27204. * on the group.
  27205. *
  27206. * Limitation:
  27207. *
  27208. * - The animated properties must be compatible among the
  27209. * all objects in the group.
  27210. *
  27211. * - A single property can either be controlled through a
  27212. * target group or directly, but not both.
  27213. */
  27214. class AnimationObjectGroup {
  27215. constructor() {
  27216. this.isAnimationObjectGroup = true;
  27217. this.uuid = generateUUID();
  27218. // cached objects followed by the active ones
  27219. this._objects = Array.prototype.slice.call( arguments );
  27220. this.nCachedObjects_ = 0; // threshold
  27221. // note: read by PropertyBinding.Composite
  27222. const indices = {};
  27223. this._indicesByUUID = indices; // for bookkeeping
  27224. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27225. indices[ arguments[ i ].uuid ] = i;
  27226. }
  27227. this._paths = []; // inside: string
  27228. this._parsedPaths = []; // inside: { we don't care, here }
  27229. this._bindings = []; // inside: Array< PropertyBinding >
  27230. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27231. const scope = this;
  27232. this.stats = {
  27233. objects: {
  27234. get total() {
  27235. return scope._objects.length;
  27236. },
  27237. get inUse() {
  27238. return this.total - scope.nCachedObjects_;
  27239. }
  27240. },
  27241. get bindingsPerObject() {
  27242. return scope._bindings.length;
  27243. }
  27244. };
  27245. }
  27246. add() {
  27247. const objects = this._objects,
  27248. indicesByUUID = this._indicesByUUID,
  27249. paths = this._paths,
  27250. parsedPaths = this._parsedPaths,
  27251. bindings = this._bindings,
  27252. nBindings = bindings.length;
  27253. let knownObject = undefined,
  27254. nObjects = objects.length,
  27255. nCachedObjects = this.nCachedObjects_;
  27256. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27257. const object = arguments[ i ],
  27258. uuid = object.uuid;
  27259. let index = indicesByUUID[ uuid ];
  27260. if ( index === undefined ) {
  27261. // unknown object -> add it to the ACTIVE region
  27262. index = nObjects ++;
  27263. indicesByUUID[ uuid ] = index;
  27264. objects.push( object );
  27265. // accounting is done, now do the same for all bindings
  27266. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27267. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27268. }
  27269. } else if ( index < nCachedObjects ) {
  27270. knownObject = objects[ index ];
  27271. // move existing object to the ACTIVE region
  27272. const firstActiveIndex = -- nCachedObjects,
  27273. lastCachedObject = objects[ firstActiveIndex ];
  27274. indicesByUUID[ lastCachedObject.uuid ] = index;
  27275. objects[ index ] = lastCachedObject;
  27276. indicesByUUID[ uuid ] = firstActiveIndex;
  27277. objects[ firstActiveIndex ] = object;
  27278. // accounting is done, now do the same for all bindings
  27279. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27280. const bindingsForPath = bindings[ j ],
  27281. lastCached = bindingsForPath[ firstActiveIndex ];
  27282. let binding = bindingsForPath[ index ];
  27283. bindingsForPath[ index ] = lastCached;
  27284. if ( binding === undefined ) {
  27285. // since we do not bother to create new bindings
  27286. // for objects that are cached, the binding may
  27287. // or may not exist
  27288. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27289. }
  27290. bindingsForPath[ firstActiveIndex ] = binding;
  27291. }
  27292. } else if ( objects[ index ] !== knownObject ) {
  27293. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27294. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27295. } // else the object is already where we want it to be
  27296. } // for arguments
  27297. this.nCachedObjects_ = nCachedObjects;
  27298. }
  27299. remove() {
  27300. const objects = this._objects,
  27301. indicesByUUID = this._indicesByUUID,
  27302. bindings = this._bindings,
  27303. nBindings = bindings.length;
  27304. let nCachedObjects = this.nCachedObjects_;
  27305. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27306. const object = arguments[ i ],
  27307. uuid = object.uuid,
  27308. index = indicesByUUID[ uuid ];
  27309. if ( index !== undefined && index >= nCachedObjects ) {
  27310. // move existing object into the CACHED region
  27311. const lastCachedIndex = nCachedObjects ++,
  27312. firstActiveObject = objects[ lastCachedIndex ];
  27313. indicesByUUID[ firstActiveObject.uuid ] = index;
  27314. objects[ index ] = firstActiveObject;
  27315. indicesByUUID[ uuid ] = lastCachedIndex;
  27316. objects[ lastCachedIndex ] = object;
  27317. // accounting is done, now do the same for all bindings
  27318. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27319. const bindingsForPath = bindings[ j ],
  27320. firstActive = bindingsForPath[ lastCachedIndex ],
  27321. binding = bindingsForPath[ index ];
  27322. bindingsForPath[ index ] = firstActive;
  27323. bindingsForPath[ lastCachedIndex ] = binding;
  27324. }
  27325. }
  27326. } // for arguments
  27327. this.nCachedObjects_ = nCachedObjects;
  27328. }
  27329. // remove & forget
  27330. uncache() {
  27331. const objects = this._objects,
  27332. indicesByUUID = this._indicesByUUID,
  27333. bindings = this._bindings,
  27334. nBindings = bindings.length;
  27335. let nCachedObjects = this.nCachedObjects_,
  27336. nObjects = objects.length;
  27337. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27338. const object = arguments[ i ],
  27339. uuid = object.uuid,
  27340. index = indicesByUUID[ uuid ];
  27341. if ( index !== undefined ) {
  27342. delete indicesByUUID[ uuid ];
  27343. if ( index < nCachedObjects ) {
  27344. // object is cached, shrink the CACHED region
  27345. const firstActiveIndex = -- nCachedObjects,
  27346. lastCachedObject = objects[ firstActiveIndex ],
  27347. lastIndex = -- nObjects,
  27348. lastObject = objects[ lastIndex ];
  27349. // last cached object takes this object's place
  27350. indicesByUUID[ lastCachedObject.uuid ] = index;
  27351. objects[ index ] = lastCachedObject;
  27352. // last object goes to the activated slot and pop
  27353. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27354. objects[ firstActiveIndex ] = lastObject;
  27355. objects.pop();
  27356. // accounting is done, now do the same for all bindings
  27357. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27358. const bindingsForPath = bindings[ j ],
  27359. lastCached = bindingsForPath[ firstActiveIndex ],
  27360. last = bindingsForPath[ lastIndex ];
  27361. bindingsForPath[ index ] = lastCached;
  27362. bindingsForPath[ firstActiveIndex ] = last;
  27363. bindingsForPath.pop();
  27364. }
  27365. } else {
  27366. // object is active, just swap with the last and pop
  27367. const lastIndex = -- nObjects,
  27368. lastObject = objects[ lastIndex ];
  27369. if ( lastIndex > 0 ) {
  27370. indicesByUUID[ lastObject.uuid ] = index;
  27371. }
  27372. objects[ index ] = lastObject;
  27373. objects.pop();
  27374. // accounting is done, now do the same for all bindings
  27375. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27376. const bindingsForPath = bindings[ j ];
  27377. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27378. bindingsForPath.pop();
  27379. }
  27380. } // cached or active
  27381. } // if object is known
  27382. } // for arguments
  27383. this.nCachedObjects_ = nCachedObjects;
  27384. }
  27385. // Internal interface used by befriended PropertyBinding.Composite:
  27386. subscribe_( path, parsedPath ) {
  27387. // returns an array of bindings for the given path that is changed
  27388. // according to the contained objects in the group
  27389. const indicesByPath = this._bindingsIndicesByPath;
  27390. let index = indicesByPath[ path ];
  27391. const bindings = this._bindings;
  27392. if ( index !== undefined ) return bindings[ index ];
  27393. const paths = this._paths,
  27394. parsedPaths = this._parsedPaths,
  27395. objects = this._objects,
  27396. nObjects = objects.length,
  27397. nCachedObjects = this.nCachedObjects_,
  27398. bindingsForPath = new Array( nObjects );
  27399. index = bindings.length;
  27400. indicesByPath[ path ] = index;
  27401. paths.push( path );
  27402. parsedPaths.push( parsedPath );
  27403. bindings.push( bindingsForPath );
  27404. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27405. const object = objects[ i ];
  27406. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27407. }
  27408. return bindingsForPath;
  27409. }
  27410. unsubscribe_( path ) {
  27411. // tells the group to forget about a property path and no longer
  27412. // update the array previously obtained with 'subscribe_'
  27413. const indicesByPath = this._bindingsIndicesByPath,
  27414. index = indicesByPath[ path ];
  27415. if ( index !== undefined ) {
  27416. const paths = this._paths,
  27417. parsedPaths = this._parsedPaths,
  27418. bindings = this._bindings,
  27419. lastBindingsIndex = bindings.length - 1,
  27420. lastBindings = bindings[ lastBindingsIndex ],
  27421. lastBindingsPath = path[ lastBindingsIndex ];
  27422. indicesByPath[ lastBindingsPath ] = index;
  27423. bindings[ index ] = lastBindings;
  27424. bindings.pop();
  27425. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27426. parsedPaths.pop();
  27427. paths[ index ] = paths[ lastBindingsIndex ];
  27428. paths.pop();
  27429. }
  27430. }
  27431. }
  27432. class AnimationAction {
  27433. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27434. this._mixer = mixer;
  27435. this._clip = clip;
  27436. this._localRoot = localRoot;
  27437. this.blendMode = blendMode;
  27438. const tracks = clip.tracks,
  27439. nTracks = tracks.length,
  27440. interpolants = new Array( nTracks );
  27441. const interpolantSettings = {
  27442. endingStart: ZeroCurvatureEnding,
  27443. endingEnd: ZeroCurvatureEnding
  27444. };
  27445. for ( let i = 0; i !== nTracks; ++ i ) {
  27446. const interpolant = tracks[ i ].createInterpolant( null );
  27447. interpolants[ i ] = interpolant;
  27448. interpolant.settings = interpolantSettings;
  27449. }
  27450. this._interpolantSettings = interpolantSettings;
  27451. this._interpolants = interpolants; // bound by the mixer
  27452. // inside: PropertyMixer (managed by the mixer)
  27453. this._propertyBindings = new Array( nTracks );
  27454. this._cacheIndex = null; // for the memory manager
  27455. this._byClipCacheIndex = null; // for the memory manager
  27456. this._timeScaleInterpolant = null;
  27457. this._weightInterpolant = null;
  27458. this.loop = LoopRepeat;
  27459. this._loopCount = - 1;
  27460. // global mixer time when the action is to be started
  27461. // it's set back to 'null' upon start of the action
  27462. this._startTime = null;
  27463. // scaled local time of the action
  27464. // gets clamped or wrapped to 0..clip.duration according to loop
  27465. this.time = 0;
  27466. this.timeScale = 1;
  27467. this._effectiveTimeScale = 1;
  27468. this.weight = 1;
  27469. this._effectiveWeight = 1;
  27470. this.repetitions = Infinity; // no. of repetitions when looping
  27471. this.paused = false; // true -> zero effective time scale
  27472. this.enabled = true; // false -> zero effective weight
  27473. this.clampWhenFinished = false;// keep feeding the last frame?
  27474. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27475. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27476. }
  27477. // State & Scheduling
  27478. play() {
  27479. this._mixer._activateAction( this );
  27480. return this;
  27481. }
  27482. stop() {
  27483. this._mixer._deactivateAction( this );
  27484. return this.reset();
  27485. }
  27486. reset() {
  27487. this.paused = false;
  27488. this.enabled = true;
  27489. this.time = 0; // restart clip
  27490. this._loopCount = - 1;// forget previous loops
  27491. this._startTime = null;// forget scheduling
  27492. return this.stopFading().stopWarping();
  27493. }
  27494. isRunning() {
  27495. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27496. this._startTime === null && this._mixer._isActiveAction( this );
  27497. }
  27498. // return true when play has been called
  27499. isScheduled() {
  27500. return this._mixer._isActiveAction( this );
  27501. }
  27502. startAt( time ) {
  27503. this._startTime = time;
  27504. return this;
  27505. }
  27506. setLoop( mode, repetitions ) {
  27507. this.loop = mode;
  27508. this.repetitions = repetitions;
  27509. return this;
  27510. }
  27511. // Weight
  27512. // set the weight stopping any scheduled fading
  27513. // although .enabled = false yields an effective weight of zero, this
  27514. // method does *not* change .enabled, because it would be confusing
  27515. setEffectiveWeight( weight ) {
  27516. this.weight = weight;
  27517. // note: same logic as when updated at runtime
  27518. this._effectiveWeight = this.enabled ? weight : 0;
  27519. return this.stopFading();
  27520. }
  27521. // return the weight considering fading and .enabled
  27522. getEffectiveWeight() {
  27523. return this._effectiveWeight;
  27524. }
  27525. fadeIn( duration ) {
  27526. return this._scheduleFading( duration, 0, 1 );
  27527. }
  27528. fadeOut( duration ) {
  27529. return this._scheduleFading( duration, 1, 0 );
  27530. }
  27531. crossFadeFrom( fadeOutAction, duration, warp ) {
  27532. fadeOutAction.fadeOut( duration );
  27533. this.fadeIn( duration );
  27534. if ( warp ) {
  27535. const fadeInDuration = this._clip.duration,
  27536. fadeOutDuration = fadeOutAction._clip.duration,
  27537. startEndRatio = fadeOutDuration / fadeInDuration,
  27538. endStartRatio = fadeInDuration / fadeOutDuration;
  27539. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27540. this.warp( endStartRatio, 1.0, duration );
  27541. }
  27542. return this;
  27543. }
  27544. crossFadeTo( fadeInAction, duration, warp ) {
  27545. return fadeInAction.crossFadeFrom( this, duration, warp );
  27546. }
  27547. stopFading() {
  27548. const weightInterpolant = this._weightInterpolant;
  27549. if ( weightInterpolant !== null ) {
  27550. this._weightInterpolant = null;
  27551. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27552. }
  27553. return this;
  27554. }
  27555. // Time Scale Control
  27556. // set the time scale stopping any scheduled warping
  27557. // although .paused = true yields an effective time scale of zero, this
  27558. // method does *not* change .paused, because it would be confusing
  27559. setEffectiveTimeScale( timeScale ) {
  27560. this.timeScale = timeScale;
  27561. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27562. return this.stopWarping();
  27563. }
  27564. // return the time scale considering warping and .paused
  27565. getEffectiveTimeScale() {
  27566. return this._effectiveTimeScale;
  27567. }
  27568. setDuration( duration ) {
  27569. this.timeScale = this._clip.duration / duration;
  27570. return this.stopWarping();
  27571. }
  27572. syncWith( action ) {
  27573. this.time = action.time;
  27574. this.timeScale = action.timeScale;
  27575. return this.stopWarping();
  27576. }
  27577. halt( duration ) {
  27578. return this.warp( this._effectiveTimeScale, 0, duration );
  27579. }
  27580. warp( startTimeScale, endTimeScale, duration ) {
  27581. const mixer = this._mixer,
  27582. now = mixer.time,
  27583. timeScale = this.timeScale;
  27584. let interpolant = this._timeScaleInterpolant;
  27585. if ( interpolant === null ) {
  27586. interpolant = mixer._lendControlInterpolant();
  27587. this._timeScaleInterpolant = interpolant;
  27588. }
  27589. const times = interpolant.parameterPositions,
  27590. values = interpolant.sampleValues;
  27591. times[ 0 ] = now;
  27592. times[ 1 ] = now + duration;
  27593. values[ 0 ] = startTimeScale / timeScale;
  27594. values[ 1 ] = endTimeScale / timeScale;
  27595. return this;
  27596. }
  27597. stopWarping() {
  27598. const timeScaleInterpolant = this._timeScaleInterpolant;
  27599. if ( timeScaleInterpolant !== null ) {
  27600. this._timeScaleInterpolant = null;
  27601. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27602. }
  27603. return this;
  27604. }
  27605. // Object Accessors
  27606. getMixer() {
  27607. return this._mixer;
  27608. }
  27609. getClip() {
  27610. return this._clip;
  27611. }
  27612. getRoot() {
  27613. return this._localRoot || this._mixer._root;
  27614. }
  27615. // Interna
  27616. _update( time, deltaTime, timeDirection, accuIndex ) {
  27617. // called by the mixer
  27618. if ( ! this.enabled ) {
  27619. // call ._updateWeight() to update ._effectiveWeight
  27620. this._updateWeight( time );
  27621. return;
  27622. }
  27623. const startTime = this._startTime;
  27624. if ( startTime !== null ) {
  27625. // check for scheduled start of action
  27626. const timeRunning = ( time - startTime ) * timeDirection;
  27627. if ( timeRunning < 0 || timeDirection === 0 ) {
  27628. deltaTime = 0;
  27629. } else {
  27630. this._startTime = null; // unschedule
  27631. deltaTime = timeDirection * timeRunning;
  27632. }
  27633. }
  27634. // apply time scale and advance time
  27635. deltaTime *= this._updateTimeScale( time );
  27636. const clipTime = this._updateTime( deltaTime );
  27637. // note: _updateTime may disable the action resulting in
  27638. // an effective weight of 0
  27639. const weight = this._updateWeight( time );
  27640. if ( weight > 0 ) {
  27641. const interpolants = this._interpolants;
  27642. const propertyMixers = this._propertyBindings;
  27643. switch ( this.blendMode ) {
  27644. case AdditiveAnimationBlendMode:
  27645. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27646. interpolants[ j ].evaluate( clipTime );
  27647. propertyMixers[ j ].accumulateAdditive( weight );
  27648. }
  27649. break;
  27650. case NormalAnimationBlendMode:
  27651. default:
  27652. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27653. interpolants[ j ].evaluate( clipTime );
  27654. propertyMixers[ j ].accumulate( accuIndex, weight );
  27655. }
  27656. }
  27657. }
  27658. }
  27659. _updateWeight( time ) {
  27660. let weight = 0;
  27661. if ( this.enabled ) {
  27662. weight = this.weight;
  27663. const interpolant = this._weightInterpolant;
  27664. if ( interpolant !== null ) {
  27665. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27666. weight *= interpolantValue;
  27667. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27668. this.stopFading();
  27669. if ( interpolantValue === 0 ) {
  27670. // faded out, disable
  27671. this.enabled = false;
  27672. }
  27673. }
  27674. }
  27675. }
  27676. this._effectiveWeight = weight;
  27677. return weight;
  27678. }
  27679. _updateTimeScale( time ) {
  27680. let timeScale = 0;
  27681. if ( ! this.paused ) {
  27682. timeScale = this.timeScale;
  27683. const interpolant = this._timeScaleInterpolant;
  27684. if ( interpolant !== null ) {
  27685. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27686. timeScale *= interpolantValue;
  27687. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27688. this.stopWarping();
  27689. if ( timeScale === 0 ) {
  27690. // motion has halted, pause
  27691. this.paused = true;
  27692. } else {
  27693. // warp done - apply final time scale
  27694. this.timeScale = timeScale;
  27695. }
  27696. }
  27697. }
  27698. }
  27699. this._effectiveTimeScale = timeScale;
  27700. return timeScale;
  27701. }
  27702. _updateTime( deltaTime ) {
  27703. const duration = this._clip.duration;
  27704. const loop = this.loop;
  27705. let time = this.time + deltaTime;
  27706. let loopCount = this._loopCount;
  27707. const pingPong = ( loop === LoopPingPong );
  27708. if ( deltaTime === 0 ) {
  27709. if ( loopCount === - 1 ) return time;
  27710. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27711. }
  27712. if ( loop === LoopOnce ) {
  27713. if ( loopCount === - 1 ) {
  27714. // just started
  27715. this._loopCount = 0;
  27716. this._setEndings( true, true, false );
  27717. }
  27718. handle_stop: {
  27719. if ( time >= duration ) {
  27720. time = duration;
  27721. } else if ( time < 0 ) {
  27722. time = 0;
  27723. } else {
  27724. this.time = time;
  27725. break handle_stop;
  27726. }
  27727. if ( this.clampWhenFinished ) this.paused = true;
  27728. else this.enabled = false;
  27729. this.time = time;
  27730. this._mixer.dispatchEvent( {
  27731. type: 'finished', action: this,
  27732. direction: deltaTime < 0 ? - 1 : 1
  27733. } );
  27734. }
  27735. } else { // repetitive Repeat or PingPong
  27736. if ( loopCount === - 1 ) {
  27737. // just started
  27738. if ( deltaTime >= 0 ) {
  27739. loopCount = 0;
  27740. this._setEndings( true, this.repetitions === 0, pingPong );
  27741. } else {
  27742. // when looping in reverse direction, the initial
  27743. // transition through zero counts as a repetition,
  27744. // so leave loopCount at -1
  27745. this._setEndings( this.repetitions === 0, true, pingPong );
  27746. }
  27747. }
  27748. if ( time >= duration || time < 0 ) {
  27749. // wrap around
  27750. const loopDelta = Math.floor( time / duration ); // signed
  27751. time -= duration * loopDelta;
  27752. loopCount += Math.abs( loopDelta );
  27753. const pending = this.repetitions - loopCount;
  27754. if ( pending <= 0 ) {
  27755. // have to stop (switch state, clamp time, fire event)
  27756. if ( this.clampWhenFinished ) this.paused = true;
  27757. else this.enabled = false;
  27758. time = deltaTime > 0 ? duration : 0;
  27759. this.time = time;
  27760. this._mixer.dispatchEvent( {
  27761. type: 'finished', action: this,
  27762. direction: deltaTime > 0 ? 1 : - 1
  27763. } );
  27764. } else {
  27765. // keep running
  27766. if ( pending === 1 ) {
  27767. // entering the last round
  27768. const atStart = deltaTime < 0;
  27769. this._setEndings( atStart, ! atStart, pingPong );
  27770. } else {
  27771. this._setEndings( false, false, pingPong );
  27772. }
  27773. this._loopCount = loopCount;
  27774. this.time = time;
  27775. this._mixer.dispatchEvent( {
  27776. type: 'loop', action: this, loopDelta: loopDelta
  27777. } );
  27778. }
  27779. } else {
  27780. this.time = time;
  27781. }
  27782. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27783. // invert time for the "pong round"
  27784. return duration - time;
  27785. }
  27786. }
  27787. return time;
  27788. }
  27789. _setEndings( atStart, atEnd, pingPong ) {
  27790. const settings = this._interpolantSettings;
  27791. if ( pingPong ) {
  27792. settings.endingStart = ZeroSlopeEnding;
  27793. settings.endingEnd = ZeroSlopeEnding;
  27794. } else {
  27795. // assuming for LoopOnce atStart == atEnd == true
  27796. if ( atStart ) {
  27797. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27798. } else {
  27799. settings.endingStart = WrapAroundEnding;
  27800. }
  27801. if ( atEnd ) {
  27802. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27803. } else {
  27804. settings.endingEnd = WrapAroundEnding;
  27805. }
  27806. }
  27807. }
  27808. _scheduleFading( duration, weightNow, weightThen ) {
  27809. const mixer = this._mixer, now = mixer.time;
  27810. let interpolant = this._weightInterpolant;
  27811. if ( interpolant === null ) {
  27812. interpolant = mixer._lendControlInterpolant();
  27813. this._weightInterpolant = interpolant;
  27814. }
  27815. const times = interpolant.parameterPositions,
  27816. values = interpolant.sampleValues;
  27817. times[ 0 ] = now;
  27818. values[ 0 ] = weightNow;
  27819. times[ 1 ] = now + duration;
  27820. values[ 1 ] = weightThen;
  27821. return this;
  27822. }
  27823. }
  27824. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27825. class AnimationMixer extends EventDispatcher {
  27826. constructor( root ) {
  27827. super();
  27828. this._root = root;
  27829. this._initMemoryManager();
  27830. this._accuIndex = 0;
  27831. this.time = 0;
  27832. this.timeScale = 1.0;
  27833. }
  27834. _bindAction( action, prototypeAction ) {
  27835. const root = action._localRoot || this._root,
  27836. tracks = action._clip.tracks,
  27837. nTracks = tracks.length,
  27838. bindings = action._propertyBindings,
  27839. interpolants = action._interpolants,
  27840. rootUuid = root.uuid,
  27841. bindingsByRoot = this._bindingsByRootAndName;
  27842. let bindingsByName = bindingsByRoot[ rootUuid ];
  27843. if ( bindingsByName === undefined ) {
  27844. bindingsByName = {};
  27845. bindingsByRoot[ rootUuid ] = bindingsByName;
  27846. }
  27847. for ( let i = 0; i !== nTracks; ++ i ) {
  27848. const track = tracks[ i ],
  27849. trackName = track.name;
  27850. let binding = bindingsByName[ trackName ];
  27851. if ( binding !== undefined ) {
  27852. ++ binding.referenceCount;
  27853. bindings[ i ] = binding;
  27854. } else {
  27855. binding = bindings[ i ];
  27856. if ( binding !== undefined ) {
  27857. // existing binding, make sure the cache knows
  27858. if ( binding._cacheIndex === null ) {
  27859. ++ binding.referenceCount;
  27860. this._addInactiveBinding( binding, rootUuid, trackName );
  27861. }
  27862. continue;
  27863. }
  27864. const path = prototypeAction && prototypeAction.
  27865. _propertyBindings[ i ].binding.parsedPath;
  27866. binding = new PropertyMixer(
  27867. PropertyBinding.create( root, trackName, path ),
  27868. track.ValueTypeName, track.getValueSize() );
  27869. ++ binding.referenceCount;
  27870. this._addInactiveBinding( binding, rootUuid, trackName );
  27871. bindings[ i ] = binding;
  27872. }
  27873. interpolants[ i ].resultBuffer = binding.buffer;
  27874. }
  27875. }
  27876. _activateAction( action ) {
  27877. if ( ! this._isActiveAction( action ) ) {
  27878. if ( action._cacheIndex === null ) {
  27879. // this action has been forgotten by the cache, but the user
  27880. // appears to be still using it -> rebind
  27881. const rootUuid = ( action._localRoot || this._root ).uuid,
  27882. clipUuid = action._clip.uuid,
  27883. actionsForClip = this._actionsByClip[ clipUuid ];
  27884. this._bindAction( action,
  27885. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27886. this._addInactiveAction( action, clipUuid, rootUuid );
  27887. }
  27888. const bindings = action._propertyBindings;
  27889. // increment reference counts / sort out state
  27890. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27891. const binding = bindings[ i ];
  27892. if ( binding.useCount ++ === 0 ) {
  27893. this._lendBinding( binding );
  27894. binding.saveOriginalState();
  27895. }
  27896. }
  27897. this._lendAction( action );
  27898. }
  27899. }
  27900. _deactivateAction( action ) {
  27901. if ( this._isActiveAction( action ) ) {
  27902. const bindings = action._propertyBindings;
  27903. // decrement reference counts / sort out state
  27904. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27905. const binding = bindings[ i ];
  27906. if ( -- binding.useCount === 0 ) {
  27907. binding.restoreOriginalState();
  27908. this._takeBackBinding( binding );
  27909. }
  27910. }
  27911. this._takeBackAction( action );
  27912. }
  27913. }
  27914. // Memory manager
  27915. _initMemoryManager() {
  27916. this._actions = []; // 'nActiveActions' followed by inactive ones
  27917. this._nActiveActions = 0;
  27918. this._actionsByClip = {};
  27919. // inside:
  27920. // {
  27921. // knownActions: Array< AnimationAction > - used as prototypes
  27922. // actionByRoot: AnimationAction - lookup
  27923. // }
  27924. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27925. this._nActiveBindings = 0;
  27926. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27927. this._controlInterpolants = []; // same game as above
  27928. this._nActiveControlInterpolants = 0;
  27929. const scope = this;
  27930. this.stats = {
  27931. actions: {
  27932. get total() {
  27933. return scope._actions.length;
  27934. },
  27935. get inUse() {
  27936. return scope._nActiveActions;
  27937. }
  27938. },
  27939. bindings: {
  27940. get total() {
  27941. return scope._bindings.length;
  27942. },
  27943. get inUse() {
  27944. return scope._nActiveBindings;
  27945. }
  27946. },
  27947. controlInterpolants: {
  27948. get total() {
  27949. return scope._controlInterpolants.length;
  27950. },
  27951. get inUse() {
  27952. return scope._nActiveControlInterpolants;
  27953. }
  27954. }
  27955. };
  27956. }
  27957. // Memory management for AnimationAction objects
  27958. _isActiveAction( action ) {
  27959. const index = action._cacheIndex;
  27960. return index !== null && index < this._nActiveActions;
  27961. }
  27962. _addInactiveAction( action, clipUuid, rootUuid ) {
  27963. const actions = this._actions,
  27964. actionsByClip = this._actionsByClip;
  27965. let actionsForClip = actionsByClip[ clipUuid ];
  27966. if ( actionsForClip === undefined ) {
  27967. actionsForClip = {
  27968. knownActions: [ action ],
  27969. actionByRoot: {}
  27970. };
  27971. action._byClipCacheIndex = 0;
  27972. actionsByClip[ clipUuid ] = actionsForClip;
  27973. } else {
  27974. const knownActions = actionsForClip.knownActions;
  27975. action._byClipCacheIndex = knownActions.length;
  27976. knownActions.push( action );
  27977. }
  27978. action._cacheIndex = actions.length;
  27979. actions.push( action );
  27980. actionsForClip.actionByRoot[ rootUuid ] = action;
  27981. }
  27982. _removeInactiveAction( action ) {
  27983. const actions = this._actions,
  27984. lastInactiveAction = actions[ actions.length - 1 ],
  27985. cacheIndex = action._cacheIndex;
  27986. lastInactiveAction._cacheIndex = cacheIndex;
  27987. actions[ cacheIndex ] = lastInactiveAction;
  27988. actions.pop();
  27989. action._cacheIndex = null;
  27990. const clipUuid = action._clip.uuid,
  27991. actionsByClip = this._actionsByClip,
  27992. actionsForClip = actionsByClip[ clipUuid ],
  27993. knownActionsForClip = actionsForClip.knownActions,
  27994. lastKnownAction =
  27995. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27996. byClipCacheIndex = action._byClipCacheIndex;
  27997. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27998. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27999. knownActionsForClip.pop();
  28000. action._byClipCacheIndex = null;
  28001. const actionByRoot = actionsForClip.actionByRoot,
  28002. rootUuid = ( action._localRoot || this._root ).uuid;
  28003. delete actionByRoot[ rootUuid ];
  28004. if ( knownActionsForClip.length === 0 ) {
  28005. delete actionsByClip[ clipUuid ];
  28006. }
  28007. this._removeInactiveBindingsForAction( action );
  28008. }
  28009. _removeInactiveBindingsForAction( action ) {
  28010. const bindings = action._propertyBindings;
  28011. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28012. const binding = bindings[ i ];
  28013. if ( -- binding.referenceCount === 0 ) {
  28014. this._removeInactiveBinding( binding );
  28015. }
  28016. }
  28017. }
  28018. _lendAction( action ) {
  28019. // [ active actions | inactive actions ]
  28020. // [ active actions >| inactive actions ]
  28021. // s a
  28022. // <-swap->
  28023. // a s
  28024. const actions = this._actions,
  28025. prevIndex = action._cacheIndex,
  28026. lastActiveIndex = this._nActiveActions ++,
  28027. firstInactiveAction = actions[ lastActiveIndex ];
  28028. action._cacheIndex = lastActiveIndex;
  28029. actions[ lastActiveIndex ] = action;
  28030. firstInactiveAction._cacheIndex = prevIndex;
  28031. actions[ prevIndex ] = firstInactiveAction;
  28032. }
  28033. _takeBackAction( action ) {
  28034. // [ active actions | inactive actions ]
  28035. // [ active actions |< inactive actions ]
  28036. // a s
  28037. // <-swap->
  28038. // s a
  28039. const actions = this._actions,
  28040. prevIndex = action._cacheIndex,
  28041. firstInactiveIndex = -- this._nActiveActions,
  28042. lastActiveAction = actions[ firstInactiveIndex ];
  28043. action._cacheIndex = firstInactiveIndex;
  28044. actions[ firstInactiveIndex ] = action;
  28045. lastActiveAction._cacheIndex = prevIndex;
  28046. actions[ prevIndex ] = lastActiveAction;
  28047. }
  28048. // Memory management for PropertyMixer objects
  28049. _addInactiveBinding( binding, rootUuid, trackName ) {
  28050. const bindingsByRoot = this._bindingsByRootAndName,
  28051. bindings = this._bindings;
  28052. let bindingByName = bindingsByRoot[ rootUuid ];
  28053. if ( bindingByName === undefined ) {
  28054. bindingByName = {};
  28055. bindingsByRoot[ rootUuid ] = bindingByName;
  28056. }
  28057. bindingByName[ trackName ] = binding;
  28058. binding._cacheIndex = bindings.length;
  28059. bindings.push( binding );
  28060. }
  28061. _removeInactiveBinding( binding ) {
  28062. const bindings = this._bindings,
  28063. propBinding = binding.binding,
  28064. rootUuid = propBinding.rootNode.uuid,
  28065. trackName = propBinding.path,
  28066. bindingsByRoot = this._bindingsByRootAndName,
  28067. bindingByName = bindingsByRoot[ rootUuid ],
  28068. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28069. cacheIndex = binding._cacheIndex;
  28070. lastInactiveBinding._cacheIndex = cacheIndex;
  28071. bindings[ cacheIndex ] = lastInactiveBinding;
  28072. bindings.pop();
  28073. delete bindingByName[ trackName ];
  28074. if ( Object.keys( bindingByName ).length === 0 ) {
  28075. delete bindingsByRoot[ rootUuid ];
  28076. }
  28077. }
  28078. _lendBinding( binding ) {
  28079. const bindings = this._bindings,
  28080. prevIndex = binding._cacheIndex,
  28081. lastActiveIndex = this._nActiveBindings ++,
  28082. firstInactiveBinding = bindings[ lastActiveIndex ];
  28083. binding._cacheIndex = lastActiveIndex;
  28084. bindings[ lastActiveIndex ] = binding;
  28085. firstInactiveBinding._cacheIndex = prevIndex;
  28086. bindings[ prevIndex ] = firstInactiveBinding;
  28087. }
  28088. _takeBackBinding( binding ) {
  28089. const bindings = this._bindings,
  28090. prevIndex = binding._cacheIndex,
  28091. firstInactiveIndex = -- this._nActiveBindings,
  28092. lastActiveBinding = bindings[ firstInactiveIndex ];
  28093. binding._cacheIndex = firstInactiveIndex;
  28094. bindings[ firstInactiveIndex ] = binding;
  28095. lastActiveBinding._cacheIndex = prevIndex;
  28096. bindings[ prevIndex ] = lastActiveBinding;
  28097. }
  28098. // Memory management of Interpolants for weight and time scale
  28099. _lendControlInterpolant() {
  28100. const interpolants = this._controlInterpolants,
  28101. lastActiveIndex = this._nActiveControlInterpolants ++;
  28102. let interpolant = interpolants[ lastActiveIndex ];
  28103. if ( interpolant === undefined ) {
  28104. interpolant = new LinearInterpolant(
  28105. new Float32Array( 2 ), new Float32Array( 2 ),
  28106. 1, _controlInterpolantsResultBuffer );
  28107. interpolant.__cacheIndex = lastActiveIndex;
  28108. interpolants[ lastActiveIndex ] = interpolant;
  28109. }
  28110. return interpolant;
  28111. }
  28112. _takeBackControlInterpolant( interpolant ) {
  28113. const interpolants = this._controlInterpolants,
  28114. prevIndex = interpolant.__cacheIndex,
  28115. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28116. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28117. interpolant.__cacheIndex = firstInactiveIndex;
  28118. interpolants[ firstInactiveIndex ] = interpolant;
  28119. lastActiveInterpolant.__cacheIndex = prevIndex;
  28120. interpolants[ prevIndex ] = lastActiveInterpolant;
  28121. }
  28122. // return an action for a clip optionally using a custom root target
  28123. // object (this method allocates a lot of dynamic memory in case a
  28124. // previously unknown clip/root combination is specified)
  28125. clipAction( clip, optionalRoot, blendMode ) {
  28126. const root = optionalRoot || this._root,
  28127. rootUuid = root.uuid;
  28128. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28129. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28130. const actionsForClip = this._actionsByClip[ clipUuid ];
  28131. let prototypeAction = null;
  28132. if ( blendMode === undefined ) {
  28133. if ( clipObject !== null ) {
  28134. blendMode = clipObject.blendMode;
  28135. } else {
  28136. blendMode = NormalAnimationBlendMode;
  28137. }
  28138. }
  28139. if ( actionsForClip !== undefined ) {
  28140. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28141. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28142. return existingAction;
  28143. }
  28144. // we know the clip, so we don't have to parse all
  28145. // the bindings again but can just copy
  28146. prototypeAction = actionsForClip.knownActions[ 0 ];
  28147. // also, take the clip from the prototype action
  28148. if ( clipObject === null )
  28149. clipObject = prototypeAction._clip;
  28150. }
  28151. // clip must be known when specified via string
  28152. if ( clipObject === null ) return null;
  28153. // allocate all resources required to run it
  28154. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28155. this._bindAction( newAction, prototypeAction );
  28156. // and make the action known to the memory manager
  28157. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28158. return newAction;
  28159. }
  28160. // get an existing action
  28161. existingAction( clip, optionalRoot ) {
  28162. const root = optionalRoot || this._root,
  28163. rootUuid = root.uuid,
  28164. clipObject = typeof clip === 'string' ?
  28165. AnimationClip.findByName( root, clip ) : clip,
  28166. clipUuid = clipObject ? clipObject.uuid : clip,
  28167. actionsForClip = this._actionsByClip[ clipUuid ];
  28168. if ( actionsForClip !== undefined ) {
  28169. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28170. }
  28171. return null;
  28172. }
  28173. // deactivates all previously scheduled actions
  28174. stopAllAction() {
  28175. const actions = this._actions,
  28176. nActions = this._nActiveActions;
  28177. for ( let i = nActions - 1; i >= 0; -- i ) {
  28178. actions[ i ].stop();
  28179. }
  28180. return this;
  28181. }
  28182. // advance the time and update apply the animation
  28183. update( deltaTime ) {
  28184. deltaTime *= this.timeScale;
  28185. const actions = this._actions,
  28186. nActions = this._nActiveActions,
  28187. time = this.time += deltaTime,
  28188. timeDirection = Math.sign( deltaTime ),
  28189. accuIndex = this._accuIndex ^= 1;
  28190. // run active actions
  28191. for ( let i = 0; i !== nActions; ++ i ) {
  28192. const action = actions[ i ];
  28193. action._update( time, deltaTime, timeDirection, accuIndex );
  28194. }
  28195. // update scene graph
  28196. const bindings = this._bindings,
  28197. nBindings = this._nActiveBindings;
  28198. for ( let i = 0; i !== nBindings; ++ i ) {
  28199. bindings[ i ].apply( accuIndex );
  28200. }
  28201. return this;
  28202. }
  28203. // Allows you to seek to a specific time in an animation.
  28204. setTime( timeInSeconds ) {
  28205. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28206. for ( let i = 0; i < this._actions.length; i ++ ) {
  28207. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28208. }
  28209. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28210. }
  28211. // return this mixer's root target object
  28212. getRoot() {
  28213. return this._root;
  28214. }
  28215. // free all resources specific to a particular clip
  28216. uncacheClip( clip ) {
  28217. const actions = this._actions,
  28218. clipUuid = clip.uuid,
  28219. actionsByClip = this._actionsByClip,
  28220. actionsForClip = actionsByClip[ clipUuid ];
  28221. if ( actionsForClip !== undefined ) {
  28222. // note: just calling _removeInactiveAction would mess up the
  28223. // iteration state and also require updating the state we can
  28224. // just throw away
  28225. const actionsToRemove = actionsForClip.knownActions;
  28226. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28227. const action = actionsToRemove[ i ];
  28228. this._deactivateAction( action );
  28229. const cacheIndex = action._cacheIndex,
  28230. lastInactiveAction = actions[ actions.length - 1 ];
  28231. action._cacheIndex = null;
  28232. action._byClipCacheIndex = null;
  28233. lastInactiveAction._cacheIndex = cacheIndex;
  28234. actions[ cacheIndex ] = lastInactiveAction;
  28235. actions.pop();
  28236. this._removeInactiveBindingsForAction( action );
  28237. }
  28238. delete actionsByClip[ clipUuid ];
  28239. }
  28240. }
  28241. // free all resources specific to a particular root target object
  28242. uncacheRoot( root ) {
  28243. const rootUuid = root.uuid,
  28244. actionsByClip = this._actionsByClip;
  28245. for ( const clipUuid in actionsByClip ) {
  28246. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28247. action = actionByRoot[ rootUuid ];
  28248. if ( action !== undefined ) {
  28249. this._deactivateAction( action );
  28250. this._removeInactiveAction( action );
  28251. }
  28252. }
  28253. const bindingsByRoot = this._bindingsByRootAndName,
  28254. bindingByName = bindingsByRoot[ rootUuid ];
  28255. if ( bindingByName !== undefined ) {
  28256. for ( const trackName in bindingByName ) {
  28257. const binding = bindingByName[ trackName ];
  28258. binding.restoreOriginalState();
  28259. this._removeInactiveBinding( binding );
  28260. }
  28261. }
  28262. }
  28263. // remove a targeted clip from the cache
  28264. uncacheAction( clip, optionalRoot ) {
  28265. const action = this.existingAction( clip, optionalRoot );
  28266. if ( action !== null ) {
  28267. this._deactivateAction( action );
  28268. this._removeInactiveAction( action );
  28269. }
  28270. }
  28271. }
  28272. class Uniform {
  28273. constructor( value ) {
  28274. this.value = value;
  28275. }
  28276. clone() {
  28277. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28278. }
  28279. }
  28280. let id = 0;
  28281. class UniformsGroup extends EventDispatcher {
  28282. constructor() {
  28283. super();
  28284. this.isUniformsGroup = true;
  28285. Object.defineProperty( this, 'id', { value: id ++ } );
  28286. this.name = '';
  28287. this.usage = StaticDrawUsage;
  28288. this.uniforms = [];
  28289. }
  28290. add( uniform ) {
  28291. this.uniforms.push( uniform );
  28292. return this;
  28293. }
  28294. remove( uniform ) {
  28295. const index = this.uniforms.indexOf( uniform );
  28296. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28297. return this;
  28298. }
  28299. setName( name ) {
  28300. this.name = name;
  28301. return this;
  28302. }
  28303. setUsage( value ) {
  28304. this.usage = value;
  28305. return this;
  28306. }
  28307. dispose() {
  28308. this.dispatchEvent( { type: 'dispose' } );
  28309. return this;
  28310. }
  28311. copy( source ) {
  28312. this.name = source.name;
  28313. this.usage = source.usage;
  28314. const uniformsSource = source.uniforms;
  28315. this.uniforms.length = 0;
  28316. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28317. this.uniforms.push( uniformsSource[ i ].clone() );
  28318. }
  28319. return this;
  28320. }
  28321. clone() {
  28322. return new this.constructor().copy( this );
  28323. }
  28324. }
  28325. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28326. constructor( array, stride, meshPerAttribute = 1 ) {
  28327. super( array, stride );
  28328. this.isInstancedInterleavedBuffer = true;
  28329. this.meshPerAttribute = meshPerAttribute;
  28330. }
  28331. copy( source ) {
  28332. super.copy( source );
  28333. this.meshPerAttribute = source.meshPerAttribute;
  28334. return this;
  28335. }
  28336. clone( data ) {
  28337. const ib = super.clone( data );
  28338. ib.meshPerAttribute = this.meshPerAttribute;
  28339. return ib;
  28340. }
  28341. toJSON( data ) {
  28342. const json = super.toJSON( data );
  28343. json.isInstancedInterleavedBuffer = true;
  28344. json.meshPerAttribute = this.meshPerAttribute;
  28345. return json;
  28346. }
  28347. }
  28348. class GLBufferAttribute {
  28349. constructor( buffer, type, itemSize, elementSize, count ) {
  28350. this.isGLBufferAttribute = true;
  28351. this.buffer = buffer;
  28352. this.type = type;
  28353. this.itemSize = itemSize;
  28354. this.elementSize = elementSize;
  28355. this.count = count;
  28356. this.version = 0;
  28357. }
  28358. set needsUpdate( value ) {
  28359. if ( value === true ) this.version ++;
  28360. }
  28361. setBuffer( buffer ) {
  28362. this.buffer = buffer;
  28363. return this;
  28364. }
  28365. setType( type, elementSize ) {
  28366. this.type = type;
  28367. this.elementSize = elementSize;
  28368. return this;
  28369. }
  28370. setItemSize( itemSize ) {
  28371. this.itemSize = itemSize;
  28372. return this;
  28373. }
  28374. setCount( count ) {
  28375. this.count = count;
  28376. return this;
  28377. }
  28378. }
  28379. class Raycaster {
  28380. constructor( origin, direction, near = 0, far = Infinity ) {
  28381. this.ray = new Ray( origin, direction );
  28382. // direction is assumed to be normalized (for accurate distance calculations)
  28383. this.near = near;
  28384. this.far = far;
  28385. this.camera = null;
  28386. this.layers = new Layers();
  28387. this.params = {
  28388. Mesh: {},
  28389. Line: { threshold: 1 },
  28390. LOD: {},
  28391. Points: { threshold: 1 },
  28392. Sprite: {}
  28393. };
  28394. }
  28395. set( origin, direction ) {
  28396. // direction is assumed to be normalized (for accurate distance calculations)
  28397. this.ray.set( origin, direction );
  28398. }
  28399. setFromCamera( coords, camera ) {
  28400. if ( camera.isPerspectiveCamera ) {
  28401. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28402. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28403. this.camera = camera;
  28404. } else if ( camera.isOrthographicCamera ) {
  28405. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28406. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28407. this.camera = camera;
  28408. } else {
  28409. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28410. }
  28411. }
  28412. intersectObject( object, recursive = true, intersects = [] ) {
  28413. intersectObject( object, this, intersects, recursive );
  28414. intersects.sort( ascSort );
  28415. return intersects;
  28416. }
  28417. intersectObjects( objects, recursive = true, intersects = [] ) {
  28418. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28419. intersectObject( objects[ i ], this, intersects, recursive );
  28420. }
  28421. intersects.sort( ascSort );
  28422. return intersects;
  28423. }
  28424. }
  28425. function ascSort( a, b ) {
  28426. return a.distance - b.distance;
  28427. }
  28428. function intersectObject( object, raycaster, intersects, recursive ) {
  28429. if ( object.layers.test( raycaster.layers ) ) {
  28430. object.raycast( raycaster, intersects );
  28431. }
  28432. if ( recursive === true ) {
  28433. const children = object.children;
  28434. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28435. intersectObject( children[ i ], raycaster, intersects, true );
  28436. }
  28437. }
  28438. }
  28439. /**
  28440. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28441. *
  28442. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28443. * The azimuthal angle (theta) is measured from the positive z-axis.
  28444. */
  28445. class Spherical {
  28446. constructor( radius = 1, phi = 0, theta = 0 ) {
  28447. this.radius = radius;
  28448. this.phi = phi; // polar angle
  28449. this.theta = theta; // azimuthal angle
  28450. return this;
  28451. }
  28452. set( radius, phi, theta ) {
  28453. this.radius = radius;
  28454. this.phi = phi;
  28455. this.theta = theta;
  28456. return this;
  28457. }
  28458. copy( other ) {
  28459. this.radius = other.radius;
  28460. this.phi = other.phi;
  28461. this.theta = other.theta;
  28462. return this;
  28463. }
  28464. // restrict phi to be between EPS and PI-EPS
  28465. makeSafe() {
  28466. const EPS = 0.000001;
  28467. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28468. return this;
  28469. }
  28470. setFromVector3( v ) {
  28471. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28472. }
  28473. setFromCartesianCoords( x, y, z ) {
  28474. this.radius = Math.sqrt( x * x + y * y + z * z );
  28475. if ( this.radius === 0 ) {
  28476. this.theta = 0;
  28477. this.phi = 0;
  28478. } else {
  28479. this.theta = Math.atan2( x, z );
  28480. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28481. }
  28482. return this;
  28483. }
  28484. clone() {
  28485. return new this.constructor().copy( this );
  28486. }
  28487. }
  28488. /**
  28489. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28490. */
  28491. class Cylindrical {
  28492. constructor( radius = 1, theta = 0, y = 0 ) {
  28493. this.radius = radius; // distance from the origin to a point in the x-z plane
  28494. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28495. this.y = y; // height above the x-z plane
  28496. return this;
  28497. }
  28498. set( radius, theta, y ) {
  28499. this.radius = radius;
  28500. this.theta = theta;
  28501. this.y = y;
  28502. return this;
  28503. }
  28504. copy( other ) {
  28505. this.radius = other.radius;
  28506. this.theta = other.theta;
  28507. this.y = other.y;
  28508. return this;
  28509. }
  28510. setFromVector3( v ) {
  28511. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28512. }
  28513. setFromCartesianCoords( x, y, z ) {
  28514. this.radius = Math.sqrt( x * x + z * z );
  28515. this.theta = Math.atan2( x, z );
  28516. this.y = y;
  28517. return this;
  28518. }
  28519. clone() {
  28520. return new this.constructor().copy( this );
  28521. }
  28522. }
  28523. const _vector$4 = /*@__PURE__*/ new Vector2();
  28524. class Box2 {
  28525. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28526. this.isBox2 = true;
  28527. this.min = min;
  28528. this.max = max;
  28529. }
  28530. set( min, max ) {
  28531. this.min.copy( min );
  28532. this.max.copy( max );
  28533. return this;
  28534. }
  28535. setFromPoints( points ) {
  28536. this.makeEmpty();
  28537. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28538. this.expandByPoint( points[ i ] );
  28539. }
  28540. return this;
  28541. }
  28542. setFromCenterAndSize( center, size ) {
  28543. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28544. this.min.copy( center ).sub( halfSize );
  28545. this.max.copy( center ).add( halfSize );
  28546. return this;
  28547. }
  28548. clone() {
  28549. return new this.constructor().copy( this );
  28550. }
  28551. copy( box ) {
  28552. this.min.copy( box.min );
  28553. this.max.copy( box.max );
  28554. return this;
  28555. }
  28556. makeEmpty() {
  28557. this.min.x = this.min.y = + Infinity;
  28558. this.max.x = this.max.y = - Infinity;
  28559. return this;
  28560. }
  28561. isEmpty() {
  28562. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28563. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28564. }
  28565. getCenter( target ) {
  28566. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28567. }
  28568. getSize( target ) {
  28569. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28570. }
  28571. expandByPoint( point ) {
  28572. this.min.min( point );
  28573. this.max.max( point );
  28574. return this;
  28575. }
  28576. expandByVector( vector ) {
  28577. this.min.sub( vector );
  28578. this.max.add( vector );
  28579. return this;
  28580. }
  28581. expandByScalar( scalar ) {
  28582. this.min.addScalar( - scalar );
  28583. this.max.addScalar( scalar );
  28584. return this;
  28585. }
  28586. containsPoint( point ) {
  28587. return point.x < this.min.x || point.x > this.max.x ||
  28588. point.y < this.min.y || point.y > this.max.y ? false : true;
  28589. }
  28590. containsBox( box ) {
  28591. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28592. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28593. }
  28594. getParameter( point, target ) {
  28595. // This can potentially have a divide by zero if the box
  28596. // has a size dimension of 0.
  28597. return target.set(
  28598. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28599. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28600. );
  28601. }
  28602. intersectsBox( box ) {
  28603. // using 4 splitting planes to rule out intersections
  28604. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28605. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28606. }
  28607. clampPoint( point, target ) {
  28608. return target.copy( point ).clamp( this.min, this.max );
  28609. }
  28610. distanceToPoint( point ) {
  28611. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28612. return clampedPoint.sub( point ).length();
  28613. }
  28614. intersect( box ) {
  28615. this.min.max( box.min );
  28616. this.max.min( box.max );
  28617. return this;
  28618. }
  28619. union( box ) {
  28620. this.min.min( box.min );
  28621. this.max.max( box.max );
  28622. return this;
  28623. }
  28624. translate( offset ) {
  28625. this.min.add( offset );
  28626. this.max.add( offset );
  28627. return this;
  28628. }
  28629. equals( box ) {
  28630. return box.min.equals( this.min ) && box.max.equals( this.max );
  28631. }
  28632. }
  28633. const _startP = /*@__PURE__*/ new Vector3();
  28634. const _startEnd = /*@__PURE__*/ new Vector3();
  28635. class Line3 {
  28636. constructor( start = new Vector3(), end = new Vector3() ) {
  28637. this.start = start;
  28638. this.end = end;
  28639. }
  28640. set( start, end ) {
  28641. this.start.copy( start );
  28642. this.end.copy( end );
  28643. return this;
  28644. }
  28645. copy( line ) {
  28646. this.start.copy( line.start );
  28647. this.end.copy( line.end );
  28648. return this;
  28649. }
  28650. getCenter( target ) {
  28651. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28652. }
  28653. delta( target ) {
  28654. return target.subVectors( this.end, this.start );
  28655. }
  28656. distanceSq() {
  28657. return this.start.distanceToSquared( this.end );
  28658. }
  28659. distance() {
  28660. return this.start.distanceTo( this.end );
  28661. }
  28662. at( t, target ) {
  28663. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28664. }
  28665. closestPointToPointParameter( point, clampToLine ) {
  28666. _startP.subVectors( point, this.start );
  28667. _startEnd.subVectors( this.end, this.start );
  28668. const startEnd2 = _startEnd.dot( _startEnd );
  28669. const startEnd_startP = _startEnd.dot( _startP );
  28670. let t = startEnd_startP / startEnd2;
  28671. if ( clampToLine ) {
  28672. t = clamp( t, 0, 1 );
  28673. }
  28674. return t;
  28675. }
  28676. closestPointToPoint( point, clampToLine, target ) {
  28677. const t = this.closestPointToPointParameter( point, clampToLine );
  28678. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28679. }
  28680. applyMatrix4( matrix ) {
  28681. this.start.applyMatrix4( matrix );
  28682. this.end.applyMatrix4( matrix );
  28683. return this;
  28684. }
  28685. equals( line ) {
  28686. return line.start.equals( this.start ) && line.end.equals( this.end );
  28687. }
  28688. clone() {
  28689. return new this.constructor().copy( this );
  28690. }
  28691. }
  28692. const _vector$3 = /*@__PURE__*/ new Vector3();
  28693. class SpotLightHelper extends Object3D {
  28694. constructor( light, color ) {
  28695. super();
  28696. this.light = light;
  28697. this.light.updateMatrixWorld();
  28698. this.matrix = light.matrixWorld;
  28699. this.matrixAutoUpdate = false;
  28700. this.color = color;
  28701. const geometry = new BufferGeometry();
  28702. const positions = [
  28703. 0, 0, 0, 0, 0, 1,
  28704. 0, 0, 0, 1, 0, 1,
  28705. 0, 0, 0, - 1, 0, 1,
  28706. 0, 0, 0, 0, 1, 1,
  28707. 0, 0, 0, 0, - 1, 1
  28708. ];
  28709. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28710. const p1 = ( i / l ) * Math.PI * 2;
  28711. const p2 = ( j / l ) * Math.PI * 2;
  28712. positions.push(
  28713. Math.cos( p1 ), Math.sin( p1 ), 1,
  28714. Math.cos( p2 ), Math.sin( p2 ), 1
  28715. );
  28716. }
  28717. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28718. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28719. this.cone = new LineSegments( geometry, material );
  28720. this.add( this.cone );
  28721. this.update();
  28722. }
  28723. dispose() {
  28724. this.cone.geometry.dispose();
  28725. this.cone.material.dispose();
  28726. }
  28727. update() {
  28728. this.light.updateMatrixWorld();
  28729. const coneLength = this.light.distance ? this.light.distance : 1000;
  28730. const coneWidth = coneLength * Math.tan( this.light.angle );
  28731. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28732. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28733. this.cone.lookAt( _vector$3 );
  28734. if ( this.color !== undefined ) {
  28735. this.cone.material.color.set( this.color );
  28736. } else {
  28737. this.cone.material.color.copy( this.light.color );
  28738. }
  28739. }
  28740. }
  28741. const _vector$2 = /*@__PURE__*/ new Vector3();
  28742. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28743. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28744. class SkeletonHelper extends LineSegments {
  28745. constructor( object ) {
  28746. const bones = getBoneList( object );
  28747. const geometry = new BufferGeometry();
  28748. const vertices = [];
  28749. const colors = [];
  28750. const color1 = new Color( 0, 0, 1 );
  28751. const color2 = new Color( 0, 1, 0 );
  28752. for ( let i = 0; i < bones.length; i ++ ) {
  28753. const bone = bones[ i ];
  28754. if ( bone.parent && bone.parent.isBone ) {
  28755. vertices.push( 0, 0, 0 );
  28756. vertices.push( 0, 0, 0 );
  28757. colors.push( color1.r, color1.g, color1.b );
  28758. colors.push( color2.r, color2.g, color2.b );
  28759. }
  28760. }
  28761. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28762. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28763. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28764. super( geometry, material );
  28765. this.isSkeletonHelper = true;
  28766. this.type = 'SkeletonHelper';
  28767. this.root = object;
  28768. this.bones = bones;
  28769. this.matrix = object.matrixWorld;
  28770. this.matrixAutoUpdate = false;
  28771. }
  28772. updateMatrixWorld( force ) {
  28773. const bones = this.bones;
  28774. const geometry = this.geometry;
  28775. const position = geometry.getAttribute( 'position' );
  28776. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28777. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28778. const bone = bones[ i ];
  28779. if ( bone.parent && bone.parent.isBone ) {
  28780. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28781. _vector$2.setFromMatrixPosition( _boneMatrix );
  28782. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28783. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28784. _vector$2.setFromMatrixPosition( _boneMatrix );
  28785. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28786. j += 2;
  28787. }
  28788. }
  28789. geometry.getAttribute( 'position' ).needsUpdate = true;
  28790. super.updateMatrixWorld( force );
  28791. }
  28792. }
  28793. function getBoneList( object ) {
  28794. const boneList = [];
  28795. if ( object.isBone === true ) {
  28796. boneList.push( object );
  28797. }
  28798. for ( let i = 0; i < object.children.length; i ++ ) {
  28799. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28800. }
  28801. return boneList;
  28802. }
  28803. class PointLightHelper extends Mesh {
  28804. constructor( light, sphereSize, color ) {
  28805. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28806. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28807. super( geometry, material );
  28808. this.light = light;
  28809. this.light.updateMatrixWorld();
  28810. this.color = color;
  28811. this.type = 'PointLightHelper';
  28812. this.matrix = this.light.matrixWorld;
  28813. this.matrixAutoUpdate = false;
  28814. this.update();
  28815. /*
  28816. // TODO: delete this comment?
  28817. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28818. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28819. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28820. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28821. const d = light.distance;
  28822. if ( d === 0.0 ) {
  28823. this.lightDistance.visible = false;
  28824. } else {
  28825. this.lightDistance.scale.set( d, d, d );
  28826. }
  28827. this.add( this.lightDistance );
  28828. */
  28829. }
  28830. dispose() {
  28831. this.geometry.dispose();
  28832. this.material.dispose();
  28833. }
  28834. update() {
  28835. if ( this.color !== undefined ) {
  28836. this.material.color.set( this.color );
  28837. } else {
  28838. this.material.color.copy( this.light.color );
  28839. }
  28840. /*
  28841. const d = this.light.distance;
  28842. if ( d === 0.0 ) {
  28843. this.lightDistance.visible = false;
  28844. } else {
  28845. this.lightDistance.visible = true;
  28846. this.lightDistance.scale.set( d, d, d );
  28847. }
  28848. */
  28849. }
  28850. }
  28851. const _vector$1 = /*@__PURE__*/ new Vector3();
  28852. const _color1 = /*@__PURE__*/ new Color();
  28853. const _color2 = /*@__PURE__*/ new Color();
  28854. class HemisphereLightHelper extends Object3D {
  28855. constructor( light, size, color ) {
  28856. super();
  28857. this.light = light;
  28858. this.light.updateMatrixWorld();
  28859. this.matrix = light.matrixWorld;
  28860. this.matrixAutoUpdate = false;
  28861. this.color = color;
  28862. const geometry = new OctahedronGeometry( size );
  28863. geometry.rotateY( Math.PI * 0.5 );
  28864. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28865. if ( this.color === undefined ) this.material.vertexColors = true;
  28866. const position = geometry.getAttribute( 'position' );
  28867. const colors = new Float32Array( position.count * 3 );
  28868. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28869. this.add( new Mesh( geometry, this.material ) );
  28870. this.update();
  28871. }
  28872. dispose() {
  28873. this.children[ 0 ].geometry.dispose();
  28874. this.children[ 0 ].material.dispose();
  28875. }
  28876. update() {
  28877. const mesh = this.children[ 0 ];
  28878. if ( this.color !== undefined ) {
  28879. this.material.color.set( this.color );
  28880. } else {
  28881. const colors = mesh.geometry.getAttribute( 'color' );
  28882. _color1.copy( this.light.color );
  28883. _color2.copy( this.light.groundColor );
  28884. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28885. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28886. colors.setXYZ( i, color.r, color.g, color.b );
  28887. }
  28888. colors.needsUpdate = true;
  28889. }
  28890. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28891. }
  28892. }
  28893. class GridHelper extends LineSegments {
  28894. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28895. color1 = new Color( color1 );
  28896. color2 = new Color( color2 );
  28897. const center = divisions / 2;
  28898. const step = size / divisions;
  28899. const halfSize = size / 2;
  28900. const vertices = [], colors = [];
  28901. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28902. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28903. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28904. const color = i === center ? color1 : color2;
  28905. color.toArray( colors, j ); j += 3;
  28906. color.toArray( colors, j ); j += 3;
  28907. color.toArray( colors, j ); j += 3;
  28908. color.toArray( colors, j ); j += 3;
  28909. }
  28910. const geometry = new BufferGeometry();
  28911. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28912. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28913. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28914. super( geometry, material );
  28915. this.type = 'GridHelper';
  28916. }
  28917. }
  28918. class PolarGridHelper extends LineSegments {
  28919. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28920. color1 = new Color( color1 );
  28921. color2 = new Color( color2 );
  28922. const vertices = [];
  28923. const colors = [];
  28924. // create the sectors
  28925. if ( sectors > 1 ) {
  28926. for ( let i = 0; i < sectors; i ++ ) {
  28927. const v = ( i / sectors ) * ( Math.PI * 2 );
  28928. const x = Math.sin( v ) * radius;
  28929. const z = Math.cos( v ) * radius;
  28930. vertices.push( 0, 0, 0 );
  28931. vertices.push( x, 0, z );
  28932. const color = ( i & 1 ) ? color1 : color2;
  28933. colors.push( color.r, color.g, color.b );
  28934. colors.push( color.r, color.g, color.b );
  28935. }
  28936. }
  28937. // create the rings
  28938. for ( let i = 0; i < rings; i ++ ) {
  28939. const color = ( i & 1 ) ? color1 : color2;
  28940. const r = radius - ( radius / rings * i );
  28941. for ( let j = 0; j < divisions; j ++ ) {
  28942. // first vertex
  28943. let v = ( j / divisions ) * ( Math.PI * 2 );
  28944. let x = Math.sin( v ) * r;
  28945. let z = Math.cos( v ) * r;
  28946. vertices.push( x, 0, z );
  28947. colors.push( color.r, color.g, color.b );
  28948. // second vertex
  28949. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28950. x = Math.sin( v ) * r;
  28951. z = Math.cos( v ) * r;
  28952. vertices.push( x, 0, z );
  28953. colors.push( color.r, color.g, color.b );
  28954. }
  28955. }
  28956. const geometry = new BufferGeometry();
  28957. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28958. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28959. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28960. super( geometry, material );
  28961. this.type = 'PolarGridHelper';
  28962. }
  28963. }
  28964. const _v1 = /*@__PURE__*/ new Vector3();
  28965. const _v2 = /*@__PURE__*/ new Vector3();
  28966. const _v3 = /*@__PURE__*/ new Vector3();
  28967. class DirectionalLightHelper extends Object3D {
  28968. constructor( light, size, color ) {
  28969. super();
  28970. this.light = light;
  28971. this.light.updateMatrixWorld();
  28972. this.matrix = light.matrixWorld;
  28973. this.matrixAutoUpdate = false;
  28974. this.color = color;
  28975. if ( size === undefined ) size = 1;
  28976. let geometry = new BufferGeometry();
  28977. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28978. - size, size, 0,
  28979. size, size, 0,
  28980. size, - size, 0,
  28981. - size, - size, 0,
  28982. - size, size, 0
  28983. ], 3 ) );
  28984. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28985. this.lightPlane = new Line( geometry, material );
  28986. this.add( this.lightPlane );
  28987. geometry = new BufferGeometry();
  28988. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28989. this.targetLine = new Line( geometry, material );
  28990. this.add( this.targetLine );
  28991. this.update();
  28992. }
  28993. dispose() {
  28994. this.lightPlane.geometry.dispose();
  28995. this.lightPlane.material.dispose();
  28996. this.targetLine.geometry.dispose();
  28997. this.targetLine.material.dispose();
  28998. }
  28999. update() {
  29000. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29001. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29002. _v3.subVectors( _v2, _v1 );
  29003. this.lightPlane.lookAt( _v2 );
  29004. if ( this.color !== undefined ) {
  29005. this.lightPlane.material.color.set( this.color );
  29006. this.targetLine.material.color.set( this.color );
  29007. } else {
  29008. this.lightPlane.material.color.copy( this.light.color );
  29009. this.targetLine.material.color.copy( this.light.color );
  29010. }
  29011. this.targetLine.lookAt( _v2 );
  29012. this.targetLine.scale.z = _v3.length();
  29013. }
  29014. }
  29015. const _vector = /*@__PURE__*/ new Vector3();
  29016. const _camera = /*@__PURE__*/ new Camera();
  29017. /**
  29018. * - shows frustum, line of sight and up of the camera
  29019. * - suitable for fast updates
  29020. * - based on frustum visualization in lightgl.js shadowmap example
  29021. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29022. */
  29023. class CameraHelper extends LineSegments {
  29024. constructor( camera ) {
  29025. const geometry = new BufferGeometry();
  29026. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29027. const vertices = [];
  29028. const colors = [];
  29029. const pointMap = {};
  29030. // near
  29031. addLine( 'n1', 'n2' );
  29032. addLine( 'n2', 'n4' );
  29033. addLine( 'n4', 'n3' );
  29034. addLine( 'n3', 'n1' );
  29035. // far
  29036. addLine( 'f1', 'f2' );
  29037. addLine( 'f2', 'f4' );
  29038. addLine( 'f4', 'f3' );
  29039. addLine( 'f3', 'f1' );
  29040. // sides
  29041. addLine( 'n1', 'f1' );
  29042. addLine( 'n2', 'f2' );
  29043. addLine( 'n3', 'f3' );
  29044. addLine( 'n4', 'f4' );
  29045. // cone
  29046. addLine( 'p', 'n1' );
  29047. addLine( 'p', 'n2' );
  29048. addLine( 'p', 'n3' );
  29049. addLine( 'p', 'n4' );
  29050. // up
  29051. addLine( 'u1', 'u2' );
  29052. addLine( 'u2', 'u3' );
  29053. addLine( 'u3', 'u1' );
  29054. // target
  29055. addLine( 'c', 't' );
  29056. addLine( 'p', 'c' );
  29057. // cross
  29058. addLine( 'cn1', 'cn2' );
  29059. addLine( 'cn3', 'cn4' );
  29060. addLine( 'cf1', 'cf2' );
  29061. addLine( 'cf3', 'cf4' );
  29062. function addLine( a, b ) {
  29063. addPoint( a );
  29064. addPoint( b );
  29065. }
  29066. function addPoint( id ) {
  29067. vertices.push( 0, 0, 0 );
  29068. colors.push( 0, 0, 0 );
  29069. if ( pointMap[ id ] === undefined ) {
  29070. pointMap[ id ] = [];
  29071. }
  29072. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29073. }
  29074. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29075. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29076. super( geometry, material );
  29077. this.type = 'CameraHelper';
  29078. this.camera = camera;
  29079. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29080. this.matrix = camera.matrixWorld;
  29081. this.matrixAutoUpdate = false;
  29082. this.pointMap = pointMap;
  29083. this.update();
  29084. // colors
  29085. const colorFrustum = new Color( 0xffaa00 );
  29086. const colorCone = new Color( 0xff0000 );
  29087. const colorUp = new Color( 0x00aaff );
  29088. const colorTarget = new Color( 0xffffff );
  29089. const colorCross = new Color( 0x333333 );
  29090. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29091. }
  29092. setColors( frustum, cone, up, target, cross ) {
  29093. const geometry = this.geometry;
  29094. const colorAttribute = geometry.getAttribute( 'color' );
  29095. // near
  29096. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29097. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29098. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29099. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29100. // far
  29101. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29102. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29103. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29104. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29105. // sides
  29106. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29107. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29108. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29109. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29110. // cone
  29111. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29112. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29113. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29114. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29115. // up
  29116. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29117. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29118. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29119. // target
  29120. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29121. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29122. // cross
  29123. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29124. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29125. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29126. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29127. colorAttribute.needsUpdate = true;
  29128. }
  29129. update() {
  29130. const geometry = this.geometry;
  29131. const pointMap = this.pointMap;
  29132. const w = 1, h = 1;
  29133. // we need just camera projection matrix inverse
  29134. // world matrix must be identity
  29135. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29136. // center / target
  29137. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29138. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29139. // near
  29140. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29141. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29142. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29143. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29144. // far
  29145. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29146. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29147. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29148. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29149. // up
  29150. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29151. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29152. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29153. // cross
  29154. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29155. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29156. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29157. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29158. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29159. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29160. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29161. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29162. geometry.getAttribute( 'position' ).needsUpdate = true;
  29163. }
  29164. dispose() {
  29165. this.geometry.dispose();
  29166. this.material.dispose();
  29167. }
  29168. }
  29169. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29170. _vector.set( x, y, z ).unproject( camera );
  29171. const points = pointMap[ point ];
  29172. if ( points !== undefined ) {
  29173. const position = geometry.getAttribute( 'position' );
  29174. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29175. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29176. }
  29177. }
  29178. }
  29179. const _box = /*@__PURE__*/ new Box3();
  29180. class BoxHelper extends LineSegments {
  29181. constructor( object, color = 0xffff00 ) {
  29182. 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 ] );
  29183. const positions = new Float32Array( 8 * 3 );
  29184. const geometry = new BufferGeometry();
  29185. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29186. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29187. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29188. this.object = object;
  29189. this.type = 'BoxHelper';
  29190. this.matrixAutoUpdate = false;
  29191. this.update();
  29192. }
  29193. update( object ) {
  29194. if ( object !== undefined ) {
  29195. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29196. }
  29197. if ( this.object !== undefined ) {
  29198. _box.setFromObject( this.object );
  29199. }
  29200. if ( _box.isEmpty() ) return;
  29201. const min = _box.min;
  29202. const max = _box.max;
  29203. /*
  29204. 5____4
  29205. 1/___0/|
  29206. | 6__|_7
  29207. 2/___3/
  29208. 0: max.x, max.y, max.z
  29209. 1: min.x, max.y, max.z
  29210. 2: min.x, min.y, max.z
  29211. 3: max.x, min.y, max.z
  29212. 4: max.x, max.y, min.z
  29213. 5: min.x, max.y, min.z
  29214. 6: min.x, min.y, min.z
  29215. 7: max.x, min.y, min.z
  29216. */
  29217. const position = this.geometry.attributes.position;
  29218. const array = position.array;
  29219. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29220. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29221. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29222. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29223. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29224. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29225. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29226. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29227. position.needsUpdate = true;
  29228. this.geometry.computeBoundingSphere();
  29229. }
  29230. setFromObject( object ) {
  29231. this.object = object;
  29232. this.update();
  29233. return this;
  29234. }
  29235. copy( source, recursive ) {
  29236. super.copy( source, recursive );
  29237. this.object = source.object;
  29238. return this;
  29239. }
  29240. }
  29241. class Box3Helper extends LineSegments {
  29242. constructor( box, color = 0xffff00 ) {
  29243. 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 ] );
  29244. 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 ];
  29245. const geometry = new BufferGeometry();
  29246. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29247. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29248. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29249. this.box = box;
  29250. this.type = 'Box3Helper';
  29251. this.geometry.computeBoundingSphere();
  29252. }
  29253. updateMatrixWorld( force ) {
  29254. const box = this.box;
  29255. if ( box.isEmpty() ) return;
  29256. box.getCenter( this.position );
  29257. box.getSize( this.scale );
  29258. this.scale.multiplyScalar( 0.5 );
  29259. super.updateMatrixWorld( force );
  29260. }
  29261. }
  29262. class PlaneHelper extends Line {
  29263. constructor( plane, size = 1, hex = 0xffff00 ) {
  29264. const color = hex;
  29265. 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 ];
  29266. const geometry = new BufferGeometry();
  29267. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29268. geometry.computeBoundingSphere();
  29269. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29270. this.type = 'PlaneHelper';
  29271. this.plane = plane;
  29272. this.size = size;
  29273. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29274. const geometry2 = new BufferGeometry();
  29275. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29276. geometry2.computeBoundingSphere();
  29277. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29278. }
  29279. updateMatrixWorld( force ) {
  29280. this.position.set( 0, 0, 0 );
  29281. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29282. this.lookAt( this.plane.normal );
  29283. this.translateZ( - this.plane.constant );
  29284. super.updateMatrixWorld( force );
  29285. }
  29286. }
  29287. const _axis = /*@__PURE__*/ new Vector3();
  29288. let _lineGeometry, _coneGeometry;
  29289. class ArrowHelper extends Object3D {
  29290. // dir is assumed to be normalized
  29291. 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 ) {
  29292. super();
  29293. this.type = 'ArrowHelper';
  29294. if ( _lineGeometry === undefined ) {
  29295. _lineGeometry = new BufferGeometry();
  29296. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29297. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29298. _coneGeometry.translate( 0, - 0.5, 0 );
  29299. }
  29300. this.position.copy( origin );
  29301. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29302. this.line.matrixAutoUpdate = false;
  29303. this.add( this.line );
  29304. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29305. this.cone.matrixAutoUpdate = false;
  29306. this.add( this.cone );
  29307. this.setDirection( dir );
  29308. this.setLength( length, headLength, headWidth );
  29309. }
  29310. setDirection( dir ) {
  29311. // dir is assumed to be normalized
  29312. if ( dir.y > 0.99999 ) {
  29313. this.quaternion.set( 0, 0, 0, 1 );
  29314. } else if ( dir.y < - 0.99999 ) {
  29315. this.quaternion.set( 1, 0, 0, 0 );
  29316. } else {
  29317. _axis.set( dir.z, 0, - dir.x ).normalize();
  29318. const radians = Math.acos( dir.y );
  29319. this.quaternion.setFromAxisAngle( _axis, radians );
  29320. }
  29321. }
  29322. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29323. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29324. this.line.updateMatrix();
  29325. this.cone.scale.set( headWidth, headLength, headWidth );
  29326. this.cone.position.y = length;
  29327. this.cone.updateMatrix();
  29328. }
  29329. setColor( color ) {
  29330. this.line.material.color.set( color );
  29331. this.cone.material.color.set( color );
  29332. }
  29333. copy( source ) {
  29334. super.copy( source, false );
  29335. this.line.copy( source.line );
  29336. this.cone.copy( source.cone );
  29337. return this;
  29338. }
  29339. }
  29340. class AxesHelper extends LineSegments {
  29341. constructor( size = 1 ) {
  29342. const vertices = [
  29343. 0, 0, 0, size, 0, 0,
  29344. 0, 0, 0, 0, size, 0,
  29345. 0, 0, 0, 0, 0, size
  29346. ];
  29347. const colors = [
  29348. 1, 0, 0, 1, 0.6, 0,
  29349. 0, 1, 0, 0.6, 1, 0,
  29350. 0, 0, 1, 0, 0.6, 1
  29351. ];
  29352. const geometry = new BufferGeometry();
  29353. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29354. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29355. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29356. super( geometry, material );
  29357. this.type = 'AxesHelper';
  29358. }
  29359. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29360. const color = new Color();
  29361. const array = this.geometry.attributes.color.array;
  29362. color.set( xAxisColor );
  29363. color.toArray( array, 0 );
  29364. color.toArray( array, 3 );
  29365. color.set( yAxisColor );
  29366. color.toArray( array, 6 );
  29367. color.toArray( array, 9 );
  29368. color.set( zAxisColor );
  29369. color.toArray( array, 12 );
  29370. color.toArray( array, 15 );
  29371. this.geometry.attributes.color.needsUpdate = true;
  29372. return this;
  29373. }
  29374. dispose() {
  29375. this.geometry.dispose();
  29376. this.material.dispose();
  29377. }
  29378. }
  29379. class ShapePath {
  29380. constructor() {
  29381. this.type = 'ShapePath';
  29382. this.color = new Color();
  29383. this.subPaths = [];
  29384. this.currentPath = null;
  29385. }
  29386. moveTo( x, y ) {
  29387. this.currentPath = new Path();
  29388. this.subPaths.push( this.currentPath );
  29389. this.currentPath.moveTo( x, y );
  29390. return this;
  29391. }
  29392. lineTo( x, y ) {
  29393. this.currentPath.lineTo( x, y );
  29394. return this;
  29395. }
  29396. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29397. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29398. return this;
  29399. }
  29400. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29401. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29402. return this;
  29403. }
  29404. splineThru( pts ) {
  29405. this.currentPath.splineThru( pts );
  29406. return this;
  29407. }
  29408. toShapes( isCCW, noHoles ) {
  29409. function toShapesNoHoles( inSubpaths ) {
  29410. const shapes = [];
  29411. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29412. const tmpPath = inSubpaths[ i ];
  29413. const tmpShape = new Shape();
  29414. tmpShape.curves = tmpPath.curves;
  29415. shapes.push( tmpShape );
  29416. }
  29417. return shapes;
  29418. }
  29419. function isPointInsidePolygon( inPt, inPolygon ) {
  29420. const polyLen = inPolygon.length;
  29421. // inPt on polygon contour => immediate success or
  29422. // toggling of inside/outside at every single! intersection point of an edge
  29423. // with the horizontal line through inPt, left of inPt
  29424. // not counting lowerY endpoints of edges and whole edges on that line
  29425. let inside = false;
  29426. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29427. let edgeLowPt = inPolygon[ p ];
  29428. let edgeHighPt = inPolygon[ q ];
  29429. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29430. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29431. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29432. // not parallel
  29433. if ( edgeDy < 0 ) {
  29434. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29435. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29436. }
  29437. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29438. if ( inPt.y === edgeLowPt.y ) {
  29439. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29440. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29441. } else {
  29442. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29443. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29444. if ( perpEdge < 0 ) continue;
  29445. inside = ! inside; // true intersection left of inPt
  29446. }
  29447. } else {
  29448. // parallel or collinear
  29449. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29450. // edge lies on the same horizontal line as inPt
  29451. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29452. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29453. // continue;
  29454. }
  29455. }
  29456. return inside;
  29457. }
  29458. const isClockWise = ShapeUtils.isClockWise;
  29459. const subPaths = this.subPaths;
  29460. if ( subPaths.length === 0 ) return [];
  29461. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  29462. let solid, tmpPath, tmpShape;
  29463. const shapes = [];
  29464. if ( subPaths.length === 1 ) {
  29465. tmpPath = subPaths[ 0 ];
  29466. tmpShape = new Shape();
  29467. tmpShape.curves = tmpPath.curves;
  29468. shapes.push( tmpShape );
  29469. return shapes;
  29470. }
  29471. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29472. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29473. // console.log("Holes first", holesFirst);
  29474. const betterShapeHoles = [];
  29475. const newShapes = [];
  29476. let newShapeHoles = [];
  29477. let mainIdx = 0;
  29478. let tmpPoints;
  29479. newShapes[ mainIdx ] = undefined;
  29480. newShapeHoles[ mainIdx ] = [];
  29481. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29482. tmpPath = subPaths[ i ];
  29483. tmpPoints = tmpPath.getPoints();
  29484. solid = isClockWise( tmpPoints );
  29485. solid = isCCW ? ! solid : solid;
  29486. if ( solid ) {
  29487. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29488. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29489. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29490. if ( holesFirst ) mainIdx ++;
  29491. newShapeHoles[ mainIdx ] = [];
  29492. //console.log('cw', i);
  29493. } else {
  29494. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29495. //console.log('ccw', i);
  29496. }
  29497. }
  29498. // only Holes? -> probably all Shapes with wrong orientation
  29499. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29500. if ( newShapes.length > 1 ) {
  29501. let ambiguous = false;
  29502. let toChange = 0;
  29503. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29504. betterShapeHoles[ sIdx ] = [];
  29505. }
  29506. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29507. const sho = newShapeHoles[ sIdx ];
  29508. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29509. const ho = sho[ hIdx ];
  29510. let hole_unassigned = true;
  29511. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29512. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29513. if ( sIdx !== s2Idx ) toChange ++;
  29514. if ( hole_unassigned ) {
  29515. hole_unassigned = false;
  29516. betterShapeHoles[ s2Idx ].push( ho );
  29517. } else {
  29518. ambiguous = true;
  29519. }
  29520. }
  29521. }
  29522. if ( hole_unassigned ) {
  29523. betterShapeHoles[ sIdx ].push( ho );
  29524. }
  29525. }
  29526. }
  29527. if ( toChange > 0 && ambiguous === false ) {
  29528. newShapeHoles = betterShapeHoles;
  29529. }
  29530. }
  29531. let tmpHoles;
  29532. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29533. tmpShape = newShapes[ i ].s;
  29534. shapes.push( tmpShape );
  29535. tmpHoles = newShapeHoles[ i ];
  29536. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29537. tmpShape.holes.push( tmpHoles[ j ].h );
  29538. }
  29539. }
  29540. //console.log("shape", shapes);
  29541. return shapes;
  29542. }
  29543. }
  29544. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29545. const _tables = /*@__PURE__*/ _generateTables();
  29546. function _generateTables() {
  29547. // float32 to float16 helpers
  29548. const buffer = new ArrayBuffer( 4 );
  29549. const floatView = new Float32Array( buffer );
  29550. const uint32View = new Uint32Array( buffer );
  29551. const baseTable = new Uint32Array( 512 );
  29552. const shiftTable = new Uint32Array( 512 );
  29553. for ( let i = 0; i < 256; ++ i ) {
  29554. const e = i - 127;
  29555. // very small number (0, -0)
  29556. if ( e < - 27 ) {
  29557. baseTable[ i ] = 0x0000;
  29558. baseTable[ i | 0x100 ] = 0x8000;
  29559. shiftTable[ i ] = 24;
  29560. shiftTable[ i | 0x100 ] = 24;
  29561. // small number (denorm)
  29562. } else if ( e < - 14 ) {
  29563. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29564. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29565. shiftTable[ i ] = - e - 1;
  29566. shiftTable[ i | 0x100 ] = - e - 1;
  29567. // normal number
  29568. } else if ( e <= 15 ) {
  29569. baseTable[ i ] = ( e + 15 ) << 10;
  29570. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29571. shiftTable[ i ] = 13;
  29572. shiftTable[ i | 0x100 ] = 13;
  29573. // large number (Infinity, -Infinity)
  29574. } else if ( e < 128 ) {
  29575. baseTable[ i ] = 0x7c00;
  29576. baseTable[ i | 0x100 ] = 0xfc00;
  29577. shiftTable[ i ] = 24;
  29578. shiftTable[ i | 0x100 ] = 24;
  29579. // stay (NaN, Infinity, -Infinity)
  29580. } else {
  29581. baseTable[ i ] = 0x7c00;
  29582. baseTable[ i | 0x100 ] = 0xfc00;
  29583. shiftTable[ i ] = 13;
  29584. shiftTable[ i | 0x100 ] = 13;
  29585. }
  29586. }
  29587. // float16 to float32 helpers
  29588. const mantissaTable = new Uint32Array( 2048 );
  29589. const exponentTable = new Uint32Array( 64 );
  29590. const offsetTable = new Uint32Array( 64 );
  29591. for ( let i = 1; i < 1024; ++ i ) {
  29592. let m = i << 13; // zero pad mantissa bits
  29593. let e = 0; // zero exponent
  29594. // normalized
  29595. while ( ( m & 0x00800000 ) === 0 ) {
  29596. m <<= 1;
  29597. e -= 0x00800000; // decrement exponent
  29598. }
  29599. m &= ~ 0x00800000; // clear leading 1 bit
  29600. e += 0x38800000; // adjust bias
  29601. mantissaTable[ i ] = m | e;
  29602. }
  29603. for ( let i = 1024; i < 2048; ++ i ) {
  29604. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29605. }
  29606. for ( let i = 1; i < 31; ++ i ) {
  29607. exponentTable[ i ] = i << 23;
  29608. }
  29609. exponentTable[ 31 ] = 0x47800000;
  29610. exponentTable[ 32 ] = 0x80000000;
  29611. for ( let i = 33; i < 63; ++ i ) {
  29612. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29613. }
  29614. exponentTable[ 63 ] = 0xc7800000;
  29615. for ( let i = 1; i < 64; ++ i ) {
  29616. if ( i !== 32 ) {
  29617. offsetTable[ i ] = 1024;
  29618. }
  29619. }
  29620. return {
  29621. floatView: floatView,
  29622. uint32View: uint32View,
  29623. baseTable: baseTable,
  29624. shiftTable: shiftTable,
  29625. mantissaTable: mantissaTable,
  29626. exponentTable: exponentTable,
  29627. offsetTable: offsetTable
  29628. };
  29629. }
  29630. // float32 to float16
  29631. function toHalfFloat( val ) {
  29632. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29633. val = clamp( val, - 65504, 65504 );
  29634. _tables.floatView[ 0 ] = val;
  29635. const f = _tables.uint32View[ 0 ];
  29636. const e = ( f >> 23 ) & 0x1ff;
  29637. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29638. }
  29639. // float16 to float32
  29640. function fromHalfFloat( val ) {
  29641. const m = val >> 10;
  29642. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29643. return _tables.floatView[ 0 ];
  29644. }
  29645. var DataUtils = /*#__PURE__*/Object.freeze({
  29646. __proto__: null,
  29647. toHalfFloat: toHalfFloat,
  29648. fromHalfFloat: fromHalfFloat
  29649. });
  29650. // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  29651. function ImmediateRenderObject() {
  29652. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29653. }
  29654. // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  29655. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  29656. constructor( width, height, options ) {
  29657. console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' );
  29658. super( width, height, options );
  29659. this.samples = 4;
  29660. }
  29661. }
  29662. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29663. class DataTexture2DArray extends DataArrayTexture {
  29664. constructor( data, width, height, depth ) {
  29665. console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' );
  29666. super( data, width, height, depth );
  29667. }
  29668. }
  29669. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29670. class DataTexture3D extends Data3DTexture {
  29671. constructor( data, width, height, depth ) {
  29672. console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' );
  29673. super( data, width, height, depth );
  29674. }
  29675. }
  29676. // r144
  29677. class BoxBufferGeometry extends BoxGeometry {
  29678. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29679. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29680. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29681. }
  29682. }
  29683. // r144
  29684. class CapsuleBufferGeometry extends CapsuleGeometry {
  29685. constructor( radius, length, capSegments, radialSegments ) {
  29686. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29687. super( radius, length, capSegments, radialSegments );
  29688. }
  29689. }
  29690. // r144
  29691. class CircleBufferGeometry extends CircleGeometry {
  29692. constructor( radius, segments, thetaStart, thetaLength ) {
  29693. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29694. super( radius, segments, thetaStart, thetaLength );
  29695. }
  29696. }
  29697. // r144
  29698. class ConeBufferGeometry extends ConeGeometry {
  29699. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29700. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29701. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29702. }
  29703. }
  29704. // r144
  29705. class CylinderBufferGeometry extends CylinderGeometry {
  29706. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29707. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29708. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29709. }
  29710. }
  29711. // r144
  29712. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29713. constructor( radius, detail ) {
  29714. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29715. super( radius, detail );
  29716. }
  29717. }
  29718. // r144
  29719. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29720. constructor( shapes, options ) {
  29721. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29722. super( shapes, options );
  29723. }
  29724. }
  29725. // r144
  29726. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29727. constructor( radius, detail ) {
  29728. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29729. super( radius, detail );
  29730. }
  29731. }
  29732. // r144
  29733. class LatheBufferGeometry extends LatheGeometry {
  29734. constructor( points, segments, phiStart, phiLength ) {
  29735. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29736. super( points, segments, phiStart, phiLength );
  29737. }
  29738. }
  29739. // r144
  29740. class OctahedronBufferGeometry extends OctahedronGeometry {
  29741. constructor( radius, detail ) {
  29742. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29743. super( radius, detail );
  29744. }
  29745. }
  29746. // r144
  29747. class PlaneBufferGeometry extends PlaneGeometry {
  29748. constructor( width, height, widthSegments, heightSegments ) {
  29749. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29750. super( width, height, widthSegments, heightSegments );
  29751. }
  29752. }
  29753. // r144
  29754. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29755. constructor( vertices, indices, radius, detail ) {
  29756. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29757. super( vertices, indices, radius, detail );
  29758. }
  29759. }
  29760. // r144
  29761. class RingBufferGeometry extends RingGeometry {
  29762. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29763. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29764. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29765. }
  29766. }
  29767. // r144
  29768. class ShapeBufferGeometry extends ShapeGeometry {
  29769. constructor( shapes, curveSegments ) {
  29770. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29771. super( shapes, curveSegments );
  29772. }
  29773. }
  29774. // r144
  29775. class SphereBufferGeometry extends SphereGeometry {
  29776. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29777. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29778. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29779. }
  29780. }
  29781. // r144
  29782. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29783. constructor( radius, detail ) {
  29784. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29785. super( radius, detail );
  29786. }
  29787. }
  29788. // r144
  29789. class TorusBufferGeometry extends TorusGeometry {
  29790. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29791. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29792. super( radius, tube, radialSegments, tubularSegments, arc );
  29793. }
  29794. }
  29795. // r144
  29796. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29797. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29798. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29799. super( radius, tube, tubularSegments, radialSegments, p, q );
  29800. }
  29801. }
  29802. // r144
  29803. class TubeBufferGeometry extends TubeGeometry {
  29804. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29805. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29806. super( path, tubularSegments, radius, radialSegments, closed );
  29807. }
  29808. }
  29809. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29810. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29811. revision: REVISION,
  29812. } } ) );
  29813. }
  29814. if ( typeof window !== 'undefined' ) {
  29815. if ( window.__THREE__ ) {
  29816. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29817. } else {
  29818. window.__THREE__ = REVISION;
  29819. }
  29820. }
  29821. export { CSS2DObject, CSS3DObject,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,Text, 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 };