three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '140';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const FlatShading = 1;
  21. const SmoothShading = 2;
  22. const NoBlending = 0;
  23. const NormalBlending = 1;
  24. const AdditiveBlending = 2;
  25. const SubtractiveBlending = 3;
  26. const MultiplyBlending = 4;
  27. const CustomBlending = 5;
  28. const AddEquation = 100;
  29. const SubtractEquation = 101;
  30. const ReverseSubtractEquation = 102;
  31. const MinEquation = 103;
  32. const MaxEquation = 104;
  33. const ZeroFactor = 200;
  34. const OneFactor = 201;
  35. const SrcColorFactor = 202;
  36. const OneMinusSrcColorFactor = 203;
  37. const SrcAlphaFactor = 204;
  38. const OneMinusSrcAlphaFactor = 205;
  39. const DstAlphaFactor = 206;
  40. const OneMinusDstAlphaFactor = 207;
  41. const DstColorFactor = 208;
  42. const OneMinusDstColorFactor = 209;
  43. const SrcAlphaSaturateFactor = 210;
  44. const NeverDepth = 0;
  45. const AlwaysDepth = 1;
  46. const LessDepth = 2;
  47. const LessEqualDepth = 3;
  48. const EqualDepth = 4;
  49. const GreaterEqualDepth = 5;
  50. const GreaterDepth = 6;
  51. const NotEqualDepth = 7;
  52. const MultiplyOperation = 0;
  53. const MixOperation = 1;
  54. const AddOperation = 2;
  55. const NoToneMapping = 0;
  56. const LinearToneMapping = 1;
  57. const ReinhardToneMapping = 2;
  58. const CineonToneMapping = 3;
  59. const ACESFilmicToneMapping = 4;
  60. const CustomToneMapping = 5;
  61. const UVMapping = 300;
  62. const CubeReflectionMapping = 301;
  63. const CubeRefractionMapping = 302;
  64. const EquirectangularReflectionMapping = 303;
  65. const EquirectangularRefractionMapping = 304;
  66. const CubeUVReflectionMapping = 306;
  67. const RepeatWrapping = 1000;
  68. const ClampToEdgeWrapping = 1001;
  69. const MirroredRepeatWrapping = 1002;
  70. const NearestFilter = 1003;
  71. const NearestMipmapNearestFilter = 1004;
  72. const NearestMipMapNearestFilter = 1004;
  73. const NearestMipmapLinearFilter = 1005;
  74. const NearestMipMapLinearFilter = 1005;
  75. const LinearFilter = 1006;
  76. const LinearMipmapNearestFilter = 1007;
  77. const LinearMipMapNearestFilter = 1007;
  78. const LinearMipmapLinearFilter = 1008;
  79. const LinearMipMapLinearFilter = 1008;
  80. const UnsignedByteType = 1009;
  81. const ByteType = 1010;
  82. const ShortType = 1011;
  83. const UnsignedShortType = 1012;
  84. const IntType = 1013;
  85. const UnsignedIntType = 1014;
  86. const FloatType = 1015;
  87. const HalfFloatType = 1016;
  88. const UnsignedShort4444Type = 1017;
  89. const UnsignedShort5551Type = 1018;
  90. const UnsignedInt248Type = 1020;
  91. const AlphaFormat = 1021;
  92. const RGBFormat = 1022;
  93. const RGBAFormat = 1023;
  94. const LuminanceFormat = 1024;
  95. const LuminanceAlphaFormat = 1025;
  96. const DepthFormat = 1026;
  97. const DepthStencilFormat = 1027;
  98. const RedFormat = 1028;
  99. const RedIntegerFormat = 1029;
  100. const RGFormat = 1030;
  101. const RGIntegerFormat = 1031;
  102. const RGBAIntegerFormat = 1033;
  103. const RGB_S3TC_DXT1_Format = 33776;
  104. const RGBA_S3TC_DXT1_Format = 33777;
  105. const RGBA_S3TC_DXT3_Format = 33778;
  106. const RGBA_S3TC_DXT5_Format = 33779;
  107. const RGB_PVRTC_4BPPV1_Format = 35840;
  108. const RGB_PVRTC_2BPPV1_Format = 35841;
  109. const RGBA_PVRTC_4BPPV1_Format = 35842;
  110. const RGBA_PVRTC_2BPPV1_Format = 35843;
  111. const RGB_ETC1_Format = 36196;
  112. const RGB_ETC2_Format = 37492;
  113. const RGBA_ETC2_EAC_Format = 37496;
  114. const RGBA_ASTC_4x4_Format = 37808;
  115. const RGBA_ASTC_5x4_Format = 37809;
  116. const RGBA_ASTC_5x5_Format = 37810;
  117. const RGBA_ASTC_6x5_Format = 37811;
  118. const RGBA_ASTC_6x6_Format = 37812;
  119. const RGBA_ASTC_8x5_Format = 37813;
  120. const RGBA_ASTC_8x6_Format = 37814;
  121. const RGBA_ASTC_8x8_Format = 37815;
  122. const RGBA_ASTC_10x5_Format = 37816;
  123. const RGBA_ASTC_10x6_Format = 37817;
  124. const RGBA_ASTC_10x8_Format = 37818;
  125. const RGBA_ASTC_10x10_Format = 37819;
  126. const RGBA_ASTC_12x10_Format = 37820;
  127. const RGBA_ASTC_12x12_Format = 37821;
  128. const RGBA_BPTC_Format = 36492;
  129. const LoopOnce = 2200;
  130. const LoopRepeat = 2201;
  131. const LoopPingPong = 2202;
  132. const InterpolateDiscrete = 2300;
  133. const InterpolateLinear = 2301;
  134. const InterpolateSmooth = 2302;
  135. const ZeroCurvatureEnding = 2400;
  136. const ZeroSlopeEnding = 2401;
  137. const WrapAroundEnding = 2402;
  138. const NormalAnimationBlendMode = 2500;
  139. const AdditiveAnimationBlendMode = 2501;
  140. const TrianglesDrawMode = 0;
  141. const TriangleStripDrawMode = 1;
  142. const TriangleFanDrawMode = 2;
  143. const LinearEncoding = 3000;
  144. const sRGBEncoding = 3001;
  145. const BasicDepthPacking = 3200;
  146. const RGBADepthPacking = 3201;
  147. const TangentSpaceNormalMap = 0;
  148. const ObjectSpaceNormalMap = 1;
  149. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  150. const NoColorSpace = '';
  151. const SRGBColorSpace = 'srgb';
  152. const LinearSRGBColorSpace = 'srgb-linear';
  153. const ZeroStencilOp = 0;
  154. const KeepStencilOp = 7680;
  155. const ReplaceStencilOp = 7681;
  156. const IncrementStencilOp = 7682;
  157. const DecrementStencilOp = 7683;
  158. const IncrementWrapStencilOp = 34055;
  159. const DecrementWrapStencilOp = 34056;
  160. const InvertStencilOp = 5386;
  161. const NeverStencilFunc = 512;
  162. const LessStencilFunc = 513;
  163. const EqualStencilFunc = 514;
  164. const LessEqualStencilFunc = 515;
  165. const GreaterStencilFunc = 516;
  166. const NotEqualStencilFunc = 517;
  167. const GreaterEqualStencilFunc = 518;
  168. const AlwaysStencilFunc = 519;
  169. const StaticDrawUsage = 35044;
  170. const DynamicDrawUsage = 35048;
  171. const StreamDrawUsage = 35040;
  172. const StaticReadUsage = 35045;
  173. const DynamicReadUsage = 35049;
  174. const StreamReadUsage = 35041;
  175. const StaticCopyUsage = 35046;
  176. const DynamicCopyUsage = 35050;
  177. const StreamCopyUsage = 35042;
  178. const GLSL1 = '100';
  179. const GLSL3 = '300 es';
  180. const _SRGBAFormat = 1035; // fallback for WebGL 1
  181. /**
  182. * https://github.com/mrdoob/eventdispatcher.js/
  183. */
  184. class EventDispatcher {
  185. addEventListener( type, listener ) {
  186. if ( this._listeners === undefined ) this._listeners = {};
  187. const listeners = this._listeners;
  188. if ( listeners[ type ] === undefined ) {
  189. listeners[ type ] = [];
  190. }
  191. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  192. listeners[ type ].push( listener );
  193. }
  194. }
  195. hasEventListener( type, listener ) {
  196. if ( this._listeners === undefined ) return false;
  197. const listeners = this._listeners;
  198. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  199. }
  200. removeEventListener( type, listener ) {
  201. if ( this._listeners === undefined ) return;
  202. const listeners = this._listeners;
  203. const listenerArray = listeners[ type ];
  204. if ( listenerArray !== undefined ) {
  205. const index = listenerArray.indexOf( listener );
  206. if ( index !== - 1 ) {
  207. listenerArray.splice( index, 1 );
  208. }
  209. }
  210. }
  211. dispatchEvent( event ) {
  212. if ( this._listeners === undefined ) return;
  213. const listeners = this._listeners;
  214. const listenerArray = listeners[ event.type ];
  215. if ( listenerArray !== undefined ) {
  216. event.target = this;
  217. // Make a copy, in case listeners are removed while iterating.
  218. const array = listenerArray.slice( 0 );
  219. for ( let i = 0, l = array.length; i < l; i ++ ) {
  220. array[ i ].call( this, event );
  221. }
  222. event.target = null;
  223. }
  224. }
  225. }
  226. const _lut = [];
  227. for ( let i = 0; i < 256; i ++ ) {
  228. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  229. }
  230. let _seed = 1234567;
  231. const DEG2RAD = Math.PI / 180;
  232. const RAD2DEG = 180 / Math.PI;
  233. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  234. function generateUUID() {
  235. const d0 = Math.random() * 0xffffffff | 0;
  236. const d1 = Math.random() * 0xffffffff | 0;
  237. const d2 = Math.random() * 0xffffffff | 0;
  238. const d3 = Math.random() * 0xffffffff | 0;
  239. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  240. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  241. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  242. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  243. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  244. return uuid.toLowerCase();
  245. }
  246. function clamp( value, min, max ) {
  247. return Math.max( min, Math.min( max, value ) );
  248. }
  249. // compute euclidean modulo of m % n
  250. // https://en.wikipedia.org/wiki/Modulo_operation
  251. function euclideanModulo( n, m ) {
  252. return ( ( n % m ) + m ) % m;
  253. }
  254. // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear( x, a1, a2, b1, b2 ) {
  256. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  257. }
  258. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  259. function inverseLerp( x, y, value ) {
  260. if ( x !== y ) {
  261. return ( value - x ) / ( y - x );
  262. } else {
  263. return 0;
  264. }
  265. }
  266. // https://en.wikipedia.org/wiki/Linear_interpolation
  267. function lerp( x, y, t ) {
  268. return ( 1 - t ) * x + t * y;
  269. }
  270. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  271. function damp( x, y, lambda, dt ) {
  272. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  273. }
  274. // https://www.desmos.com/calculator/vcsjnyz7x4
  275. function pingpong( x, length = 1 ) {
  276. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  277. }
  278. // http://en.wikipedia.org/wiki/Smoothstep
  279. function smoothstep( x, min, max ) {
  280. if ( x <= min ) return 0;
  281. if ( x >= max ) return 1;
  282. x = ( x - min ) / ( max - min );
  283. return x * x * ( 3 - 2 * x );
  284. }
  285. function smootherstep( x, min, max ) {
  286. if ( x <= min ) return 0;
  287. if ( x >= max ) return 1;
  288. x = ( x - min ) / ( max - min );
  289. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  290. }
  291. // Random integer from <low, high> interval
  292. function randInt( low, high ) {
  293. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  294. }
  295. // Random float from <low, high> interval
  296. function randFloat( low, high ) {
  297. return low + Math.random() * ( high - low );
  298. }
  299. // Random float from <-range/2, range/2> interval
  300. function randFloatSpread( range ) {
  301. return range * ( 0.5 - Math.random() );
  302. }
  303. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  304. function seededRandom( s ) {
  305. if ( s !== undefined ) _seed = s;
  306. // Mulberry32 generator
  307. let t = _seed += 0x6D2B79F5;
  308. t = Math.imul( t ^ t >>> 15, t | 1 );
  309. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  310. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  311. }
  312. function degToRad( degrees ) {
  313. return degrees * DEG2RAD;
  314. }
  315. function radToDeg( radians ) {
  316. return radians * RAD2DEG;
  317. }
  318. function isPowerOfTwo( value ) {
  319. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  320. }
  321. function ceilPowerOfTwo( value ) {
  322. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  323. }
  324. function floorPowerOfTwo( value ) {
  325. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  326. }
  327. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  328. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  329. // rotations are applied to the axes in the order specified by 'order'
  330. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  331. // angles are in radians
  332. const cos = Math.cos;
  333. const sin = Math.sin;
  334. const c2 = cos( b / 2 );
  335. const s2 = sin( b / 2 );
  336. const c13 = cos( ( a + c ) / 2 );
  337. const s13 = sin( ( a + c ) / 2 );
  338. const c1_3 = cos( ( a - c ) / 2 );
  339. const s1_3 = sin( ( a - c ) / 2 );
  340. const c3_1 = cos( ( c - a ) / 2 );
  341. const s3_1 = sin( ( c - a ) / 2 );
  342. switch ( order ) {
  343. case 'XYX':
  344. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  345. break;
  346. case 'YZY':
  347. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  348. break;
  349. case 'ZXZ':
  350. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  351. break;
  352. case 'XZX':
  353. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  354. break;
  355. case 'YXY':
  356. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  357. break;
  358. case 'ZYZ':
  359. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  360. break;
  361. default:
  362. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  363. }
  364. }
  365. function denormalize$1( value, array ) {
  366. switch ( array.constructor ) {
  367. case Float32Array:
  368. return value;
  369. case Uint16Array:
  370. return value / 65535.0;
  371. case Uint8Array:
  372. return value / 255.0;
  373. case Int16Array:
  374. return Math.max( value / 32767.0, - 1.0 );
  375. case Int8Array:
  376. return Math.max( value / 127.0, - 1.0 );
  377. default:
  378. throw new Error( 'Invalid component type.' );
  379. }
  380. }
  381. function normalize( value, array ) {
  382. switch ( array.constructor ) {
  383. case Float32Array:
  384. return value;
  385. case Uint16Array:
  386. return Math.round( value * 65535.0 );
  387. case Uint8Array:
  388. return Math.round( value * 255.0 );
  389. case Int16Array:
  390. return Math.round( value * 32767.0 );
  391. case Int8Array:
  392. return Math.round( value * 127.0 );
  393. default:
  394. throw new Error( 'Invalid component type.' );
  395. }
  396. }
  397. var MathUtils = /*#__PURE__*/Object.freeze({
  398. __proto__: null,
  399. DEG2RAD: DEG2RAD,
  400. RAD2DEG: RAD2DEG,
  401. generateUUID: generateUUID,
  402. clamp: clamp,
  403. euclideanModulo: euclideanModulo,
  404. mapLinear: mapLinear,
  405. inverseLerp: inverseLerp,
  406. lerp: lerp,
  407. damp: damp,
  408. pingpong: pingpong,
  409. smoothstep: smoothstep,
  410. smootherstep: smootherstep,
  411. randInt: randInt,
  412. randFloat: randFloat,
  413. randFloatSpread: randFloatSpread,
  414. seededRandom: seededRandom,
  415. degToRad: degToRad,
  416. radToDeg: radToDeg,
  417. isPowerOfTwo: isPowerOfTwo,
  418. ceilPowerOfTwo: ceilPowerOfTwo,
  419. floorPowerOfTwo: floorPowerOfTwo,
  420. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  421. normalize: normalize,
  422. denormalize: denormalize$1
  423. });
  424. class Vector2 {
  425. constructor( x = 0, y = 0 ) {
  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, w ) {
  483. if ( w !== undefined ) {
  484. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  485. return this.addVectors( v, w );
  486. }
  487. this.x += v.x;
  488. this.y += v.y;
  489. return this;
  490. }
  491. addScalar( s ) {
  492. this.x += s;
  493. this.y += s;
  494. return this;
  495. }
  496. addVectors( a, b ) {
  497. this.x = a.x + b.x;
  498. this.y = a.y + b.y;
  499. return this;
  500. }
  501. addScaledVector( v, s ) {
  502. this.x += v.x * s;
  503. this.y += v.y * s;
  504. return this;
  505. }
  506. sub( v, w ) {
  507. if ( w !== undefined ) {
  508. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  509. return this.subVectors( v, w );
  510. }
  511. this.x -= v.x;
  512. this.y -= v.y;
  513. return this;
  514. }
  515. subScalar( s ) {
  516. this.x -= s;
  517. this.y -= s;
  518. return this;
  519. }
  520. subVectors( a, b ) {
  521. this.x = a.x - b.x;
  522. this.y = a.y - b.y;
  523. return this;
  524. }
  525. multiply( v ) {
  526. this.x *= v.x;
  527. this.y *= v.y;
  528. return this;
  529. }
  530. multiplyScalar( scalar ) {
  531. this.x *= scalar;
  532. this.y *= scalar;
  533. return this;
  534. }
  535. divide( v ) {
  536. this.x /= v.x;
  537. this.y /= v.y;
  538. return this;
  539. }
  540. divideScalar( scalar ) {
  541. return this.multiplyScalar( 1 / scalar );
  542. }
  543. applyMatrix3( m ) {
  544. const x = this.x, y = this.y;
  545. const e = m.elements;
  546. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  547. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  548. return this;
  549. }
  550. min( v ) {
  551. this.x = Math.min( this.x, v.x );
  552. this.y = Math.min( this.y, v.y );
  553. return this;
  554. }
  555. max( v ) {
  556. this.x = Math.max( this.x, v.x );
  557. this.y = Math.max( this.y, v.y );
  558. return this;
  559. }
  560. clamp( min, max ) {
  561. // assumes min < max, componentwise
  562. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  563. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  564. return this;
  565. }
  566. clampScalar( minVal, maxVal ) {
  567. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  568. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  569. return this;
  570. }
  571. clampLength( min, max ) {
  572. const length = this.length();
  573. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  574. }
  575. floor() {
  576. this.x = Math.floor( this.x );
  577. this.y = Math.floor( this.y );
  578. return this;
  579. }
  580. ceil() {
  581. this.x = Math.ceil( this.x );
  582. this.y = Math.ceil( this.y );
  583. return this;
  584. }
  585. round() {
  586. this.x = Math.round( this.x );
  587. this.y = Math.round( this.y );
  588. return this;
  589. }
  590. roundToZero() {
  591. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  592. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  593. return this;
  594. }
  595. negate() {
  596. this.x = - this.x;
  597. this.y = - this.y;
  598. return this;
  599. }
  600. dot( v ) {
  601. return this.x * v.x + this.y * v.y;
  602. }
  603. cross( v ) {
  604. return this.x * v.y - this.y * v.x;
  605. }
  606. lengthSq() {
  607. return this.x * this.x + this.y * this.y;
  608. }
  609. length() {
  610. return Math.sqrt( this.x * this.x + this.y * this.y );
  611. }
  612. manhattanLength() {
  613. return Math.abs( this.x ) + Math.abs( this.y );
  614. }
  615. normalize() {
  616. return this.divideScalar( this.length() || 1 );
  617. }
  618. angle() {
  619. // computes the angle in radians with respect to the positive x-axis
  620. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  621. return angle;
  622. }
  623. distanceTo( v ) {
  624. return Math.sqrt( this.distanceToSquared( v ) );
  625. }
  626. distanceToSquared( v ) {
  627. const dx = this.x - v.x, dy = this.y - v.y;
  628. return dx * dx + dy * dy;
  629. }
  630. manhattanDistanceTo( v ) {
  631. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  632. }
  633. setLength( length ) {
  634. return this.normalize().multiplyScalar( length );
  635. }
  636. lerp( v, alpha ) {
  637. this.x += ( v.x - this.x ) * alpha;
  638. this.y += ( v.y - this.y ) * alpha;
  639. return this;
  640. }
  641. lerpVectors( v1, v2, alpha ) {
  642. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  643. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  644. return this;
  645. }
  646. equals( v ) {
  647. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  648. }
  649. fromArray( array, offset = 0 ) {
  650. this.x = array[ offset ];
  651. this.y = array[ offset + 1 ];
  652. return this;
  653. }
  654. toArray( array = [], offset = 0 ) {
  655. array[ offset ] = this.x;
  656. array[ offset + 1 ] = this.y;
  657. return array;
  658. }
  659. fromBufferAttribute( attribute, index, offset ) {
  660. if ( offset !== undefined ) {
  661. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  662. }
  663. this.x = attribute.getX( index );
  664. this.y = attribute.getY( index );
  665. return this;
  666. }
  667. rotateAround( center, angle ) {
  668. const c = Math.cos( angle ), s = Math.sin( angle );
  669. const x = this.x - center.x;
  670. const y = this.y - center.y;
  671. this.x = x * c - y * s + center.x;
  672. this.y = x * s + y * c + center.y;
  673. return this;
  674. }
  675. random() {
  676. this.x = Math.random();
  677. this.y = Math.random();
  678. return this;
  679. }
  680. *[ Symbol.iterator ]() {
  681. yield this.x;
  682. yield this.y;
  683. }
  684. }
  685. Vector2.prototype.isVector2 = true;
  686. class Matrix3 {
  687. constructor() {
  688. this.elements = [
  689. 1, 0, 0,
  690. 0, 1, 0,
  691. 0, 0, 1
  692. ];
  693. if ( arguments.length > 0 ) {
  694. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  695. }
  696. }
  697. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  698. const te = this.elements;
  699. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  700. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  701. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  702. return this;
  703. }
  704. identity() {
  705. this.set(
  706. 1, 0, 0,
  707. 0, 1, 0,
  708. 0, 0, 1
  709. );
  710. return this;
  711. }
  712. copy( m ) {
  713. const te = this.elements;
  714. const me = m.elements;
  715. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  716. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  717. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  718. return this;
  719. }
  720. extractBasis( xAxis, yAxis, zAxis ) {
  721. xAxis.setFromMatrix3Column( this, 0 );
  722. yAxis.setFromMatrix3Column( this, 1 );
  723. zAxis.setFromMatrix3Column( this, 2 );
  724. return this;
  725. }
  726. setFromMatrix4( m ) {
  727. const me = m.elements;
  728. this.set(
  729. me[ 0 ], me[ 4 ], me[ 8 ],
  730. me[ 1 ], me[ 5 ], me[ 9 ],
  731. me[ 2 ], me[ 6 ], me[ 10 ]
  732. );
  733. return this;
  734. }
  735. multiply( m ) {
  736. return this.multiplyMatrices( this, m );
  737. }
  738. premultiply( m ) {
  739. return this.multiplyMatrices( m, this );
  740. }
  741. multiplyMatrices( a, b ) {
  742. const ae = a.elements;
  743. const be = b.elements;
  744. const te = this.elements;
  745. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  746. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  747. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  748. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  749. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  750. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  751. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  752. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  753. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  754. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  755. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  756. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  757. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  758. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  759. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  760. return this;
  761. }
  762. multiplyScalar( s ) {
  763. const te = this.elements;
  764. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  765. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  766. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  767. return this;
  768. }
  769. determinant() {
  770. const te = this.elements;
  771. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  772. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  773. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  774. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  775. }
  776. invert() {
  777. const te = this.elements,
  778. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  779. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  780. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  781. t11 = n33 * n22 - n32 * n23,
  782. t12 = n32 * n13 - n33 * n12,
  783. t13 = n23 * n12 - n22 * n13,
  784. det = n11 * t11 + n21 * t12 + n31 * t13;
  785. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  786. const detInv = 1 / det;
  787. te[ 0 ] = t11 * detInv;
  788. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  789. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  790. te[ 3 ] = t12 * detInv;
  791. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  792. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  793. te[ 6 ] = t13 * detInv;
  794. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  795. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  796. return this;
  797. }
  798. transpose() {
  799. let tmp;
  800. const m = this.elements;
  801. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  802. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  803. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  804. return this;
  805. }
  806. getNormalMatrix( matrix4 ) {
  807. return this.setFromMatrix4( matrix4 ).invert().transpose();
  808. }
  809. transposeIntoArray( r ) {
  810. const m = this.elements;
  811. r[ 0 ] = m[ 0 ];
  812. r[ 1 ] = m[ 3 ];
  813. r[ 2 ] = m[ 6 ];
  814. r[ 3 ] = m[ 1 ];
  815. r[ 4 ] = m[ 4 ];
  816. r[ 5 ] = m[ 7 ];
  817. r[ 6 ] = m[ 2 ];
  818. r[ 7 ] = m[ 5 ];
  819. r[ 8 ] = m[ 8 ];
  820. return this;
  821. }
  822. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  823. const c = Math.cos( rotation );
  824. const s = Math.sin( rotation );
  825. this.set(
  826. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  827. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  828. 0, 0, 1
  829. );
  830. return this;
  831. }
  832. scale( sx, sy ) {
  833. const te = this.elements;
  834. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  835. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  836. return this;
  837. }
  838. rotate( theta ) {
  839. const c = Math.cos( theta );
  840. const s = Math.sin( theta );
  841. const te = this.elements;
  842. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  843. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  844. te[ 0 ] = c * a11 + s * a21;
  845. te[ 3 ] = c * a12 + s * a22;
  846. te[ 6 ] = c * a13 + s * a23;
  847. te[ 1 ] = - s * a11 + c * a21;
  848. te[ 4 ] = - s * a12 + c * a22;
  849. te[ 7 ] = - s * a13 + c * a23;
  850. return this;
  851. }
  852. translate( tx, ty ) {
  853. const te = this.elements;
  854. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  855. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  856. return this;
  857. }
  858. equals( matrix ) {
  859. const te = this.elements;
  860. const me = matrix.elements;
  861. for ( let i = 0; i < 9; i ++ ) {
  862. if ( te[ i ] !== me[ i ] ) return false;
  863. }
  864. return true;
  865. }
  866. fromArray( array, offset = 0 ) {
  867. for ( let i = 0; i < 9; i ++ ) {
  868. this.elements[ i ] = array[ i + offset ];
  869. }
  870. return this;
  871. }
  872. toArray( array = [], offset = 0 ) {
  873. const te = this.elements;
  874. array[ offset ] = te[ 0 ];
  875. array[ offset + 1 ] = te[ 1 ];
  876. array[ offset + 2 ] = te[ 2 ];
  877. array[ offset + 3 ] = te[ 3 ];
  878. array[ offset + 4 ] = te[ 4 ];
  879. array[ offset + 5 ] = te[ 5 ];
  880. array[ offset + 6 ] = te[ 6 ];
  881. array[ offset + 7 ] = te[ 7 ];
  882. array[ offset + 8 ] = te[ 8 ];
  883. return array;
  884. }
  885. clone() {
  886. return new this.constructor().fromArray( this.elements );
  887. }
  888. }
  889. Matrix3.prototype.isMatrix3 = true;
  890. function arrayNeedsUint32( array ) {
  891. // assumes larger values usually on last
  892. for ( let i = array.length - 1; i >= 0; -- i ) {
  893. if ( array[ i ] > 65535 ) return true;
  894. }
  895. return false;
  896. }
  897. const TYPED_ARRAYS = {
  898. Int8Array: Int8Array,
  899. Uint8Array: Uint8Array,
  900. Uint8ClampedArray: Uint8ClampedArray,
  901. Int16Array: Int16Array,
  902. Uint16Array: Uint16Array,
  903. Int32Array: Int32Array,
  904. Uint32Array: Uint32Array,
  905. Float32Array: Float32Array,
  906. Float64Array: Float64Array
  907. };
  908. function getTypedArray( type, buffer ) {
  909. return new TYPED_ARRAYS[ type ]( buffer );
  910. }
  911. function createElementNS( name ) {
  912. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  913. }
  914. function SRGBToLinear( c ) {
  915. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  916. }
  917. function LinearToSRGB( c ) {
  918. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  919. }
  920. // JavaScript RGB-to-RGB transforms, defined as
  921. // FN[InputColorSpace][OutputColorSpace] callback functions.
  922. const FN = {
  923. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  924. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  925. };
  926. const ColorManagement = {
  927. legacyMode: true,
  928. get workingColorSpace() {
  929. return LinearSRGBColorSpace;
  930. },
  931. set workingColorSpace( colorSpace ) {
  932. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  933. },
  934. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  935. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  936. return color;
  937. }
  938. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  939. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  940. color.r = fn( color.r );
  941. color.g = fn( color.g );
  942. color.b = fn( color.b );
  943. return color;
  944. }
  945. throw new Error( 'Unsupported color space conversion.' );
  946. },
  947. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  948. return this.convert( color, this.workingColorSpace, targetColorSpace );
  949. },
  950. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  951. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  952. },
  953. };
  954. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  955. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  956. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  957. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  958. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  959. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  960. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  961. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  962. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  963. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  964. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  965. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  966. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  967. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  968. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  969. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  970. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  971. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  972. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  973. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  974. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  975. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  976. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  977. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  978. const _rgb = { r: 0, g: 0, b: 0 };
  979. const _hslA = { h: 0, s: 0, l: 0 };
  980. const _hslB = { h: 0, s: 0, l: 0 };
  981. function hue2rgb( p, q, t ) {
  982. if ( t < 0 ) t += 1;
  983. if ( t > 1 ) t -= 1;
  984. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  985. if ( t < 1 / 2 ) return q;
  986. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  987. return p;
  988. }
  989. function toComponents( source, target ) {
  990. target.r = source.r;
  991. target.g = source.g;
  992. target.b = source.b;
  993. return target;
  994. }
  995. class Color {
  996. constructor( r, g, b ) {
  997. if ( g === undefined && b === undefined ) {
  998. // r is THREE.Color, hex or string
  999. return this.set( r );
  1000. }
  1001. return this.setRGB( r, g, b );
  1002. }
  1003. set( value ) {
  1004. if ( value && value.isColor ) {
  1005. this.copy( value );
  1006. } else if ( typeof value === 'number' ) {
  1007. this.setHex( value );
  1008. } else if ( typeof value === 'string' ) {
  1009. this.setStyle( value );
  1010. }
  1011. return this;
  1012. }
  1013. setScalar( scalar ) {
  1014. this.r = scalar;
  1015. this.g = scalar;
  1016. this.b = scalar;
  1017. return this;
  1018. }
  1019. setHex( hex, colorSpace = SRGBColorSpace ) {
  1020. hex = Math.floor( hex );
  1021. this.r = ( hex >> 16 & 255 ) / 255;
  1022. this.g = ( hex >> 8 & 255 ) / 255;
  1023. this.b = ( hex & 255 ) / 255;
  1024. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1025. return this;
  1026. }
  1027. setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) {
  1028. this.r = r;
  1029. this.g = g;
  1030. this.b = b;
  1031. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1032. return this;
  1033. }
  1034. setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) {
  1035. // h,s,l ranges are in 0.0 - 1.0
  1036. h = euclideanModulo( h, 1 );
  1037. s = clamp( s, 0, 1 );
  1038. l = clamp( l, 0, 1 );
  1039. if ( s === 0 ) {
  1040. this.r = this.g = this.b = l;
  1041. } else {
  1042. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1043. const q = ( 2 * l ) - p;
  1044. this.r = hue2rgb( q, p, h + 1 / 3 );
  1045. this.g = hue2rgb( q, p, h );
  1046. this.b = hue2rgb( q, p, h - 1 / 3 );
  1047. }
  1048. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1049. return this;
  1050. }
  1051. setStyle( style, colorSpace = SRGBColorSpace ) {
  1052. function handleAlpha( string ) {
  1053. if ( string === undefined ) return;
  1054. if ( parseFloat( string ) < 1 ) {
  1055. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1056. }
  1057. }
  1058. let m;
  1059. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1060. // rgb / hsl
  1061. let color;
  1062. const name = m[ 1 ];
  1063. const components = m[ 2 ];
  1064. switch ( name ) {
  1065. case 'rgb':
  1066. case 'rgba':
  1067. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1068. // rgb(255,0,0) rgba(255,0,0,0.5)
  1069. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1070. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1071. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1072. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1073. handleAlpha( color[ 4 ] );
  1074. return this;
  1075. }
  1076. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1077. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1078. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1079. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1080. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1081. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1082. handleAlpha( color[ 4 ] );
  1083. return this;
  1084. }
  1085. break;
  1086. case 'hsl':
  1087. case 'hsla':
  1088. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1089. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1090. const h = parseFloat( color[ 1 ] ) / 360;
  1091. const s = parseInt( color[ 2 ], 10 ) / 100;
  1092. const l = parseInt( color[ 3 ], 10 ) / 100;
  1093. handleAlpha( color[ 4 ] );
  1094. return this.setHSL( h, s, l, colorSpace );
  1095. }
  1096. break;
  1097. }
  1098. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1099. // hex color
  1100. const hex = m[ 1 ];
  1101. const size = hex.length;
  1102. if ( size === 3 ) {
  1103. // #ff0
  1104. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1105. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1106. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1107. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1108. return this;
  1109. } else if ( size === 6 ) {
  1110. // #ff0000
  1111. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1112. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1113. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1114. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1115. return this;
  1116. }
  1117. }
  1118. if ( style && style.length > 0 ) {
  1119. return this.setColorName( style, colorSpace );
  1120. }
  1121. return this;
  1122. }
  1123. setColorName( style, colorSpace = SRGBColorSpace ) {
  1124. // color keywords
  1125. const hex = _colorKeywords[ style.toLowerCase() ];
  1126. if ( hex !== undefined ) {
  1127. // red
  1128. this.setHex( hex, colorSpace );
  1129. } else {
  1130. // unknown color
  1131. console.warn( 'THREE.Color: Unknown color ' + style );
  1132. }
  1133. return this;
  1134. }
  1135. clone() {
  1136. return new this.constructor( this.r, this.g, this.b );
  1137. }
  1138. copy( color ) {
  1139. this.r = color.r;
  1140. this.g = color.g;
  1141. this.b = color.b;
  1142. return this;
  1143. }
  1144. copySRGBToLinear( color ) {
  1145. this.r = SRGBToLinear( color.r );
  1146. this.g = SRGBToLinear( color.g );
  1147. this.b = SRGBToLinear( color.b );
  1148. return this;
  1149. }
  1150. copyLinearToSRGB( color ) {
  1151. this.r = LinearToSRGB( color.r );
  1152. this.g = LinearToSRGB( color.g );
  1153. this.b = LinearToSRGB( color.b );
  1154. return this;
  1155. }
  1156. convertSRGBToLinear() {
  1157. this.copySRGBToLinear( this );
  1158. return this;
  1159. }
  1160. convertLinearToSRGB() {
  1161. this.copyLinearToSRGB( this );
  1162. return this;
  1163. }
  1164. getHex( colorSpace = SRGBColorSpace ) {
  1165. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1166. return clamp( _rgb.r * 255, 0, 255 ) << 16 ^ clamp( _rgb.g * 255, 0, 255 ) << 8 ^ clamp( _rgb.b * 255, 0, 255 ) << 0;
  1167. }
  1168. getHexString( colorSpace = SRGBColorSpace ) {
  1169. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1170. }
  1171. getHSL( target, colorSpace = LinearSRGBColorSpace ) {
  1172. // h,s,l ranges are in 0.0 - 1.0
  1173. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1174. const r = _rgb.r, g = _rgb.g, b = _rgb.b;
  1175. const max = Math.max( r, g, b );
  1176. const min = Math.min( r, g, b );
  1177. let hue, saturation;
  1178. const lightness = ( min + max ) / 2.0;
  1179. if ( min === max ) {
  1180. hue = 0;
  1181. saturation = 0;
  1182. } else {
  1183. const delta = max - min;
  1184. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1185. switch ( max ) {
  1186. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1187. case g: hue = ( b - r ) / delta + 2; break;
  1188. case b: hue = ( r - g ) / delta + 4; break;
  1189. }
  1190. hue /= 6;
  1191. }
  1192. target.h = hue;
  1193. target.s = saturation;
  1194. target.l = lightness;
  1195. return target;
  1196. }
  1197. getRGB( target, colorSpace = LinearSRGBColorSpace ) {
  1198. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1199. target.r = _rgb.r;
  1200. target.g = _rgb.g;
  1201. target.b = _rgb.b;
  1202. return target;
  1203. }
  1204. getStyle( colorSpace = SRGBColorSpace ) {
  1205. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1206. if ( colorSpace !== SRGBColorSpace ) {
  1207. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1208. return `color(${ colorSpace } ${ _rgb.r } ${ _rgb.g } ${ _rgb.b })`;
  1209. }
  1210. return `rgb(${( _rgb.r * 255 ) | 0},${( _rgb.g * 255 ) | 0},${( _rgb.b * 255 ) | 0})`;
  1211. }
  1212. offsetHSL( h, s, l ) {
  1213. this.getHSL( _hslA );
  1214. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1215. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1216. return this;
  1217. }
  1218. add( color ) {
  1219. this.r += color.r;
  1220. this.g += color.g;
  1221. this.b += color.b;
  1222. return this;
  1223. }
  1224. addColors( color1, color2 ) {
  1225. this.r = color1.r + color2.r;
  1226. this.g = color1.g + color2.g;
  1227. this.b = color1.b + color2.b;
  1228. return this;
  1229. }
  1230. addScalar( s ) {
  1231. this.r += s;
  1232. this.g += s;
  1233. this.b += s;
  1234. return this;
  1235. }
  1236. sub( color ) {
  1237. this.r = Math.max( 0, this.r - color.r );
  1238. this.g = Math.max( 0, this.g - color.g );
  1239. this.b = Math.max( 0, this.b - color.b );
  1240. return this;
  1241. }
  1242. multiply( color ) {
  1243. this.r *= color.r;
  1244. this.g *= color.g;
  1245. this.b *= color.b;
  1246. return this;
  1247. }
  1248. multiplyScalar( s ) {
  1249. this.r *= s;
  1250. this.g *= s;
  1251. this.b *= s;
  1252. return this;
  1253. }
  1254. lerp( color, alpha ) {
  1255. this.r += ( color.r - this.r ) * alpha;
  1256. this.g += ( color.g - this.g ) * alpha;
  1257. this.b += ( color.b - this.b ) * alpha;
  1258. return this;
  1259. }
  1260. lerpColors( color1, color2, alpha ) {
  1261. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1262. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1263. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1264. return this;
  1265. }
  1266. lerpHSL( color, alpha ) {
  1267. this.getHSL( _hslA );
  1268. color.getHSL( _hslB );
  1269. const h = lerp( _hslA.h, _hslB.h, alpha );
  1270. const s = lerp( _hslA.s, _hslB.s, alpha );
  1271. const l = lerp( _hslA.l, _hslB.l, alpha );
  1272. this.setHSL( h, s, l );
  1273. return this;
  1274. }
  1275. equals( c ) {
  1276. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1277. }
  1278. fromArray( array, offset = 0 ) {
  1279. this.r = array[ offset ];
  1280. this.g = array[ offset + 1 ];
  1281. this.b = array[ offset + 2 ];
  1282. return this;
  1283. }
  1284. toArray( array = [], offset = 0 ) {
  1285. array[ offset ] = this.r;
  1286. array[ offset + 1 ] = this.g;
  1287. array[ offset + 2 ] = this.b;
  1288. return array;
  1289. }
  1290. fromBufferAttribute( attribute, index ) {
  1291. this.r = attribute.getX( index );
  1292. this.g = attribute.getY( index );
  1293. this.b = attribute.getZ( index );
  1294. if ( attribute.normalized === true ) {
  1295. // assuming Uint8Array
  1296. this.r /= 255;
  1297. this.g /= 255;
  1298. this.b /= 255;
  1299. }
  1300. return this;
  1301. }
  1302. toJSON() {
  1303. return this.getHex();
  1304. }
  1305. *[ Symbol.iterator ]() {
  1306. yield this.r;
  1307. yield this.g;
  1308. yield this.b;
  1309. }
  1310. }
  1311. Color.NAMES = _colorKeywords;
  1312. Color.prototype.isColor = true;
  1313. Color.prototype.r = 1;
  1314. Color.prototype.g = 1;
  1315. Color.prototype.b = 1;
  1316. let _canvas;
  1317. class ImageUtils {
  1318. static getDataURL( image ) {
  1319. if ( /^data:/i.test( image.src ) ) {
  1320. return image.src;
  1321. }
  1322. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1323. return image.src;
  1324. }
  1325. let canvas;
  1326. if ( image instanceof HTMLCanvasElement ) {
  1327. canvas = image;
  1328. } else {
  1329. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1330. _canvas.width = image.width;
  1331. _canvas.height = image.height;
  1332. const context = _canvas.getContext( '2d' );
  1333. if ( image instanceof ImageData ) {
  1334. context.putImageData( image, 0, 0 );
  1335. } else {
  1336. context.drawImage( image, 0, 0, image.width, image.height );
  1337. }
  1338. canvas = _canvas;
  1339. }
  1340. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1341. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1342. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1343. } else {
  1344. return canvas.toDataURL( 'image/png' );
  1345. }
  1346. }
  1347. static sRGBToLinear( image ) {
  1348. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1349. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1350. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1351. const canvas = createElementNS( 'canvas' );
  1352. canvas.width = image.width;
  1353. canvas.height = image.height;
  1354. const context = canvas.getContext( '2d' );
  1355. context.drawImage( image, 0, 0, image.width, image.height );
  1356. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1357. const data = imageData.data;
  1358. for ( let i = 0; i < data.length; i ++ ) {
  1359. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1360. }
  1361. context.putImageData( imageData, 0, 0 );
  1362. return canvas;
  1363. } else if ( image.data ) {
  1364. const data = image.data.slice( 0 );
  1365. for ( let i = 0; i < data.length; i ++ ) {
  1366. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1367. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1368. } else {
  1369. // assuming float
  1370. data[ i ] = SRGBToLinear( data[ i ] );
  1371. }
  1372. }
  1373. return {
  1374. data: data,
  1375. width: image.width,
  1376. height: image.height
  1377. };
  1378. } else {
  1379. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1380. return image;
  1381. }
  1382. }
  1383. }
  1384. class Source {
  1385. constructor( data = null ) {
  1386. this.uuid = generateUUID();
  1387. this.data = data;
  1388. this.version = 0;
  1389. }
  1390. set needsUpdate( value ) {
  1391. if ( value === true ) this.version ++;
  1392. }
  1393. toJSON( meta ) {
  1394. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1395. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1396. return meta.images[ this.uuid ];
  1397. }
  1398. const output = {
  1399. uuid: this.uuid,
  1400. url: ''
  1401. };
  1402. const data = this.data;
  1403. if ( data !== null ) {
  1404. let url;
  1405. if ( Array.isArray( data ) ) {
  1406. // cube texture
  1407. url = [];
  1408. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1409. if ( data[ i ].isDataTexture ) {
  1410. url.push( serializeImage( data[ i ].image ) );
  1411. } else {
  1412. url.push( serializeImage( data[ i ] ) );
  1413. }
  1414. }
  1415. } else {
  1416. // texture
  1417. url = serializeImage( data );
  1418. }
  1419. output.url = url;
  1420. }
  1421. if ( ! isRootObject ) {
  1422. meta.images[ this.uuid ] = output;
  1423. }
  1424. return output;
  1425. }
  1426. }
  1427. function serializeImage( image ) {
  1428. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1429. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1430. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1431. // default images
  1432. return ImageUtils.getDataURL( image );
  1433. } else {
  1434. if ( image.data ) {
  1435. // images of DataTexture
  1436. return {
  1437. data: Array.prototype.slice.call( image.data ),
  1438. width: image.width,
  1439. height: image.height,
  1440. type: image.data.constructor.name
  1441. };
  1442. } else {
  1443. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1444. return {};
  1445. }
  1446. }
  1447. }
  1448. Source.prototype.isSource = true;
  1449. let textureId = 0;
  1450. class Texture extends EventDispatcher {
  1451. 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 ) {
  1452. super();
  1453. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1454. this.uuid = generateUUID();
  1455. this.name = '';
  1456. this.source = new Source( image );
  1457. this.mipmaps = [];
  1458. this.mapping = mapping;
  1459. this.wrapS = wrapS;
  1460. this.wrapT = wrapT;
  1461. this.magFilter = magFilter;
  1462. this.minFilter = minFilter;
  1463. this.anisotropy = anisotropy;
  1464. this.format = format;
  1465. this.internalFormat = null;
  1466. this.type = type;
  1467. this.offset = new Vector2( 0, 0 );
  1468. this.repeat = new Vector2( 1, 1 );
  1469. this.center = new Vector2( 0, 0 );
  1470. this.rotation = 0;
  1471. this.matrixAutoUpdate = true;
  1472. this.matrix = new Matrix3();
  1473. this.generateMipmaps = true;
  1474. this.premultiplyAlpha = false;
  1475. this.flipY = true;
  1476. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1477. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1478. //
  1479. // Also changing the encoding after already used by a Material will not automatically make the Material
  1480. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1481. this.encoding = encoding;
  1482. this.userData = {};
  1483. this.version = 0;
  1484. this.onUpdate = null;
  1485. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1486. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1487. }
  1488. get image() {
  1489. return this.source.data;
  1490. }
  1491. set image( value ) {
  1492. this.source.data = value;
  1493. }
  1494. updateMatrix() {
  1495. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1496. }
  1497. clone() {
  1498. return new this.constructor().copy( this );
  1499. }
  1500. copy( source ) {
  1501. this.name = source.name;
  1502. this.source = source.source;
  1503. this.mipmaps = source.mipmaps.slice( 0 );
  1504. this.mapping = source.mapping;
  1505. this.wrapS = source.wrapS;
  1506. this.wrapT = source.wrapT;
  1507. this.magFilter = source.magFilter;
  1508. this.minFilter = source.minFilter;
  1509. this.anisotropy = source.anisotropy;
  1510. this.format = source.format;
  1511. this.internalFormat = source.internalFormat;
  1512. this.type = source.type;
  1513. this.offset.copy( source.offset );
  1514. this.repeat.copy( source.repeat );
  1515. this.center.copy( source.center );
  1516. this.rotation = source.rotation;
  1517. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1518. this.matrix.copy( source.matrix );
  1519. this.generateMipmaps = source.generateMipmaps;
  1520. this.premultiplyAlpha = source.premultiplyAlpha;
  1521. this.flipY = source.flipY;
  1522. this.unpackAlignment = source.unpackAlignment;
  1523. this.encoding = source.encoding;
  1524. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1525. this.needsUpdate = true;
  1526. return this;
  1527. }
  1528. toJSON( meta ) {
  1529. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1530. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1531. return meta.textures[ this.uuid ];
  1532. }
  1533. const output = {
  1534. metadata: {
  1535. version: 4.5,
  1536. type: 'Texture',
  1537. generator: 'Texture.toJSON'
  1538. },
  1539. uuid: this.uuid,
  1540. name: this.name,
  1541. image: this.source.toJSON( meta ).uuid,
  1542. mapping: this.mapping,
  1543. repeat: [ this.repeat.x, this.repeat.y ],
  1544. offset: [ this.offset.x, this.offset.y ],
  1545. center: [ this.center.x, this.center.y ],
  1546. rotation: this.rotation,
  1547. wrap: [ this.wrapS, this.wrapT ],
  1548. format: this.format,
  1549. type: this.type,
  1550. encoding: this.encoding,
  1551. minFilter: this.minFilter,
  1552. magFilter: this.magFilter,
  1553. anisotropy: this.anisotropy,
  1554. flipY: this.flipY,
  1555. premultiplyAlpha: this.premultiplyAlpha,
  1556. unpackAlignment: this.unpackAlignment
  1557. };
  1558. if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData;
  1559. if ( ! isRootObject ) {
  1560. meta.textures[ this.uuid ] = output;
  1561. }
  1562. return output;
  1563. }
  1564. dispose() {
  1565. this.dispatchEvent( { type: 'dispose' } );
  1566. }
  1567. transformUv( uv ) {
  1568. if ( this.mapping !== UVMapping ) return uv;
  1569. uv.applyMatrix3( this.matrix );
  1570. if ( uv.x < 0 || uv.x > 1 ) {
  1571. switch ( this.wrapS ) {
  1572. case RepeatWrapping:
  1573. uv.x = uv.x - Math.floor( uv.x );
  1574. break;
  1575. case ClampToEdgeWrapping:
  1576. uv.x = uv.x < 0 ? 0 : 1;
  1577. break;
  1578. case MirroredRepeatWrapping:
  1579. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1580. uv.x = Math.ceil( uv.x ) - uv.x;
  1581. } else {
  1582. uv.x = uv.x - Math.floor( uv.x );
  1583. }
  1584. break;
  1585. }
  1586. }
  1587. if ( uv.y < 0 || uv.y > 1 ) {
  1588. switch ( this.wrapT ) {
  1589. case RepeatWrapping:
  1590. uv.y = uv.y - Math.floor( uv.y );
  1591. break;
  1592. case ClampToEdgeWrapping:
  1593. uv.y = uv.y < 0 ? 0 : 1;
  1594. break;
  1595. case MirroredRepeatWrapping:
  1596. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1597. uv.y = Math.ceil( uv.y ) - uv.y;
  1598. } else {
  1599. uv.y = uv.y - Math.floor( uv.y );
  1600. }
  1601. break;
  1602. }
  1603. }
  1604. if ( this.flipY ) {
  1605. uv.y = 1 - uv.y;
  1606. }
  1607. return uv;
  1608. }
  1609. set needsUpdate( value ) {
  1610. if ( value === true ) {
  1611. this.version ++;
  1612. this.source.needsUpdate = true;
  1613. }
  1614. }
  1615. }
  1616. Texture.DEFAULT_IMAGE = null;
  1617. Texture.DEFAULT_MAPPING = UVMapping;
  1618. Texture.prototype.isTexture = true;
  1619. class Vector4 {
  1620. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1621. this.x = x;
  1622. this.y = y;
  1623. this.z = z;
  1624. this.w = w;
  1625. }
  1626. get width() {
  1627. return this.z;
  1628. }
  1629. set width( value ) {
  1630. this.z = value;
  1631. }
  1632. get height() {
  1633. return this.w;
  1634. }
  1635. set height( value ) {
  1636. this.w = value;
  1637. }
  1638. set( x, y, z, w ) {
  1639. this.x = x;
  1640. this.y = y;
  1641. this.z = z;
  1642. this.w = w;
  1643. return this;
  1644. }
  1645. setScalar( scalar ) {
  1646. this.x = scalar;
  1647. this.y = scalar;
  1648. this.z = scalar;
  1649. this.w = scalar;
  1650. return this;
  1651. }
  1652. setX( x ) {
  1653. this.x = x;
  1654. return this;
  1655. }
  1656. setY( y ) {
  1657. this.y = y;
  1658. return this;
  1659. }
  1660. setZ( z ) {
  1661. this.z = z;
  1662. return this;
  1663. }
  1664. setW( w ) {
  1665. this.w = w;
  1666. return this;
  1667. }
  1668. setComponent( index, value ) {
  1669. switch ( index ) {
  1670. case 0: this.x = value; break;
  1671. case 1: this.y = value; break;
  1672. case 2: this.z = value; break;
  1673. case 3: this.w = value; break;
  1674. default: throw new Error( 'index is out of range: ' + index );
  1675. }
  1676. return this;
  1677. }
  1678. getComponent( index ) {
  1679. switch ( index ) {
  1680. case 0: return this.x;
  1681. case 1: return this.y;
  1682. case 2: return this.z;
  1683. case 3: return this.w;
  1684. default: throw new Error( 'index is out of range: ' + index );
  1685. }
  1686. }
  1687. clone() {
  1688. return new this.constructor( this.x, this.y, this.z, this.w );
  1689. }
  1690. copy( v ) {
  1691. this.x = v.x;
  1692. this.y = v.y;
  1693. this.z = v.z;
  1694. this.w = ( v.w !== undefined ) ? v.w : 1;
  1695. return this;
  1696. }
  1697. add( v, w ) {
  1698. if ( w !== undefined ) {
  1699. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1700. return this.addVectors( v, w );
  1701. }
  1702. this.x += v.x;
  1703. this.y += v.y;
  1704. this.z += v.z;
  1705. this.w += v.w;
  1706. return this;
  1707. }
  1708. addScalar( s ) {
  1709. this.x += s;
  1710. this.y += s;
  1711. this.z += s;
  1712. this.w += s;
  1713. return this;
  1714. }
  1715. addVectors( a, b ) {
  1716. this.x = a.x + b.x;
  1717. this.y = a.y + b.y;
  1718. this.z = a.z + b.z;
  1719. this.w = a.w + b.w;
  1720. return this;
  1721. }
  1722. addScaledVector( v, s ) {
  1723. this.x += v.x * s;
  1724. this.y += v.y * s;
  1725. this.z += v.z * s;
  1726. this.w += v.w * s;
  1727. return this;
  1728. }
  1729. sub( v, w ) {
  1730. if ( w !== undefined ) {
  1731. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1732. return this.subVectors( v, w );
  1733. }
  1734. this.x -= v.x;
  1735. this.y -= v.y;
  1736. this.z -= v.z;
  1737. this.w -= v.w;
  1738. return this;
  1739. }
  1740. subScalar( s ) {
  1741. this.x -= s;
  1742. this.y -= s;
  1743. this.z -= s;
  1744. this.w -= s;
  1745. return this;
  1746. }
  1747. subVectors( a, b ) {
  1748. this.x = a.x - b.x;
  1749. this.y = a.y - b.y;
  1750. this.z = a.z - b.z;
  1751. this.w = a.w - b.w;
  1752. return this;
  1753. }
  1754. multiply( v ) {
  1755. this.x *= v.x;
  1756. this.y *= v.y;
  1757. this.z *= v.z;
  1758. this.w *= v.w;
  1759. return this;
  1760. }
  1761. multiplyScalar( scalar ) {
  1762. this.x *= scalar;
  1763. this.y *= scalar;
  1764. this.z *= scalar;
  1765. this.w *= scalar;
  1766. return this;
  1767. }
  1768. applyMatrix4( m ) {
  1769. const x = this.x, y = this.y, z = this.z, w = this.w;
  1770. const e = m.elements;
  1771. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1772. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1773. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1774. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1775. return this;
  1776. }
  1777. divideScalar( scalar ) {
  1778. return this.multiplyScalar( 1 / scalar );
  1779. }
  1780. setAxisAngleFromQuaternion( q ) {
  1781. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1782. // q is assumed to be normalized
  1783. this.w = 2 * Math.acos( q.w );
  1784. const s = Math.sqrt( 1 - q.w * q.w );
  1785. if ( s < 0.0001 ) {
  1786. this.x = 1;
  1787. this.y = 0;
  1788. this.z = 0;
  1789. } else {
  1790. this.x = q.x / s;
  1791. this.y = q.y / s;
  1792. this.z = q.z / s;
  1793. }
  1794. return this;
  1795. }
  1796. setAxisAngleFromRotationMatrix( m ) {
  1797. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1798. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1799. let angle, x, y, z; // variables for result
  1800. const epsilon = 0.01, // margin to allow for rounding errors
  1801. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1802. te = m.elements,
  1803. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1804. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1805. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1806. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1807. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1808. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1809. // singularity found
  1810. // first check for identity matrix which must have +1 for all terms
  1811. // in leading diagonal and zero in other terms
  1812. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1813. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1814. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1815. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1816. // this singularity is identity matrix so angle = 0
  1817. this.set( 1, 0, 0, 0 );
  1818. return this; // zero angle, arbitrary axis
  1819. }
  1820. // otherwise this singularity is angle = 180
  1821. angle = Math.PI;
  1822. const xx = ( m11 + 1 ) / 2;
  1823. const yy = ( m22 + 1 ) / 2;
  1824. const zz = ( m33 + 1 ) / 2;
  1825. const xy = ( m12 + m21 ) / 4;
  1826. const xz = ( m13 + m31 ) / 4;
  1827. const yz = ( m23 + m32 ) / 4;
  1828. if ( ( xx > yy ) && ( xx > zz ) ) {
  1829. // m11 is the largest diagonal term
  1830. if ( xx < epsilon ) {
  1831. x = 0;
  1832. y = 0.707106781;
  1833. z = 0.707106781;
  1834. } else {
  1835. x = Math.sqrt( xx );
  1836. y = xy / x;
  1837. z = xz / x;
  1838. }
  1839. } else if ( yy > zz ) {
  1840. // m22 is the largest diagonal term
  1841. if ( yy < epsilon ) {
  1842. x = 0.707106781;
  1843. y = 0;
  1844. z = 0.707106781;
  1845. } else {
  1846. y = Math.sqrt( yy );
  1847. x = xy / y;
  1848. z = yz / y;
  1849. }
  1850. } else {
  1851. // m33 is the largest diagonal term so base result on this
  1852. if ( zz < epsilon ) {
  1853. x = 0.707106781;
  1854. y = 0.707106781;
  1855. z = 0;
  1856. } else {
  1857. z = Math.sqrt( zz );
  1858. x = xz / z;
  1859. y = yz / z;
  1860. }
  1861. }
  1862. this.set( x, y, z, angle );
  1863. return this; // return 180 deg rotation
  1864. }
  1865. // as we have reached here there are no singularities so we can handle normally
  1866. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1867. ( m13 - m31 ) * ( m13 - m31 ) +
  1868. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1869. if ( Math.abs( s ) < 0.001 ) s = 1;
  1870. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1871. // caught by singularity test above, but I've left it in just in case
  1872. this.x = ( m32 - m23 ) / s;
  1873. this.y = ( m13 - m31 ) / s;
  1874. this.z = ( m21 - m12 ) / s;
  1875. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1876. return this;
  1877. }
  1878. min( v ) {
  1879. this.x = Math.min( this.x, v.x );
  1880. this.y = Math.min( this.y, v.y );
  1881. this.z = Math.min( this.z, v.z );
  1882. this.w = Math.min( this.w, v.w );
  1883. return this;
  1884. }
  1885. max( v ) {
  1886. this.x = Math.max( this.x, v.x );
  1887. this.y = Math.max( this.y, v.y );
  1888. this.z = Math.max( this.z, v.z );
  1889. this.w = Math.max( this.w, v.w );
  1890. return this;
  1891. }
  1892. clamp( min, max ) {
  1893. // assumes min < max, componentwise
  1894. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1895. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1896. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1897. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1898. return this;
  1899. }
  1900. clampScalar( minVal, maxVal ) {
  1901. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1902. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1903. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1904. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1905. return this;
  1906. }
  1907. clampLength( min, max ) {
  1908. const length = this.length();
  1909. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1910. }
  1911. floor() {
  1912. this.x = Math.floor( this.x );
  1913. this.y = Math.floor( this.y );
  1914. this.z = Math.floor( this.z );
  1915. this.w = Math.floor( this.w );
  1916. return this;
  1917. }
  1918. ceil() {
  1919. this.x = Math.ceil( this.x );
  1920. this.y = Math.ceil( this.y );
  1921. this.z = Math.ceil( this.z );
  1922. this.w = Math.ceil( this.w );
  1923. return this;
  1924. }
  1925. round() {
  1926. this.x = Math.round( this.x );
  1927. this.y = Math.round( this.y );
  1928. this.z = Math.round( this.z );
  1929. this.w = Math.round( this.w );
  1930. return this;
  1931. }
  1932. roundToZero() {
  1933. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1934. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1935. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1936. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1937. return this;
  1938. }
  1939. negate() {
  1940. this.x = - this.x;
  1941. this.y = - this.y;
  1942. this.z = - this.z;
  1943. this.w = - this.w;
  1944. return this;
  1945. }
  1946. dot( v ) {
  1947. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1948. }
  1949. lengthSq() {
  1950. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1951. }
  1952. length() {
  1953. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1954. }
  1955. manhattanLength() {
  1956. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1957. }
  1958. normalize() {
  1959. return this.divideScalar( this.length() || 1 );
  1960. }
  1961. setLength( length ) {
  1962. return this.normalize().multiplyScalar( length );
  1963. }
  1964. lerp( v, alpha ) {
  1965. this.x += ( v.x - this.x ) * alpha;
  1966. this.y += ( v.y - this.y ) * alpha;
  1967. this.z += ( v.z - this.z ) * alpha;
  1968. this.w += ( v.w - this.w ) * alpha;
  1969. return this;
  1970. }
  1971. lerpVectors( v1, v2, alpha ) {
  1972. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1973. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1974. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1975. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1976. return this;
  1977. }
  1978. equals( v ) {
  1979. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1980. }
  1981. fromArray( array, offset = 0 ) {
  1982. this.x = array[ offset ];
  1983. this.y = array[ offset + 1 ];
  1984. this.z = array[ offset + 2 ];
  1985. this.w = array[ offset + 3 ];
  1986. return this;
  1987. }
  1988. toArray( array = [], offset = 0 ) {
  1989. array[ offset ] = this.x;
  1990. array[ offset + 1 ] = this.y;
  1991. array[ offset + 2 ] = this.z;
  1992. array[ offset + 3 ] = this.w;
  1993. return array;
  1994. }
  1995. fromBufferAttribute( attribute, index, offset ) {
  1996. if ( offset !== undefined ) {
  1997. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1998. }
  1999. this.x = attribute.getX( index );
  2000. this.y = attribute.getY( index );
  2001. this.z = attribute.getZ( index );
  2002. this.w = attribute.getW( index );
  2003. return this;
  2004. }
  2005. random() {
  2006. this.x = Math.random();
  2007. this.y = Math.random();
  2008. this.z = Math.random();
  2009. this.w = Math.random();
  2010. return this;
  2011. }
  2012. *[ Symbol.iterator ]() {
  2013. yield this.x;
  2014. yield this.y;
  2015. yield this.z;
  2016. yield this.w;
  2017. }
  2018. }
  2019. Vector4.prototype.isVector4 = true;
  2020. /*
  2021. In options, we can specify:
  2022. * Texture parameters for an auto-generated target texture
  2023. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2024. */
  2025. class WebGLRenderTarget extends EventDispatcher {
  2026. constructor( width, height, options = {} ) {
  2027. super();
  2028. this.width = width;
  2029. this.height = height;
  2030. this.depth = 1;
  2031. this.scissor = new Vector4( 0, 0, width, height );
  2032. this.scissorTest = false;
  2033. this.viewport = new Vector4( 0, 0, width, height );
  2034. const image = { width: width, height: height, depth: 1 };
  2035. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2036. this.texture.isRenderTargetTexture = true;
  2037. this.texture.flipY = false;
  2038. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2039. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2040. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2041. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2042. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2043. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2044. this.samples = options.samples !== undefined ? options.samples : 0;
  2045. }
  2046. setSize( width, height, depth = 1 ) {
  2047. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2048. this.width = width;
  2049. this.height = height;
  2050. this.depth = depth;
  2051. this.texture.image.width = width;
  2052. this.texture.image.height = height;
  2053. this.texture.image.depth = depth;
  2054. this.dispose();
  2055. }
  2056. this.viewport.set( 0, 0, width, height );
  2057. this.scissor.set( 0, 0, width, height );
  2058. }
  2059. clone() {
  2060. return new this.constructor().copy( this );
  2061. }
  2062. copy( source ) {
  2063. this.width = source.width;
  2064. this.height = source.height;
  2065. this.depth = source.depth;
  2066. this.viewport.copy( source.viewport );
  2067. this.texture = source.texture.clone();
  2068. this.texture.isRenderTargetTexture = true;
  2069. // ensure image object is not shared, see #20328
  2070. const image = Object.assign( {}, source.texture.image );
  2071. this.texture.source = new Source( image );
  2072. this.depthBuffer = source.depthBuffer;
  2073. this.stencilBuffer = source.stencilBuffer;
  2074. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2075. this.samples = source.samples;
  2076. return this;
  2077. }
  2078. dispose() {
  2079. this.dispatchEvent( { type: 'dispose' } );
  2080. }
  2081. }
  2082. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  2083. class DataArrayTexture extends Texture {
  2084. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2085. super( null );
  2086. this.image = { data, width, height, depth };
  2087. this.magFilter = NearestFilter;
  2088. this.minFilter = NearestFilter;
  2089. this.wrapR = ClampToEdgeWrapping;
  2090. this.generateMipmaps = false;
  2091. this.flipY = false;
  2092. this.unpackAlignment = 1;
  2093. }
  2094. }
  2095. DataArrayTexture.prototype.isDataArrayTexture = true;
  2096. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2097. constructor( width, height, depth ) {
  2098. super( width, height );
  2099. this.depth = depth;
  2100. this.texture = new DataArrayTexture( null, width, height, depth );
  2101. this.texture.isRenderTargetTexture = true;
  2102. }
  2103. }
  2104. WebGLArrayRenderTarget.prototype.isWebGLArrayRenderTarget = true;
  2105. class Data3DTexture extends Texture {
  2106. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2107. // We're going to add .setXXX() methods for setting properties later.
  2108. // Users can still set in DataTexture3D directly.
  2109. //
  2110. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2111. // texture.anisotropy = 16;
  2112. //
  2113. // See #14839
  2114. super( null );
  2115. this.image = { data, width, height, depth };
  2116. this.magFilter = NearestFilter;
  2117. this.minFilter = NearestFilter;
  2118. this.wrapR = ClampToEdgeWrapping;
  2119. this.generateMipmaps = false;
  2120. this.flipY = false;
  2121. this.unpackAlignment = 1;
  2122. }
  2123. }
  2124. Data3DTexture.prototype.isData3DTexture = true;
  2125. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2126. constructor( width, height, depth ) {
  2127. super( width, height );
  2128. this.depth = depth;
  2129. this.texture = new Data3DTexture( null, width, height, depth );
  2130. this.texture.isRenderTargetTexture = true;
  2131. }
  2132. }
  2133. WebGL3DRenderTarget.prototype.isWebGL3DRenderTarget = true;
  2134. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2135. constructor( width, height, count, options = {} ) {
  2136. super( width, height, options );
  2137. const texture = this.texture;
  2138. this.texture = [];
  2139. for ( let i = 0; i < count; i ++ ) {
  2140. this.texture[ i ] = texture.clone();
  2141. this.texture[ i ].isRenderTargetTexture = true;
  2142. }
  2143. }
  2144. setSize( width, height, depth = 1 ) {
  2145. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2146. this.width = width;
  2147. this.height = height;
  2148. this.depth = depth;
  2149. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2150. this.texture[ i ].image.width = width;
  2151. this.texture[ i ].image.height = height;
  2152. this.texture[ i ].image.depth = depth;
  2153. }
  2154. this.dispose();
  2155. }
  2156. this.viewport.set( 0, 0, width, height );
  2157. this.scissor.set( 0, 0, width, height );
  2158. return this;
  2159. }
  2160. copy( source ) {
  2161. this.dispose();
  2162. this.width = source.width;
  2163. this.height = source.height;
  2164. this.depth = source.depth;
  2165. this.viewport.set( 0, 0, this.width, this.height );
  2166. this.scissor.set( 0, 0, this.width, this.height );
  2167. this.depthBuffer = source.depthBuffer;
  2168. this.stencilBuffer = source.stencilBuffer;
  2169. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2170. this.texture.length = 0;
  2171. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2172. this.texture[ i ] = source.texture[ i ].clone();
  2173. this.texture[ i ].isRenderTargetTexture = true;
  2174. }
  2175. return this;
  2176. }
  2177. }
  2178. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  2179. class Quaternion {
  2180. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2181. this._x = x;
  2182. this._y = y;
  2183. this._z = z;
  2184. this._w = w;
  2185. }
  2186. static slerp( qa, qb, qm, t ) {
  2187. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  2188. return qm.slerpQuaternions( qa, qb, t );
  2189. }
  2190. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2191. // fuzz-free, array-based Quaternion SLERP operation
  2192. let x0 = src0[ srcOffset0 + 0 ],
  2193. y0 = src0[ srcOffset0 + 1 ],
  2194. z0 = src0[ srcOffset0 + 2 ],
  2195. w0 = src0[ srcOffset0 + 3 ];
  2196. const x1 = src1[ srcOffset1 + 0 ],
  2197. y1 = src1[ srcOffset1 + 1 ],
  2198. z1 = src1[ srcOffset1 + 2 ],
  2199. w1 = src1[ srcOffset1 + 3 ];
  2200. if ( t === 0 ) {
  2201. dst[ dstOffset + 0 ] = x0;
  2202. dst[ dstOffset + 1 ] = y0;
  2203. dst[ dstOffset + 2 ] = z0;
  2204. dst[ dstOffset + 3 ] = w0;
  2205. return;
  2206. }
  2207. if ( t === 1 ) {
  2208. dst[ dstOffset + 0 ] = x1;
  2209. dst[ dstOffset + 1 ] = y1;
  2210. dst[ dstOffset + 2 ] = z1;
  2211. dst[ dstOffset + 3 ] = w1;
  2212. return;
  2213. }
  2214. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2215. let s = 1 - t;
  2216. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2217. dir = ( cos >= 0 ? 1 : - 1 ),
  2218. sqrSin = 1 - cos * cos;
  2219. // Skip the Slerp for tiny steps to avoid numeric problems:
  2220. if ( sqrSin > Number.EPSILON ) {
  2221. const sin = Math.sqrt( sqrSin ),
  2222. len = Math.atan2( sin, cos * dir );
  2223. s = Math.sin( s * len ) / sin;
  2224. t = Math.sin( t * len ) / sin;
  2225. }
  2226. const tDir = t * dir;
  2227. x0 = x0 * s + x1 * tDir;
  2228. y0 = y0 * s + y1 * tDir;
  2229. z0 = z0 * s + z1 * tDir;
  2230. w0 = w0 * s + w1 * tDir;
  2231. // Normalize in case we just did a lerp:
  2232. if ( s === 1 - t ) {
  2233. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2234. x0 *= f;
  2235. y0 *= f;
  2236. z0 *= f;
  2237. w0 *= f;
  2238. }
  2239. }
  2240. dst[ dstOffset ] = x0;
  2241. dst[ dstOffset + 1 ] = y0;
  2242. dst[ dstOffset + 2 ] = z0;
  2243. dst[ dstOffset + 3 ] = w0;
  2244. }
  2245. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2246. const x0 = src0[ srcOffset0 ];
  2247. const y0 = src0[ srcOffset0 + 1 ];
  2248. const z0 = src0[ srcOffset0 + 2 ];
  2249. const w0 = src0[ srcOffset0 + 3 ];
  2250. const x1 = src1[ srcOffset1 ];
  2251. const y1 = src1[ srcOffset1 + 1 ];
  2252. const z1 = src1[ srcOffset1 + 2 ];
  2253. const w1 = src1[ srcOffset1 + 3 ];
  2254. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2255. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2256. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2257. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2258. return dst;
  2259. }
  2260. get x() {
  2261. return this._x;
  2262. }
  2263. set x( value ) {
  2264. this._x = value;
  2265. this._onChangeCallback();
  2266. }
  2267. get y() {
  2268. return this._y;
  2269. }
  2270. set y( value ) {
  2271. this._y = value;
  2272. this._onChangeCallback();
  2273. }
  2274. get z() {
  2275. return this._z;
  2276. }
  2277. set z( value ) {
  2278. this._z = value;
  2279. this._onChangeCallback();
  2280. }
  2281. get w() {
  2282. return this._w;
  2283. }
  2284. set w( value ) {
  2285. this._w = value;
  2286. this._onChangeCallback();
  2287. }
  2288. set( x, y, z, w ) {
  2289. this._x = x;
  2290. this._y = y;
  2291. this._z = z;
  2292. this._w = w;
  2293. this._onChangeCallback();
  2294. return this;
  2295. }
  2296. clone() {
  2297. return new this.constructor( this._x, this._y, this._z, this._w );
  2298. }
  2299. copy( quaternion ) {
  2300. this._x = quaternion.x;
  2301. this._y = quaternion.y;
  2302. this._z = quaternion.z;
  2303. this._w = quaternion.w;
  2304. this._onChangeCallback();
  2305. return this;
  2306. }
  2307. setFromEuler( euler, update ) {
  2308. if ( ! ( euler && euler.isEuler ) ) {
  2309. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2310. }
  2311. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2312. // http://www.mathworks.com/matlabcentral/fileexchange/
  2313. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2314. // content/SpinCalc.m
  2315. const cos = Math.cos;
  2316. const sin = Math.sin;
  2317. const c1 = cos( x / 2 );
  2318. const c2 = cos( y / 2 );
  2319. const c3 = cos( z / 2 );
  2320. const s1 = sin( x / 2 );
  2321. const s2 = sin( y / 2 );
  2322. const s3 = sin( z / 2 );
  2323. switch ( order ) {
  2324. case 'XYZ':
  2325. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2326. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2327. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2328. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2329. break;
  2330. case 'YXZ':
  2331. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2332. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2333. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2334. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2335. break;
  2336. case 'ZXY':
  2337. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2338. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2339. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2340. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2341. break;
  2342. case 'ZYX':
  2343. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2344. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2345. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2346. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2347. break;
  2348. case 'YZX':
  2349. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2350. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2351. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2352. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2353. break;
  2354. case 'XZY':
  2355. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2356. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2357. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2358. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2359. break;
  2360. default:
  2361. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2362. }
  2363. if ( update !== false ) this._onChangeCallback();
  2364. return this;
  2365. }
  2366. setFromAxisAngle( axis, angle ) {
  2367. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2368. // assumes axis is normalized
  2369. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2370. this._x = axis.x * s;
  2371. this._y = axis.y * s;
  2372. this._z = axis.z * s;
  2373. this._w = Math.cos( halfAngle );
  2374. this._onChangeCallback();
  2375. return this;
  2376. }
  2377. setFromRotationMatrix( m ) {
  2378. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2379. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2380. const te = m.elements,
  2381. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2382. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2383. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2384. trace = m11 + m22 + m33;
  2385. if ( trace > 0 ) {
  2386. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2387. this._w = 0.25 / s;
  2388. this._x = ( m32 - m23 ) * s;
  2389. this._y = ( m13 - m31 ) * s;
  2390. this._z = ( m21 - m12 ) * s;
  2391. } else if ( m11 > m22 && m11 > m33 ) {
  2392. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2393. this._w = ( m32 - m23 ) / s;
  2394. this._x = 0.25 * s;
  2395. this._y = ( m12 + m21 ) / s;
  2396. this._z = ( m13 + m31 ) / s;
  2397. } else if ( m22 > m33 ) {
  2398. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2399. this._w = ( m13 - m31 ) / s;
  2400. this._x = ( m12 + m21 ) / s;
  2401. this._y = 0.25 * s;
  2402. this._z = ( m23 + m32 ) / s;
  2403. } else {
  2404. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2405. this._w = ( m21 - m12 ) / s;
  2406. this._x = ( m13 + m31 ) / s;
  2407. this._y = ( m23 + m32 ) / s;
  2408. this._z = 0.25 * s;
  2409. }
  2410. this._onChangeCallback();
  2411. return this;
  2412. }
  2413. setFromUnitVectors( vFrom, vTo ) {
  2414. // assumes direction vectors vFrom and vTo are normalized
  2415. let r = vFrom.dot( vTo ) + 1;
  2416. if ( r < Number.EPSILON ) {
  2417. // vFrom and vTo point in opposite directions
  2418. r = 0;
  2419. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2420. this._x = - vFrom.y;
  2421. this._y = vFrom.x;
  2422. this._z = 0;
  2423. this._w = r;
  2424. } else {
  2425. this._x = 0;
  2426. this._y = - vFrom.z;
  2427. this._z = vFrom.y;
  2428. this._w = r;
  2429. }
  2430. } else {
  2431. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2432. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2433. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2434. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2435. this._w = r;
  2436. }
  2437. return this.normalize();
  2438. }
  2439. angleTo( q ) {
  2440. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2441. }
  2442. rotateTowards( q, step ) {
  2443. const angle = this.angleTo( q );
  2444. if ( angle === 0 ) return this;
  2445. const t = Math.min( 1, step / angle );
  2446. this.slerp( q, t );
  2447. return this;
  2448. }
  2449. identity() {
  2450. return this.set( 0, 0, 0, 1 );
  2451. }
  2452. invert() {
  2453. // quaternion is assumed to have unit length
  2454. return this.conjugate();
  2455. }
  2456. conjugate() {
  2457. this._x *= - 1;
  2458. this._y *= - 1;
  2459. this._z *= - 1;
  2460. this._onChangeCallback();
  2461. return this;
  2462. }
  2463. dot( v ) {
  2464. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2465. }
  2466. lengthSq() {
  2467. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2468. }
  2469. length() {
  2470. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2471. }
  2472. normalize() {
  2473. let l = this.length();
  2474. if ( l === 0 ) {
  2475. this._x = 0;
  2476. this._y = 0;
  2477. this._z = 0;
  2478. this._w = 1;
  2479. } else {
  2480. l = 1 / l;
  2481. this._x = this._x * l;
  2482. this._y = this._y * l;
  2483. this._z = this._z * l;
  2484. this._w = this._w * l;
  2485. }
  2486. this._onChangeCallback();
  2487. return this;
  2488. }
  2489. multiply( q, p ) {
  2490. if ( p !== undefined ) {
  2491. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2492. return this.multiplyQuaternions( q, p );
  2493. }
  2494. return this.multiplyQuaternions( this, q );
  2495. }
  2496. premultiply( q ) {
  2497. return this.multiplyQuaternions( q, this );
  2498. }
  2499. multiplyQuaternions( a, b ) {
  2500. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2501. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2502. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2503. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2504. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2505. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2506. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2507. this._onChangeCallback();
  2508. return this;
  2509. }
  2510. slerp( qb, t ) {
  2511. if ( t === 0 ) return this;
  2512. if ( t === 1 ) return this.copy( qb );
  2513. const x = this._x, y = this._y, z = this._z, w = this._w;
  2514. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2515. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2516. if ( cosHalfTheta < 0 ) {
  2517. this._w = - qb._w;
  2518. this._x = - qb._x;
  2519. this._y = - qb._y;
  2520. this._z = - qb._z;
  2521. cosHalfTheta = - cosHalfTheta;
  2522. } else {
  2523. this.copy( qb );
  2524. }
  2525. if ( cosHalfTheta >= 1.0 ) {
  2526. this._w = w;
  2527. this._x = x;
  2528. this._y = y;
  2529. this._z = z;
  2530. return this;
  2531. }
  2532. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2533. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2534. const s = 1 - t;
  2535. this._w = s * w + t * this._w;
  2536. this._x = s * x + t * this._x;
  2537. this._y = s * y + t * this._y;
  2538. this._z = s * z + t * this._z;
  2539. this.normalize();
  2540. this._onChangeCallback();
  2541. return this;
  2542. }
  2543. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2544. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2545. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2546. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2547. this._w = ( w * ratioA + this._w * ratioB );
  2548. this._x = ( x * ratioA + this._x * ratioB );
  2549. this._y = ( y * ratioA + this._y * ratioB );
  2550. this._z = ( z * ratioA + this._z * ratioB );
  2551. this._onChangeCallback();
  2552. return this;
  2553. }
  2554. slerpQuaternions( qa, qb, t ) {
  2555. return this.copy( qa ).slerp( qb, t );
  2556. }
  2557. random() {
  2558. // Derived from http://planning.cs.uiuc.edu/node198.html
  2559. // Note, this source uses w, x, y, z ordering,
  2560. // so we swap the order below.
  2561. const u1 = Math.random();
  2562. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2563. const sqrtu1 = Math.sqrt( u1 );
  2564. const u2 = 2 * Math.PI * Math.random();
  2565. const u3 = 2 * Math.PI * Math.random();
  2566. return this.set(
  2567. sqrt1u1 * Math.cos( u2 ),
  2568. sqrtu1 * Math.sin( u3 ),
  2569. sqrtu1 * Math.cos( u3 ),
  2570. sqrt1u1 * Math.sin( u2 ),
  2571. );
  2572. }
  2573. equals( quaternion ) {
  2574. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2575. }
  2576. fromArray( array, offset = 0 ) {
  2577. this._x = array[ offset ];
  2578. this._y = array[ offset + 1 ];
  2579. this._z = array[ offset + 2 ];
  2580. this._w = array[ offset + 3 ];
  2581. this._onChangeCallback();
  2582. return this;
  2583. }
  2584. toArray( array = [], offset = 0 ) {
  2585. array[ offset ] = this._x;
  2586. array[ offset + 1 ] = this._y;
  2587. array[ offset + 2 ] = this._z;
  2588. array[ offset + 3 ] = this._w;
  2589. return array;
  2590. }
  2591. fromBufferAttribute( attribute, index ) {
  2592. this._x = attribute.getX( index );
  2593. this._y = attribute.getY( index );
  2594. this._z = attribute.getZ( index );
  2595. this._w = attribute.getW( index );
  2596. return this;
  2597. }
  2598. _onChange( callback ) {
  2599. this._onChangeCallback = callback;
  2600. return this;
  2601. }
  2602. _onChangeCallback() {}
  2603. *[ Symbol.iterator ]() {
  2604. yield this._x;
  2605. yield this._y;
  2606. yield this._z;
  2607. yield this._w;
  2608. }
  2609. }
  2610. Quaternion.prototype.isQuaternion = true;
  2611. class Vector3 {
  2612. constructor( x = 0, y = 0, z = 0 ) {
  2613. this.x = x;
  2614. this.y = y;
  2615. this.z = z;
  2616. }
  2617. set( x, y, z ) {
  2618. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2619. this.x = x;
  2620. this.y = y;
  2621. this.z = z;
  2622. return this;
  2623. }
  2624. setScalar( scalar ) {
  2625. this.x = scalar;
  2626. this.y = scalar;
  2627. this.z = scalar;
  2628. return this;
  2629. }
  2630. setX( x ) {
  2631. this.x = x;
  2632. return this;
  2633. }
  2634. setY( y ) {
  2635. this.y = y;
  2636. return this;
  2637. }
  2638. setZ( z ) {
  2639. this.z = z;
  2640. return this;
  2641. }
  2642. setComponent( index, value ) {
  2643. switch ( index ) {
  2644. case 0: this.x = value; break;
  2645. case 1: this.y = value; break;
  2646. case 2: this.z = value; break;
  2647. default: throw new Error( 'index is out of range: ' + index );
  2648. }
  2649. return this;
  2650. }
  2651. getComponent( index ) {
  2652. switch ( index ) {
  2653. case 0: return this.x;
  2654. case 1: return this.y;
  2655. case 2: return this.z;
  2656. default: throw new Error( 'index is out of range: ' + index );
  2657. }
  2658. }
  2659. clone() {
  2660. return new this.constructor( this.x, this.y, this.z );
  2661. }
  2662. copy( v ) {
  2663. this.x = v.x;
  2664. this.y = v.y;
  2665. this.z = v.z;
  2666. return this;
  2667. }
  2668. add( v, w ) {
  2669. if ( w !== undefined ) {
  2670. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2671. return this.addVectors( v, w );
  2672. }
  2673. this.x += v.x;
  2674. this.y += v.y;
  2675. this.z += v.z;
  2676. return this;
  2677. }
  2678. addScalar( s ) {
  2679. this.x += s;
  2680. this.y += s;
  2681. this.z += s;
  2682. return this;
  2683. }
  2684. addVectors( a, b ) {
  2685. this.x = a.x + b.x;
  2686. this.y = a.y + b.y;
  2687. this.z = a.z + b.z;
  2688. return this;
  2689. }
  2690. addScaledVector( v, s ) {
  2691. this.x += v.x * s;
  2692. this.y += v.y * s;
  2693. this.z += v.z * s;
  2694. return this;
  2695. }
  2696. sub( v, w ) {
  2697. if ( w !== undefined ) {
  2698. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2699. return this.subVectors( v, w );
  2700. }
  2701. this.x -= v.x;
  2702. this.y -= v.y;
  2703. this.z -= v.z;
  2704. return this;
  2705. }
  2706. subScalar( s ) {
  2707. this.x -= s;
  2708. this.y -= s;
  2709. this.z -= s;
  2710. return this;
  2711. }
  2712. subVectors( a, b ) {
  2713. this.x = a.x - b.x;
  2714. this.y = a.y - b.y;
  2715. this.z = a.z - b.z;
  2716. return this;
  2717. }
  2718. multiply( v, w ) {
  2719. if ( w !== undefined ) {
  2720. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2721. return this.multiplyVectors( v, w );
  2722. }
  2723. this.x *= v.x;
  2724. this.y *= v.y;
  2725. this.z *= v.z;
  2726. return this;
  2727. }
  2728. multiplyScalar( scalar ) {
  2729. this.x *= scalar;
  2730. this.y *= scalar;
  2731. this.z *= scalar;
  2732. return this;
  2733. }
  2734. multiplyVectors( a, b ) {
  2735. this.x = a.x * b.x;
  2736. this.y = a.y * b.y;
  2737. this.z = a.z * b.z;
  2738. return this;
  2739. }
  2740. applyEuler( euler ) {
  2741. if ( ! ( euler && euler.isEuler ) ) {
  2742. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2743. }
  2744. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2745. }
  2746. applyAxisAngle( axis, angle ) {
  2747. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2748. }
  2749. applyMatrix3( m ) {
  2750. const x = this.x, y = this.y, z = this.z;
  2751. const e = m.elements;
  2752. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2753. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2754. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2755. return this;
  2756. }
  2757. applyNormalMatrix( m ) {
  2758. return this.applyMatrix3( m ).normalize();
  2759. }
  2760. applyMatrix4( m ) {
  2761. const x = this.x, y = this.y, z = this.z;
  2762. const e = m.elements;
  2763. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2764. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2765. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2766. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2767. return this;
  2768. }
  2769. applyQuaternion( q ) {
  2770. const x = this.x, y = this.y, z = this.z;
  2771. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2772. // calculate quat * vector
  2773. const ix = qw * x + qy * z - qz * y;
  2774. const iy = qw * y + qz * x - qx * z;
  2775. const iz = qw * z + qx * y - qy * x;
  2776. const iw = - qx * x - qy * y - qz * z;
  2777. // calculate result * inverse quat
  2778. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2779. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2780. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2781. return this;
  2782. }
  2783. project( camera ) {
  2784. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2785. }
  2786. unproject( camera ) {
  2787. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2788. }
  2789. transformDirection( m ) {
  2790. // input: THREE.Matrix4 affine matrix
  2791. // vector interpreted as a direction
  2792. const x = this.x, y = this.y, z = this.z;
  2793. const e = m.elements;
  2794. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2795. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2796. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2797. return this.normalize();
  2798. }
  2799. divide( v ) {
  2800. this.x /= v.x;
  2801. this.y /= v.y;
  2802. this.z /= v.z;
  2803. return this;
  2804. }
  2805. divideScalar( scalar ) {
  2806. return this.multiplyScalar( 1 / scalar );
  2807. }
  2808. min( v ) {
  2809. this.x = Math.min( this.x, v.x );
  2810. this.y = Math.min( this.y, v.y );
  2811. this.z = Math.min( this.z, v.z );
  2812. return this;
  2813. }
  2814. max( v ) {
  2815. this.x = Math.max( this.x, v.x );
  2816. this.y = Math.max( this.y, v.y );
  2817. this.z = Math.max( this.z, v.z );
  2818. return this;
  2819. }
  2820. clamp( min, max ) {
  2821. // assumes min < max, componentwise
  2822. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2823. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2824. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2825. return this;
  2826. }
  2827. clampScalar( minVal, maxVal ) {
  2828. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2829. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2830. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2831. return this;
  2832. }
  2833. clampLength( min, max ) {
  2834. const length = this.length();
  2835. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2836. }
  2837. floor() {
  2838. this.x = Math.floor( this.x );
  2839. this.y = Math.floor( this.y );
  2840. this.z = Math.floor( this.z );
  2841. return this;
  2842. }
  2843. ceil() {
  2844. this.x = Math.ceil( this.x );
  2845. this.y = Math.ceil( this.y );
  2846. this.z = Math.ceil( this.z );
  2847. return this;
  2848. }
  2849. round() {
  2850. this.x = Math.round( this.x );
  2851. this.y = Math.round( this.y );
  2852. this.z = Math.round( this.z );
  2853. return this;
  2854. }
  2855. roundToZero() {
  2856. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2857. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2858. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2859. return this;
  2860. }
  2861. negate() {
  2862. this.x = - this.x;
  2863. this.y = - this.y;
  2864. this.z = - this.z;
  2865. return this;
  2866. }
  2867. dot( v ) {
  2868. return this.x * v.x + this.y * v.y + this.z * v.z;
  2869. }
  2870. // TODO lengthSquared?
  2871. lengthSq() {
  2872. return this.x * this.x + this.y * this.y + this.z * this.z;
  2873. }
  2874. length() {
  2875. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2876. }
  2877. manhattanLength() {
  2878. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2879. }
  2880. normalize() {
  2881. return this.divideScalar( this.length() || 1 );
  2882. }
  2883. setLength( length ) {
  2884. return this.normalize().multiplyScalar( length );
  2885. }
  2886. lerp( v, alpha ) {
  2887. this.x += ( v.x - this.x ) * alpha;
  2888. this.y += ( v.y - this.y ) * alpha;
  2889. this.z += ( v.z - this.z ) * alpha;
  2890. return this;
  2891. }
  2892. lerpVectors( v1, v2, alpha ) {
  2893. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2894. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2895. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2896. return this;
  2897. }
  2898. cross( v, w ) {
  2899. if ( w !== undefined ) {
  2900. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2901. return this.crossVectors( v, w );
  2902. }
  2903. return this.crossVectors( this, v );
  2904. }
  2905. crossVectors( a, b ) {
  2906. const ax = a.x, ay = a.y, az = a.z;
  2907. const bx = b.x, by = b.y, bz = b.z;
  2908. this.x = ay * bz - az * by;
  2909. this.y = az * bx - ax * bz;
  2910. this.z = ax * by - ay * bx;
  2911. return this;
  2912. }
  2913. projectOnVector( v ) {
  2914. const denominator = v.lengthSq();
  2915. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2916. const scalar = v.dot( this ) / denominator;
  2917. return this.copy( v ).multiplyScalar( scalar );
  2918. }
  2919. projectOnPlane( planeNormal ) {
  2920. _vector$c.copy( this ).projectOnVector( planeNormal );
  2921. return this.sub( _vector$c );
  2922. }
  2923. reflect( normal ) {
  2924. // reflect incident vector off plane orthogonal to normal
  2925. // normal is assumed to have unit length
  2926. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2927. }
  2928. angleTo( v ) {
  2929. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2930. if ( denominator === 0 ) return Math.PI / 2;
  2931. const theta = this.dot( v ) / denominator;
  2932. // clamp, to handle numerical problems
  2933. return Math.acos( clamp( theta, - 1, 1 ) );
  2934. }
  2935. distanceTo( v ) {
  2936. return Math.sqrt( this.distanceToSquared( v ) );
  2937. }
  2938. distanceToSquared( v ) {
  2939. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2940. return dx * dx + dy * dy + dz * dz;
  2941. }
  2942. manhattanDistanceTo( v ) {
  2943. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2944. }
  2945. setFromSpherical( s ) {
  2946. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2947. }
  2948. setFromSphericalCoords( radius, phi, theta ) {
  2949. const sinPhiRadius = Math.sin( phi ) * radius;
  2950. this.x = sinPhiRadius * Math.sin( theta );
  2951. this.y = Math.cos( phi ) * radius;
  2952. this.z = sinPhiRadius * Math.cos( theta );
  2953. return this;
  2954. }
  2955. setFromCylindrical( c ) {
  2956. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2957. }
  2958. setFromCylindricalCoords( radius, theta, y ) {
  2959. this.x = radius * Math.sin( theta );
  2960. this.y = y;
  2961. this.z = radius * Math.cos( theta );
  2962. return this;
  2963. }
  2964. setFromMatrixPosition( m ) {
  2965. const e = m.elements;
  2966. this.x = e[ 12 ];
  2967. this.y = e[ 13 ];
  2968. this.z = e[ 14 ];
  2969. return this;
  2970. }
  2971. setFromMatrixScale( m ) {
  2972. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2973. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2974. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2975. this.x = sx;
  2976. this.y = sy;
  2977. this.z = sz;
  2978. return this;
  2979. }
  2980. setFromMatrixColumn( m, index ) {
  2981. return this.fromArray( m.elements, index * 4 );
  2982. }
  2983. setFromMatrix3Column( m, index ) {
  2984. return this.fromArray( m.elements, index * 3 );
  2985. }
  2986. setFromEuler( e ) {
  2987. this.x = e._x;
  2988. this.y = e._y;
  2989. this.z = e._z;
  2990. return this;
  2991. }
  2992. equals( v ) {
  2993. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2994. }
  2995. fromArray( array, offset = 0 ) {
  2996. this.x = array[ offset ];
  2997. this.y = array[ offset + 1 ];
  2998. this.z = array[ offset + 2 ];
  2999. return this;
  3000. }
  3001. toArray( array = [], offset = 0 ) {
  3002. array[ offset ] = this.x;
  3003. array[ offset + 1 ] = this.y;
  3004. array[ offset + 2 ] = this.z;
  3005. return array;
  3006. }
  3007. fromBufferAttribute( attribute, index, offset ) {
  3008. if ( offset !== undefined ) {
  3009. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  3010. }
  3011. this.x = attribute.getX( index );
  3012. this.y = attribute.getY( index );
  3013. this.z = attribute.getZ( index );
  3014. return this;
  3015. }
  3016. random() {
  3017. this.x = Math.random();
  3018. this.y = Math.random();
  3019. this.z = Math.random();
  3020. return this;
  3021. }
  3022. randomDirection() {
  3023. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3024. const u = ( Math.random() - 0.5 ) * 2;
  3025. const t = Math.random() * Math.PI * 2;
  3026. const f = Math.sqrt( 1 - u ** 2 );
  3027. this.x = f * Math.cos( t );
  3028. this.y = f * Math.sin( t );
  3029. this.z = u;
  3030. return this;
  3031. }
  3032. *[ Symbol.iterator ]() {
  3033. yield this.x;
  3034. yield this.y;
  3035. yield this.z;
  3036. }
  3037. }
  3038. Vector3.prototype.isVector3 = true;
  3039. const _vector$c = /*@__PURE__*/ new Vector3();
  3040. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3041. class Box3 {
  3042. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3043. this.min = min;
  3044. this.max = max;
  3045. }
  3046. set( min, max ) {
  3047. this.min.copy( min );
  3048. this.max.copy( max );
  3049. return this;
  3050. }
  3051. setFromArray( array ) {
  3052. let minX = + Infinity;
  3053. let minY = + Infinity;
  3054. let minZ = + Infinity;
  3055. let maxX = - Infinity;
  3056. let maxY = - Infinity;
  3057. let maxZ = - Infinity;
  3058. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3059. const x = array[ i ];
  3060. const y = array[ i + 1 ];
  3061. const z = array[ i + 2 ];
  3062. if ( x < minX ) minX = x;
  3063. if ( y < minY ) minY = y;
  3064. if ( z < minZ ) minZ = z;
  3065. if ( x > maxX ) maxX = x;
  3066. if ( y > maxY ) maxY = y;
  3067. if ( z > maxZ ) maxZ = z;
  3068. }
  3069. this.min.set( minX, minY, minZ );
  3070. this.max.set( maxX, maxY, maxZ );
  3071. return this;
  3072. }
  3073. setFromBufferAttribute( attribute ) {
  3074. let minX = + Infinity;
  3075. let minY = + Infinity;
  3076. let minZ = + Infinity;
  3077. let maxX = - Infinity;
  3078. let maxY = - Infinity;
  3079. let maxZ = - Infinity;
  3080. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3081. const x = attribute.getX( i );
  3082. const y = attribute.getY( i );
  3083. const z = attribute.getZ( i );
  3084. if ( x < minX ) minX = x;
  3085. if ( y < minY ) minY = y;
  3086. if ( z < minZ ) minZ = z;
  3087. if ( x > maxX ) maxX = x;
  3088. if ( y > maxY ) maxY = y;
  3089. if ( z > maxZ ) maxZ = z;
  3090. }
  3091. this.min.set( minX, minY, minZ );
  3092. this.max.set( maxX, maxY, maxZ );
  3093. return this;
  3094. }
  3095. setFromPoints( points ) {
  3096. this.makeEmpty();
  3097. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3098. this.expandByPoint( points[ i ] );
  3099. }
  3100. return this;
  3101. }
  3102. setFromCenterAndSize( center, size ) {
  3103. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3104. this.min.copy( center ).sub( halfSize );
  3105. this.max.copy( center ).add( halfSize );
  3106. return this;
  3107. }
  3108. setFromObject( object, precise = false ) {
  3109. this.makeEmpty();
  3110. return this.expandByObject( object, precise );
  3111. }
  3112. clone() {
  3113. return new this.constructor().copy( this );
  3114. }
  3115. copy( box ) {
  3116. this.min.copy( box.min );
  3117. this.max.copy( box.max );
  3118. return this;
  3119. }
  3120. makeEmpty() {
  3121. this.min.x = this.min.y = this.min.z = + Infinity;
  3122. this.max.x = this.max.y = this.max.z = - Infinity;
  3123. return this;
  3124. }
  3125. isEmpty() {
  3126. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3127. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3128. }
  3129. getCenter( target ) {
  3130. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3131. }
  3132. getSize( target ) {
  3133. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3134. }
  3135. expandByPoint( point ) {
  3136. this.min.min( point );
  3137. this.max.max( point );
  3138. return this;
  3139. }
  3140. expandByVector( vector ) {
  3141. this.min.sub( vector );
  3142. this.max.add( vector );
  3143. return this;
  3144. }
  3145. expandByScalar( scalar ) {
  3146. this.min.addScalar( - scalar );
  3147. this.max.addScalar( scalar );
  3148. return this;
  3149. }
  3150. expandByObject( object, precise = false ) {
  3151. // Computes the world-axis-aligned bounding box of an object (including its children),
  3152. // accounting for both the object's, and children's, world transforms
  3153. object.updateWorldMatrix( false, false );
  3154. const geometry = object.geometry;
  3155. if ( geometry !== undefined ) {
  3156. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3157. const position = geometry.attributes.position;
  3158. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3159. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3160. this.expandByPoint( _vector$b );
  3161. }
  3162. } else {
  3163. if ( geometry.boundingBox === null ) {
  3164. geometry.computeBoundingBox();
  3165. }
  3166. _box$3.copy( geometry.boundingBox );
  3167. _box$3.applyMatrix4( object.matrixWorld );
  3168. this.union( _box$3 );
  3169. }
  3170. }
  3171. const children = object.children;
  3172. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3173. this.expandByObject( children[ i ], precise );
  3174. }
  3175. return this;
  3176. }
  3177. containsPoint( point ) {
  3178. return point.x < this.min.x || point.x > this.max.x ||
  3179. point.y < this.min.y || point.y > this.max.y ||
  3180. point.z < this.min.z || point.z > this.max.z ? false : true;
  3181. }
  3182. containsBox( box ) {
  3183. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3184. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3185. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3186. }
  3187. getParameter( point, target ) {
  3188. // This can potentially have a divide by zero if the box
  3189. // has a size dimension of 0.
  3190. return target.set(
  3191. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3192. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3193. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3194. );
  3195. }
  3196. intersectsBox( box ) {
  3197. // using 6 splitting planes to rule out intersections.
  3198. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3199. box.max.y < this.min.y || box.min.y > this.max.y ||
  3200. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3201. }
  3202. intersectsSphere( sphere ) {
  3203. // Find the point on the AABB closest to the sphere center.
  3204. this.clampPoint( sphere.center, _vector$b );
  3205. // If that point is inside the sphere, the AABB and sphere intersect.
  3206. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3207. }
  3208. intersectsPlane( plane ) {
  3209. // We compute the minimum and maximum dot product values. If those values
  3210. // are on the same side (back or front) of the plane, then there is no intersection.
  3211. let min, max;
  3212. if ( plane.normal.x > 0 ) {
  3213. min = plane.normal.x * this.min.x;
  3214. max = plane.normal.x * this.max.x;
  3215. } else {
  3216. min = plane.normal.x * this.max.x;
  3217. max = plane.normal.x * this.min.x;
  3218. }
  3219. if ( plane.normal.y > 0 ) {
  3220. min += plane.normal.y * this.min.y;
  3221. max += plane.normal.y * this.max.y;
  3222. } else {
  3223. min += plane.normal.y * this.max.y;
  3224. max += plane.normal.y * this.min.y;
  3225. }
  3226. if ( plane.normal.z > 0 ) {
  3227. min += plane.normal.z * this.min.z;
  3228. max += plane.normal.z * this.max.z;
  3229. } else {
  3230. min += plane.normal.z * this.max.z;
  3231. max += plane.normal.z * this.min.z;
  3232. }
  3233. return ( min <= - plane.constant && max >= - plane.constant );
  3234. }
  3235. intersectsTriangle( triangle ) {
  3236. if ( this.isEmpty() ) {
  3237. return false;
  3238. }
  3239. // compute box center and extents
  3240. this.getCenter( _center );
  3241. _extents.subVectors( this.max, _center );
  3242. // translate triangle to aabb origin
  3243. _v0$2.subVectors( triangle.a, _center );
  3244. _v1$7.subVectors( triangle.b, _center );
  3245. _v2$3.subVectors( triangle.c, _center );
  3246. // compute edge vectors for triangle
  3247. _f0.subVectors( _v1$7, _v0$2 );
  3248. _f1.subVectors( _v2$3, _v1$7 );
  3249. _f2.subVectors( _v0$2, _v2$3 );
  3250. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3251. // 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
  3252. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3253. let axes = [
  3254. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3255. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3256. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3257. ];
  3258. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3259. return false;
  3260. }
  3261. // test 3 face normals from the aabb
  3262. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3263. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3264. return false;
  3265. }
  3266. // finally testing the face normal of the triangle
  3267. // use already existing triangle edge vectors here
  3268. _triangleNormal.crossVectors( _f0, _f1 );
  3269. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3270. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  3271. }
  3272. clampPoint( point, target ) {
  3273. return target.copy( point ).clamp( this.min, this.max );
  3274. }
  3275. distanceToPoint( point ) {
  3276. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3277. return clampedPoint.sub( point ).length();
  3278. }
  3279. getBoundingSphere( target ) {
  3280. this.getCenter( target.center );
  3281. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3282. return target;
  3283. }
  3284. intersect( box ) {
  3285. this.min.max( box.min );
  3286. this.max.min( box.max );
  3287. // 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.
  3288. if ( this.isEmpty() ) this.makeEmpty();
  3289. return this;
  3290. }
  3291. union( box ) {
  3292. this.min.min( box.min );
  3293. this.max.max( box.max );
  3294. return this;
  3295. }
  3296. applyMatrix4( matrix ) {
  3297. // transform of empty box is an empty box.
  3298. if ( this.isEmpty() ) return this;
  3299. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3300. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3301. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3302. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3303. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3304. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3305. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3306. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3307. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3308. this.setFromPoints( _points );
  3309. return this;
  3310. }
  3311. translate( offset ) {
  3312. this.min.add( offset );
  3313. this.max.add( offset );
  3314. return this;
  3315. }
  3316. equals( box ) {
  3317. return box.min.equals( this.min ) && box.max.equals( this.max );
  3318. }
  3319. }
  3320. Box3.prototype.isBox3 = true;
  3321. const _points = [
  3322. /*@__PURE__*/ new Vector3(),
  3323. /*@__PURE__*/ new Vector3(),
  3324. /*@__PURE__*/ new Vector3(),
  3325. /*@__PURE__*/ new Vector3(),
  3326. /*@__PURE__*/ new Vector3(),
  3327. /*@__PURE__*/ new Vector3(),
  3328. /*@__PURE__*/ new Vector3(),
  3329. /*@__PURE__*/ new Vector3()
  3330. ];
  3331. const _vector$b = /*@__PURE__*/ new Vector3();
  3332. const _box$3 = /*@__PURE__*/ new Box3();
  3333. // triangle centered vertices
  3334. const _v0$2 = /*@__PURE__*/ new Vector3();
  3335. const _v1$7 = /*@__PURE__*/ new Vector3();
  3336. const _v2$3 = /*@__PURE__*/ new Vector3();
  3337. // triangle edge vectors
  3338. const _f0 = /*@__PURE__*/ new Vector3();
  3339. const _f1 = /*@__PURE__*/ new Vector3();
  3340. const _f2 = /*@__PURE__*/ new Vector3();
  3341. const _center = /*@__PURE__*/ new Vector3();
  3342. const _extents = /*@__PURE__*/ new Vector3();
  3343. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3344. const _testAxis = /*@__PURE__*/ new Vector3();
  3345. function satForAxes( axes, v0, v1, v2, extents ) {
  3346. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3347. _testAxis.fromArray( axes, i );
  3348. // project the aabb onto the separating axis
  3349. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3350. // project all 3 vertices of the triangle onto the separating axis
  3351. const p0 = v0.dot( _testAxis );
  3352. const p1 = v1.dot( _testAxis );
  3353. const p2 = v2.dot( _testAxis );
  3354. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3355. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3356. // points of the projected triangle are outside the projected half-length of the aabb
  3357. // the axis is separating and we can exit
  3358. return false;
  3359. }
  3360. }
  3361. return true;
  3362. }
  3363. const _box$2 = /*@__PURE__*/ new Box3();
  3364. const _v1$6 = /*@__PURE__*/ new Vector3();
  3365. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  3366. const _toPoint = /*@__PURE__*/ new Vector3();
  3367. class Sphere {
  3368. constructor( center = new Vector3(), radius = - 1 ) {
  3369. this.center = center;
  3370. this.radius = radius;
  3371. }
  3372. set( center, radius ) {
  3373. this.center.copy( center );
  3374. this.radius = radius;
  3375. return this;
  3376. }
  3377. setFromPoints( points, optionalCenter ) {
  3378. const center = this.center;
  3379. if ( optionalCenter !== undefined ) {
  3380. center.copy( optionalCenter );
  3381. } else {
  3382. _box$2.setFromPoints( points ).getCenter( center );
  3383. }
  3384. let maxRadiusSq = 0;
  3385. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3386. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3387. }
  3388. this.radius = Math.sqrt( maxRadiusSq );
  3389. return this;
  3390. }
  3391. copy( sphere ) {
  3392. this.center.copy( sphere.center );
  3393. this.radius = sphere.radius;
  3394. return this;
  3395. }
  3396. isEmpty() {
  3397. return ( this.radius < 0 );
  3398. }
  3399. makeEmpty() {
  3400. this.center.set( 0, 0, 0 );
  3401. this.radius = - 1;
  3402. return this;
  3403. }
  3404. containsPoint( point ) {
  3405. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3406. }
  3407. distanceToPoint( point ) {
  3408. return ( point.distanceTo( this.center ) - this.radius );
  3409. }
  3410. intersectsSphere( sphere ) {
  3411. const radiusSum = this.radius + sphere.radius;
  3412. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3413. }
  3414. intersectsBox( box ) {
  3415. return box.intersectsSphere( this );
  3416. }
  3417. intersectsPlane( plane ) {
  3418. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3419. }
  3420. clampPoint( point, target ) {
  3421. const deltaLengthSq = this.center.distanceToSquared( point );
  3422. target.copy( point );
  3423. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3424. target.sub( this.center ).normalize();
  3425. target.multiplyScalar( this.radius ).add( this.center );
  3426. }
  3427. return target;
  3428. }
  3429. getBoundingBox( target ) {
  3430. if ( this.isEmpty() ) {
  3431. // Empty sphere produces empty bounding box
  3432. target.makeEmpty();
  3433. return target;
  3434. }
  3435. target.set( this.center, this.center );
  3436. target.expandByScalar( this.radius );
  3437. return target;
  3438. }
  3439. applyMatrix4( matrix ) {
  3440. this.center.applyMatrix4( matrix );
  3441. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3442. return this;
  3443. }
  3444. translate( offset ) {
  3445. this.center.add( offset );
  3446. return this;
  3447. }
  3448. expandByPoint( point ) {
  3449. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3450. _toPoint.subVectors( point, this.center );
  3451. const lengthSq = _toPoint.lengthSq();
  3452. if ( lengthSq > ( this.radius * this.radius ) ) {
  3453. const length = Math.sqrt( lengthSq );
  3454. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  3455. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3456. // and the other half to position. This gives a tighter enclosure, instead of if
  3457. // the whole missing distance were just added to radius.
  3458. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  3459. this.radius += missingRadiusHalf;
  3460. }
  3461. return this;
  3462. }
  3463. union( sphere ) {
  3464. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3465. // To enclose another sphere into this sphere, we only need to enclose two points:
  3466. // 1) Enclose the farthest point on the other sphere into this sphere.
  3467. // 2) Enclose the opposite point of the farthest point into this sphere.
  3468. if ( this.center.equals( sphere.center ) === true ) {
  3469. _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius );
  3470. } else {
  3471. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  3472. }
  3473. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  3474. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  3475. return this;
  3476. }
  3477. equals( sphere ) {
  3478. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3479. }
  3480. clone() {
  3481. return new this.constructor().copy( this );
  3482. }
  3483. }
  3484. const _vector$a = /*@__PURE__*/ new Vector3();
  3485. const _segCenter = /*@__PURE__*/ new Vector3();
  3486. const _segDir = /*@__PURE__*/ new Vector3();
  3487. const _diff = /*@__PURE__*/ new Vector3();
  3488. const _edge1 = /*@__PURE__*/ new Vector3();
  3489. const _edge2 = /*@__PURE__*/ new Vector3();
  3490. const _normal$1 = /*@__PURE__*/ new Vector3();
  3491. class Ray {
  3492. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3493. this.origin = origin;
  3494. this.direction = direction;
  3495. }
  3496. set( origin, direction ) {
  3497. this.origin.copy( origin );
  3498. this.direction.copy( direction );
  3499. return this;
  3500. }
  3501. copy( ray ) {
  3502. this.origin.copy( ray.origin );
  3503. this.direction.copy( ray.direction );
  3504. return this;
  3505. }
  3506. at( t, target ) {
  3507. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3508. }
  3509. lookAt( v ) {
  3510. this.direction.copy( v ).sub( this.origin ).normalize();
  3511. return this;
  3512. }
  3513. recast( t ) {
  3514. this.origin.copy( this.at( t, _vector$a ) );
  3515. return this;
  3516. }
  3517. closestPointToPoint( point, target ) {
  3518. target.subVectors( point, this.origin );
  3519. const directionDistance = target.dot( this.direction );
  3520. if ( directionDistance < 0 ) {
  3521. return target.copy( this.origin );
  3522. }
  3523. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3524. }
  3525. distanceToPoint( point ) {
  3526. return Math.sqrt( this.distanceSqToPoint( point ) );
  3527. }
  3528. distanceSqToPoint( point ) {
  3529. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3530. // point behind the ray
  3531. if ( directionDistance < 0 ) {
  3532. return this.origin.distanceToSquared( point );
  3533. }
  3534. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3535. return _vector$a.distanceToSquared( point );
  3536. }
  3537. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3538. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3539. // It returns the min distance between the ray and the segment
  3540. // defined by v0 and v1
  3541. // It can also set two optional targets :
  3542. // - The closest point on the ray
  3543. // - The closest point on the segment
  3544. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3545. _segDir.copy( v1 ).sub( v0 ).normalize();
  3546. _diff.copy( this.origin ).sub( _segCenter );
  3547. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3548. const a01 = - this.direction.dot( _segDir );
  3549. const b0 = _diff.dot( this.direction );
  3550. const b1 = - _diff.dot( _segDir );
  3551. const c = _diff.lengthSq();
  3552. const det = Math.abs( 1 - a01 * a01 );
  3553. let s0, s1, sqrDist, extDet;
  3554. if ( det > 0 ) {
  3555. // The ray and segment are not parallel.
  3556. s0 = a01 * b1 - b0;
  3557. s1 = a01 * b0 - b1;
  3558. extDet = segExtent * det;
  3559. if ( s0 >= 0 ) {
  3560. if ( s1 >= - extDet ) {
  3561. if ( s1 <= extDet ) {
  3562. // region 0
  3563. // Minimum at interior points of ray and segment.
  3564. const invDet = 1 / det;
  3565. s0 *= invDet;
  3566. s1 *= invDet;
  3567. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3568. } else {
  3569. // region 1
  3570. s1 = segExtent;
  3571. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3572. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3573. }
  3574. } else {
  3575. // region 5
  3576. s1 = - segExtent;
  3577. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3578. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3579. }
  3580. } else {
  3581. if ( s1 <= - extDet ) {
  3582. // region 4
  3583. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3584. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3585. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3586. } else if ( s1 <= extDet ) {
  3587. // region 3
  3588. s0 = 0;
  3589. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3590. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3591. } else {
  3592. // region 2
  3593. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3594. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3595. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3596. }
  3597. }
  3598. } else {
  3599. // Ray and segment are parallel.
  3600. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3601. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3602. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3603. }
  3604. if ( optionalPointOnRay ) {
  3605. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3606. }
  3607. if ( optionalPointOnSegment ) {
  3608. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3609. }
  3610. return sqrDist;
  3611. }
  3612. intersectSphere( sphere, target ) {
  3613. _vector$a.subVectors( sphere.center, this.origin );
  3614. const tca = _vector$a.dot( this.direction );
  3615. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3616. const radius2 = sphere.radius * sphere.radius;
  3617. if ( d2 > radius2 ) return null;
  3618. const thc = Math.sqrt( radius2 - d2 );
  3619. // t0 = first intersect point - entrance on front of sphere
  3620. const t0 = tca - thc;
  3621. // t1 = second intersect point - exit point on back of sphere
  3622. const t1 = tca + thc;
  3623. // test to see if both t0 and t1 are behind the ray - if so, return null
  3624. if ( t0 < 0 && t1 < 0 ) return null;
  3625. // test to see if t0 is behind the ray:
  3626. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3627. // in order to always return an intersect point that is in front of the ray.
  3628. if ( t0 < 0 ) return this.at( t1, target );
  3629. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3630. return this.at( t0, target );
  3631. }
  3632. intersectsSphere( sphere ) {
  3633. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3634. }
  3635. distanceToPlane( plane ) {
  3636. const denominator = plane.normal.dot( this.direction );
  3637. if ( denominator === 0 ) {
  3638. // line is coplanar, return origin
  3639. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3640. return 0;
  3641. }
  3642. // Null is preferable to undefined since undefined means.... it is undefined
  3643. return null;
  3644. }
  3645. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3646. // Return if the ray never intersects the plane
  3647. return t >= 0 ? t : null;
  3648. }
  3649. intersectPlane( plane, target ) {
  3650. const t = this.distanceToPlane( plane );
  3651. if ( t === null ) {
  3652. return null;
  3653. }
  3654. return this.at( t, target );
  3655. }
  3656. intersectsPlane( plane ) {
  3657. // check if the ray lies on the plane first
  3658. const distToPoint = plane.distanceToPoint( this.origin );
  3659. if ( distToPoint === 0 ) {
  3660. return true;
  3661. }
  3662. const denominator = plane.normal.dot( this.direction );
  3663. if ( denominator * distToPoint < 0 ) {
  3664. return true;
  3665. }
  3666. // ray origin is behind the plane (and is pointing behind it)
  3667. return false;
  3668. }
  3669. intersectBox( box, target ) {
  3670. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3671. const invdirx = 1 / this.direction.x,
  3672. invdiry = 1 / this.direction.y,
  3673. invdirz = 1 / this.direction.z;
  3674. const origin = this.origin;
  3675. if ( invdirx >= 0 ) {
  3676. tmin = ( box.min.x - origin.x ) * invdirx;
  3677. tmax = ( box.max.x - origin.x ) * invdirx;
  3678. } else {
  3679. tmin = ( box.max.x - origin.x ) * invdirx;
  3680. tmax = ( box.min.x - origin.x ) * invdirx;
  3681. }
  3682. if ( invdiry >= 0 ) {
  3683. tymin = ( box.min.y - origin.y ) * invdiry;
  3684. tymax = ( box.max.y - origin.y ) * invdiry;
  3685. } else {
  3686. tymin = ( box.max.y - origin.y ) * invdiry;
  3687. tymax = ( box.min.y - origin.y ) * invdiry;
  3688. }
  3689. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3690. // These lines also handle the case where tmin or tmax is NaN
  3691. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3692. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3693. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3694. if ( invdirz >= 0 ) {
  3695. tzmin = ( box.min.z - origin.z ) * invdirz;
  3696. tzmax = ( box.max.z - origin.z ) * invdirz;
  3697. } else {
  3698. tzmin = ( box.max.z - origin.z ) * invdirz;
  3699. tzmax = ( box.min.z - origin.z ) * invdirz;
  3700. }
  3701. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3702. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3703. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3704. //return point closest to the ray (positive side)
  3705. if ( tmax < 0 ) return null;
  3706. return this.at( tmin >= 0 ? tmin : tmax, target );
  3707. }
  3708. intersectsBox( box ) {
  3709. return this.intersectBox( box, _vector$a ) !== null;
  3710. }
  3711. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3712. // Compute the offset origin, edges, and normal.
  3713. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3714. _edge1.subVectors( b, a );
  3715. _edge2.subVectors( c, a );
  3716. _normal$1.crossVectors( _edge1, _edge2 );
  3717. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3718. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3719. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3720. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3721. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3722. let DdN = this.direction.dot( _normal$1 );
  3723. let sign;
  3724. if ( DdN > 0 ) {
  3725. if ( backfaceCulling ) return null;
  3726. sign = 1;
  3727. } else if ( DdN < 0 ) {
  3728. sign = - 1;
  3729. DdN = - DdN;
  3730. } else {
  3731. return null;
  3732. }
  3733. _diff.subVectors( this.origin, a );
  3734. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3735. // b1 < 0, no intersection
  3736. if ( DdQxE2 < 0 ) {
  3737. return null;
  3738. }
  3739. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3740. // b2 < 0, no intersection
  3741. if ( DdE1xQ < 0 ) {
  3742. return null;
  3743. }
  3744. // b1+b2 > 1, no intersection
  3745. if ( DdQxE2 + DdE1xQ > DdN ) {
  3746. return null;
  3747. }
  3748. // Line intersects triangle, check if ray does.
  3749. const QdN = - sign * _diff.dot( _normal$1 );
  3750. // t < 0, no intersection
  3751. if ( QdN < 0 ) {
  3752. return null;
  3753. }
  3754. // Ray intersects triangle.
  3755. return this.at( QdN / DdN, target );
  3756. }
  3757. applyMatrix4( matrix4 ) {
  3758. this.origin.applyMatrix4( matrix4 );
  3759. this.direction.transformDirection( matrix4 );
  3760. return this;
  3761. }
  3762. equals( ray ) {
  3763. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3764. }
  3765. clone() {
  3766. return new this.constructor().copy( this );
  3767. }
  3768. }
  3769. class Matrix4 {
  3770. constructor() {
  3771. this.elements = [
  3772. 1, 0, 0, 0,
  3773. 0, 1, 0, 0,
  3774. 0, 0, 1, 0,
  3775. 0, 0, 0, 1
  3776. ];
  3777. if ( arguments.length > 0 ) {
  3778. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3779. }
  3780. }
  3781. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3782. const te = this.elements;
  3783. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3784. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3785. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3786. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3787. return this;
  3788. }
  3789. identity() {
  3790. this.set(
  3791. 1, 0, 0, 0,
  3792. 0, 1, 0, 0,
  3793. 0, 0, 1, 0,
  3794. 0, 0, 0, 1
  3795. );
  3796. return this;
  3797. }
  3798. clone() {
  3799. return new Matrix4().fromArray( this.elements );
  3800. }
  3801. copy( m ) {
  3802. const te = this.elements;
  3803. const me = m.elements;
  3804. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3805. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3806. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3807. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3808. return this;
  3809. }
  3810. copyPosition( m ) {
  3811. const te = this.elements, me = m.elements;
  3812. te[ 12 ] = me[ 12 ];
  3813. te[ 13 ] = me[ 13 ];
  3814. te[ 14 ] = me[ 14 ];
  3815. return this;
  3816. }
  3817. setFromMatrix3( m ) {
  3818. const me = m.elements;
  3819. this.set(
  3820. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3821. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3822. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3823. 0, 0, 0, 1
  3824. );
  3825. return this;
  3826. }
  3827. extractBasis( xAxis, yAxis, zAxis ) {
  3828. xAxis.setFromMatrixColumn( this, 0 );
  3829. yAxis.setFromMatrixColumn( this, 1 );
  3830. zAxis.setFromMatrixColumn( this, 2 );
  3831. return this;
  3832. }
  3833. makeBasis( xAxis, yAxis, zAxis ) {
  3834. this.set(
  3835. xAxis.x, yAxis.x, zAxis.x, 0,
  3836. xAxis.y, yAxis.y, zAxis.y, 0,
  3837. xAxis.z, yAxis.z, zAxis.z, 0,
  3838. 0, 0, 0, 1
  3839. );
  3840. return this;
  3841. }
  3842. extractRotation( m ) {
  3843. // this method does not support reflection matrices
  3844. const te = this.elements;
  3845. const me = m.elements;
  3846. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3847. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3848. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3849. te[ 0 ] = me[ 0 ] * scaleX;
  3850. te[ 1 ] = me[ 1 ] * scaleX;
  3851. te[ 2 ] = me[ 2 ] * scaleX;
  3852. te[ 3 ] = 0;
  3853. te[ 4 ] = me[ 4 ] * scaleY;
  3854. te[ 5 ] = me[ 5 ] * scaleY;
  3855. te[ 6 ] = me[ 6 ] * scaleY;
  3856. te[ 7 ] = 0;
  3857. te[ 8 ] = me[ 8 ] * scaleZ;
  3858. te[ 9 ] = me[ 9 ] * scaleZ;
  3859. te[ 10 ] = me[ 10 ] * scaleZ;
  3860. te[ 11 ] = 0;
  3861. te[ 12 ] = 0;
  3862. te[ 13 ] = 0;
  3863. te[ 14 ] = 0;
  3864. te[ 15 ] = 1;
  3865. return this;
  3866. }
  3867. makeRotationFromEuler( euler ) {
  3868. if ( ! ( euler && euler.isEuler ) ) {
  3869. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3870. }
  3871. const te = this.elements;
  3872. const x = euler.x, y = euler.y, z = euler.z;
  3873. const a = Math.cos( x ), b = Math.sin( x );
  3874. const c = Math.cos( y ), d = Math.sin( y );
  3875. const e = Math.cos( z ), f = Math.sin( z );
  3876. if ( euler.order === 'XYZ' ) {
  3877. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3878. te[ 0 ] = c * e;
  3879. te[ 4 ] = - c * f;
  3880. te[ 8 ] = d;
  3881. te[ 1 ] = af + be * d;
  3882. te[ 5 ] = ae - bf * d;
  3883. te[ 9 ] = - b * c;
  3884. te[ 2 ] = bf - ae * d;
  3885. te[ 6 ] = be + af * d;
  3886. te[ 10 ] = a * c;
  3887. } else if ( euler.order === 'YXZ' ) {
  3888. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3889. te[ 0 ] = ce + df * b;
  3890. te[ 4 ] = de * b - cf;
  3891. te[ 8 ] = a * d;
  3892. te[ 1 ] = a * f;
  3893. te[ 5 ] = a * e;
  3894. te[ 9 ] = - b;
  3895. te[ 2 ] = cf * b - de;
  3896. te[ 6 ] = df + ce * b;
  3897. te[ 10 ] = a * c;
  3898. } else if ( euler.order === 'ZXY' ) {
  3899. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3900. te[ 0 ] = ce - df * b;
  3901. te[ 4 ] = - a * f;
  3902. te[ 8 ] = de + cf * b;
  3903. te[ 1 ] = cf + de * b;
  3904. te[ 5 ] = a * e;
  3905. te[ 9 ] = df - ce * b;
  3906. te[ 2 ] = - a * d;
  3907. te[ 6 ] = b;
  3908. te[ 10 ] = a * c;
  3909. } else if ( euler.order === 'ZYX' ) {
  3910. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3911. te[ 0 ] = c * e;
  3912. te[ 4 ] = be * d - af;
  3913. te[ 8 ] = ae * d + bf;
  3914. te[ 1 ] = c * f;
  3915. te[ 5 ] = bf * d + ae;
  3916. te[ 9 ] = af * d - be;
  3917. te[ 2 ] = - d;
  3918. te[ 6 ] = b * c;
  3919. te[ 10 ] = a * c;
  3920. } else if ( euler.order === 'YZX' ) {
  3921. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3922. te[ 0 ] = c * e;
  3923. te[ 4 ] = bd - ac * f;
  3924. te[ 8 ] = bc * f + ad;
  3925. te[ 1 ] = f;
  3926. te[ 5 ] = a * e;
  3927. te[ 9 ] = - b * e;
  3928. te[ 2 ] = - d * e;
  3929. te[ 6 ] = ad * f + bc;
  3930. te[ 10 ] = ac - bd * f;
  3931. } else if ( euler.order === 'XZY' ) {
  3932. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3933. te[ 0 ] = c * e;
  3934. te[ 4 ] = - f;
  3935. te[ 8 ] = d * e;
  3936. te[ 1 ] = ac * f + bd;
  3937. te[ 5 ] = a * e;
  3938. te[ 9 ] = ad * f - bc;
  3939. te[ 2 ] = bc * f - ad;
  3940. te[ 6 ] = b * e;
  3941. te[ 10 ] = bd * f + ac;
  3942. }
  3943. // bottom row
  3944. te[ 3 ] = 0;
  3945. te[ 7 ] = 0;
  3946. te[ 11 ] = 0;
  3947. // last column
  3948. te[ 12 ] = 0;
  3949. te[ 13 ] = 0;
  3950. te[ 14 ] = 0;
  3951. te[ 15 ] = 1;
  3952. return this;
  3953. }
  3954. makeRotationFromQuaternion( q ) {
  3955. return this.compose( _zero, q, _one );
  3956. }
  3957. lookAt( eye, target, up ) {
  3958. const te = this.elements;
  3959. _z.subVectors( eye, target );
  3960. if ( _z.lengthSq() === 0 ) {
  3961. // eye and target are in the same position
  3962. _z.z = 1;
  3963. }
  3964. _z.normalize();
  3965. _x.crossVectors( up, _z );
  3966. if ( _x.lengthSq() === 0 ) {
  3967. // up and z are parallel
  3968. if ( Math.abs( up.z ) === 1 ) {
  3969. _z.x += 0.0001;
  3970. } else {
  3971. _z.z += 0.0001;
  3972. }
  3973. _z.normalize();
  3974. _x.crossVectors( up, _z );
  3975. }
  3976. _x.normalize();
  3977. _y.crossVectors( _z, _x );
  3978. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3979. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3980. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3981. return this;
  3982. }
  3983. multiply( m, n ) {
  3984. if ( n !== undefined ) {
  3985. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3986. return this.multiplyMatrices( m, n );
  3987. }
  3988. return this.multiplyMatrices( this, m );
  3989. }
  3990. premultiply( m ) {
  3991. return this.multiplyMatrices( m, this );
  3992. }
  3993. multiplyMatrices( a, b ) {
  3994. const ae = a.elements;
  3995. const be = b.elements;
  3996. const te = this.elements;
  3997. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3998. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3999. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4000. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4001. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4002. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4003. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4004. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4005. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4006. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4007. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4008. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4009. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4010. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4011. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4012. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4013. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4014. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4015. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4016. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4017. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4018. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4019. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4020. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4021. return this;
  4022. }
  4023. multiplyScalar( s ) {
  4024. const te = this.elements;
  4025. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4026. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4027. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4028. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4029. return this;
  4030. }
  4031. determinant() {
  4032. const te = this.elements;
  4033. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4034. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4035. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4036. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4037. //TODO: make this more efficient
  4038. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4039. return (
  4040. n41 * (
  4041. + n14 * n23 * n32
  4042. - n13 * n24 * n32
  4043. - n14 * n22 * n33
  4044. + n12 * n24 * n33
  4045. + n13 * n22 * n34
  4046. - n12 * n23 * n34
  4047. ) +
  4048. n42 * (
  4049. + n11 * n23 * n34
  4050. - n11 * n24 * n33
  4051. + n14 * n21 * n33
  4052. - n13 * n21 * n34
  4053. + n13 * n24 * n31
  4054. - n14 * n23 * n31
  4055. ) +
  4056. n43 * (
  4057. + n11 * n24 * n32
  4058. - n11 * n22 * n34
  4059. - n14 * n21 * n32
  4060. + n12 * n21 * n34
  4061. + n14 * n22 * n31
  4062. - n12 * n24 * n31
  4063. ) +
  4064. n44 * (
  4065. - n13 * n22 * n31
  4066. - n11 * n23 * n32
  4067. + n11 * n22 * n33
  4068. + n13 * n21 * n32
  4069. - n12 * n21 * n33
  4070. + n12 * n23 * n31
  4071. )
  4072. );
  4073. }
  4074. transpose() {
  4075. const te = this.elements;
  4076. let tmp;
  4077. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4078. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4079. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4080. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4081. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4082. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4083. return this;
  4084. }
  4085. setPosition( x, y, z ) {
  4086. const te = this.elements;
  4087. if ( x.isVector3 ) {
  4088. te[ 12 ] = x.x;
  4089. te[ 13 ] = x.y;
  4090. te[ 14 ] = x.z;
  4091. } else {
  4092. te[ 12 ] = x;
  4093. te[ 13 ] = y;
  4094. te[ 14 ] = z;
  4095. }
  4096. return this;
  4097. }
  4098. invert() {
  4099. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4100. const te = this.elements,
  4101. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4102. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4103. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4104. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4105. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4106. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4107. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4108. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4109. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4110. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4111. const detInv = 1 / det;
  4112. te[ 0 ] = t11 * detInv;
  4113. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4114. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4115. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4116. te[ 4 ] = t12 * detInv;
  4117. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4118. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4119. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4120. te[ 8 ] = t13 * detInv;
  4121. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4122. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4123. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4124. te[ 12 ] = t14 * detInv;
  4125. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4126. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4127. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4128. return this;
  4129. }
  4130. scale( v ) {
  4131. const te = this.elements;
  4132. const x = v.x, y = v.y, z = v.z;
  4133. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4134. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4135. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4136. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4137. return this;
  4138. }
  4139. getMaxScaleOnAxis() {
  4140. const te = this.elements;
  4141. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4142. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4143. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4144. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4145. }
  4146. makeTranslation( x, y, z ) {
  4147. this.set(
  4148. 1, 0, 0, x,
  4149. 0, 1, 0, y,
  4150. 0, 0, 1, z,
  4151. 0, 0, 0, 1
  4152. );
  4153. return this;
  4154. }
  4155. makeRotationX( theta ) {
  4156. const c = Math.cos( theta ), s = Math.sin( theta );
  4157. this.set(
  4158. 1, 0, 0, 0,
  4159. 0, c, - s, 0,
  4160. 0, s, c, 0,
  4161. 0, 0, 0, 1
  4162. );
  4163. return this;
  4164. }
  4165. makeRotationY( theta ) {
  4166. const c = Math.cos( theta ), s = Math.sin( theta );
  4167. this.set(
  4168. c, 0, s, 0,
  4169. 0, 1, 0, 0,
  4170. - s, 0, c, 0,
  4171. 0, 0, 0, 1
  4172. );
  4173. return this;
  4174. }
  4175. makeRotationZ( theta ) {
  4176. const c = Math.cos( theta ), s = Math.sin( theta );
  4177. this.set(
  4178. c, - s, 0, 0,
  4179. s, c, 0, 0,
  4180. 0, 0, 1, 0,
  4181. 0, 0, 0, 1
  4182. );
  4183. return this;
  4184. }
  4185. makeRotationAxis( axis, angle ) {
  4186. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4187. const c = Math.cos( angle );
  4188. const s = Math.sin( angle );
  4189. const t = 1 - c;
  4190. const x = axis.x, y = axis.y, z = axis.z;
  4191. const tx = t * x, ty = t * y;
  4192. this.set(
  4193. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4194. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4195. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4196. 0, 0, 0, 1
  4197. );
  4198. return this;
  4199. }
  4200. makeScale( x, y, z ) {
  4201. this.set(
  4202. x, 0, 0, 0,
  4203. 0, y, 0, 0,
  4204. 0, 0, z, 0,
  4205. 0, 0, 0, 1
  4206. );
  4207. return this;
  4208. }
  4209. makeShear( xy, xz, yx, yz, zx, zy ) {
  4210. this.set(
  4211. 1, yx, zx, 0,
  4212. xy, 1, zy, 0,
  4213. xz, yz, 1, 0,
  4214. 0, 0, 0, 1
  4215. );
  4216. return this;
  4217. }
  4218. compose( position, quaternion, scale ) {
  4219. const te = this.elements;
  4220. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4221. const x2 = x + x, y2 = y + y, z2 = z + z;
  4222. const xx = x * x2, xy = x * y2, xz = x * z2;
  4223. const yy = y * y2, yz = y * z2, zz = z * z2;
  4224. const wx = w * x2, wy = w * y2, wz = w * z2;
  4225. const sx = scale.x, sy = scale.y, sz = scale.z;
  4226. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4227. te[ 1 ] = ( xy + wz ) * sx;
  4228. te[ 2 ] = ( xz - wy ) * sx;
  4229. te[ 3 ] = 0;
  4230. te[ 4 ] = ( xy - wz ) * sy;
  4231. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4232. te[ 6 ] = ( yz + wx ) * sy;
  4233. te[ 7 ] = 0;
  4234. te[ 8 ] = ( xz + wy ) * sz;
  4235. te[ 9 ] = ( yz - wx ) * sz;
  4236. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4237. te[ 11 ] = 0;
  4238. te[ 12 ] = position.x;
  4239. te[ 13 ] = position.y;
  4240. te[ 14 ] = position.z;
  4241. te[ 15 ] = 1;
  4242. return this;
  4243. }
  4244. decompose( position, quaternion, scale ) {
  4245. const te = this.elements;
  4246. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4247. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4248. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4249. // if determine is negative, we need to invert one scale
  4250. const det = this.determinant();
  4251. if ( det < 0 ) sx = - sx;
  4252. position.x = te[ 12 ];
  4253. position.y = te[ 13 ];
  4254. position.z = te[ 14 ];
  4255. // scale the rotation part
  4256. _m1$2.copy( this );
  4257. const invSX = 1 / sx;
  4258. const invSY = 1 / sy;
  4259. const invSZ = 1 / sz;
  4260. _m1$2.elements[ 0 ] *= invSX;
  4261. _m1$2.elements[ 1 ] *= invSX;
  4262. _m1$2.elements[ 2 ] *= invSX;
  4263. _m1$2.elements[ 4 ] *= invSY;
  4264. _m1$2.elements[ 5 ] *= invSY;
  4265. _m1$2.elements[ 6 ] *= invSY;
  4266. _m1$2.elements[ 8 ] *= invSZ;
  4267. _m1$2.elements[ 9 ] *= invSZ;
  4268. _m1$2.elements[ 10 ] *= invSZ;
  4269. quaternion.setFromRotationMatrix( _m1$2 );
  4270. scale.x = sx;
  4271. scale.y = sy;
  4272. scale.z = sz;
  4273. return this;
  4274. }
  4275. makePerspective( left, right, top, bottom, near, far ) {
  4276. if ( far === undefined ) {
  4277. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4278. }
  4279. const te = this.elements;
  4280. const x = 2 * near / ( right - left );
  4281. const y = 2 * near / ( top - bottom );
  4282. const a = ( right + left ) / ( right - left );
  4283. const b = ( top + bottom ) / ( top - bottom );
  4284. const c = - ( far + near ) / ( far - near );
  4285. const d = - 2 * far * near / ( far - near );
  4286. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4287. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4288. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4289. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4290. return this;
  4291. }
  4292. makeOrthographic( left, right, top, bottom, near, far ) {
  4293. const te = this.elements;
  4294. const w = 1.0 / ( right - left );
  4295. const h = 1.0 / ( top - bottom );
  4296. const p = 1.0 / ( far - near );
  4297. const x = ( right + left ) * w;
  4298. const y = ( top + bottom ) * h;
  4299. const z = ( far + near ) * p;
  4300. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4301. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4302. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4303. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4304. return this;
  4305. }
  4306. equals( matrix ) {
  4307. const te = this.elements;
  4308. const me = matrix.elements;
  4309. for ( let i = 0; i < 16; i ++ ) {
  4310. if ( te[ i ] !== me[ i ] ) return false;
  4311. }
  4312. return true;
  4313. }
  4314. fromArray( array, offset = 0 ) {
  4315. for ( let i = 0; i < 16; i ++ ) {
  4316. this.elements[ i ] = array[ i + offset ];
  4317. }
  4318. return this;
  4319. }
  4320. toArray( array = [], offset = 0 ) {
  4321. const te = this.elements;
  4322. array[ offset ] = te[ 0 ];
  4323. array[ offset + 1 ] = te[ 1 ];
  4324. array[ offset + 2 ] = te[ 2 ];
  4325. array[ offset + 3 ] = te[ 3 ];
  4326. array[ offset + 4 ] = te[ 4 ];
  4327. array[ offset + 5 ] = te[ 5 ];
  4328. array[ offset + 6 ] = te[ 6 ];
  4329. array[ offset + 7 ] = te[ 7 ];
  4330. array[ offset + 8 ] = te[ 8 ];
  4331. array[ offset + 9 ] = te[ 9 ];
  4332. array[ offset + 10 ] = te[ 10 ];
  4333. array[ offset + 11 ] = te[ 11 ];
  4334. array[ offset + 12 ] = te[ 12 ];
  4335. array[ offset + 13 ] = te[ 13 ];
  4336. array[ offset + 14 ] = te[ 14 ];
  4337. array[ offset + 15 ] = te[ 15 ];
  4338. return array;
  4339. }
  4340. }
  4341. Matrix4.prototype.isMatrix4 = true;
  4342. const _v1$5 = /*@__PURE__*/ new Vector3();
  4343. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4344. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4345. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4346. const _x = /*@__PURE__*/ new Vector3();
  4347. const _y = /*@__PURE__*/ new Vector3();
  4348. const _z = /*@__PURE__*/ new Vector3();
  4349. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4350. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4351. class Euler {
  4352. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4353. this._x = x;
  4354. this._y = y;
  4355. this._z = z;
  4356. this._order = order;
  4357. }
  4358. get x() {
  4359. return this._x;
  4360. }
  4361. set x( value ) {
  4362. this._x = value;
  4363. this._onChangeCallback();
  4364. }
  4365. get y() {
  4366. return this._y;
  4367. }
  4368. set y( value ) {
  4369. this._y = value;
  4370. this._onChangeCallback();
  4371. }
  4372. get z() {
  4373. return this._z;
  4374. }
  4375. set z( value ) {
  4376. this._z = value;
  4377. this._onChangeCallback();
  4378. }
  4379. get order() {
  4380. return this._order;
  4381. }
  4382. set order( value ) {
  4383. this._order = value;
  4384. this._onChangeCallback();
  4385. }
  4386. set( x, y, z, order = this._order ) {
  4387. this._x = x;
  4388. this._y = y;
  4389. this._z = z;
  4390. this._order = order;
  4391. this._onChangeCallback();
  4392. return this;
  4393. }
  4394. clone() {
  4395. return new this.constructor( this._x, this._y, this._z, this._order );
  4396. }
  4397. copy( euler ) {
  4398. this._x = euler._x;
  4399. this._y = euler._y;
  4400. this._z = euler._z;
  4401. this._order = euler._order;
  4402. this._onChangeCallback();
  4403. return this;
  4404. }
  4405. setFromRotationMatrix( m, order = this._order, update = true ) {
  4406. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4407. const te = m.elements;
  4408. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4409. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4410. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4411. switch ( order ) {
  4412. case 'XYZ':
  4413. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4414. if ( Math.abs( m13 ) < 0.9999999 ) {
  4415. this._x = Math.atan2( - m23, m33 );
  4416. this._z = Math.atan2( - m12, m11 );
  4417. } else {
  4418. this._x = Math.atan2( m32, m22 );
  4419. this._z = 0;
  4420. }
  4421. break;
  4422. case 'YXZ':
  4423. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4424. if ( Math.abs( m23 ) < 0.9999999 ) {
  4425. this._y = Math.atan2( m13, m33 );
  4426. this._z = Math.atan2( m21, m22 );
  4427. } else {
  4428. this._y = Math.atan2( - m31, m11 );
  4429. this._z = 0;
  4430. }
  4431. break;
  4432. case 'ZXY':
  4433. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4434. if ( Math.abs( m32 ) < 0.9999999 ) {
  4435. this._y = Math.atan2( - m31, m33 );
  4436. this._z = Math.atan2( - m12, m22 );
  4437. } else {
  4438. this._y = 0;
  4439. this._z = Math.atan2( m21, m11 );
  4440. }
  4441. break;
  4442. case 'ZYX':
  4443. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4444. if ( Math.abs( m31 ) < 0.9999999 ) {
  4445. this._x = Math.atan2( m32, m33 );
  4446. this._z = Math.atan2( m21, m11 );
  4447. } else {
  4448. this._x = 0;
  4449. this._z = Math.atan2( - m12, m22 );
  4450. }
  4451. break;
  4452. case 'YZX':
  4453. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4454. if ( Math.abs( m21 ) < 0.9999999 ) {
  4455. this._x = Math.atan2( - m23, m22 );
  4456. this._y = Math.atan2( - m31, m11 );
  4457. } else {
  4458. this._x = 0;
  4459. this._y = Math.atan2( m13, m33 );
  4460. }
  4461. break;
  4462. case 'XZY':
  4463. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4464. if ( Math.abs( m12 ) < 0.9999999 ) {
  4465. this._x = Math.atan2( m32, m22 );
  4466. this._y = Math.atan2( m13, m11 );
  4467. } else {
  4468. this._x = Math.atan2( - m23, m33 );
  4469. this._y = 0;
  4470. }
  4471. break;
  4472. default:
  4473. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4474. }
  4475. this._order = order;
  4476. if ( update === true ) this._onChangeCallback();
  4477. return this;
  4478. }
  4479. setFromQuaternion( q, order, update ) {
  4480. _matrix$1.makeRotationFromQuaternion( q );
  4481. return this.setFromRotationMatrix( _matrix$1, order, update );
  4482. }
  4483. setFromVector3( v, order = this._order ) {
  4484. return this.set( v.x, v.y, v.z, order );
  4485. }
  4486. reorder( newOrder ) {
  4487. // WARNING: this discards revolution information -bhouston
  4488. _quaternion$3.setFromEuler( this );
  4489. return this.setFromQuaternion( _quaternion$3, newOrder );
  4490. }
  4491. equals( euler ) {
  4492. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4493. }
  4494. fromArray( array ) {
  4495. this._x = array[ 0 ];
  4496. this._y = array[ 1 ];
  4497. this._z = array[ 2 ];
  4498. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4499. this._onChangeCallback();
  4500. return this;
  4501. }
  4502. toArray( array = [], offset = 0 ) {
  4503. array[ offset ] = this._x;
  4504. array[ offset + 1 ] = this._y;
  4505. array[ offset + 2 ] = this._z;
  4506. array[ offset + 3 ] = this._order;
  4507. return array;
  4508. }
  4509. _onChange( callback ) {
  4510. this._onChangeCallback = callback;
  4511. return this;
  4512. }
  4513. _onChangeCallback() {}
  4514. *[ Symbol.iterator ]() {
  4515. yield this._x;
  4516. yield this._y;
  4517. yield this._z;
  4518. yield this._order;
  4519. }
  4520. }
  4521. Euler.prototype.isEuler = true;
  4522. Euler.DefaultOrder = 'XYZ';
  4523. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4524. class Layers {
  4525. constructor() {
  4526. this.mask = 1 | 0;
  4527. }
  4528. set( channel ) {
  4529. this.mask = ( 1 << channel | 0 ) >>> 0;
  4530. }
  4531. enable( channel ) {
  4532. this.mask |= 1 << channel | 0;
  4533. }
  4534. enableAll() {
  4535. this.mask = 0xffffffff | 0;
  4536. }
  4537. toggle( channel ) {
  4538. this.mask ^= 1 << channel | 0;
  4539. }
  4540. disable( channel ) {
  4541. this.mask &= ~ ( 1 << channel | 0 );
  4542. }
  4543. disableAll() {
  4544. this.mask = 0;
  4545. }
  4546. test( layers ) {
  4547. return ( this.mask & layers.mask ) !== 0;
  4548. }
  4549. isEnabled( channel ) {
  4550. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4551. }
  4552. }
  4553. let _object3DId = 0;
  4554. const _v1$4 = /*@__PURE__*/ new Vector3();
  4555. const _q1 = /*@__PURE__*/ new Quaternion();
  4556. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4557. const _target = /*@__PURE__*/ new Vector3();
  4558. const _position$3 = /*@__PURE__*/ new Vector3();
  4559. const _scale$2 = /*@__PURE__*/ new Vector3();
  4560. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4561. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4562. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4563. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4564. const _addedEvent = { type: 'added' };
  4565. const _removedEvent = { type: 'removed' };
  4566. class Object3D extends EventDispatcher {
  4567. constructor() {
  4568. super();
  4569. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4570. this.uuid = generateUUID();
  4571. this.name = '';
  4572. this.type = 'Object3D';
  4573. this.parent = null;
  4574. this.children = [];
  4575. this.up = Object3D.DefaultUp.clone();
  4576. const position = new Vector3();
  4577. const rotation = new Euler();
  4578. const quaternion = new Quaternion();
  4579. const scale = new Vector3( 1, 1, 1 );
  4580. function onRotationChange() {
  4581. quaternion.setFromEuler( rotation, false );
  4582. }
  4583. function onQuaternionChange() {
  4584. rotation.setFromQuaternion( quaternion, undefined, false );
  4585. }
  4586. rotation._onChange( onRotationChange );
  4587. quaternion._onChange( onQuaternionChange );
  4588. Object.defineProperties( this, {
  4589. position: {
  4590. configurable: true,
  4591. enumerable: true,
  4592. value: position
  4593. },
  4594. rotation: {
  4595. configurable: true,
  4596. enumerable: true,
  4597. value: rotation
  4598. },
  4599. quaternion: {
  4600. configurable: true,
  4601. enumerable: true,
  4602. value: quaternion
  4603. },
  4604. scale: {
  4605. configurable: true,
  4606. enumerable: true,
  4607. value: scale
  4608. },
  4609. modelViewMatrix: {
  4610. value: new Matrix4()
  4611. },
  4612. normalMatrix: {
  4613. value: new Matrix3()
  4614. }
  4615. } );
  4616. this.matrix = new Matrix4();
  4617. this.matrixWorld = new Matrix4();
  4618. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4619. this.matrixWorldNeedsUpdate = false;
  4620. this.layers = new Layers();
  4621. this.visible = true;
  4622. this.castShadow = false;
  4623. this.receiveShadow = false;
  4624. this.frustumCulled = true;
  4625. this.renderOrder = 0;
  4626. this.animations = [];
  4627. this.userData = {};
  4628. }
  4629. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4630. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4631. applyMatrix4( matrix ) {
  4632. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4633. this.matrix.premultiply( matrix );
  4634. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4635. }
  4636. applyQuaternion( q ) {
  4637. this.quaternion.premultiply( q );
  4638. return this;
  4639. }
  4640. setRotationFromAxisAngle( axis, angle ) {
  4641. // assumes axis is normalized
  4642. this.quaternion.setFromAxisAngle( axis, angle );
  4643. }
  4644. setRotationFromEuler( euler ) {
  4645. this.quaternion.setFromEuler( euler, true );
  4646. }
  4647. setRotationFromMatrix( m ) {
  4648. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4649. this.quaternion.setFromRotationMatrix( m );
  4650. }
  4651. setRotationFromQuaternion( q ) {
  4652. // assumes q is normalized
  4653. this.quaternion.copy( q );
  4654. }
  4655. rotateOnAxis( axis, angle ) {
  4656. // rotate object on axis in object space
  4657. // axis is assumed to be normalized
  4658. _q1.setFromAxisAngle( axis, angle );
  4659. this.quaternion.multiply( _q1 );
  4660. return this;
  4661. }
  4662. rotateOnWorldAxis( axis, angle ) {
  4663. // rotate object on axis in world space
  4664. // axis is assumed to be normalized
  4665. // method assumes no rotated parent
  4666. _q1.setFromAxisAngle( axis, angle );
  4667. this.quaternion.premultiply( _q1 );
  4668. return this;
  4669. }
  4670. rotateX( angle ) {
  4671. return this.rotateOnAxis( _xAxis, angle );
  4672. }
  4673. rotateY( angle ) {
  4674. return this.rotateOnAxis( _yAxis, angle );
  4675. }
  4676. rotateZ( angle ) {
  4677. return this.rotateOnAxis( _zAxis, angle );
  4678. }
  4679. translateOnAxis( axis, distance ) {
  4680. // translate object by distance along axis in object space
  4681. // axis is assumed to be normalized
  4682. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4683. this.position.add( _v1$4.multiplyScalar( distance ) );
  4684. return this;
  4685. }
  4686. translateX( distance ) {
  4687. return this.translateOnAxis( _xAxis, distance );
  4688. }
  4689. translateY( distance ) {
  4690. return this.translateOnAxis( _yAxis, distance );
  4691. }
  4692. translateZ( distance ) {
  4693. return this.translateOnAxis( _zAxis, distance );
  4694. }
  4695. localToWorld( vector ) {
  4696. return vector.applyMatrix4( this.matrixWorld );
  4697. }
  4698. worldToLocal( vector ) {
  4699. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4700. }
  4701. lookAt( x, y, z ) {
  4702. // This method does not support objects having non-uniformly-scaled parent(s)
  4703. if ( x.isVector3 ) {
  4704. _target.copy( x );
  4705. } else {
  4706. _target.set( x, y, z );
  4707. }
  4708. const parent = this.parent;
  4709. this.updateWorldMatrix( true, false );
  4710. _position$3.setFromMatrixPosition( this.matrixWorld );
  4711. if ( this.isCamera || this.isLight ) {
  4712. _m1$1.lookAt( _position$3, _target, this.up );
  4713. } else {
  4714. _m1$1.lookAt( _target, _position$3, this.up );
  4715. }
  4716. this.quaternion.setFromRotationMatrix( _m1$1 );
  4717. if ( parent ) {
  4718. _m1$1.extractRotation( parent.matrixWorld );
  4719. _q1.setFromRotationMatrix( _m1$1 );
  4720. this.quaternion.premultiply( _q1.invert() );
  4721. }
  4722. }
  4723. add( object ) {
  4724. if ( arguments.length > 1 ) {
  4725. for ( let i = 0; i < arguments.length; i ++ ) {
  4726. this.add( arguments[ i ] );
  4727. }
  4728. return this;
  4729. }
  4730. if ( object === this ) {
  4731. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4732. return this;
  4733. }
  4734. if ( object && object.isObject3D ) {
  4735. if ( object.parent !== null ) {
  4736. object.parent.remove( object );
  4737. }
  4738. object.parent = this;
  4739. this.children.push( object );
  4740. object.dispatchEvent( _addedEvent );
  4741. } else {
  4742. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4743. }
  4744. return this;
  4745. }
  4746. remove( object ) {
  4747. if ( arguments.length > 1 ) {
  4748. for ( let i = 0; i < arguments.length; i ++ ) {
  4749. this.remove( arguments[ i ] );
  4750. }
  4751. return this;
  4752. }
  4753. const index = this.children.indexOf( object );
  4754. if ( index !== - 1 ) {
  4755. object.parent = null;
  4756. this.children.splice( index, 1 );
  4757. object.dispatchEvent( _removedEvent );
  4758. }
  4759. return this;
  4760. }
  4761. removeFromParent() {
  4762. const parent = this.parent;
  4763. if ( parent !== null ) {
  4764. parent.remove( this );
  4765. }
  4766. return this;
  4767. }
  4768. clear() {
  4769. for ( let i = 0; i < this.children.length; i ++ ) {
  4770. const object = this.children[ i ];
  4771. object.parent = null;
  4772. object.dispatchEvent( _removedEvent );
  4773. }
  4774. this.children.length = 0;
  4775. return this;
  4776. }
  4777. attach( object ) {
  4778. // adds object as a child of this, while maintaining the object's world transform
  4779. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4780. this.updateWorldMatrix( true, false );
  4781. _m1$1.copy( this.matrixWorld ).invert();
  4782. if ( object.parent !== null ) {
  4783. object.parent.updateWorldMatrix( true, false );
  4784. _m1$1.multiply( object.parent.matrixWorld );
  4785. }
  4786. object.applyMatrix4( _m1$1 );
  4787. this.add( object );
  4788. object.updateWorldMatrix( false, true );
  4789. return this;
  4790. }
  4791. getObjectById( id ) {
  4792. return this.getObjectByProperty( 'id', id );
  4793. }
  4794. getObjectByName( name ) {
  4795. return this.getObjectByProperty( 'name', name );
  4796. }
  4797. getObjectByProperty( name, value ) {
  4798. if ( this[ name ] === value ) return this;
  4799. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4800. const child = this.children[ i ];
  4801. const object = child.getObjectByProperty( name, value );
  4802. if ( object !== undefined ) {
  4803. return object;
  4804. }
  4805. }
  4806. return undefined;
  4807. }
  4808. getWorldPosition( target ) {
  4809. this.updateWorldMatrix( true, false );
  4810. return target.setFromMatrixPosition( this.matrixWorld );
  4811. }
  4812. getWorldQuaternion( target ) {
  4813. this.updateWorldMatrix( true, false );
  4814. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4815. return target;
  4816. }
  4817. getWorldScale( target ) {
  4818. this.updateWorldMatrix( true, false );
  4819. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4820. return target;
  4821. }
  4822. getWorldDirection( target ) {
  4823. this.updateWorldMatrix( true, false );
  4824. const e = this.matrixWorld.elements;
  4825. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4826. }
  4827. raycast( /* raycaster, intersects */ ) {}
  4828. traverse( callback ) {
  4829. callback( this );
  4830. const children = this.children;
  4831. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4832. children[ i ].traverse( callback );
  4833. }
  4834. }
  4835. traverseVisible( callback ) {
  4836. if ( this.visible === false ) return;
  4837. callback( this );
  4838. const children = this.children;
  4839. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4840. children[ i ].traverseVisible( callback );
  4841. }
  4842. }
  4843. traverseAncestors( callback ) {
  4844. const parent = this.parent;
  4845. if ( parent !== null ) {
  4846. callback( parent );
  4847. parent.traverseAncestors( callback );
  4848. }
  4849. }
  4850. updateMatrix() {
  4851. this.matrix.compose( this.position, this.quaternion, this.scale );
  4852. this.matrixWorldNeedsUpdate = true;
  4853. }
  4854. updateMatrixWorld( force ) {
  4855. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4856. if ( this.matrixWorldNeedsUpdate || force ) {
  4857. if ( this.parent === null ) {
  4858. this.matrixWorld.copy( this.matrix );
  4859. } else {
  4860. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4861. }
  4862. this.matrixWorldNeedsUpdate = false;
  4863. force = true;
  4864. }
  4865. // update children
  4866. const children = this.children;
  4867. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4868. children[ i ].updateMatrixWorld( force );
  4869. }
  4870. }
  4871. updateWorldMatrix( updateParents, updateChildren ) {
  4872. const parent = this.parent;
  4873. if ( updateParents === true && parent !== null ) {
  4874. parent.updateWorldMatrix( true, false );
  4875. }
  4876. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4877. if ( this.parent === null ) {
  4878. this.matrixWorld.copy( this.matrix );
  4879. } else {
  4880. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4881. }
  4882. // update children
  4883. if ( updateChildren === true ) {
  4884. const children = this.children;
  4885. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4886. children[ i ].updateWorldMatrix( false, true );
  4887. }
  4888. }
  4889. }
  4890. toJSON( meta ) {
  4891. // meta is a string when called from JSON.stringify
  4892. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4893. const output = {};
  4894. // meta is a hash used to collect geometries, materials.
  4895. // not providing it implies that this is the root object
  4896. // being serialized.
  4897. if ( isRootObject ) {
  4898. // initialize meta obj
  4899. meta = {
  4900. geometries: {},
  4901. materials: {},
  4902. textures: {},
  4903. images: {},
  4904. shapes: {},
  4905. skeletons: {},
  4906. animations: {},
  4907. nodes: {}
  4908. };
  4909. output.metadata = {
  4910. version: 4.5,
  4911. type: 'Object',
  4912. generator: 'Object3D.toJSON'
  4913. };
  4914. }
  4915. // standard Object3D serialization
  4916. const object = {};
  4917. object.uuid = this.uuid;
  4918. object.type = this.type;
  4919. if ( this.name !== '' ) object.name = this.name;
  4920. if ( this.castShadow === true ) object.castShadow = true;
  4921. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4922. if ( this.visible === false ) object.visible = false;
  4923. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4924. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4925. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4926. object.layers = this.layers.mask;
  4927. object.matrix = this.matrix.toArray();
  4928. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4929. // object specific properties
  4930. if ( this.isInstancedMesh ) {
  4931. object.type = 'InstancedMesh';
  4932. object.count = this.count;
  4933. object.instanceMatrix = this.instanceMatrix.toJSON();
  4934. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4935. }
  4936. //
  4937. function serialize( library, element ) {
  4938. if ( library[ element.uuid ] === undefined ) {
  4939. library[ element.uuid ] = element.toJSON( meta );
  4940. }
  4941. return element.uuid;
  4942. }
  4943. if ( this.isScene ) {
  4944. if ( this.background ) {
  4945. if ( this.background.isColor ) {
  4946. object.background = this.background.toJSON();
  4947. } else if ( this.background.isTexture ) {
  4948. object.background = this.background.toJSON( meta ).uuid;
  4949. }
  4950. }
  4951. if ( this.environment && this.environment.isTexture ) {
  4952. object.environment = this.environment.toJSON( meta ).uuid;
  4953. }
  4954. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4955. object.geometry = serialize( meta.geometries, this.geometry );
  4956. const parameters = this.geometry.parameters;
  4957. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4958. const shapes = parameters.shapes;
  4959. if ( Array.isArray( shapes ) ) {
  4960. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4961. const shape = shapes[ i ];
  4962. serialize( meta.shapes, shape );
  4963. }
  4964. } else {
  4965. serialize( meta.shapes, shapes );
  4966. }
  4967. }
  4968. }
  4969. if ( this.isSkinnedMesh ) {
  4970. object.bindMode = this.bindMode;
  4971. object.bindMatrix = this.bindMatrix.toArray();
  4972. if ( this.skeleton !== undefined ) {
  4973. serialize( meta.skeletons, this.skeleton );
  4974. object.skeleton = this.skeleton.uuid;
  4975. }
  4976. }
  4977. if ( this.material !== undefined ) {
  4978. if ( Array.isArray( this.material ) ) {
  4979. const uuids = [];
  4980. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4981. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4982. }
  4983. object.material = uuids;
  4984. } else {
  4985. object.material = serialize( meta.materials, this.material );
  4986. }
  4987. }
  4988. //
  4989. if ( this.children.length > 0 ) {
  4990. object.children = [];
  4991. for ( let i = 0; i < this.children.length; i ++ ) {
  4992. object.children.push( this.children[ i ].toJSON( meta ).object );
  4993. }
  4994. }
  4995. //
  4996. if ( this.animations.length > 0 ) {
  4997. object.animations = [];
  4998. for ( let i = 0; i < this.animations.length; i ++ ) {
  4999. const animation = this.animations[ i ];
  5000. object.animations.push( serialize( meta.animations, animation ) );
  5001. }
  5002. }
  5003. if ( isRootObject ) {
  5004. const geometries = extractFromCache( meta.geometries );
  5005. const materials = extractFromCache( meta.materials );
  5006. const textures = extractFromCache( meta.textures );
  5007. const images = extractFromCache( meta.images );
  5008. const shapes = extractFromCache( meta.shapes );
  5009. const skeletons = extractFromCache( meta.skeletons );
  5010. const animations = extractFromCache( meta.animations );
  5011. const nodes = extractFromCache( meta.nodes );
  5012. if ( geometries.length > 0 ) output.geometries = geometries;
  5013. if ( materials.length > 0 ) output.materials = materials;
  5014. if ( textures.length > 0 ) output.textures = textures;
  5015. if ( images.length > 0 ) output.images = images;
  5016. if ( shapes.length > 0 ) output.shapes = shapes;
  5017. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  5018. if ( animations.length > 0 ) output.animations = animations;
  5019. if ( nodes.length > 0 ) output.nodes = nodes;
  5020. }
  5021. output.object = object;
  5022. return output;
  5023. // extract data from the cache hash
  5024. // remove metadata on each item
  5025. // and return as array
  5026. function extractFromCache( cache ) {
  5027. const values = [];
  5028. for ( const key in cache ) {
  5029. const data = cache[ key ];
  5030. delete data.metadata;
  5031. values.push( data );
  5032. }
  5033. return values;
  5034. }
  5035. }
  5036. clone( recursive ) {
  5037. return new this.constructor().copy( this, recursive );
  5038. }
  5039. copy( source, recursive = true ) {
  5040. this.name = source.name;
  5041. this.up.copy( source.up );
  5042. this.position.copy( source.position );
  5043. this.rotation.order = source.rotation.order;
  5044. this.quaternion.copy( source.quaternion );
  5045. this.scale.copy( source.scale );
  5046. this.matrix.copy( source.matrix );
  5047. this.matrixWorld.copy( source.matrixWorld );
  5048. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5049. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5050. this.layers.mask = source.layers.mask;
  5051. this.visible = source.visible;
  5052. this.castShadow = source.castShadow;
  5053. this.receiveShadow = source.receiveShadow;
  5054. this.frustumCulled = source.frustumCulled;
  5055. this.renderOrder = source.renderOrder;
  5056. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5057. if ( recursive === true ) {
  5058. for ( let i = 0; i < source.children.length; i ++ ) {
  5059. const child = source.children[ i ];
  5060. this.add( child.clone() );
  5061. }
  5062. }
  5063. return this;
  5064. }
  5065. }
  5066. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  5067. Object3D.DefaultMatrixAutoUpdate = true;
  5068. Object3D.prototype.isObject3D = true;
  5069. const _v0$1 = /*@__PURE__*/ new Vector3();
  5070. const _v1$3 = /*@__PURE__*/ new Vector3();
  5071. const _v2$2 = /*@__PURE__*/ new Vector3();
  5072. const _v3$1 = /*@__PURE__*/ new Vector3();
  5073. const _vab = /*@__PURE__*/ new Vector3();
  5074. const _vac = /*@__PURE__*/ new Vector3();
  5075. const _vbc = /*@__PURE__*/ new Vector3();
  5076. const _vap = /*@__PURE__*/ new Vector3();
  5077. const _vbp = /*@__PURE__*/ new Vector3();
  5078. const _vcp = /*@__PURE__*/ new Vector3();
  5079. class Triangle {
  5080. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5081. this.a = a;
  5082. this.b = b;
  5083. this.c = c;
  5084. }
  5085. static getNormal( a, b, c, target ) {
  5086. target.subVectors( c, b );
  5087. _v0$1.subVectors( a, b );
  5088. target.cross( _v0$1 );
  5089. const targetLengthSq = target.lengthSq();
  5090. if ( targetLengthSq > 0 ) {
  5091. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5092. }
  5093. return target.set( 0, 0, 0 );
  5094. }
  5095. // static/instance method to calculate barycentric coordinates
  5096. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5097. static getBarycoord( point, a, b, c, target ) {
  5098. _v0$1.subVectors( c, a );
  5099. _v1$3.subVectors( b, a );
  5100. _v2$2.subVectors( point, a );
  5101. const dot00 = _v0$1.dot( _v0$1 );
  5102. const dot01 = _v0$1.dot( _v1$3 );
  5103. const dot02 = _v0$1.dot( _v2$2 );
  5104. const dot11 = _v1$3.dot( _v1$3 );
  5105. const dot12 = _v1$3.dot( _v2$2 );
  5106. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5107. // collinear or singular triangle
  5108. if ( denom === 0 ) {
  5109. // arbitrary location outside of triangle?
  5110. // not sure if this is the best idea, maybe should be returning undefined
  5111. return target.set( - 2, - 1, - 1 );
  5112. }
  5113. const invDenom = 1 / denom;
  5114. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5115. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5116. // barycentric coordinates must always sum to 1
  5117. return target.set( 1 - u - v, v, u );
  5118. }
  5119. static containsPoint( point, a, b, c ) {
  5120. this.getBarycoord( point, a, b, c, _v3$1 );
  5121. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5122. }
  5123. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5124. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5125. target.set( 0, 0 );
  5126. target.addScaledVector( uv1, _v3$1.x );
  5127. target.addScaledVector( uv2, _v3$1.y );
  5128. target.addScaledVector( uv3, _v3$1.z );
  5129. return target;
  5130. }
  5131. static isFrontFacing( a, b, c, direction ) {
  5132. _v0$1.subVectors( c, b );
  5133. _v1$3.subVectors( a, b );
  5134. // strictly front facing
  5135. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5136. }
  5137. set( a, b, c ) {
  5138. this.a.copy( a );
  5139. this.b.copy( b );
  5140. this.c.copy( c );
  5141. return this;
  5142. }
  5143. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5144. this.a.copy( points[ i0 ] );
  5145. this.b.copy( points[ i1 ] );
  5146. this.c.copy( points[ i2 ] );
  5147. return this;
  5148. }
  5149. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5150. this.a.fromBufferAttribute( attribute, i0 );
  5151. this.b.fromBufferAttribute( attribute, i1 );
  5152. this.c.fromBufferAttribute( attribute, i2 );
  5153. return this;
  5154. }
  5155. clone() {
  5156. return new this.constructor().copy( this );
  5157. }
  5158. copy( triangle ) {
  5159. this.a.copy( triangle.a );
  5160. this.b.copy( triangle.b );
  5161. this.c.copy( triangle.c );
  5162. return this;
  5163. }
  5164. getArea() {
  5165. _v0$1.subVectors( this.c, this.b );
  5166. _v1$3.subVectors( this.a, this.b );
  5167. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5168. }
  5169. getMidpoint( target ) {
  5170. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5171. }
  5172. getNormal( target ) {
  5173. return Triangle.getNormal( this.a, this.b, this.c, target );
  5174. }
  5175. getPlane( target ) {
  5176. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5177. }
  5178. getBarycoord( point, target ) {
  5179. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5180. }
  5181. getUV( point, uv1, uv2, uv3, target ) {
  5182. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5183. }
  5184. containsPoint( point ) {
  5185. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5186. }
  5187. isFrontFacing( direction ) {
  5188. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5189. }
  5190. intersectsBox( box ) {
  5191. return box.intersectsTriangle( this );
  5192. }
  5193. closestPointToPoint( p, target ) {
  5194. const a = this.a, b = this.b, c = this.c;
  5195. let v, w;
  5196. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5197. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5198. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5199. // basically, we're distinguishing which of the voronoi regions of the triangle
  5200. // the point lies in with the minimum amount of redundant computation.
  5201. _vab.subVectors( b, a );
  5202. _vac.subVectors( c, a );
  5203. _vap.subVectors( p, a );
  5204. const d1 = _vab.dot( _vap );
  5205. const d2 = _vac.dot( _vap );
  5206. if ( d1 <= 0 && d2 <= 0 ) {
  5207. // vertex region of A; barycentric coords (1, 0, 0)
  5208. return target.copy( a );
  5209. }
  5210. _vbp.subVectors( p, b );
  5211. const d3 = _vab.dot( _vbp );
  5212. const d4 = _vac.dot( _vbp );
  5213. if ( d3 >= 0 && d4 <= d3 ) {
  5214. // vertex region of B; barycentric coords (0, 1, 0)
  5215. return target.copy( b );
  5216. }
  5217. const vc = d1 * d4 - d3 * d2;
  5218. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5219. v = d1 / ( d1 - d3 );
  5220. // edge region of AB; barycentric coords (1-v, v, 0)
  5221. return target.copy( a ).addScaledVector( _vab, v );
  5222. }
  5223. _vcp.subVectors( p, c );
  5224. const d5 = _vab.dot( _vcp );
  5225. const d6 = _vac.dot( _vcp );
  5226. if ( d6 >= 0 && d5 <= d6 ) {
  5227. // vertex region of C; barycentric coords (0, 0, 1)
  5228. return target.copy( c );
  5229. }
  5230. const vb = d5 * d2 - d1 * d6;
  5231. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5232. w = d2 / ( d2 - d6 );
  5233. // edge region of AC; barycentric coords (1-w, 0, w)
  5234. return target.copy( a ).addScaledVector( _vac, w );
  5235. }
  5236. const va = d3 * d6 - d5 * d4;
  5237. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5238. _vbc.subVectors( c, b );
  5239. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5240. // edge region of BC; barycentric coords (0, 1-w, w)
  5241. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5242. }
  5243. // face region
  5244. const denom = 1 / ( va + vb + vc );
  5245. // u = va * denom
  5246. v = vb * denom;
  5247. w = vc * denom;
  5248. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5249. }
  5250. equals( triangle ) {
  5251. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5252. }
  5253. }
  5254. let materialId = 0;
  5255. class Material extends EventDispatcher {
  5256. constructor() {
  5257. super();
  5258. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5259. this.uuid = generateUUID();
  5260. this.name = '';
  5261. this.type = 'Material';
  5262. this.blending = NormalBlending;
  5263. this.side = FrontSide;
  5264. this.vertexColors = false;
  5265. this.opacity = 1;
  5266. this.transparent = false;
  5267. this.blendSrc = SrcAlphaFactor;
  5268. this.blendDst = OneMinusSrcAlphaFactor;
  5269. this.blendEquation = AddEquation;
  5270. this.blendSrcAlpha = null;
  5271. this.blendDstAlpha = null;
  5272. this.blendEquationAlpha = null;
  5273. this.depthFunc = LessEqualDepth;
  5274. this.depthTest = true;
  5275. this.depthWrite = true;
  5276. this.stencilWriteMask = 0xff;
  5277. this.stencilFunc = AlwaysStencilFunc;
  5278. this.stencilRef = 0;
  5279. this.stencilFuncMask = 0xff;
  5280. this.stencilFail = KeepStencilOp;
  5281. this.stencilZFail = KeepStencilOp;
  5282. this.stencilZPass = KeepStencilOp;
  5283. this.stencilWrite = false;
  5284. this.clippingPlanes = null;
  5285. this.clipIntersection = false;
  5286. this.clipShadows = false;
  5287. this.shadowSide = null;
  5288. this.colorWrite = true;
  5289. this.precision = null; // override the renderer's default precision for this material
  5290. this.polygonOffset = false;
  5291. this.polygonOffsetFactor = 0;
  5292. this.polygonOffsetUnits = 0;
  5293. this.dithering = false;
  5294. this.alphaToCoverage = false;
  5295. this.premultipliedAlpha = false;
  5296. this.visible = true;
  5297. this.toneMapped = true;
  5298. this.userData = {};
  5299. this.version = 0;
  5300. this._alphaTest = 0;
  5301. }
  5302. get alphaTest() {
  5303. return this._alphaTest;
  5304. }
  5305. set alphaTest( value ) {
  5306. if ( this._alphaTest > 0 !== value > 0 ) {
  5307. this.version ++;
  5308. }
  5309. this._alphaTest = value;
  5310. }
  5311. onBuild( /* shaderobject, renderer */ ) {}
  5312. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5313. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5314. customProgramCacheKey() {
  5315. return this.onBeforeCompile.toString();
  5316. }
  5317. setValues( values ) {
  5318. if ( values === undefined ) return;
  5319. for ( const key in values ) {
  5320. const newValue = values[ key ];
  5321. if ( newValue === undefined ) {
  5322. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5323. continue;
  5324. }
  5325. // for backward compatibility if shading is set in the constructor
  5326. if ( key === 'shading' ) {
  5327. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5328. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5329. continue;
  5330. }
  5331. const currentValue = this[ key ];
  5332. if ( currentValue === undefined ) {
  5333. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5334. continue;
  5335. }
  5336. if ( currentValue && currentValue.isColor ) {
  5337. currentValue.set( newValue );
  5338. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5339. currentValue.copy( newValue );
  5340. } else {
  5341. this[ key ] = newValue;
  5342. }
  5343. }
  5344. }
  5345. toJSON( meta ) {
  5346. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5347. if ( isRootObject ) {
  5348. meta = {
  5349. textures: {},
  5350. images: {}
  5351. };
  5352. }
  5353. const data = {
  5354. metadata: {
  5355. version: 4.5,
  5356. type: 'Material',
  5357. generator: 'Material.toJSON'
  5358. }
  5359. };
  5360. // standard Material serialization
  5361. data.uuid = this.uuid;
  5362. data.type = this.type;
  5363. if ( this.name !== '' ) data.name = this.name;
  5364. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5365. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5366. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5367. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5368. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5369. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5370. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5371. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5372. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5373. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5374. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5375. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5376. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5377. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5378. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5379. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5380. }
  5381. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5382. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5383. }
  5384. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5385. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5386. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5387. }
  5388. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5389. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5390. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5391. if ( this.lightMap && this.lightMap.isTexture ) {
  5392. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5393. data.lightMapIntensity = this.lightMapIntensity;
  5394. }
  5395. if ( this.aoMap && this.aoMap.isTexture ) {
  5396. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5397. data.aoMapIntensity = this.aoMapIntensity;
  5398. }
  5399. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5400. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5401. data.bumpScale = this.bumpScale;
  5402. }
  5403. if ( this.normalMap && this.normalMap.isTexture ) {
  5404. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5405. data.normalMapType = this.normalMapType;
  5406. data.normalScale = this.normalScale.toArray();
  5407. }
  5408. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5409. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5410. data.displacementScale = this.displacementScale;
  5411. data.displacementBias = this.displacementBias;
  5412. }
  5413. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5414. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5415. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5416. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5417. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5418. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5419. if ( this.envMap && this.envMap.isTexture ) {
  5420. data.envMap = this.envMap.toJSON( meta ).uuid;
  5421. if ( this.combine !== undefined ) data.combine = this.combine;
  5422. }
  5423. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5424. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5425. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5426. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5427. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5428. }
  5429. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5430. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5431. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5432. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5433. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  5434. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5435. if ( this.size !== undefined ) data.size = this.size;
  5436. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5437. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5438. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5439. if ( this.side !== FrontSide ) data.side = this.side;
  5440. if ( this.vertexColors ) data.vertexColors = true;
  5441. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5442. if ( this.transparent === true ) data.transparent = this.transparent;
  5443. data.depthFunc = this.depthFunc;
  5444. data.depthTest = this.depthTest;
  5445. data.depthWrite = this.depthWrite;
  5446. data.colorWrite = this.colorWrite;
  5447. data.stencilWrite = this.stencilWrite;
  5448. data.stencilWriteMask = this.stencilWriteMask;
  5449. data.stencilFunc = this.stencilFunc;
  5450. data.stencilRef = this.stencilRef;
  5451. data.stencilFuncMask = this.stencilFuncMask;
  5452. data.stencilFail = this.stencilFail;
  5453. data.stencilZFail = this.stencilZFail;
  5454. data.stencilZPass = this.stencilZPass;
  5455. // rotation (SpriteMaterial)
  5456. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5457. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5458. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5459. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5460. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5461. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5462. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5463. if ( this.scale !== undefined ) data.scale = this.scale;
  5464. if ( this.dithering === true ) data.dithering = true;
  5465. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5466. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5467. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5468. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5469. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5470. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5471. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5472. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5473. if ( this.visible === false ) data.visible = false;
  5474. if ( this.toneMapped === false ) data.toneMapped = false;
  5475. if ( this.fog === false ) data.fog = false;
  5476. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5477. // TODO: Copied from Object3D.toJSON
  5478. function extractFromCache( cache ) {
  5479. const values = [];
  5480. for ( const key in cache ) {
  5481. const data = cache[ key ];
  5482. delete data.metadata;
  5483. values.push( data );
  5484. }
  5485. return values;
  5486. }
  5487. if ( isRootObject ) {
  5488. const textures = extractFromCache( meta.textures );
  5489. const images = extractFromCache( meta.images );
  5490. if ( textures.length > 0 ) data.textures = textures;
  5491. if ( images.length > 0 ) data.images = images;
  5492. }
  5493. return data;
  5494. }
  5495. clone() {
  5496. return new this.constructor().copy( this );
  5497. }
  5498. copy( source ) {
  5499. this.name = source.name;
  5500. this.blending = source.blending;
  5501. this.side = source.side;
  5502. this.vertexColors = source.vertexColors;
  5503. this.opacity = source.opacity;
  5504. this.transparent = source.transparent;
  5505. this.blendSrc = source.blendSrc;
  5506. this.blendDst = source.blendDst;
  5507. this.blendEquation = source.blendEquation;
  5508. this.blendSrcAlpha = source.blendSrcAlpha;
  5509. this.blendDstAlpha = source.blendDstAlpha;
  5510. this.blendEquationAlpha = source.blendEquationAlpha;
  5511. this.depthFunc = source.depthFunc;
  5512. this.depthTest = source.depthTest;
  5513. this.depthWrite = source.depthWrite;
  5514. this.stencilWriteMask = source.stencilWriteMask;
  5515. this.stencilFunc = source.stencilFunc;
  5516. this.stencilRef = source.stencilRef;
  5517. this.stencilFuncMask = source.stencilFuncMask;
  5518. this.stencilFail = source.stencilFail;
  5519. this.stencilZFail = source.stencilZFail;
  5520. this.stencilZPass = source.stencilZPass;
  5521. this.stencilWrite = source.stencilWrite;
  5522. const srcPlanes = source.clippingPlanes;
  5523. let dstPlanes = null;
  5524. if ( srcPlanes !== null ) {
  5525. const n = srcPlanes.length;
  5526. dstPlanes = new Array( n );
  5527. for ( let i = 0; i !== n; ++ i ) {
  5528. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5529. }
  5530. }
  5531. this.clippingPlanes = dstPlanes;
  5532. this.clipIntersection = source.clipIntersection;
  5533. this.clipShadows = source.clipShadows;
  5534. this.shadowSide = source.shadowSide;
  5535. this.colorWrite = source.colorWrite;
  5536. this.precision = source.precision;
  5537. this.polygonOffset = source.polygonOffset;
  5538. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5539. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5540. this.dithering = source.dithering;
  5541. this.alphaTest = source.alphaTest;
  5542. this.alphaToCoverage = source.alphaToCoverage;
  5543. this.premultipliedAlpha = source.premultipliedAlpha;
  5544. this.visible = source.visible;
  5545. this.toneMapped = source.toneMapped;
  5546. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5547. return this;
  5548. }
  5549. dispose() {
  5550. this.dispatchEvent( { type: 'dispose' } );
  5551. }
  5552. set needsUpdate( value ) {
  5553. if ( value === true ) this.version ++;
  5554. }
  5555. }
  5556. Material.prototype.isMaterial = true;
  5557. Material.fromType = function ( /*type*/ ) {
  5558. // TODO: Behavior added in Materials.js
  5559. return null;
  5560. };
  5561. class MeshBasicMaterial extends Material {
  5562. constructor( parameters ) {
  5563. super();
  5564. this.type = 'MeshBasicMaterial';
  5565. this.color = new Color( 0xffffff ); // emissive
  5566. this.map = null;
  5567. this.lightMap = null;
  5568. this.lightMapIntensity = 1.0;
  5569. this.aoMap = null;
  5570. this.aoMapIntensity = 1.0;
  5571. this.specularMap = null;
  5572. this.alphaMap = null;
  5573. this.envMap = null;
  5574. this.combine = MultiplyOperation;
  5575. this.reflectivity = 1;
  5576. this.refractionRatio = 0.98;
  5577. this.wireframe = false;
  5578. this.wireframeLinewidth = 1;
  5579. this.wireframeLinecap = 'round';
  5580. this.wireframeLinejoin = 'round';
  5581. this.fog = true;
  5582. this.setValues( parameters );
  5583. }
  5584. copy( source ) {
  5585. super.copy( source );
  5586. this.color.copy( source.color );
  5587. this.map = source.map;
  5588. this.lightMap = source.lightMap;
  5589. this.lightMapIntensity = source.lightMapIntensity;
  5590. this.aoMap = source.aoMap;
  5591. this.aoMapIntensity = source.aoMapIntensity;
  5592. this.specularMap = source.specularMap;
  5593. this.alphaMap = source.alphaMap;
  5594. this.envMap = source.envMap;
  5595. this.combine = source.combine;
  5596. this.reflectivity = source.reflectivity;
  5597. this.refractionRatio = source.refractionRatio;
  5598. this.wireframe = source.wireframe;
  5599. this.wireframeLinewidth = source.wireframeLinewidth;
  5600. this.wireframeLinecap = source.wireframeLinecap;
  5601. this.wireframeLinejoin = source.wireframeLinejoin;
  5602. this.fog = source.fog;
  5603. return this;
  5604. }
  5605. }
  5606. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5607. const _vector$9 = /*@__PURE__*/ new Vector3();
  5608. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5609. class BufferAttribute {
  5610. constructor( array, itemSize, normalized ) {
  5611. if ( Array.isArray( array ) ) {
  5612. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5613. }
  5614. this.name = '';
  5615. this.array = array;
  5616. this.itemSize = itemSize;
  5617. this.count = array !== undefined ? array.length / itemSize : 0;
  5618. this.normalized = normalized === true;
  5619. this.usage = StaticDrawUsage;
  5620. this.updateRange = { offset: 0, count: - 1 };
  5621. this.version = 0;
  5622. }
  5623. onUploadCallback() {}
  5624. set needsUpdate( value ) {
  5625. if ( value === true ) this.version ++;
  5626. }
  5627. setUsage( value ) {
  5628. this.usage = value;
  5629. return this;
  5630. }
  5631. copy( source ) {
  5632. this.name = source.name;
  5633. this.array = new source.array.constructor( source.array );
  5634. this.itemSize = source.itemSize;
  5635. this.count = source.count;
  5636. this.normalized = source.normalized;
  5637. this.usage = source.usage;
  5638. return this;
  5639. }
  5640. copyAt( index1, attribute, index2 ) {
  5641. index1 *= this.itemSize;
  5642. index2 *= attribute.itemSize;
  5643. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5644. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5645. }
  5646. return this;
  5647. }
  5648. copyArray( array ) {
  5649. this.array.set( array );
  5650. return this;
  5651. }
  5652. copyColorsArray( colors ) {
  5653. const array = this.array;
  5654. let offset = 0;
  5655. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5656. let color = colors[ i ];
  5657. if ( color === undefined ) {
  5658. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5659. color = new Color();
  5660. }
  5661. array[ offset ++ ] = color.r;
  5662. array[ offset ++ ] = color.g;
  5663. array[ offset ++ ] = color.b;
  5664. }
  5665. return this;
  5666. }
  5667. copyVector2sArray( vectors ) {
  5668. const array = this.array;
  5669. let offset = 0;
  5670. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5671. let vector = vectors[ i ];
  5672. if ( vector === undefined ) {
  5673. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5674. vector = new Vector2();
  5675. }
  5676. array[ offset ++ ] = vector.x;
  5677. array[ offset ++ ] = vector.y;
  5678. }
  5679. return this;
  5680. }
  5681. copyVector3sArray( vectors ) {
  5682. const array = this.array;
  5683. let offset = 0;
  5684. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5685. let vector = vectors[ i ];
  5686. if ( vector === undefined ) {
  5687. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5688. vector = new Vector3();
  5689. }
  5690. array[ offset ++ ] = vector.x;
  5691. array[ offset ++ ] = vector.y;
  5692. array[ offset ++ ] = vector.z;
  5693. }
  5694. return this;
  5695. }
  5696. copyVector4sArray( vectors ) {
  5697. const array = this.array;
  5698. let offset = 0;
  5699. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5700. let vector = vectors[ i ];
  5701. if ( vector === undefined ) {
  5702. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5703. vector = new Vector4();
  5704. }
  5705. array[ offset ++ ] = vector.x;
  5706. array[ offset ++ ] = vector.y;
  5707. array[ offset ++ ] = vector.z;
  5708. array[ offset ++ ] = vector.w;
  5709. }
  5710. return this;
  5711. }
  5712. applyMatrix3( m ) {
  5713. if ( this.itemSize === 2 ) {
  5714. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5715. _vector2$1.fromBufferAttribute( this, i );
  5716. _vector2$1.applyMatrix3( m );
  5717. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5718. }
  5719. } else if ( this.itemSize === 3 ) {
  5720. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5721. _vector$9.fromBufferAttribute( this, i );
  5722. _vector$9.applyMatrix3( m );
  5723. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5724. }
  5725. }
  5726. return this;
  5727. }
  5728. applyMatrix4( m ) {
  5729. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5730. _vector$9.fromBufferAttribute( this, i );
  5731. _vector$9.applyMatrix4( m );
  5732. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5733. }
  5734. return this;
  5735. }
  5736. applyNormalMatrix( m ) {
  5737. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5738. _vector$9.fromBufferAttribute( this, i );
  5739. _vector$9.applyNormalMatrix( m );
  5740. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5741. }
  5742. return this;
  5743. }
  5744. transformDirection( m ) {
  5745. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5746. _vector$9.fromBufferAttribute( this, i );
  5747. _vector$9.transformDirection( m );
  5748. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5749. }
  5750. return this;
  5751. }
  5752. set( value, offset = 0 ) {
  5753. this.array.set( value, offset );
  5754. return this;
  5755. }
  5756. getX( index ) {
  5757. return this.array[ index * this.itemSize ];
  5758. }
  5759. setX( index, x ) {
  5760. this.array[ index * this.itemSize ] = x;
  5761. return this;
  5762. }
  5763. getY( index ) {
  5764. return this.array[ index * this.itemSize + 1 ];
  5765. }
  5766. setY( index, y ) {
  5767. this.array[ index * this.itemSize + 1 ] = y;
  5768. return this;
  5769. }
  5770. getZ( index ) {
  5771. return this.array[ index * this.itemSize + 2 ];
  5772. }
  5773. setZ( index, z ) {
  5774. this.array[ index * this.itemSize + 2 ] = z;
  5775. return this;
  5776. }
  5777. getW( index ) {
  5778. return this.array[ index * this.itemSize + 3 ];
  5779. }
  5780. setW( index, w ) {
  5781. this.array[ index * this.itemSize + 3 ] = w;
  5782. return this;
  5783. }
  5784. setXY( index, x, y ) {
  5785. index *= this.itemSize;
  5786. this.array[ index + 0 ] = x;
  5787. this.array[ index + 1 ] = y;
  5788. return this;
  5789. }
  5790. setXYZ( index, x, y, z ) {
  5791. index *= this.itemSize;
  5792. this.array[ index + 0 ] = x;
  5793. this.array[ index + 1 ] = y;
  5794. this.array[ index + 2 ] = z;
  5795. return this;
  5796. }
  5797. setXYZW( index, x, y, z, w ) {
  5798. index *= this.itemSize;
  5799. this.array[ index + 0 ] = x;
  5800. this.array[ index + 1 ] = y;
  5801. this.array[ index + 2 ] = z;
  5802. this.array[ index + 3 ] = w;
  5803. return this;
  5804. }
  5805. onUpload( callback ) {
  5806. this.onUploadCallback = callback;
  5807. return this;
  5808. }
  5809. clone() {
  5810. return new this.constructor( this.array, this.itemSize ).copy( this );
  5811. }
  5812. toJSON() {
  5813. const data = {
  5814. itemSize: this.itemSize,
  5815. type: this.array.constructor.name,
  5816. array: Array.prototype.slice.call( this.array ),
  5817. normalized: this.normalized
  5818. };
  5819. if ( this.name !== '' ) data.name = this.name;
  5820. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5821. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5822. return data;
  5823. }
  5824. }
  5825. BufferAttribute.prototype.isBufferAttribute = true;
  5826. //
  5827. class Int8BufferAttribute extends BufferAttribute {
  5828. constructor( array, itemSize, normalized ) {
  5829. super( new Int8Array( array ), itemSize, normalized );
  5830. }
  5831. }
  5832. class Uint8BufferAttribute extends BufferAttribute {
  5833. constructor( array, itemSize, normalized ) {
  5834. super( new Uint8Array( array ), itemSize, normalized );
  5835. }
  5836. }
  5837. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5838. constructor( array, itemSize, normalized ) {
  5839. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5840. }
  5841. }
  5842. class Int16BufferAttribute extends BufferAttribute {
  5843. constructor( array, itemSize, normalized ) {
  5844. super( new Int16Array( array ), itemSize, normalized );
  5845. }
  5846. }
  5847. class Uint16BufferAttribute extends BufferAttribute {
  5848. constructor( array, itemSize, normalized ) {
  5849. super( new Uint16Array( array ), itemSize, normalized );
  5850. }
  5851. }
  5852. class Int32BufferAttribute extends BufferAttribute {
  5853. constructor( array, itemSize, normalized ) {
  5854. super( new Int32Array( array ), itemSize, normalized );
  5855. }
  5856. }
  5857. class Uint32BufferAttribute extends BufferAttribute {
  5858. constructor( array, itemSize, normalized ) {
  5859. super( new Uint32Array( array ), itemSize, normalized );
  5860. }
  5861. }
  5862. class Float16BufferAttribute extends BufferAttribute {
  5863. constructor( array, itemSize, normalized ) {
  5864. super( new Uint16Array( array ), itemSize, normalized );
  5865. }
  5866. }
  5867. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5868. class Float32BufferAttribute extends BufferAttribute {
  5869. constructor( array, itemSize, normalized ) {
  5870. super( new Float32Array( array ), itemSize, normalized );
  5871. }
  5872. }
  5873. class Float64BufferAttribute extends BufferAttribute {
  5874. constructor( array, itemSize, normalized ) {
  5875. super( new Float64Array( array ), itemSize, normalized );
  5876. }
  5877. }
  5878. let _id$1 = 0;
  5879. const _m1 = /*@__PURE__*/ new Matrix4();
  5880. const _obj = /*@__PURE__*/ new Object3D();
  5881. const _offset = /*@__PURE__*/ new Vector3();
  5882. const _box$1 = /*@__PURE__*/ new Box3();
  5883. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5884. const _vector$8 = /*@__PURE__*/ new Vector3();
  5885. class BufferGeometry extends EventDispatcher {
  5886. constructor() {
  5887. super();
  5888. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5889. this.uuid = generateUUID();
  5890. this.name = '';
  5891. this.type = 'BufferGeometry';
  5892. this.index = null;
  5893. this.attributes = {};
  5894. this.morphAttributes = {};
  5895. this.morphTargetsRelative = false;
  5896. this.groups = [];
  5897. this.boundingBox = null;
  5898. this.boundingSphere = null;
  5899. this.drawRange = { start: 0, count: Infinity };
  5900. this.userData = {};
  5901. }
  5902. getIndex() {
  5903. return this.index;
  5904. }
  5905. setIndex( index ) {
  5906. if ( Array.isArray( index ) ) {
  5907. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5908. } else {
  5909. this.index = index;
  5910. }
  5911. return this;
  5912. }
  5913. getAttribute( name ) {
  5914. return this.attributes[ name ];
  5915. }
  5916. setAttribute( name, attribute ) {
  5917. this.attributes[ name ] = attribute;
  5918. return this;
  5919. }
  5920. deleteAttribute( name ) {
  5921. delete this.attributes[ name ];
  5922. return this;
  5923. }
  5924. hasAttribute( name ) {
  5925. return this.attributes[ name ] !== undefined;
  5926. }
  5927. addGroup( start, count, materialIndex = 0 ) {
  5928. this.groups.push( {
  5929. start: start,
  5930. count: count,
  5931. materialIndex: materialIndex
  5932. } );
  5933. }
  5934. clearGroups() {
  5935. this.groups = [];
  5936. }
  5937. setDrawRange( start, count ) {
  5938. this.drawRange.start = start;
  5939. this.drawRange.count = count;
  5940. }
  5941. applyMatrix4( matrix ) {
  5942. const position = this.attributes.position;
  5943. if ( position !== undefined ) {
  5944. position.applyMatrix4( matrix );
  5945. position.needsUpdate = true;
  5946. }
  5947. const normal = this.attributes.normal;
  5948. if ( normal !== undefined ) {
  5949. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5950. normal.applyNormalMatrix( normalMatrix );
  5951. normal.needsUpdate = true;
  5952. }
  5953. const tangent = this.attributes.tangent;
  5954. if ( tangent !== undefined ) {
  5955. tangent.transformDirection( matrix );
  5956. tangent.needsUpdate = true;
  5957. }
  5958. if ( this.boundingBox !== null ) {
  5959. this.computeBoundingBox();
  5960. }
  5961. if ( this.boundingSphere !== null ) {
  5962. this.computeBoundingSphere();
  5963. }
  5964. return this;
  5965. }
  5966. applyQuaternion( q ) {
  5967. _m1.makeRotationFromQuaternion( q );
  5968. this.applyMatrix4( _m1 );
  5969. return this;
  5970. }
  5971. rotateX( angle ) {
  5972. // rotate geometry around world x-axis
  5973. _m1.makeRotationX( angle );
  5974. this.applyMatrix4( _m1 );
  5975. return this;
  5976. }
  5977. rotateY( angle ) {
  5978. // rotate geometry around world y-axis
  5979. _m1.makeRotationY( angle );
  5980. this.applyMatrix4( _m1 );
  5981. return this;
  5982. }
  5983. rotateZ( angle ) {
  5984. // rotate geometry around world z-axis
  5985. _m1.makeRotationZ( angle );
  5986. this.applyMatrix4( _m1 );
  5987. return this;
  5988. }
  5989. translate( x, y, z ) {
  5990. // translate geometry
  5991. _m1.makeTranslation( x, y, z );
  5992. this.applyMatrix4( _m1 );
  5993. return this;
  5994. }
  5995. scale( x, y, z ) {
  5996. // scale geometry
  5997. _m1.makeScale( x, y, z );
  5998. this.applyMatrix4( _m1 );
  5999. return this;
  6000. }
  6001. lookAt( vector ) {
  6002. _obj.lookAt( vector );
  6003. _obj.updateMatrix();
  6004. this.applyMatrix4( _obj.matrix );
  6005. return this;
  6006. }
  6007. center() {
  6008. this.computeBoundingBox();
  6009. this.boundingBox.getCenter( _offset ).negate();
  6010. this.translate( _offset.x, _offset.y, _offset.z );
  6011. return this;
  6012. }
  6013. setFromPoints( points ) {
  6014. const position = [];
  6015. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6016. const point = points[ i ];
  6017. position.push( point.x, point.y, point.z || 0 );
  6018. }
  6019. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6020. return this;
  6021. }
  6022. computeBoundingBox() {
  6023. if ( this.boundingBox === null ) {
  6024. this.boundingBox = new Box3();
  6025. }
  6026. const position = this.attributes.position;
  6027. const morphAttributesPosition = this.morphAttributes.position;
  6028. if ( position && position.isGLBufferAttribute ) {
  6029. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6030. this.boundingBox.set(
  6031. new Vector3( - Infinity, - Infinity, - Infinity ),
  6032. new Vector3( + Infinity, + Infinity, + Infinity )
  6033. );
  6034. return;
  6035. }
  6036. if ( position !== undefined ) {
  6037. this.boundingBox.setFromBufferAttribute( position );
  6038. // process morph attributes if present
  6039. if ( morphAttributesPosition ) {
  6040. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6041. const morphAttribute = morphAttributesPosition[ i ];
  6042. _box$1.setFromBufferAttribute( morphAttribute );
  6043. if ( this.morphTargetsRelative ) {
  6044. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  6045. this.boundingBox.expandByPoint( _vector$8 );
  6046. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6047. this.boundingBox.expandByPoint( _vector$8 );
  6048. } else {
  6049. this.boundingBox.expandByPoint( _box$1.min );
  6050. this.boundingBox.expandByPoint( _box$1.max );
  6051. }
  6052. }
  6053. }
  6054. } else {
  6055. this.boundingBox.makeEmpty();
  6056. }
  6057. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6058. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6059. }
  6060. }
  6061. computeBoundingSphere() {
  6062. if ( this.boundingSphere === null ) {
  6063. this.boundingSphere = new Sphere();
  6064. }
  6065. const position = this.attributes.position;
  6066. const morphAttributesPosition = this.morphAttributes.position;
  6067. if ( position && position.isGLBufferAttribute ) {
  6068. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6069. this.boundingSphere.set( new Vector3(), Infinity );
  6070. return;
  6071. }
  6072. if ( position ) {
  6073. // first, find the center of the bounding sphere
  6074. const center = this.boundingSphere.center;
  6075. _box$1.setFromBufferAttribute( position );
  6076. // process morph attributes if present
  6077. if ( morphAttributesPosition ) {
  6078. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6079. const morphAttribute = morphAttributesPosition[ i ];
  6080. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6081. if ( this.morphTargetsRelative ) {
  6082. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6083. _box$1.expandByPoint( _vector$8 );
  6084. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6085. _box$1.expandByPoint( _vector$8 );
  6086. } else {
  6087. _box$1.expandByPoint( _boxMorphTargets.min );
  6088. _box$1.expandByPoint( _boxMorphTargets.max );
  6089. }
  6090. }
  6091. }
  6092. _box$1.getCenter( center );
  6093. // second, try to find a boundingSphere with a radius smaller than the
  6094. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6095. let maxRadiusSq = 0;
  6096. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6097. _vector$8.fromBufferAttribute( position, i );
  6098. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6099. }
  6100. // process morph attributes if present
  6101. if ( morphAttributesPosition ) {
  6102. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6103. const morphAttribute = morphAttributesPosition[ i ];
  6104. const morphTargetsRelative = this.morphTargetsRelative;
  6105. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6106. _vector$8.fromBufferAttribute( morphAttribute, j );
  6107. if ( morphTargetsRelative ) {
  6108. _offset.fromBufferAttribute( position, j );
  6109. _vector$8.add( _offset );
  6110. }
  6111. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6112. }
  6113. }
  6114. }
  6115. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6116. if ( isNaN( this.boundingSphere.radius ) ) {
  6117. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6118. }
  6119. }
  6120. }
  6121. computeTangents() {
  6122. const index = this.index;
  6123. const attributes = this.attributes;
  6124. // based on http://www.terathon.com/code/tangent.html
  6125. // (per vertex tangents)
  6126. if ( index === null ||
  6127. attributes.position === undefined ||
  6128. attributes.normal === undefined ||
  6129. attributes.uv === undefined ) {
  6130. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6131. return;
  6132. }
  6133. const indices = index.array;
  6134. const positions = attributes.position.array;
  6135. const normals = attributes.normal.array;
  6136. const uvs = attributes.uv.array;
  6137. const nVertices = positions.length / 3;
  6138. if ( this.hasAttribute( 'tangent' ) === false ) {
  6139. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6140. }
  6141. const tangents = this.getAttribute( 'tangent' ).array;
  6142. const tan1 = [], tan2 = [];
  6143. for ( let i = 0; i < nVertices; i ++ ) {
  6144. tan1[ i ] = new Vector3();
  6145. tan2[ i ] = new Vector3();
  6146. }
  6147. const vA = new Vector3(),
  6148. vB = new Vector3(),
  6149. vC = new Vector3(),
  6150. uvA = new Vector2(),
  6151. uvB = new Vector2(),
  6152. uvC = new Vector2(),
  6153. sdir = new Vector3(),
  6154. tdir = new Vector3();
  6155. function handleTriangle( a, b, c ) {
  6156. vA.fromArray( positions, a * 3 );
  6157. vB.fromArray( positions, b * 3 );
  6158. vC.fromArray( positions, c * 3 );
  6159. uvA.fromArray( uvs, a * 2 );
  6160. uvB.fromArray( uvs, b * 2 );
  6161. uvC.fromArray( uvs, c * 2 );
  6162. vB.sub( vA );
  6163. vC.sub( vA );
  6164. uvB.sub( uvA );
  6165. uvC.sub( uvA );
  6166. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6167. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6168. if ( ! isFinite( r ) ) return;
  6169. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6170. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6171. tan1[ a ].add( sdir );
  6172. tan1[ b ].add( sdir );
  6173. tan1[ c ].add( sdir );
  6174. tan2[ a ].add( tdir );
  6175. tan2[ b ].add( tdir );
  6176. tan2[ c ].add( tdir );
  6177. }
  6178. let groups = this.groups;
  6179. if ( groups.length === 0 ) {
  6180. groups = [ {
  6181. start: 0,
  6182. count: indices.length
  6183. } ];
  6184. }
  6185. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6186. const group = groups[ i ];
  6187. const start = group.start;
  6188. const count = group.count;
  6189. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6190. handleTriangle(
  6191. indices[ j + 0 ],
  6192. indices[ j + 1 ],
  6193. indices[ j + 2 ]
  6194. );
  6195. }
  6196. }
  6197. const tmp = new Vector3(), tmp2 = new Vector3();
  6198. const n = new Vector3(), n2 = new Vector3();
  6199. function handleVertex( v ) {
  6200. n.fromArray( normals, v * 3 );
  6201. n2.copy( n );
  6202. const t = tan1[ v ];
  6203. // Gram-Schmidt orthogonalize
  6204. tmp.copy( t );
  6205. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6206. // Calculate handedness
  6207. tmp2.crossVectors( n2, t );
  6208. const test = tmp2.dot( tan2[ v ] );
  6209. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6210. tangents[ v * 4 ] = tmp.x;
  6211. tangents[ v * 4 + 1 ] = tmp.y;
  6212. tangents[ v * 4 + 2 ] = tmp.z;
  6213. tangents[ v * 4 + 3 ] = w;
  6214. }
  6215. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6216. const group = groups[ i ];
  6217. const start = group.start;
  6218. const count = group.count;
  6219. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6220. handleVertex( indices[ j + 0 ] );
  6221. handleVertex( indices[ j + 1 ] );
  6222. handleVertex( indices[ j + 2 ] );
  6223. }
  6224. }
  6225. }
  6226. computeVertexNormals() {
  6227. const index = this.index;
  6228. const positionAttribute = this.getAttribute( 'position' );
  6229. if ( positionAttribute !== undefined ) {
  6230. let normalAttribute = this.getAttribute( 'normal' );
  6231. if ( normalAttribute === undefined ) {
  6232. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6233. this.setAttribute( 'normal', normalAttribute );
  6234. } else {
  6235. // reset existing normals to zero
  6236. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6237. normalAttribute.setXYZ( i, 0, 0, 0 );
  6238. }
  6239. }
  6240. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6241. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6242. const cb = new Vector3(), ab = new Vector3();
  6243. // indexed elements
  6244. if ( index ) {
  6245. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6246. const vA = index.getX( i + 0 );
  6247. const vB = index.getX( i + 1 );
  6248. const vC = index.getX( i + 2 );
  6249. pA.fromBufferAttribute( positionAttribute, vA );
  6250. pB.fromBufferAttribute( positionAttribute, vB );
  6251. pC.fromBufferAttribute( positionAttribute, vC );
  6252. cb.subVectors( pC, pB );
  6253. ab.subVectors( pA, pB );
  6254. cb.cross( ab );
  6255. nA.fromBufferAttribute( normalAttribute, vA );
  6256. nB.fromBufferAttribute( normalAttribute, vB );
  6257. nC.fromBufferAttribute( normalAttribute, vC );
  6258. nA.add( cb );
  6259. nB.add( cb );
  6260. nC.add( cb );
  6261. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6262. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6263. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6264. }
  6265. } else {
  6266. // non-indexed elements (unconnected triangle soup)
  6267. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6268. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6269. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6270. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6271. cb.subVectors( pC, pB );
  6272. ab.subVectors( pA, pB );
  6273. cb.cross( ab );
  6274. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6275. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6276. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6277. }
  6278. }
  6279. this.normalizeNormals();
  6280. normalAttribute.needsUpdate = true;
  6281. }
  6282. }
  6283. merge( geometry, offset ) {
  6284. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6285. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6286. return;
  6287. }
  6288. if ( offset === undefined ) {
  6289. offset = 0;
  6290. console.warn(
  6291. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6292. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6293. );
  6294. }
  6295. const attributes = this.attributes;
  6296. for ( const key in attributes ) {
  6297. if ( geometry.attributes[ key ] === undefined ) continue;
  6298. const attribute1 = attributes[ key ];
  6299. const attributeArray1 = attribute1.array;
  6300. const attribute2 = geometry.attributes[ key ];
  6301. const attributeArray2 = attribute2.array;
  6302. const attributeOffset = attribute2.itemSize * offset;
  6303. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6304. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6305. attributeArray1[ j ] = attributeArray2[ i ];
  6306. }
  6307. }
  6308. return this;
  6309. }
  6310. normalizeNormals() {
  6311. const normals = this.attributes.normal;
  6312. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6313. _vector$8.fromBufferAttribute( normals, i );
  6314. _vector$8.normalize();
  6315. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6316. }
  6317. }
  6318. toNonIndexed() {
  6319. function convertBufferAttribute( attribute, indices ) {
  6320. const array = attribute.array;
  6321. const itemSize = attribute.itemSize;
  6322. const normalized = attribute.normalized;
  6323. const array2 = new array.constructor( indices.length * itemSize );
  6324. let index = 0, index2 = 0;
  6325. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6326. if ( attribute.isInterleavedBufferAttribute ) {
  6327. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6328. } else {
  6329. index = indices[ i ] * itemSize;
  6330. }
  6331. for ( let j = 0; j < itemSize; j ++ ) {
  6332. array2[ index2 ++ ] = array[ index ++ ];
  6333. }
  6334. }
  6335. return new BufferAttribute( array2, itemSize, normalized );
  6336. }
  6337. //
  6338. if ( this.index === null ) {
  6339. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6340. return this;
  6341. }
  6342. const geometry2 = new BufferGeometry();
  6343. const indices = this.index.array;
  6344. const attributes = this.attributes;
  6345. // attributes
  6346. for ( const name in attributes ) {
  6347. const attribute = attributes[ name ];
  6348. const newAttribute = convertBufferAttribute( attribute, indices );
  6349. geometry2.setAttribute( name, newAttribute );
  6350. }
  6351. // morph attributes
  6352. const morphAttributes = this.morphAttributes;
  6353. for ( const name in morphAttributes ) {
  6354. const morphArray = [];
  6355. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6356. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6357. const attribute = morphAttribute[ i ];
  6358. const newAttribute = convertBufferAttribute( attribute, indices );
  6359. morphArray.push( newAttribute );
  6360. }
  6361. geometry2.morphAttributes[ name ] = morphArray;
  6362. }
  6363. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6364. // groups
  6365. const groups = this.groups;
  6366. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6367. const group = groups[ i ];
  6368. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6369. }
  6370. return geometry2;
  6371. }
  6372. toJSON() {
  6373. const data = {
  6374. metadata: {
  6375. version: 4.5,
  6376. type: 'BufferGeometry',
  6377. generator: 'BufferGeometry.toJSON'
  6378. }
  6379. };
  6380. // standard BufferGeometry serialization
  6381. data.uuid = this.uuid;
  6382. data.type = this.type;
  6383. if ( this.name !== '' ) data.name = this.name;
  6384. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6385. if ( this.parameters !== undefined ) {
  6386. const parameters = this.parameters;
  6387. for ( const key in parameters ) {
  6388. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6389. }
  6390. return data;
  6391. }
  6392. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6393. data.data = { attributes: {} };
  6394. const index = this.index;
  6395. if ( index !== null ) {
  6396. data.data.index = {
  6397. type: index.array.constructor.name,
  6398. array: Array.prototype.slice.call( index.array )
  6399. };
  6400. }
  6401. const attributes = this.attributes;
  6402. for ( const key in attributes ) {
  6403. const attribute = attributes[ key ];
  6404. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6405. }
  6406. const morphAttributes = {};
  6407. let hasMorphAttributes = false;
  6408. for ( const key in this.morphAttributes ) {
  6409. const attributeArray = this.morphAttributes[ key ];
  6410. const array = [];
  6411. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6412. const attribute = attributeArray[ i ];
  6413. array.push( attribute.toJSON( data.data ) );
  6414. }
  6415. if ( array.length > 0 ) {
  6416. morphAttributes[ key ] = array;
  6417. hasMorphAttributes = true;
  6418. }
  6419. }
  6420. if ( hasMorphAttributes ) {
  6421. data.data.morphAttributes = morphAttributes;
  6422. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6423. }
  6424. const groups = this.groups;
  6425. if ( groups.length > 0 ) {
  6426. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6427. }
  6428. const boundingSphere = this.boundingSphere;
  6429. if ( boundingSphere !== null ) {
  6430. data.data.boundingSphere = {
  6431. center: boundingSphere.center.toArray(),
  6432. radius: boundingSphere.radius
  6433. };
  6434. }
  6435. return data;
  6436. }
  6437. clone() {
  6438. return new this.constructor().copy( this );
  6439. }
  6440. copy( source ) {
  6441. // reset
  6442. this.index = null;
  6443. this.attributes = {};
  6444. this.morphAttributes = {};
  6445. this.groups = [];
  6446. this.boundingBox = null;
  6447. this.boundingSphere = null;
  6448. // used for storing cloned, shared data
  6449. const data = {};
  6450. // name
  6451. this.name = source.name;
  6452. // index
  6453. const index = source.index;
  6454. if ( index !== null ) {
  6455. this.setIndex( index.clone( data ) );
  6456. }
  6457. // attributes
  6458. const attributes = source.attributes;
  6459. for ( const name in attributes ) {
  6460. const attribute = attributes[ name ];
  6461. this.setAttribute( name, attribute.clone( data ) );
  6462. }
  6463. // morph attributes
  6464. const morphAttributes = source.morphAttributes;
  6465. for ( const name in morphAttributes ) {
  6466. const array = [];
  6467. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6468. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6469. array.push( morphAttribute[ i ].clone( data ) );
  6470. }
  6471. this.morphAttributes[ name ] = array;
  6472. }
  6473. this.morphTargetsRelative = source.morphTargetsRelative;
  6474. // groups
  6475. const groups = source.groups;
  6476. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6477. const group = groups[ i ];
  6478. this.addGroup( group.start, group.count, group.materialIndex );
  6479. }
  6480. // bounding box
  6481. const boundingBox = source.boundingBox;
  6482. if ( boundingBox !== null ) {
  6483. this.boundingBox = boundingBox.clone();
  6484. }
  6485. // bounding sphere
  6486. const boundingSphere = source.boundingSphere;
  6487. if ( boundingSphere !== null ) {
  6488. this.boundingSphere = boundingSphere.clone();
  6489. }
  6490. // draw range
  6491. this.drawRange.start = source.drawRange.start;
  6492. this.drawRange.count = source.drawRange.count;
  6493. // user data
  6494. this.userData = source.userData;
  6495. // geometry generator parameters
  6496. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6497. return this;
  6498. }
  6499. dispose() {
  6500. this.dispatchEvent( { type: 'dispose' } );
  6501. }
  6502. }
  6503. BufferGeometry.prototype.isBufferGeometry = true;
  6504. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6505. const _ray$2 = /*@__PURE__*/ new Ray();
  6506. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6507. const _vA$1 = /*@__PURE__*/ new Vector3();
  6508. const _vB$1 = /*@__PURE__*/ new Vector3();
  6509. const _vC$1 = /*@__PURE__*/ new Vector3();
  6510. const _tempA = /*@__PURE__*/ new Vector3();
  6511. const _tempB = /*@__PURE__*/ new Vector3();
  6512. const _tempC = /*@__PURE__*/ new Vector3();
  6513. const _morphA = /*@__PURE__*/ new Vector3();
  6514. const _morphB = /*@__PURE__*/ new Vector3();
  6515. const _morphC = /*@__PURE__*/ new Vector3();
  6516. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6517. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6518. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6519. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6520. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6521. class Mesh extends Object3D {
  6522. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6523. super();
  6524. this.type = 'Mesh';
  6525. this.geometry = geometry;
  6526. this.material = material;
  6527. this.updateMorphTargets();
  6528. }
  6529. copy( source ) {
  6530. super.copy( source );
  6531. if ( source.morphTargetInfluences !== undefined ) {
  6532. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6533. }
  6534. if ( source.morphTargetDictionary !== undefined ) {
  6535. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6536. }
  6537. this.material = source.material;
  6538. this.geometry = source.geometry;
  6539. return this;
  6540. }
  6541. updateMorphTargets() {
  6542. const geometry = this.geometry;
  6543. if ( geometry.isBufferGeometry ) {
  6544. const morphAttributes = geometry.morphAttributes;
  6545. const keys = Object.keys( morphAttributes );
  6546. if ( keys.length > 0 ) {
  6547. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6548. if ( morphAttribute !== undefined ) {
  6549. this.morphTargetInfluences = [];
  6550. this.morphTargetDictionary = {};
  6551. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6552. const name = morphAttribute[ m ].name || String( m );
  6553. this.morphTargetInfluences.push( 0 );
  6554. this.morphTargetDictionary[ name ] = m;
  6555. }
  6556. }
  6557. }
  6558. } else {
  6559. const morphTargets = geometry.morphTargets;
  6560. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6561. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6562. }
  6563. }
  6564. }
  6565. raycast( raycaster, intersects ) {
  6566. const geometry = this.geometry;
  6567. const material = this.material;
  6568. const matrixWorld = this.matrixWorld;
  6569. if ( material === undefined ) return;
  6570. // Checking boundingSphere distance to ray
  6571. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6572. _sphere$3.copy( geometry.boundingSphere );
  6573. _sphere$3.applyMatrix4( matrixWorld );
  6574. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6575. //
  6576. _inverseMatrix$2.copy( matrixWorld ).invert();
  6577. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6578. // Check boundingBox before continuing
  6579. if ( geometry.boundingBox !== null ) {
  6580. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6581. }
  6582. let intersection;
  6583. if ( geometry.isBufferGeometry ) {
  6584. const index = geometry.index;
  6585. const position = geometry.attributes.position;
  6586. const morphPosition = geometry.morphAttributes.position;
  6587. const morphTargetsRelative = geometry.morphTargetsRelative;
  6588. const uv = geometry.attributes.uv;
  6589. const uv2 = geometry.attributes.uv2;
  6590. const groups = geometry.groups;
  6591. const drawRange = geometry.drawRange;
  6592. if ( index !== null ) {
  6593. // indexed buffer geometry
  6594. if ( Array.isArray( material ) ) {
  6595. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6596. const group = groups[ i ];
  6597. const groupMaterial = material[ group.materialIndex ];
  6598. const start = Math.max( group.start, drawRange.start );
  6599. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6600. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6601. const a = index.getX( j );
  6602. const b = index.getX( j + 1 );
  6603. const c = index.getX( j + 2 );
  6604. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6605. if ( intersection ) {
  6606. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6607. intersection.face.materialIndex = group.materialIndex;
  6608. intersects.push( intersection );
  6609. }
  6610. }
  6611. }
  6612. } else {
  6613. const start = Math.max( 0, drawRange.start );
  6614. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6615. for ( let i = start, il = end; i < il; i += 3 ) {
  6616. const a = index.getX( i );
  6617. const b = index.getX( i + 1 );
  6618. const c = index.getX( i + 2 );
  6619. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6620. if ( intersection ) {
  6621. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6622. intersects.push( intersection );
  6623. }
  6624. }
  6625. }
  6626. } else if ( position !== undefined ) {
  6627. // non-indexed buffer geometry
  6628. if ( Array.isArray( material ) ) {
  6629. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6630. const group = groups[ i ];
  6631. const groupMaterial = material[ group.materialIndex ];
  6632. const start = Math.max( group.start, drawRange.start );
  6633. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6634. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6635. const a = j;
  6636. const b = j + 1;
  6637. const c = j + 2;
  6638. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6639. if ( intersection ) {
  6640. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6641. intersection.face.materialIndex = group.materialIndex;
  6642. intersects.push( intersection );
  6643. }
  6644. }
  6645. }
  6646. } else {
  6647. const start = Math.max( 0, drawRange.start );
  6648. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6649. for ( let i = start, il = end; i < il; i += 3 ) {
  6650. const a = i;
  6651. const b = i + 1;
  6652. const c = i + 2;
  6653. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6654. if ( intersection ) {
  6655. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6656. intersects.push( intersection );
  6657. }
  6658. }
  6659. }
  6660. }
  6661. } else if ( geometry.isGeometry ) {
  6662. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6663. }
  6664. }
  6665. }
  6666. Mesh.prototype.isMesh = true;
  6667. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6668. let intersect;
  6669. if ( material.side === BackSide ) {
  6670. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6671. } else {
  6672. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6673. }
  6674. if ( intersect === null ) return null;
  6675. _intersectionPointWorld.copy( point );
  6676. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6677. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6678. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6679. return {
  6680. distance: distance,
  6681. point: _intersectionPointWorld.clone(),
  6682. object: object
  6683. };
  6684. }
  6685. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6686. _vA$1.fromBufferAttribute( position, a );
  6687. _vB$1.fromBufferAttribute( position, b );
  6688. _vC$1.fromBufferAttribute( position, c );
  6689. const morphInfluences = object.morphTargetInfluences;
  6690. if ( morphPosition && morphInfluences ) {
  6691. _morphA.set( 0, 0, 0 );
  6692. _morphB.set( 0, 0, 0 );
  6693. _morphC.set( 0, 0, 0 );
  6694. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6695. const influence = morphInfluences[ i ];
  6696. const morphAttribute = morphPosition[ i ];
  6697. if ( influence === 0 ) continue;
  6698. _tempA.fromBufferAttribute( morphAttribute, a );
  6699. _tempB.fromBufferAttribute( morphAttribute, b );
  6700. _tempC.fromBufferAttribute( morphAttribute, c );
  6701. if ( morphTargetsRelative ) {
  6702. _morphA.addScaledVector( _tempA, influence );
  6703. _morphB.addScaledVector( _tempB, influence );
  6704. _morphC.addScaledVector( _tempC, influence );
  6705. } else {
  6706. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6707. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6708. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6709. }
  6710. }
  6711. _vA$1.add( _morphA );
  6712. _vB$1.add( _morphB );
  6713. _vC$1.add( _morphC );
  6714. }
  6715. if ( object.isSkinnedMesh ) {
  6716. object.boneTransform( a, _vA$1 );
  6717. object.boneTransform( b, _vB$1 );
  6718. object.boneTransform( c, _vC$1 );
  6719. }
  6720. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6721. if ( intersection ) {
  6722. if ( uv ) {
  6723. _uvA$1.fromBufferAttribute( uv, a );
  6724. _uvB$1.fromBufferAttribute( uv, b );
  6725. _uvC$1.fromBufferAttribute( uv, c );
  6726. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6727. }
  6728. if ( uv2 ) {
  6729. _uvA$1.fromBufferAttribute( uv2, a );
  6730. _uvB$1.fromBufferAttribute( uv2, b );
  6731. _uvC$1.fromBufferAttribute( uv2, c );
  6732. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6733. }
  6734. const face = {
  6735. a: a,
  6736. b: b,
  6737. c: c,
  6738. normal: new Vector3(),
  6739. materialIndex: 0
  6740. };
  6741. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6742. intersection.face = face;
  6743. }
  6744. return intersection;
  6745. }
  6746. class BoxGeometry extends BufferGeometry {
  6747. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6748. super();
  6749. this.type = 'BoxGeometry';
  6750. this.parameters = {
  6751. width: width,
  6752. height: height,
  6753. depth: depth,
  6754. widthSegments: widthSegments,
  6755. heightSegments: heightSegments,
  6756. depthSegments: depthSegments
  6757. };
  6758. const scope = this;
  6759. // segments
  6760. widthSegments = Math.floor( widthSegments );
  6761. heightSegments = Math.floor( heightSegments );
  6762. depthSegments = Math.floor( depthSegments );
  6763. // buffers
  6764. const indices = [];
  6765. const vertices = [];
  6766. const normals = [];
  6767. const uvs = [];
  6768. // helper variables
  6769. let numberOfVertices = 0;
  6770. let groupStart = 0;
  6771. // build each side of the box geometry
  6772. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6773. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6774. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6775. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6776. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6777. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6778. // build geometry
  6779. this.setIndex( indices );
  6780. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6781. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6782. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6783. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6784. const segmentWidth = width / gridX;
  6785. const segmentHeight = height / gridY;
  6786. const widthHalf = width / 2;
  6787. const heightHalf = height / 2;
  6788. const depthHalf = depth / 2;
  6789. const gridX1 = gridX + 1;
  6790. const gridY1 = gridY + 1;
  6791. let vertexCounter = 0;
  6792. let groupCount = 0;
  6793. const vector = new Vector3();
  6794. // generate vertices, normals and uvs
  6795. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6796. const y = iy * segmentHeight - heightHalf;
  6797. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6798. const x = ix * segmentWidth - widthHalf;
  6799. // set values to correct vector component
  6800. vector[ u ] = x * udir;
  6801. vector[ v ] = y * vdir;
  6802. vector[ w ] = depthHalf;
  6803. // now apply vector to vertex buffer
  6804. vertices.push( vector.x, vector.y, vector.z );
  6805. // set values to correct vector component
  6806. vector[ u ] = 0;
  6807. vector[ v ] = 0;
  6808. vector[ w ] = depth > 0 ? 1 : - 1;
  6809. // now apply vector to normal buffer
  6810. normals.push( vector.x, vector.y, vector.z );
  6811. // uvs
  6812. uvs.push( ix / gridX );
  6813. uvs.push( 1 - ( iy / gridY ) );
  6814. // counters
  6815. vertexCounter += 1;
  6816. }
  6817. }
  6818. // indices
  6819. // 1. you need three indices to draw a single face
  6820. // 2. a single segment consists of two faces
  6821. // 3. so we need to generate six (2*3) indices per segment
  6822. for ( let iy = 0; iy < gridY; iy ++ ) {
  6823. for ( let ix = 0; ix < gridX; ix ++ ) {
  6824. const a = numberOfVertices + ix + gridX1 * iy;
  6825. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6826. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6827. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6828. // faces
  6829. indices.push( a, b, d );
  6830. indices.push( b, c, d );
  6831. // increase counter
  6832. groupCount += 6;
  6833. }
  6834. }
  6835. // add a group to the geometry. this will ensure multi material support
  6836. scope.addGroup( groupStart, groupCount, materialIndex );
  6837. // calculate new start value for groups
  6838. groupStart += groupCount;
  6839. // update total number of vertices
  6840. numberOfVertices += vertexCounter;
  6841. }
  6842. }
  6843. static fromJSON( data ) {
  6844. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6845. }
  6846. }
  6847. /**
  6848. * Uniform Utilities
  6849. */
  6850. function cloneUniforms( src ) {
  6851. const dst = {};
  6852. for ( const u in src ) {
  6853. dst[ u ] = {};
  6854. for ( const p in src[ u ] ) {
  6855. const property = src[ u ][ p ];
  6856. if ( property && ( property.isColor ||
  6857. property.isMatrix3 || property.isMatrix4 ||
  6858. property.isVector2 || property.isVector3 || property.isVector4 ||
  6859. property.isTexture || property.isQuaternion ) ) {
  6860. dst[ u ][ p ] = property.clone();
  6861. } else if ( Array.isArray( property ) ) {
  6862. dst[ u ][ p ] = property.slice();
  6863. } else {
  6864. dst[ u ][ p ] = property;
  6865. }
  6866. }
  6867. }
  6868. return dst;
  6869. }
  6870. function mergeUniforms( uniforms ) {
  6871. const merged = {};
  6872. for ( let u = 0; u < uniforms.length; u ++ ) {
  6873. const tmp = cloneUniforms( uniforms[ u ] );
  6874. for ( const p in tmp ) {
  6875. merged[ p ] = tmp[ p ];
  6876. }
  6877. }
  6878. return merged;
  6879. }
  6880. // Legacy
  6881. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6882. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6883. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6884. class ShaderMaterial extends Material {
  6885. constructor( parameters ) {
  6886. super();
  6887. this.type = 'ShaderMaterial';
  6888. this.defines = {};
  6889. this.uniforms = {};
  6890. this.vertexShader = default_vertex;
  6891. this.fragmentShader = default_fragment;
  6892. this.linewidth = 1;
  6893. this.wireframe = false;
  6894. this.wireframeLinewidth = 1;
  6895. this.fog = false; // set to use scene fog
  6896. this.lights = false; // set to use scene lights
  6897. this.clipping = false; // set to use user-defined clipping planes
  6898. this.extensions = {
  6899. derivatives: false, // set to use derivatives
  6900. fragDepth: false, // set to use fragment depth values
  6901. drawBuffers: false, // set to use draw buffers
  6902. shaderTextureLOD: false // set to use shader texture LOD
  6903. };
  6904. // When rendered geometry doesn't include these attributes but the material does,
  6905. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6906. this.defaultAttributeValues = {
  6907. 'color': [ 1, 1, 1 ],
  6908. 'uv': [ 0, 0 ],
  6909. 'uv2': [ 0, 0 ]
  6910. };
  6911. this.index0AttributeName = undefined;
  6912. this.uniformsNeedUpdate = false;
  6913. this.glslVersion = null;
  6914. if ( parameters !== undefined ) {
  6915. if ( parameters.attributes !== undefined ) {
  6916. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6917. }
  6918. this.setValues( parameters );
  6919. }
  6920. }
  6921. copy( source ) {
  6922. super.copy( source );
  6923. this.fragmentShader = source.fragmentShader;
  6924. this.vertexShader = source.vertexShader;
  6925. this.uniforms = cloneUniforms( source.uniforms );
  6926. this.defines = Object.assign( {}, source.defines );
  6927. this.wireframe = source.wireframe;
  6928. this.wireframeLinewidth = source.wireframeLinewidth;
  6929. this.fog = source.fog;
  6930. this.lights = source.lights;
  6931. this.clipping = source.clipping;
  6932. this.extensions = Object.assign( {}, source.extensions );
  6933. this.glslVersion = source.glslVersion;
  6934. return this;
  6935. }
  6936. toJSON( meta ) {
  6937. const data = super.toJSON( meta );
  6938. data.glslVersion = this.glslVersion;
  6939. data.uniforms = {};
  6940. for ( const name in this.uniforms ) {
  6941. const uniform = this.uniforms[ name ];
  6942. const value = uniform.value;
  6943. if ( value && value.isTexture ) {
  6944. data.uniforms[ name ] = {
  6945. type: 't',
  6946. value: value.toJSON( meta ).uuid
  6947. };
  6948. } else if ( value && value.isColor ) {
  6949. data.uniforms[ name ] = {
  6950. type: 'c',
  6951. value: value.getHex()
  6952. };
  6953. } else if ( value && value.isVector2 ) {
  6954. data.uniforms[ name ] = {
  6955. type: 'v2',
  6956. value: value.toArray()
  6957. };
  6958. } else if ( value && value.isVector3 ) {
  6959. data.uniforms[ name ] = {
  6960. type: 'v3',
  6961. value: value.toArray()
  6962. };
  6963. } else if ( value && value.isVector4 ) {
  6964. data.uniforms[ name ] = {
  6965. type: 'v4',
  6966. value: value.toArray()
  6967. };
  6968. } else if ( value && value.isMatrix3 ) {
  6969. data.uniforms[ name ] = {
  6970. type: 'm3',
  6971. value: value.toArray()
  6972. };
  6973. } else if ( value && value.isMatrix4 ) {
  6974. data.uniforms[ name ] = {
  6975. type: 'm4',
  6976. value: value.toArray()
  6977. };
  6978. } else {
  6979. data.uniforms[ name ] = {
  6980. value: value
  6981. };
  6982. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6983. }
  6984. }
  6985. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6986. data.vertexShader = this.vertexShader;
  6987. data.fragmentShader = this.fragmentShader;
  6988. const extensions = {};
  6989. for ( const key in this.extensions ) {
  6990. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6991. }
  6992. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6993. return data;
  6994. }
  6995. }
  6996. ShaderMaterial.prototype.isShaderMaterial = true;
  6997. class Camera extends Object3D {
  6998. constructor() {
  6999. super();
  7000. this.type = 'Camera';
  7001. this.matrixWorldInverse = new Matrix4();
  7002. this.projectionMatrix = new Matrix4();
  7003. this.projectionMatrixInverse = new Matrix4();
  7004. }
  7005. copy( source, recursive ) {
  7006. super.copy( source, recursive );
  7007. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7008. this.projectionMatrix.copy( source.projectionMatrix );
  7009. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7010. return this;
  7011. }
  7012. getWorldDirection( target ) {
  7013. this.updateWorldMatrix( true, false );
  7014. const e = this.matrixWorld.elements;
  7015. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7016. }
  7017. updateMatrixWorld( force ) {
  7018. super.updateMatrixWorld( force );
  7019. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7020. }
  7021. updateWorldMatrix( updateParents, updateChildren ) {
  7022. super.updateWorldMatrix( updateParents, updateChildren );
  7023. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7024. }
  7025. clone() {
  7026. return new this.constructor().copy( this );
  7027. }
  7028. }
  7029. Camera.prototype.isCamera = true;
  7030. class PerspectiveCamera extends Camera {
  7031. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7032. super();
  7033. this.type = 'PerspectiveCamera';
  7034. this.fov = fov;
  7035. this.zoom = 1;
  7036. this.near = near;
  7037. this.far = far;
  7038. this.focus = 10;
  7039. this.aspect = aspect;
  7040. this.view = null;
  7041. this.filmGauge = 35; // width of the film (default in millimeters)
  7042. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7043. this.updateProjectionMatrix();
  7044. }
  7045. copy( source, recursive ) {
  7046. super.copy( source, recursive );
  7047. this.fov = source.fov;
  7048. this.zoom = source.zoom;
  7049. this.near = source.near;
  7050. this.far = source.far;
  7051. this.focus = source.focus;
  7052. this.aspect = source.aspect;
  7053. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7054. this.filmGauge = source.filmGauge;
  7055. this.filmOffset = source.filmOffset;
  7056. return this;
  7057. }
  7058. /**
  7059. * Sets the FOV by focal length in respect to the current .filmGauge.
  7060. *
  7061. * The default film gauge is 35, so that the focal length can be specified for
  7062. * a 35mm (full frame) camera.
  7063. *
  7064. * Values for focal length and film gauge must have the same unit.
  7065. */
  7066. setFocalLength( focalLength ) {
  7067. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7068. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7069. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7070. this.updateProjectionMatrix();
  7071. }
  7072. /**
  7073. * Calculates the focal length from the current .fov and .filmGauge.
  7074. */
  7075. getFocalLength() {
  7076. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7077. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7078. }
  7079. getEffectiveFOV() {
  7080. return RAD2DEG * 2 * Math.atan(
  7081. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7082. }
  7083. getFilmWidth() {
  7084. // film not completely covered in portrait format (aspect < 1)
  7085. return this.filmGauge * Math.min( this.aspect, 1 );
  7086. }
  7087. getFilmHeight() {
  7088. // film not completely covered in landscape format (aspect > 1)
  7089. return this.filmGauge / Math.max( this.aspect, 1 );
  7090. }
  7091. /**
  7092. * Sets an offset in a larger frustum. This is useful for multi-window or
  7093. * multi-monitor/multi-machine setups.
  7094. *
  7095. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7096. * the monitors are in grid like this
  7097. *
  7098. * +---+---+---+
  7099. * | A | B | C |
  7100. * +---+---+---+
  7101. * | D | E | F |
  7102. * +---+---+---+
  7103. *
  7104. * then for each monitor you would call it like this
  7105. *
  7106. * const w = 1920;
  7107. * const h = 1080;
  7108. * const fullWidth = w * 3;
  7109. * const fullHeight = h * 2;
  7110. *
  7111. * --A--
  7112. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7113. * --B--
  7114. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7115. * --C--
  7116. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7117. * --D--
  7118. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7119. * --E--
  7120. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7121. * --F--
  7122. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7123. *
  7124. * Note there is no reason monitors have to be the same size or in a grid.
  7125. */
  7126. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7127. this.aspect = fullWidth / fullHeight;
  7128. if ( this.view === null ) {
  7129. this.view = {
  7130. enabled: true,
  7131. fullWidth: 1,
  7132. fullHeight: 1,
  7133. offsetX: 0,
  7134. offsetY: 0,
  7135. width: 1,
  7136. height: 1
  7137. };
  7138. }
  7139. this.view.enabled = true;
  7140. this.view.fullWidth = fullWidth;
  7141. this.view.fullHeight = fullHeight;
  7142. this.view.offsetX = x;
  7143. this.view.offsetY = y;
  7144. this.view.width = width;
  7145. this.view.height = height;
  7146. this.updateProjectionMatrix();
  7147. }
  7148. clearViewOffset() {
  7149. if ( this.view !== null ) {
  7150. this.view.enabled = false;
  7151. }
  7152. this.updateProjectionMatrix();
  7153. }
  7154. updateProjectionMatrix() {
  7155. const near = this.near;
  7156. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7157. let height = 2 * top;
  7158. let width = this.aspect * height;
  7159. let left = - 0.5 * width;
  7160. const view = this.view;
  7161. if ( this.view !== null && this.view.enabled ) {
  7162. const fullWidth = view.fullWidth,
  7163. fullHeight = view.fullHeight;
  7164. left += view.offsetX * width / fullWidth;
  7165. top -= view.offsetY * height / fullHeight;
  7166. width *= view.width / fullWidth;
  7167. height *= view.height / fullHeight;
  7168. }
  7169. const skew = this.filmOffset;
  7170. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7171. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7172. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7173. }
  7174. toJSON( meta ) {
  7175. const data = super.toJSON( meta );
  7176. data.object.fov = this.fov;
  7177. data.object.zoom = this.zoom;
  7178. data.object.near = this.near;
  7179. data.object.far = this.far;
  7180. data.object.focus = this.focus;
  7181. data.object.aspect = this.aspect;
  7182. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7183. data.object.filmGauge = this.filmGauge;
  7184. data.object.filmOffset = this.filmOffset;
  7185. return data;
  7186. }
  7187. }
  7188. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7189. const fov = 90, aspect = 1;
  7190. class CubeCamera extends Object3D {
  7191. constructor( near, far, renderTarget ) {
  7192. super();
  7193. this.type = 'CubeCamera';
  7194. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7195. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7196. return;
  7197. }
  7198. this.renderTarget = renderTarget;
  7199. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7200. cameraPX.layers = this.layers;
  7201. cameraPX.up.set( 0, - 1, 0 );
  7202. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7203. this.add( cameraPX );
  7204. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7205. cameraNX.layers = this.layers;
  7206. cameraNX.up.set( 0, - 1, 0 );
  7207. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7208. this.add( cameraNX );
  7209. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7210. cameraPY.layers = this.layers;
  7211. cameraPY.up.set( 0, 0, 1 );
  7212. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7213. this.add( cameraPY );
  7214. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7215. cameraNY.layers = this.layers;
  7216. cameraNY.up.set( 0, 0, - 1 );
  7217. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7218. this.add( cameraNY );
  7219. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7220. cameraPZ.layers = this.layers;
  7221. cameraPZ.up.set( 0, - 1, 0 );
  7222. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7223. this.add( cameraPZ );
  7224. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7225. cameraNZ.layers = this.layers;
  7226. cameraNZ.up.set( 0, - 1, 0 );
  7227. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7228. this.add( cameraNZ );
  7229. }
  7230. update( renderer, scene ) {
  7231. if ( this.parent === null ) this.updateMatrixWorld();
  7232. const renderTarget = this.renderTarget;
  7233. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7234. const currentRenderTarget = renderer.getRenderTarget();
  7235. const currentToneMapping = renderer.toneMapping;
  7236. const currentXrEnabled = renderer.xr.enabled;
  7237. renderer.toneMapping = NoToneMapping;
  7238. renderer.xr.enabled = false;
  7239. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7240. renderTarget.texture.generateMipmaps = false;
  7241. renderer.setRenderTarget( renderTarget, 0 );
  7242. renderer.render( scene, cameraPX );
  7243. renderer.setRenderTarget( renderTarget, 1 );
  7244. renderer.render( scene, cameraNX );
  7245. renderer.setRenderTarget( renderTarget, 2 );
  7246. renderer.render( scene, cameraPY );
  7247. renderer.setRenderTarget( renderTarget, 3 );
  7248. renderer.render( scene, cameraNY );
  7249. renderer.setRenderTarget( renderTarget, 4 );
  7250. renderer.render( scene, cameraPZ );
  7251. renderTarget.texture.generateMipmaps = generateMipmaps;
  7252. renderer.setRenderTarget( renderTarget, 5 );
  7253. renderer.render( scene, cameraNZ );
  7254. renderer.setRenderTarget( currentRenderTarget );
  7255. renderer.toneMapping = currentToneMapping;
  7256. renderer.xr.enabled = currentXrEnabled;
  7257. renderTarget.texture.needsPMREMUpdate = true;
  7258. }
  7259. }
  7260. class CubeTexture extends Texture {
  7261. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7262. images = images !== undefined ? images : [];
  7263. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7264. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7265. this.flipY = false;
  7266. }
  7267. get images() {
  7268. return this.image;
  7269. }
  7270. set images( value ) {
  7271. this.image = value;
  7272. }
  7273. }
  7274. CubeTexture.prototype.isCubeTexture = true;
  7275. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7276. constructor( size, options = {} ) {
  7277. super( size, size, options );
  7278. const image = { width: size, height: size, depth: 1 };
  7279. const images = [ image, image, image, image, image, image ];
  7280. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7281. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7282. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7283. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7284. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7285. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7286. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7287. this.texture.isRenderTargetTexture = true;
  7288. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7289. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7290. }
  7291. fromEquirectangularTexture( renderer, texture ) {
  7292. this.texture.type = texture.type;
  7293. this.texture.encoding = texture.encoding;
  7294. this.texture.generateMipmaps = texture.generateMipmaps;
  7295. this.texture.minFilter = texture.minFilter;
  7296. this.texture.magFilter = texture.magFilter;
  7297. const shader = {
  7298. uniforms: {
  7299. tEquirect: { value: null },
  7300. },
  7301. vertexShader: /* glsl */`
  7302. varying vec3 vWorldDirection;
  7303. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7304. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7305. }
  7306. void main() {
  7307. vWorldDirection = transformDirection( position, modelMatrix );
  7308. #include <begin_vertex>
  7309. #include <project_vertex>
  7310. }
  7311. `,
  7312. fragmentShader: /* glsl */`
  7313. uniform sampler2D tEquirect;
  7314. varying vec3 vWorldDirection;
  7315. #include <common>
  7316. void main() {
  7317. vec3 direction = normalize( vWorldDirection );
  7318. vec2 sampleUV = equirectUv( direction );
  7319. gl_FragColor = texture2D( tEquirect, sampleUV );
  7320. }
  7321. `
  7322. };
  7323. const geometry = new BoxGeometry( 5, 5, 5 );
  7324. const material = new ShaderMaterial( {
  7325. name: 'CubemapFromEquirect',
  7326. uniforms: cloneUniforms( shader.uniforms ),
  7327. vertexShader: shader.vertexShader,
  7328. fragmentShader: shader.fragmentShader,
  7329. side: BackSide,
  7330. blending: NoBlending
  7331. } );
  7332. material.uniforms.tEquirect.value = texture;
  7333. const mesh = new Mesh( geometry, material );
  7334. const currentMinFilter = texture.minFilter;
  7335. // Avoid blurred poles
  7336. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7337. const camera = new CubeCamera( 1, 10, this );
  7338. camera.update( renderer, mesh );
  7339. texture.minFilter = currentMinFilter;
  7340. mesh.geometry.dispose();
  7341. mesh.material.dispose();
  7342. return this;
  7343. }
  7344. clear( renderer, color, depth, stencil ) {
  7345. const currentRenderTarget = renderer.getRenderTarget();
  7346. for ( let i = 0; i < 6; i ++ ) {
  7347. renderer.setRenderTarget( this, i );
  7348. renderer.clear( color, depth, stencil );
  7349. }
  7350. renderer.setRenderTarget( currentRenderTarget );
  7351. }
  7352. }
  7353. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7354. const _vector1 = /*@__PURE__*/ new Vector3();
  7355. const _vector2 = /*@__PURE__*/ new Vector3();
  7356. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7357. class Plane {
  7358. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7359. // normal is assumed to be normalized
  7360. this.normal = normal;
  7361. this.constant = constant;
  7362. }
  7363. set( normal, constant ) {
  7364. this.normal.copy( normal );
  7365. this.constant = constant;
  7366. return this;
  7367. }
  7368. setComponents( x, y, z, w ) {
  7369. this.normal.set( x, y, z );
  7370. this.constant = w;
  7371. return this;
  7372. }
  7373. setFromNormalAndCoplanarPoint( normal, point ) {
  7374. this.normal.copy( normal );
  7375. this.constant = - point.dot( this.normal );
  7376. return this;
  7377. }
  7378. setFromCoplanarPoints( a, b, c ) {
  7379. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7380. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7381. this.setFromNormalAndCoplanarPoint( normal, a );
  7382. return this;
  7383. }
  7384. copy( plane ) {
  7385. this.normal.copy( plane.normal );
  7386. this.constant = plane.constant;
  7387. return this;
  7388. }
  7389. normalize() {
  7390. // Note: will lead to a divide by zero if the plane is invalid.
  7391. const inverseNormalLength = 1.0 / this.normal.length();
  7392. this.normal.multiplyScalar( inverseNormalLength );
  7393. this.constant *= inverseNormalLength;
  7394. return this;
  7395. }
  7396. negate() {
  7397. this.constant *= - 1;
  7398. this.normal.negate();
  7399. return this;
  7400. }
  7401. distanceToPoint( point ) {
  7402. return this.normal.dot( point ) + this.constant;
  7403. }
  7404. distanceToSphere( sphere ) {
  7405. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7406. }
  7407. projectPoint( point, target ) {
  7408. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7409. }
  7410. intersectLine( line, target ) {
  7411. const direction = line.delta( _vector1 );
  7412. const denominator = this.normal.dot( direction );
  7413. if ( denominator === 0 ) {
  7414. // line is coplanar, return origin
  7415. if ( this.distanceToPoint( line.start ) === 0 ) {
  7416. return target.copy( line.start );
  7417. }
  7418. // Unsure if this is the correct method to handle this case.
  7419. return null;
  7420. }
  7421. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7422. if ( t < 0 || t > 1 ) {
  7423. return null;
  7424. }
  7425. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7426. }
  7427. intersectsLine( line ) {
  7428. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7429. const startSign = this.distanceToPoint( line.start );
  7430. const endSign = this.distanceToPoint( line.end );
  7431. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7432. }
  7433. intersectsBox( box ) {
  7434. return box.intersectsPlane( this );
  7435. }
  7436. intersectsSphere( sphere ) {
  7437. return sphere.intersectsPlane( this );
  7438. }
  7439. coplanarPoint( target ) {
  7440. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7441. }
  7442. applyMatrix4( matrix, optionalNormalMatrix ) {
  7443. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7444. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7445. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7446. this.constant = - referencePoint.dot( normal );
  7447. return this;
  7448. }
  7449. translate( offset ) {
  7450. this.constant -= offset.dot( this.normal );
  7451. return this;
  7452. }
  7453. equals( plane ) {
  7454. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7455. }
  7456. clone() {
  7457. return new this.constructor().copy( this );
  7458. }
  7459. }
  7460. Plane.prototype.isPlane = true;
  7461. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7462. const _vector$7 = /*@__PURE__*/ new Vector3();
  7463. class Frustum {
  7464. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7465. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7466. }
  7467. set( p0, p1, p2, p3, p4, p5 ) {
  7468. const planes = this.planes;
  7469. planes[ 0 ].copy( p0 );
  7470. planes[ 1 ].copy( p1 );
  7471. planes[ 2 ].copy( p2 );
  7472. planes[ 3 ].copy( p3 );
  7473. planes[ 4 ].copy( p4 );
  7474. planes[ 5 ].copy( p5 );
  7475. return this;
  7476. }
  7477. copy( frustum ) {
  7478. const planes = this.planes;
  7479. for ( let i = 0; i < 6; i ++ ) {
  7480. planes[ i ].copy( frustum.planes[ i ] );
  7481. }
  7482. return this;
  7483. }
  7484. setFromProjectionMatrix( m ) {
  7485. const planes = this.planes;
  7486. const me = m.elements;
  7487. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7488. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7489. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7490. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7491. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7492. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7493. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7494. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7495. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7496. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7497. return this;
  7498. }
  7499. intersectsObject( object ) {
  7500. const geometry = object.geometry;
  7501. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7502. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7503. return this.intersectsSphere( _sphere$2 );
  7504. }
  7505. intersectsSprite( sprite ) {
  7506. _sphere$2.center.set( 0, 0, 0 );
  7507. _sphere$2.radius = 0.7071067811865476;
  7508. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7509. return this.intersectsSphere( _sphere$2 );
  7510. }
  7511. intersectsSphere( sphere ) {
  7512. const planes = this.planes;
  7513. const center = sphere.center;
  7514. const negRadius = - sphere.radius;
  7515. for ( let i = 0; i < 6; i ++ ) {
  7516. const distance = planes[ i ].distanceToPoint( center );
  7517. if ( distance < negRadius ) {
  7518. return false;
  7519. }
  7520. }
  7521. return true;
  7522. }
  7523. intersectsBox( box ) {
  7524. const planes = this.planes;
  7525. for ( let i = 0; i < 6; i ++ ) {
  7526. const plane = planes[ i ];
  7527. // corner at max distance
  7528. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7529. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7530. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7531. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7532. return false;
  7533. }
  7534. }
  7535. return true;
  7536. }
  7537. containsPoint( point ) {
  7538. const planes = this.planes;
  7539. for ( let i = 0; i < 6; i ++ ) {
  7540. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7541. return false;
  7542. }
  7543. }
  7544. return true;
  7545. }
  7546. clone() {
  7547. return new this.constructor().copy( this );
  7548. }
  7549. }
  7550. function WebGLAnimation() {
  7551. let context = null;
  7552. let isAnimating = false;
  7553. let animationLoop = null;
  7554. let requestId = null;
  7555. function onAnimationFrame( time, frame ) {
  7556. animationLoop( time, frame );
  7557. requestId = context.requestAnimationFrame( onAnimationFrame );
  7558. }
  7559. return {
  7560. start: function () {
  7561. if ( isAnimating === true ) return;
  7562. if ( animationLoop === null ) return;
  7563. requestId = context.requestAnimationFrame( onAnimationFrame );
  7564. isAnimating = true;
  7565. },
  7566. stop: function () {
  7567. context.cancelAnimationFrame( requestId );
  7568. isAnimating = false;
  7569. },
  7570. setAnimationLoop: function ( callback ) {
  7571. animationLoop = callback;
  7572. },
  7573. setContext: function ( value ) {
  7574. context = value;
  7575. }
  7576. };
  7577. }
  7578. function WebGLAttributes( gl, capabilities ) {
  7579. const isWebGL2 = capabilities.isWebGL2;
  7580. const buffers = new WeakMap();
  7581. function createBuffer( attribute, bufferType ) {
  7582. const array = attribute.array;
  7583. const usage = attribute.usage;
  7584. const buffer = gl.createBuffer();
  7585. gl.bindBuffer( bufferType, buffer );
  7586. gl.bufferData( bufferType, array, usage );
  7587. attribute.onUploadCallback();
  7588. let type;
  7589. if ( array instanceof Float32Array ) {
  7590. type = 5126;
  7591. } else if ( array instanceof Uint16Array ) {
  7592. if ( attribute.isFloat16BufferAttribute ) {
  7593. if ( isWebGL2 ) {
  7594. type = 5131;
  7595. } else {
  7596. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7597. }
  7598. } else {
  7599. type = 5123;
  7600. }
  7601. } else if ( array instanceof Int16Array ) {
  7602. type = 5122;
  7603. } else if ( array instanceof Uint32Array ) {
  7604. type = 5125;
  7605. } else if ( array instanceof Int32Array ) {
  7606. type = 5124;
  7607. } else if ( array instanceof Int8Array ) {
  7608. type = 5120;
  7609. } else if ( array instanceof Uint8Array ) {
  7610. type = 5121;
  7611. } else if ( array instanceof Uint8ClampedArray ) {
  7612. type = 5121;
  7613. } else {
  7614. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7615. }
  7616. return {
  7617. buffer: buffer,
  7618. type: type,
  7619. bytesPerElement: array.BYTES_PER_ELEMENT,
  7620. version: attribute.version
  7621. };
  7622. }
  7623. function updateBuffer( buffer, attribute, bufferType ) {
  7624. const array = attribute.array;
  7625. const updateRange = attribute.updateRange;
  7626. gl.bindBuffer( bufferType, buffer );
  7627. if ( updateRange.count === - 1 ) {
  7628. // Not using update ranges
  7629. gl.bufferSubData( bufferType, 0, array );
  7630. } else {
  7631. if ( isWebGL2 ) {
  7632. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7633. array, updateRange.offset, updateRange.count );
  7634. } else {
  7635. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7636. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7637. }
  7638. updateRange.count = - 1; // reset range
  7639. }
  7640. }
  7641. //
  7642. function get( attribute ) {
  7643. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7644. return buffers.get( attribute );
  7645. }
  7646. function remove( attribute ) {
  7647. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7648. const data = buffers.get( attribute );
  7649. if ( data ) {
  7650. gl.deleteBuffer( data.buffer );
  7651. buffers.delete( attribute );
  7652. }
  7653. }
  7654. function update( attribute, bufferType ) {
  7655. if ( attribute.isGLBufferAttribute ) {
  7656. const cached = buffers.get( attribute );
  7657. if ( ! cached || cached.version < attribute.version ) {
  7658. buffers.set( attribute, {
  7659. buffer: attribute.buffer,
  7660. type: attribute.type,
  7661. bytesPerElement: attribute.elementSize,
  7662. version: attribute.version
  7663. } );
  7664. }
  7665. return;
  7666. }
  7667. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7668. const data = buffers.get( attribute );
  7669. if ( data === undefined ) {
  7670. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7671. } else if ( data.version < attribute.version ) {
  7672. updateBuffer( data.buffer, attribute, bufferType );
  7673. data.version = attribute.version;
  7674. }
  7675. }
  7676. return {
  7677. get: get,
  7678. remove: remove,
  7679. update: update
  7680. };
  7681. }
  7682. class PlaneGeometry extends BufferGeometry {
  7683. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7684. super();
  7685. this.type = 'PlaneGeometry';
  7686. this.parameters = {
  7687. width: width,
  7688. height: height,
  7689. widthSegments: widthSegments,
  7690. heightSegments: heightSegments
  7691. };
  7692. const width_half = width / 2;
  7693. const height_half = height / 2;
  7694. const gridX = Math.floor( widthSegments );
  7695. const gridY = Math.floor( heightSegments );
  7696. const gridX1 = gridX + 1;
  7697. const gridY1 = gridY + 1;
  7698. const segment_width = width / gridX;
  7699. const segment_height = height / gridY;
  7700. //
  7701. const indices = [];
  7702. const vertices = [];
  7703. const normals = [];
  7704. const uvs = [];
  7705. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7706. const y = iy * segment_height - height_half;
  7707. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7708. const x = ix * segment_width - width_half;
  7709. vertices.push( x, - y, 0 );
  7710. normals.push( 0, 0, 1 );
  7711. uvs.push( ix / gridX );
  7712. uvs.push( 1 - ( iy / gridY ) );
  7713. }
  7714. }
  7715. for ( let iy = 0; iy < gridY; iy ++ ) {
  7716. for ( let ix = 0; ix < gridX; ix ++ ) {
  7717. const a = ix + gridX1 * iy;
  7718. const b = ix + gridX1 * ( iy + 1 );
  7719. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7720. const d = ( ix + 1 ) + gridX1 * iy;
  7721. indices.push( a, b, d );
  7722. indices.push( b, c, d );
  7723. }
  7724. }
  7725. this.setIndex( indices );
  7726. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7727. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7728. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7729. }
  7730. static fromJSON( data ) {
  7731. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7732. }
  7733. }
  7734. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7735. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7736. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7737. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7738. 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";
  7739. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7740. var begin_vertex = "vec3 transformed = vec3( position );";
  7741. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7742. 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 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}\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";
  7743. 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 = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\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";
  7744. 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";
  7745. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7746. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7747. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7748. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7749. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7750. 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";
  7751. 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";
  7752. 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; }\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 color ) { return dot( color, vec3( 0.3333 ) ); }\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 linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.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}";
  7753. 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 r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + 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 ), 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";
  7754. 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";
  7755. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7756. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7757. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7758. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7759. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7760. 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}";
  7761. 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";
  7762. 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";
  7763. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\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";
  7764. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\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";
  7765. 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";
  7766. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7767. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7768. 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";
  7769. 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";
  7770. 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\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7771. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7772. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7773. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7774. 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";
  7775. 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";
  7776. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7777. 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)";
  7778. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7779. 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)";
  7780. 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\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( ( ior - 1.0 ) / ( 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_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";
  7781. 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_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\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}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 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\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\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\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\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}";
  7782. 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\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7783. 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";
  7784. 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";
  7785. 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";
  7786. 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";
  7787. 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";
  7788. 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";
  7789. 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";
  7790. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7791. 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";
  7792. 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";
  7793. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7794. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7795. 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";
  7796. 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";
  7797. 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";
  7798. 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";
  7799. 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;";
  7800. 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";
  7801. 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";
  7802. 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";
  7803. 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";
  7804. 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 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\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";
  7805. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7806. 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";
  7807. 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";
  7808. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7809. 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}";
  7810. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7811. 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;";
  7812. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7813. 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";
  7814. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7815. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7816. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7817. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7818. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7819. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7820. 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";
  7821. 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";
  7822. 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";
  7823. 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";
  7824. 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";
  7825. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7826. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7827. 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; }";
  7828. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= 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, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  7829. 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";
  7830. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7831. 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";
  7832. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7833. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7834. 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";
  7835. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7836. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7837. 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}";
  7838. 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}";
  7839. 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}";
  7840. 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}";
  7841. 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}";
  7842. 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}";
  7843. 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}";
  7844. 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}";
  7845. 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}";
  7846. 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}";
  7847. 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}";
  7848. 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}";
  7849. 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}";
  7850. 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 <cube_uv_reflection_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}";
  7851. const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_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 <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 <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7852. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\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 <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_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 <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\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}";
  7853. 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}";
  7854. 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}";
  7855. 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}";
  7856. 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}";
  7857. 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}";
  7858. 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 <cube_uv_reflection_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}";
  7859. 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}";
  7860. 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_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 <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 <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}";
  7861. 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}";
  7862. 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}";
  7863. 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}";
  7864. 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}";
  7865. 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}";
  7866. 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}";
  7867. 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}";
  7868. 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}";
  7869. const ShaderChunk = {
  7870. alphamap_fragment: alphamap_fragment,
  7871. alphamap_pars_fragment: alphamap_pars_fragment,
  7872. alphatest_fragment: alphatest_fragment,
  7873. alphatest_pars_fragment: alphatest_pars_fragment,
  7874. aomap_fragment: aomap_fragment,
  7875. aomap_pars_fragment: aomap_pars_fragment,
  7876. begin_vertex: begin_vertex,
  7877. beginnormal_vertex: beginnormal_vertex,
  7878. bsdfs: bsdfs,
  7879. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7880. clipping_planes_fragment: clipping_planes_fragment,
  7881. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7882. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7883. clipping_planes_vertex: clipping_planes_vertex,
  7884. color_fragment: color_fragment,
  7885. color_pars_fragment: color_pars_fragment,
  7886. color_pars_vertex: color_pars_vertex,
  7887. color_vertex: color_vertex,
  7888. common: common,
  7889. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7890. defaultnormal_vertex: defaultnormal_vertex,
  7891. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7892. displacementmap_vertex: displacementmap_vertex,
  7893. emissivemap_fragment: emissivemap_fragment,
  7894. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7895. encodings_fragment: encodings_fragment,
  7896. encodings_pars_fragment: encodings_pars_fragment,
  7897. envmap_fragment: envmap_fragment,
  7898. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7899. envmap_pars_fragment: envmap_pars_fragment,
  7900. envmap_pars_vertex: envmap_pars_vertex,
  7901. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7902. envmap_vertex: envmap_vertex,
  7903. fog_vertex: fog_vertex,
  7904. fog_pars_vertex: fog_pars_vertex,
  7905. fog_fragment: fog_fragment,
  7906. fog_pars_fragment: fog_pars_fragment,
  7907. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7908. lightmap_fragment: lightmap_fragment,
  7909. lightmap_pars_fragment: lightmap_pars_fragment,
  7910. lights_lambert_vertex: lights_lambert_vertex,
  7911. lights_pars_begin: lights_pars_begin,
  7912. lights_toon_fragment: lights_toon_fragment,
  7913. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7914. lights_phong_fragment: lights_phong_fragment,
  7915. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7916. lights_physical_fragment: lights_physical_fragment,
  7917. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7918. lights_fragment_begin: lights_fragment_begin,
  7919. lights_fragment_maps: lights_fragment_maps,
  7920. lights_fragment_end: lights_fragment_end,
  7921. logdepthbuf_fragment: logdepthbuf_fragment,
  7922. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7923. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7924. logdepthbuf_vertex: logdepthbuf_vertex,
  7925. map_fragment: map_fragment,
  7926. map_pars_fragment: map_pars_fragment,
  7927. map_particle_fragment: map_particle_fragment,
  7928. map_particle_pars_fragment: map_particle_pars_fragment,
  7929. metalnessmap_fragment: metalnessmap_fragment,
  7930. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7931. morphcolor_vertex: morphcolor_vertex,
  7932. morphnormal_vertex: morphnormal_vertex,
  7933. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7934. morphtarget_vertex: morphtarget_vertex,
  7935. normal_fragment_begin: normal_fragment_begin,
  7936. normal_fragment_maps: normal_fragment_maps,
  7937. normal_pars_fragment: normal_pars_fragment,
  7938. normal_pars_vertex: normal_pars_vertex,
  7939. normal_vertex: normal_vertex,
  7940. normalmap_pars_fragment: normalmap_pars_fragment,
  7941. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7942. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7943. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7944. output_fragment: output_fragment,
  7945. packing: packing,
  7946. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7947. project_vertex: project_vertex,
  7948. dithering_fragment: dithering_fragment,
  7949. dithering_pars_fragment: dithering_pars_fragment,
  7950. roughnessmap_fragment: roughnessmap_fragment,
  7951. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7952. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7953. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7954. shadowmap_vertex: shadowmap_vertex,
  7955. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7956. skinbase_vertex: skinbase_vertex,
  7957. skinning_pars_vertex: skinning_pars_vertex,
  7958. skinning_vertex: skinning_vertex,
  7959. skinnormal_vertex: skinnormal_vertex,
  7960. specularmap_fragment: specularmap_fragment,
  7961. specularmap_pars_fragment: specularmap_pars_fragment,
  7962. tonemapping_fragment: tonemapping_fragment,
  7963. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7964. transmission_fragment: transmission_fragment,
  7965. transmission_pars_fragment: transmission_pars_fragment,
  7966. uv_pars_fragment: uv_pars_fragment,
  7967. uv_pars_vertex: uv_pars_vertex,
  7968. uv_vertex: uv_vertex,
  7969. uv2_pars_fragment: uv2_pars_fragment,
  7970. uv2_pars_vertex: uv2_pars_vertex,
  7971. uv2_vertex: uv2_vertex,
  7972. worldpos_vertex: worldpos_vertex,
  7973. background_vert: vertex$g,
  7974. background_frag: fragment$g,
  7975. cube_vert: vertex$f,
  7976. cube_frag: fragment$f,
  7977. depth_vert: vertex$e,
  7978. depth_frag: fragment$e,
  7979. distanceRGBA_vert: vertex$d,
  7980. distanceRGBA_frag: fragment$d,
  7981. equirect_vert: vertex$c,
  7982. equirect_frag: fragment$c,
  7983. linedashed_vert: vertex$b,
  7984. linedashed_frag: fragment$b,
  7985. meshbasic_vert: vertex$a,
  7986. meshbasic_frag: fragment$a,
  7987. meshlambert_vert: vertex$9,
  7988. meshlambert_frag: fragment$9,
  7989. meshmatcap_vert: vertex$8,
  7990. meshmatcap_frag: fragment$8,
  7991. meshnormal_vert: vertex$7,
  7992. meshnormal_frag: fragment$7,
  7993. meshphong_vert: vertex$6,
  7994. meshphong_frag: fragment$6,
  7995. meshphysical_vert: vertex$5,
  7996. meshphysical_frag: fragment$5,
  7997. meshtoon_vert: vertex$4,
  7998. meshtoon_frag: fragment$4,
  7999. points_vert: vertex$3,
  8000. points_frag: fragment$3,
  8001. shadow_vert: vertex$2,
  8002. shadow_frag: fragment$2,
  8003. sprite_vert: vertex$1,
  8004. sprite_frag: fragment$1
  8005. };
  8006. /**
  8007. * Uniforms library for shared webgl shaders
  8008. */
  8009. const UniformsLib = {
  8010. common: {
  8011. diffuse: { value: new Color( 0xffffff ) },
  8012. opacity: { value: 1.0 },
  8013. map: { value: null },
  8014. uvTransform: { value: new Matrix3() },
  8015. uv2Transform: { value: new Matrix3() },
  8016. alphaMap: { value: null },
  8017. alphaTest: { value: 0 }
  8018. },
  8019. specularmap: {
  8020. specularMap: { value: null },
  8021. },
  8022. envmap: {
  8023. envMap: { value: null },
  8024. flipEnvMap: { value: - 1 },
  8025. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8026. ior: { value: 1.5 }, // physical
  8027. refractionRatio: { value: 0.98 } // basic, lambert, phong
  8028. },
  8029. aomap: {
  8030. aoMap: { value: null },
  8031. aoMapIntensity: { value: 1 }
  8032. },
  8033. lightmap: {
  8034. lightMap: { value: null },
  8035. lightMapIntensity: { value: 1 }
  8036. },
  8037. emissivemap: {
  8038. emissiveMap: { value: null }
  8039. },
  8040. bumpmap: {
  8041. bumpMap: { value: null },
  8042. bumpScale: { value: 1 }
  8043. },
  8044. normalmap: {
  8045. normalMap: { value: null },
  8046. normalScale: { value: new Vector2( 1, 1 ) }
  8047. },
  8048. displacementmap: {
  8049. displacementMap: { value: null },
  8050. displacementScale: { value: 1 },
  8051. displacementBias: { value: 0 }
  8052. },
  8053. roughnessmap: {
  8054. roughnessMap: { value: null }
  8055. },
  8056. metalnessmap: {
  8057. metalnessMap: { value: null }
  8058. },
  8059. gradientmap: {
  8060. gradientMap: { value: null }
  8061. },
  8062. fog: {
  8063. fogDensity: { value: 0.00025 },
  8064. fogNear: { value: 1 },
  8065. fogFar: { value: 2000 },
  8066. fogColor: { value: new Color( 0xffffff ) }
  8067. },
  8068. lights: {
  8069. ambientLightColor: { value: [] },
  8070. lightProbe: { value: [] },
  8071. directionalLights: { value: [], properties: {
  8072. direction: {},
  8073. color: {}
  8074. } },
  8075. directionalLightShadows: { value: [], properties: {
  8076. shadowBias: {},
  8077. shadowNormalBias: {},
  8078. shadowRadius: {},
  8079. shadowMapSize: {}
  8080. } },
  8081. directionalShadowMap: { value: [] },
  8082. directionalShadowMatrix: { value: [] },
  8083. spotLights: { value: [], properties: {
  8084. color: {},
  8085. position: {},
  8086. direction: {},
  8087. distance: {},
  8088. coneCos: {},
  8089. penumbraCos: {},
  8090. decay: {}
  8091. } },
  8092. spotLightShadows: { value: [], properties: {
  8093. shadowBias: {},
  8094. shadowNormalBias: {},
  8095. shadowRadius: {},
  8096. shadowMapSize: {}
  8097. } },
  8098. spotShadowMap: { value: [] },
  8099. spotShadowMatrix: { value: [] },
  8100. pointLights: { value: [], properties: {
  8101. color: {},
  8102. position: {},
  8103. decay: {},
  8104. distance: {}
  8105. } },
  8106. pointLightShadows: { value: [], properties: {
  8107. shadowBias: {},
  8108. shadowNormalBias: {},
  8109. shadowRadius: {},
  8110. shadowMapSize: {},
  8111. shadowCameraNear: {},
  8112. shadowCameraFar: {}
  8113. } },
  8114. pointShadowMap: { value: [] },
  8115. pointShadowMatrix: { value: [] },
  8116. hemisphereLights: { value: [], properties: {
  8117. direction: {},
  8118. skyColor: {},
  8119. groundColor: {}
  8120. } },
  8121. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8122. rectAreaLights: { value: [], properties: {
  8123. color: {},
  8124. position: {},
  8125. width: {},
  8126. height: {}
  8127. } },
  8128. ltc_1: { value: null },
  8129. ltc_2: { value: null }
  8130. },
  8131. points: {
  8132. diffuse: { value: new Color( 0xffffff ) },
  8133. opacity: { value: 1.0 },
  8134. size: { value: 1.0 },
  8135. scale: { value: 1.0 },
  8136. map: { value: null },
  8137. alphaMap: { value: null },
  8138. alphaTest: { value: 0 },
  8139. uvTransform: { value: new Matrix3() }
  8140. },
  8141. sprite: {
  8142. diffuse: { value: new Color( 0xffffff ) },
  8143. opacity: { value: 1.0 },
  8144. center: { value: new Vector2( 0.5, 0.5 ) },
  8145. rotation: { value: 0.0 },
  8146. map: { value: null },
  8147. alphaMap: { value: null },
  8148. alphaTest: { value: 0 },
  8149. uvTransform: { value: new Matrix3() }
  8150. }
  8151. };
  8152. const ShaderLib = {
  8153. basic: {
  8154. uniforms: mergeUniforms( [
  8155. UniformsLib.common,
  8156. UniformsLib.specularmap,
  8157. UniformsLib.envmap,
  8158. UniformsLib.aomap,
  8159. UniformsLib.lightmap,
  8160. UniformsLib.fog
  8161. ] ),
  8162. vertexShader: ShaderChunk.meshbasic_vert,
  8163. fragmentShader: ShaderChunk.meshbasic_frag
  8164. },
  8165. lambert: {
  8166. uniforms: mergeUniforms( [
  8167. UniformsLib.common,
  8168. UniformsLib.specularmap,
  8169. UniformsLib.envmap,
  8170. UniformsLib.aomap,
  8171. UniformsLib.lightmap,
  8172. UniformsLib.emissivemap,
  8173. UniformsLib.fog,
  8174. UniformsLib.lights,
  8175. {
  8176. emissive: { value: new Color( 0x000000 ) }
  8177. }
  8178. ] ),
  8179. vertexShader: ShaderChunk.meshlambert_vert,
  8180. fragmentShader: ShaderChunk.meshlambert_frag
  8181. },
  8182. phong: {
  8183. uniforms: mergeUniforms( [
  8184. UniformsLib.common,
  8185. UniformsLib.specularmap,
  8186. UniformsLib.envmap,
  8187. UniformsLib.aomap,
  8188. UniformsLib.lightmap,
  8189. UniformsLib.emissivemap,
  8190. UniformsLib.bumpmap,
  8191. UniformsLib.normalmap,
  8192. UniformsLib.displacementmap,
  8193. UniformsLib.fog,
  8194. UniformsLib.lights,
  8195. {
  8196. emissive: { value: new Color( 0x000000 ) },
  8197. specular: { value: new Color( 0x111111 ) },
  8198. shininess: { value: 30 }
  8199. }
  8200. ] ),
  8201. vertexShader: ShaderChunk.meshphong_vert,
  8202. fragmentShader: ShaderChunk.meshphong_frag
  8203. },
  8204. standard: {
  8205. uniforms: mergeUniforms( [
  8206. UniformsLib.common,
  8207. UniformsLib.envmap,
  8208. UniformsLib.aomap,
  8209. UniformsLib.lightmap,
  8210. UniformsLib.emissivemap,
  8211. UniformsLib.bumpmap,
  8212. UniformsLib.normalmap,
  8213. UniformsLib.displacementmap,
  8214. UniformsLib.roughnessmap,
  8215. UniformsLib.metalnessmap,
  8216. UniformsLib.fog,
  8217. UniformsLib.lights,
  8218. {
  8219. emissive: { value: new Color( 0x000000 ) },
  8220. roughness: { value: 1.0 },
  8221. metalness: { value: 0.0 },
  8222. envMapIntensity: { value: 1 } // temporary
  8223. }
  8224. ] ),
  8225. vertexShader: ShaderChunk.meshphysical_vert,
  8226. fragmentShader: ShaderChunk.meshphysical_frag
  8227. },
  8228. toon: {
  8229. uniforms: mergeUniforms( [
  8230. UniformsLib.common,
  8231. UniformsLib.aomap,
  8232. UniformsLib.lightmap,
  8233. UniformsLib.emissivemap,
  8234. UniformsLib.bumpmap,
  8235. UniformsLib.normalmap,
  8236. UniformsLib.displacementmap,
  8237. UniformsLib.gradientmap,
  8238. UniformsLib.fog,
  8239. UniformsLib.lights,
  8240. {
  8241. emissive: { value: new Color( 0x000000 ) }
  8242. }
  8243. ] ),
  8244. vertexShader: ShaderChunk.meshtoon_vert,
  8245. fragmentShader: ShaderChunk.meshtoon_frag
  8246. },
  8247. matcap: {
  8248. uniforms: mergeUniforms( [
  8249. UniformsLib.common,
  8250. UniformsLib.bumpmap,
  8251. UniformsLib.normalmap,
  8252. UniformsLib.displacementmap,
  8253. UniformsLib.fog,
  8254. {
  8255. matcap: { value: null }
  8256. }
  8257. ] ),
  8258. vertexShader: ShaderChunk.meshmatcap_vert,
  8259. fragmentShader: ShaderChunk.meshmatcap_frag
  8260. },
  8261. points: {
  8262. uniforms: mergeUniforms( [
  8263. UniformsLib.points,
  8264. UniformsLib.fog
  8265. ] ),
  8266. vertexShader: ShaderChunk.points_vert,
  8267. fragmentShader: ShaderChunk.points_frag
  8268. },
  8269. dashed: {
  8270. uniforms: mergeUniforms( [
  8271. UniformsLib.common,
  8272. UniformsLib.fog,
  8273. {
  8274. scale: { value: 1 },
  8275. dashSize: { value: 1 },
  8276. totalSize: { value: 2 }
  8277. }
  8278. ] ),
  8279. vertexShader: ShaderChunk.linedashed_vert,
  8280. fragmentShader: ShaderChunk.linedashed_frag
  8281. },
  8282. depth: {
  8283. uniforms: mergeUniforms( [
  8284. UniformsLib.common,
  8285. UniformsLib.displacementmap
  8286. ] ),
  8287. vertexShader: ShaderChunk.depth_vert,
  8288. fragmentShader: ShaderChunk.depth_frag
  8289. },
  8290. normal: {
  8291. uniforms: mergeUniforms( [
  8292. UniformsLib.common,
  8293. UniformsLib.bumpmap,
  8294. UniformsLib.normalmap,
  8295. UniformsLib.displacementmap,
  8296. {
  8297. opacity: { value: 1.0 }
  8298. }
  8299. ] ),
  8300. vertexShader: ShaderChunk.meshnormal_vert,
  8301. fragmentShader: ShaderChunk.meshnormal_frag
  8302. },
  8303. sprite: {
  8304. uniforms: mergeUniforms( [
  8305. UniformsLib.sprite,
  8306. UniformsLib.fog
  8307. ] ),
  8308. vertexShader: ShaderChunk.sprite_vert,
  8309. fragmentShader: ShaderChunk.sprite_frag
  8310. },
  8311. background: {
  8312. uniforms: {
  8313. uvTransform: { value: new Matrix3() },
  8314. t2D: { value: null },
  8315. },
  8316. vertexShader: ShaderChunk.background_vert,
  8317. fragmentShader: ShaderChunk.background_frag
  8318. },
  8319. /* -------------------------------------------------------------------------
  8320. // Cube map shader
  8321. ------------------------------------------------------------------------- */
  8322. cube: {
  8323. uniforms: mergeUniforms( [
  8324. UniformsLib.envmap,
  8325. {
  8326. opacity: { value: 1.0 }
  8327. }
  8328. ] ),
  8329. vertexShader: ShaderChunk.cube_vert,
  8330. fragmentShader: ShaderChunk.cube_frag
  8331. },
  8332. equirect: {
  8333. uniforms: {
  8334. tEquirect: { value: null },
  8335. },
  8336. vertexShader: ShaderChunk.equirect_vert,
  8337. fragmentShader: ShaderChunk.equirect_frag
  8338. },
  8339. distanceRGBA: {
  8340. uniforms: mergeUniforms( [
  8341. UniformsLib.common,
  8342. UniformsLib.displacementmap,
  8343. {
  8344. referencePosition: { value: new Vector3() },
  8345. nearDistance: { value: 1 },
  8346. farDistance: { value: 1000 }
  8347. }
  8348. ] ),
  8349. vertexShader: ShaderChunk.distanceRGBA_vert,
  8350. fragmentShader: ShaderChunk.distanceRGBA_frag
  8351. },
  8352. shadow: {
  8353. uniforms: mergeUniforms( [
  8354. UniformsLib.lights,
  8355. UniformsLib.fog,
  8356. {
  8357. color: { value: new Color( 0x00000 ) },
  8358. opacity: { value: 1.0 }
  8359. },
  8360. ] ),
  8361. vertexShader: ShaderChunk.shadow_vert,
  8362. fragmentShader: ShaderChunk.shadow_frag
  8363. }
  8364. };
  8365. ShaderLib.physical = {
  8366. uniforms: mergeUniforms( [
  8367. ShaderLib.standard.uniforms,
  8368. {
  8369. clearcoat: { value: 0 },
  8370. clearcoatMap: { value: null },
  8371. clearcoatRoughness: { value: 0 },
  8372. clearcoatRoughnessMap: { value: null },
  8373. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8374. clearcoatNormalMap: { value: null },
  8375. sheen: { value: 0 },
  8376. sheenColor: { value: new Color( 0x000000 ) },
  8377. sheenColorMap: { value: null },
  8378. sheenRoughness: { value: 1 },
  8379. sheenRoughnessMap: { value: null },
  8380. transmission: { value: 0 },
  8381. transmissionMap: { value: null },
  8382. transmissionSamplerSize: { value: new Vector2() },
  8383. transmissionSamplerMap: { value: null },
  8384. thickness: { value: 0 },
  8385. thicknessMap: { value: null },
  8386. attenuationDistance: { value: 0 },
  8387. attenuationColor: { value: new Color( 0x000000 ) },
  8388. specularIntensity: { value: 1 },
  8389. specularIntensityMap: { value: null },
  8390. specularColor: { value: new Color( 1, 1, 1 ) },
  8391. specularColorMap: { value: null },
  8392. }
  8393. ] ),
  8394. vertexShader: ShaderChunk.meshphysical_vert,
  8395. fragmentShader: ShaderChunk.meshphysical_frag
  8396. };
  8397. function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
  8398. const clearColor = new Color( 0x000000 );
  8399. let clearAlpha = alpha === true ? 0 : 1;
  8400. let planeMesh;
  8401. let boxMesh;
  8402. let currentBackground = null;
  8403. let currentBackgroundVersion = 0;
  8404. let currentTonemapping = null;
  8405. function render( renderList, scene ) {
  8406. let forceClear = false;
  8407. let background = scene.isScene === true ? scene.background : null;
  8408. if ( background && background.isTexture ) {
  8409. background = cubemaps.get( background );
  8410. }
  8411. // Ignore background in AR
  8412. // TODO: Reconsider this.
  8413. const xr = renderer.xr;
  8414. const session = xr.getSession && xr.getSession();
  8415. if ( session && session.environmentBlendMode === 'additive' ) {
  8416. background = null;
  8417. }
  8418. if ( background === null ) {
  8419. setClear( clearColor, clearAlpha );
  8420. } else if ( background && background.isColor ) {
  8421. setClear( background, 1 );
  8422. forceClear = true;
  8423. }
  8424. if ( renderer.autoClear || forceClear ) {
  8425. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8426. }
  8427. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8428. if ( boxMesh === undefined ) {
  8429. boxMesh = new Mesh(
  8430. new BoxGeometry( 1, 1, 1 ),
  8431. new ShaderMaterial( {
  8432. name: 'BackgroundCubeMaterial',
  8433. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8434. vertexShader: ShaderLib.cube.vertexShader,
  8435. fragmentShader: ShaderLib.cube.fragmentShader,
  8436. side: BackSide,
  8437. depthTest: false,
  8438. depthWrite: false,
  8439. fog: false
  8440. } )
  8441. );
  8442. boxMesh.geometry.deleteAttribute( 'normal' );
  8443. boxMesh.geometry.deleteAttribute( 'uv' );
  8444. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8445. this.matrixWorld.copyPosition( camera.matrixWorld );
  8446. };
  8447. // enable code injection for non-built-in material
  8448. Object.defineProperty( boxMesh.material, 'envMap', {
  8449. get: function () {
  8450. return this.uniforms.envMap.value;
  8451. }
  8452. } );
  8453. objects.update( boxMesh );
  8454. }
  8455. boxMesh.material.uniforms.envMap.value = background;
  8456. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8457. if ( currentBackground !== background ||
  8458. currentBackgroundVersion !== background.version ||
  8459. currentTonemapping !== renderer.toneMapping ) {
  8460. boxMesh.material.needsUpdate = true;
  8461. currentBackground = background;
  8462. currentBackgroundVersion = background.version;
  8463. currentTonemapping = renderer.toneMapping;
  8464. }
  8465. boxMesh.layers.enableAll();
  8466. // push to the pre-sorted opaque render list
  8467. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8468. } else if ( background && background.isTexture ) {
  8469. if ( planeMesh === undefined ) {
  8470. planeMesh = new Mesh(
  8471. new PlaneGeometry( 2, 2 ),
  8472. new ShaderMaterial( {
  8473. name: 'BackgroundMaterial',
  8474. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8475. vertexShader: ShaderLib.background.vertexShader,
  8476. fragmentShader: ShaderLib.background.fragmentShader,
  8477. side: FrontSide,
  8478. depthTest: false,
  8479. depthWrite: false,
  8480. fog: false
  8481. } )
  8482. );
  8483. planeMesh.geometry.deleteAttribute( 'normal' );
  8484. // enable code injection for non-built-in material
  8485. Object.defineProperty( planeMesh.material, 'map', {
  8486. get: function () {
  8487. return this.uniforms.t2D.value;
  8488. }
  8489. } );
  8490. objects.update( planeMesh );
  8491. }
  8492. planeMesh.material.uniforms.t2D.value = background;
  8493. if ( background.matrixAutoUpdate === true ) {
  8494. background.updateMatrix();
  8495. }
  8496. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8497. if ( currentBackground !== background ||
  8498. currentBackgroundVersion !== background.version ||
  8499. currentTonemapping !== renderer.toneMapping ) {
  8500. planeMesh.material.needsUpdate = true;
  8501. currentBackground = background;
  8502. currentBackgroundVersion = background.version;
  8503. currentTonemapping = renderer.toneMapping;
  8504. }
  8505. planeMesh.layers.enableAll();
  8506. // push to the pre-sorted opaque render list
  8507. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8508. }
  8509. }
  8510. function setClear( color, alpha ) {
  8511. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8512. }
  8513. return {
  8514. getClearColor: function () {
  8515. return clearColor;
  8516. },
  8517. setClearColor: function ( color, alpha = 1 ) {
  8518. clearColor.set( color );
  8519. clearAlpha = alpha;
  8520. setClear( clearColor, clearAlpha );
  8521. },
  8522. getClearAlpha: function () {
  8523. return clearAlpha;
  8524. },
  8525. setClearAlpha: function ( alpha ) {
  8526. clearAlpha = alpha;
  8527. setClear( clearColor, clearAlpha );
  8528. },
  8529. render: render
  8530. };
  8531. }
  8532. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8533. const maxVertexAttributes = gl.getParameter( 34921 );
  8534. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8535. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8536. const bindingStates = {};
  8537. const defaultState = createBindingState( null );
  8538. let currentState = defaultState;
  8539. let forceUpdate = false;
  8540. function setup( object, material, program, geometry, index ) {
  8541. let updateBuffers = false;
  8542. if ( vaoAvailable ) {
  8543. const state = getBindingState( geometry, program, material );
  8544. if ( currentState !== state ) {
  8545. currentState = state;
  8546. bindVertexArrayObject( currentState.object );
  8547. }
  8548. updateBuffers = needsUpdate( object, geometry, program, index );
  8549. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8550. } else {
  8551. const wireframe = ( material.wireframe === true );
  8552. if ( currentState.geometry !== geometry.id ||
  8553. currentState.program !== program.id ||
  8554. currentState.wireframe !== wireframe ) {
  8555. currentState.geometry = geometry.id;
  8556. currentState.program = program.id;
  8557. currentState.wireframe = wireframe;
  8558. updateBuffers = true;
  8559. }
  8560. }
  8561. if ( index !== null ) {
  8562. attributes.update( index, 34963 );
  8563. }
  8564. if ( updateBuffers || forceUpdate ) {
  8565. forceUpdate = false;
  8566. setupVertexAttributes( object, material, program, geometry );
  8567. if ( index !== null ) {
  8568. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8569. }
  8570. }
  8571. }
  8572. function createVertexArrayObject() {
  8573. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8574. return extension.createVertexArrayOES();
  8575. }
  8576. function bindVertexArrayObject( vao ) {
  8577. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8578. return extension.bindVertexArrayOES( vao );
  8579. }
  8580. function deleteVertexArrayObject( vao ) {
  8581. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8582. return extension.deleteVertexArrayOES( vao );
  8583. }
  8584. function getBindingState( geometry, program, material ) {
  8585. const wireframe = ( material.wireframe === true );
  8586. let programMap = bindingStates[ geometry.id ];
  8587. if ( programMap === undefined ) {
  8588. programMap = {};
  8589. bindingStates[ geometry.id ] = programMap;
  8590. }
  8591. let stateMap = programMap[ program.id ];
  8592. if ( stateMap === undefined ) {
  8593. stateMap = {};
  8594. programMap[ program.id ] = stateMap;
  8595. }
  8596. let state = stateMap[ wireframe ];
  8597. if ( state === undefined ) {
  8598. state = createBindingState( createVertexArrayObject() );
  8599. stateMap[ wireframe ] = state;
  8600. }
  8601. return state;
  8602. }
  8603. function createBindingState( vao ) {
  8604. const newAttributes = [];
  8605. const enabledAttributes = [];
  8606. const attributeDivisors = [];
  8607. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8608. newAttributes[ i ] = 0;
  8609. enabledAttributes[ i ] = 0;
  8610. attributeDivisors[ i ] = 0;
  8611. }
  8612. return {
  8613. // for backward compatibility on non-VAO support browser
  8614. geometry: null,
  8615. program: null,
  8616. wireframe: false,
  8617. newAttributes: newAttributes,
  8618. enabledAttributes: enabledAttributes,
  8619. attributeDivisors: attributeDivisors,
  8620. object: vao,
  8621. attributes: {},
  8622. index: null
  8623. };
  8624. }
  8625. function needsUpdate( object, geometry, program, index ) {
  8626. const cachedAttributes = currentState.attributes;
  8627. const geometryAttributes = geometry.attributes;
  8628. let attributesNum = 0;
  8629. const programAttributes = program.getAttributes();
  8630. for ( const name in programAttributes ) {
  8631. const programAttribute = programAttributes[ name ];
  8632. if ( programAttribute.location >= 0 ) {
  8633. const cachedAttribute = cachedAttributes[ name ];
  8634. let geometryAttribute = geometryAttributes[ name ];
  8635. if ( geometryAttribute === undefined ) {
  8636. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8637. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8638. }
  8639. if ( cachedAttribute === undefined ) return true;
  8640. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8641. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8642. attributesNum ++;
  8643. }
  8644. }
  8645. if ( currentState.attributesNum !== attributesNum ) return true;
  8646. if ( currentState.index !== index ) return true;
  8647. return false;
  8648. }
  8649. function saveCache( object, geometry, program, index ) {
  8650. const cache = {};
  8651. const attributes = geometry.attributes;
  8652. let attributesNum = 0;
  8653. const programAttributes = program.getAttributes();
  8654. for ( const name in programAttributes ) {
  8655. const programAttribute = programAttributes[ name ];
  8656. if ( programAttribute.location >= 0 ) {
  8657. let attribute = attributes[ name ];
  8658. if ( attribute === undefined ) {
  8659. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8660. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8661. }
  8662. const data = {};
  8663. data.attribute = attribute;
  8664. if ( attribute && attribute.data ) {
  8665. data.data = attribute.data;
  8666. }
  8667. cache[ name ] = data;
  8668. attributesNum ++;
  8669. }
  8670. }
  8671. currentState.attributes = cache;
  8672. currentState.attributesNum = attributesNum;
  8673. currentState.index = index;
  8674. }
  8675. function initAttributes() {
  8676. const newAttributes = currentState.newAttributes;
  8677. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8678. newAttributes[ i ] = 0;
  8679. }
  8680. }
  8681. function enableAttribute( attribute ) {
  8682. enableAttributeAndDivisor( attribute, 0 );
  8683. }
  8684. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8685. const newAttributes = currentState.newAttributes;
  8686. const enabledAttributes = currentState.enabledAttributes;
  8687. const attributeDivisors = currentState.attributeDivisors;
  8688. newAttributes[ attribute ] = 1;
  8689. if ( enabledAttributes[ attribute ] === 0 ) {
  8690. gl.enableVertexAttribArray( attribute );
  8691. enabledAttributes[ attribute ] = 1;
  8692. }
  8693. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8694. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8695. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8696. attributeDivisors[ attribute ] = meshPerAttribute;
  8697. }
  8698. }
  8699. function disableUnusedAttributes() {
  8700. const newAttributes = currentState.newAttributes;
  8701. const enabledAttributes = currentState.enabledAttributes;
  8702. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8703. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8704. gl.disableVertexAttribArray( i );
  8705. enabledAttributes[ i ] = 0;
  8706. }
  8707. }
  8708. }
  8709. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8710. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8711. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8712. } else {
  8713. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8714. }
  8715. }
  8716. function setupVertexAttributes( object, material, program, geometry ) {
  8717. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8718. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8719. }
  8720. initAttributes();
  8721. const geometryAttributes = geometry.attributes;
  8722. const programAttributes = program.getAttributes();
  8723. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8724. for ( const name in programAttributes ) {
  8725. const programAttribute = programAttributes[ name ];
  8726. if ( programAttribute.location >= 0 ) {
  8727. let geometryAttribute = geometryAttributes[ name ];
  8728. if ( geometryAttribute === undefined ) {
  8729. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8730. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8731. }
  8732. if ( geometryAttribute !== undefined ) {
  8733. const normalized = geometryAttribute.normalized;
  8734. const size = geometryAttribute.itemSize;
  8735. const attribute = attributes.get( geometryAttribute );
  8736. // TODO Attribute may not be available on context restore
  8737. if ( attribute === undefined ) continue;
  8738. const buffer = attribute.buffer;
  8739. const type = attribute.type;
  8740. const bytesPerElement = attribute.bytesPerElement;
  8741. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8742. const data = geometryAttribute.data;
  8743. const stride = data.stride;
  8744. const offset = geometryAttribute.offset;
  8745. if ( data.isInstancedInterleavedBuffer ) {
  8746. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8747. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8748. }
  8749. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8750. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8751. }
  8752. } else {
  8753. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8754. enableAttribute( programAttribute.location + i );
  8755. }
  8756. }
  8757. gl.bindBuffer( 34962, buffer );
  8758. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8759. vertexAttribPointer(
  8760. programAttribute.location + i,
  8761. size / programAttribute.locationSize,
  8762. type,
  8763. normalized,
  8764. stride * bytesPerElement,
  8765. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8766. );
  8767. }
  8768. } else {
  8769. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8770. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8771. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8772. }
  8773. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8774. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8775. }
  8776. } else {
  8777. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8778. enableAttribute( programAttribute.location + i );
  8779. }
  8780. }
  8781. gl.bindBuffer( 34962, buffer );
  8782. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8783. vertexAttribPointer(
  8784. programAttribute.location + i,
  8785. size / programAttribute.locationSize,
  8786. type,
  8787. normalized,
  8788. size * bytesPerElement,
  8789. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8790. );
  8791. }
  8792. }
  8793. } else if ( materialDefaultAttributeValues !== undefined ) {
  8794. const value = materialDefaultAttributeValues[ name ];
  8795. if ( value !== undefined ) {
  8796. switch ( value.length ) {
  8797. case 2:
  8798. gl.vertexAttrib2fv( programAttribute.location, value );
  8799. break;
  8800. case 3:
  8801. gl.vertexAttrib3fv( programAttribute.location, value );
  8802. break;
  8803. case 4:
  8804. gl.vertexAttrib4fv( programAttribute.location, value );
  8805. break;
  8806. default:
  8807. gl.vertexAttrib1fv( programAttribute.location, value );
  8808. }
  8809. }
  8810. }
  8811. }
  8812. }
  8813. disableUnusedAttributes();
  8814. }
  8815. function dispose() {
  8816. reset();
  8817. for ( const geometryId in bindingStates ) {
  8818. const programMap = bindingStates[ geometryId ];
  8819. for ( const programId in programMap ) {
  8820. const stateMap = programMap[ programId ];
  8821. for ( const wireframe in stateMap ) {
  8822. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8823. delete stateMap[ wireframe ];
  8824. }
  8825. delete programMap[ programId ];
  8826. }
  8827. delete bindingStates[ geometryId ];
  8828. }
  8829. }
  8830. function releaseStatesOfGeometry( geometry ) {
  8831. if ( bindingStates[ geometry.id ] === undefined ) return;
  8832. const programMap = bindingStates[ geometry.id ];
  8833. for ( const programId in programMap ) {
  8834. const stateMap = programMap[ programId ];
  8835. for ( const wireframe in stateMap ) {
  8836. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8837. delete stateMap[ wireframe ];
  8838. }
  8839. delete programMap[ programId ];
  8840. }
  8841. delete bindingStates[ geometry.id ];
  8842. }
  8843. function releaseStatesOfProgram( program ) {
  8844. for ( const geometryId in bindingStates ) {
  8845. const programMap = bindingStates[ geometryId ];
  8846. if ( programMap[ program.id ] === undefined ) continue;
  8847. const stateMap = programMap[ program.id ];
  8848. for ( const wireframe in stateMap ) {
  8849. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8850. delete stateMap[ wireframe ];
  8851. }
  8852. delete programMap[ program.id ];
  8853. }
  8854. }
  8855. function reset() {
  8856. resetDefaultState();
  8857. forceUpdate = true;
  8858. if ( currentState === defaultState ) return;
  8859. currentState = defaultState;
  8860. bindVertexArrayObject( currentState.object );
  8861. }
  8862. // for backward-compatibility
  8863. function resetDefaultState() {
  8864. defaultState.geometry = null;
  8865. defaultState.program = null;
  8866. defaultState.wireframe = false;
  8867. }
  8868. return {
  8869. setup: setup,
  8870. reset: reset,
  8871. resetDefaultState: resetDefaultState,
  8872. dispose: dispose,
  8873. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8874. releaseStatesOfProgram: releaseStatesOfProgram,
  8875. initAttributes: initAttributes,
  8876. enableAttribute: enableAttribute,
  8877. disableUnusedAttributes: disableUnusedAttributes
  8878. };
  8879. }
  8880. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8881. const isWebGL2 = capabilities.isWebGL2;
  8882. let mode;
  8883. function setMode( value ) {
  8884. mode = value;
  8885. }
  8886. function render( start, count ) {
  8887. gl.drawArrays( mode, start, count );
  8888. info.update( count, mode, 1 );
  8889. }
  8890. function renderInstances( start, count, primcount ) {
  8891. if ( primcount === 0 ) return;
  8892. let extension, methodName;
  8893. if ( isWebGL2 ) {
  8894. extension = gl;
  8895. methodName = 'drawArraysInstanced';
  8896. } else {
  8897. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8898. methodName = 'drawArraysInstancedANGLE';
  8899. if ( extension === null ) {
  8900. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8901. return;
  8902. }
  8903. }
  8904. extension[ methodName ]( mode, start, count, primcount );
  8905. info.update( count, mode, primcount );
  8906. }
  8907. //
  8908. this.setMode = setMode;
  8909. this.render = render;
  8910. this.renderInstances = renderInstances;
  8911. }
  8912. function WebGLCapabilities( gl, extensions, parameters ) {
  8913. let maxAnisotropy;
  8914. function getMaxAnisotropy() {
  8915. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8916. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8917. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8918. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8919. } else {
  8920. maxAnisotropy = 0;
  8921. }
  8922. return maxAnisotropy;
  8923. }
  8924. function getMaxPrecision( precision ) {
  8925. if ( precision === 'highp' ) {
  8926. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8927. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8928. return 'highp';
  8929. }
  8930. precision = 'mediump';
  8931. }
  8932. if ( precision === 'mediump' ) {
  8933. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8934. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8935. return 'mediump';
  8936. }
  8937. }
  8938. return 'lowp';
  8939. }
  8940. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8941. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8942. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8943. const maxPrecision = getMaxPrecision( precision );
  8944. if ( maxPrecision !== precision ) {
  8945. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8946. precision = maxPrecision;
  8947. }
  8948. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8949. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8950. const maxTextures = gl.getParameter( 34930 );
  8951. const maxVertexTextures = gl.getParameter( 35660 );
  8952. const maxTextureSize = gl.getParameter( 3379 );
  8953. const maxCubemapSize = gl.getParameter( 34076 );
  8954. const maxAttributes = gl.getParameter( 34921 );
  8955. const maxVertexUniforms = gl.getParameter( 36347 );
  8956. const maxVaryings = gl.getParameter( 36348 );
  8957. const maxFragmentUniforms = gl.getParameter( 36349 );
  8958. const vertexTextures = maxVertexTextures > 0;
  8959. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8960. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8961. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8962. return {
  8963. isWebGL2: isWebGL2,
  8964. drawBuffers: drawBuffers,
  8965. getMaxAnisotropy: getMaxAnisotropy,
  8966. getMaxPrecision: getMaxPrecision,
  8967. precision: precision,
  8968. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8969. maxTextures: maxTextures,
  8970. maxVertexTextures: maxVertexTextures,
  8971. maxTextureSize: maxTextureSize,
  8972. maxCubemapSize: maxCubemapSize,
  8973. maxAttributes: maxAttributes,
  8974. maxVertexUniforms: maxVertexUniforms,
  8975. maxVaryings: maxVaryings,
  8976. maxFragmentUniforms: maxFragmentUniforms,
  8977. vertexTextures: vertexTextures,
  8978. floatFragmentTextures: floatFragmentTextures,
  8979. floatVertexTextures: floatVertexTextures,
  8980. maxSamples: maxSamples
  8981. };
  8982. }
  8983. function WebGLClipping( properties ) {
  8984. const scope = this;
  8985. let globalState = null,
  8986. numGlobalPlanes = 0,
  8987. localClippingEnabled = false,
  8988. renderingShadows = false;
  8989. const plane = new Plane(),
  8990. viewNormalMatrix = new Matrix3(),
  8991. uniform = { value: null, needsUpdate: false };
  8992. this.uniform = uniform;
  8993. this.numPlanes = 0;
  8994. this.numIntersection = 0;
  8995. this.init = function ( planes, enableLocalClipping, camera ) {
  8996. const enabled =
  8997. planes.length !== 0 ||
  8998. enableLocalClipping ||
  8999. // enable state of previous frame - the clipping code has to
  9000. // run another frame in order to reset the state:
  9001. numGlobalPlanes !== 0 ||
  9002. localClippingEnabled;
  9003. localClippingEnabled = enableLocalClipping;
  9004. globalState = projectPlanes( planes, camera, 0 );
  9005. numGlobalPlanes = planes.length;
  9006. return enabled;
  9007. };
  9008. this.beginShadows = function () {
  9009. renderingShadows = true;
  9010. projectPlanes( null );
  9011. };
  9012. this.endShadows = function () {
  9013. renderingShadows = false;
  9014. resetGlobalState();
  9015. };
  9016. this.setState = function ( material, camera, useCache ) {
  9017. const planes = material.clippingPlanes,
  9018. clipIntersection = material.clipIntersection,
  9019. clipShadows = material.clipShadows;
  9020. const materialProperties = properties.get( material );
  9021. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9022. // there's no local clipping
  9023. if ( renderingShadows ) {
  9024. // there's no global clipping
  9025. projectPlanes( null );
  9026. } else {
  9027. resetGlobalState();
  9028. }
  9029. } else {
  9030. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9031. lGlobal = nGlobal * 4;
  9032. let dstArray = materialProperties.clippingState || null;
  9033. uniform.value = dstArray; // ensure unique state
  9034. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9035. for ( let i = 0; i !== lGlobal; ++ i ) {
  9036. dstArray[ i ] = globalState[ i ];
  9037. }
  9038. materialProperties.clippingState = dstArray;
  9039. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9040. this.numPlanes += nGlobal;
  9041. }
  9042. };
  9043. function resetGlobalState() {
  9044. if ( uniform.value !== globalState ) {
  9045. uniform.value = globalState;
  9046. uniform.needsUpdate = numGlobalPlanes > 0;
  9047. }
  9048. scope.numPlanes = numGlobalPlanes;
  9049. scope.numIntersection = 0;
  9050. }
  9051. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9052. const nPlanes = planes !== null ? planes.length : 0;
  9053. let dstArray = null;
  9054. if ( nPlanes !== 0 ) {
  9055. dstArray = uniform.value;
  9056. if ( skipTransform !== true || dstArray === null ) {
  9057. const flatSize = dstOffset + nPlanes * 4,
  9058. viewMatrix = camera.matrixWorldInverse;
  9059. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9060. if ( dstArray === null || dstArray.length < flatSize ) {
  9061. dstArray = new Float32Array( flatSize );
  9062. }
  9063. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9064. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9065. plane.normal.toArray( dstArray, i4 );
  9066. dstArray[ i4 + 3 ] = plane.constant;
  9067. }
  9068. }
  9069. uniform.value = dstArray;
  9070. uniform.needsUpdate = true;
  9071. }
  9072. scope.numPlanes = nPlanes;
  9073. scope.numIntersection = 0;
  9074. return dstArray;
  9075. }
  9076. }
  9077. function WebGLCubeMaps( renderer ) {
  9078. let cubemaps = new WeakMap();
  9079. function mapTextureMapping( texture, mapping ) {
  9080. if ( mapping === EquirectangularReflectionMapping ) {
  9081. texture.mapping = CubeReflectionMapping;
  9082. } else if ( mapping === EquirectangularRefractionMapping ) {
  9083. texture.mapping = CubeRefractionMapping;
  9084. }
  9085. return texture;
  9086. }
  9087. function get( texture ) {
  9088. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9089. const mapping = texture.mapping;
  9090. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9091. if ( cubemaps.has( texture ) ) {
  9092. const cubemap = cubemaps.get( texture ).texture;
  9093. return mapTextureMapping( cubemap, texture.mapping );
  9094. } else {
  9095. const image = texture.image;
  9096. if ( image && image.height > 0 ) {
  9097. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9098. renderTarget.fromEquirectangularTexture( renderer, texture );
  9099. cubemaps.set( texture, renderTarget );
  9100. texture.addEventListener( 'dispose', onTextureDispose );
  9101. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9102. } else {
  9103. // image not yet ready. try the conversion next frame
  9104. return null;
  9105. }
  9106. }
  9107. }
  9108. }
  9109. return texture;
  9110. }
  9111. function onTextureDispose( event ) {
  9112. const texture = event.target;
  9113. texture.removeEventListener( 'dispose', onTextureDispose );
  9114. const cubemap = cubemaps.get( texture );
  9115. if ( cubemap !== undefined ) {
  9116. cubemaps.delete( texture );
  9117. cubemap.dispose();
  9118. }
  9119. }
  9120. function dispose() {
  9121. cubemaps = new WeakMap();
  9122. }
  9123. return {
  9124. get: get,
  9125. dispose: dispose
  9126. };
  9127. }
  9128. class OrthographicCamera extends Camera {
  9129. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9130. super();
  9131. this.type = 'OrthographicCamera';
  9132. this.zoom = 1;
  9133. this.view = null;
  9134. this.left = left;
  9135. this.right = right;
  9136. this.top = top;
  9137. this.bottom = bottom;
  9138. this.near = near;
  9139. this.far = far;
  9140. this.updateProjectionMatrix();
  9141. }
  9142. copy( source, recursive ) {
  9143. super.copy( source, recursive );
  9144. this.left = source.left;
  9145. this.right = source.right;
  9146. this.top = source.top;
  9147. this.bottom = source.bottom;
  9148. this.near = source.near;
  9149. this.far = source.far;
  9150. this.zoom = source.zoom;
  9151. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9152. return this;
  9153. }
  9154. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9155. if ( this.view === null ) {
  9156. this.view = {
  9157. enabled: true,
  9158. fullWidth: 1,
  9159. fullHeight: 1,
  9160. offsetX: 0,
  9161. offsetY: 0,
  9162. width: 1,
  9163. height: 1
  9164. };
  9165. }
  9166. this.view.enabled = true;
  9167. this.view.fullWidth = fullWidth;
  9168. this.view.fullHeight = fullHeight;
  9169. this.view.offsetX = x;
  9170. this.view.offsetY = y;
  9171. this.view.width = width;
  9172. this.view.height = height;
  9173. this.updateProjectionMatrix();
  9174. }
  9175. clearViewOffset() {
  9176. if ( this.view !== null ) {
  9177. this.view.enabled = false;
  9178. }
  9179. this.updateProjectionMatrix();
  9180. }
  9181. updateProjectionMatrix() {
  9182. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9183. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9184. const cx = ( this.right + this.left ) / 2;
  9185. const cy = ( this.top + this.bottom ) / 2;
  9186. let left = cx - dx;
  9187. let right = cx + dx;
  9188. let top = cy + dy;
  9189. let bottom = cy - dy;
  9190. if ( this.view !== null && this.view.enabled ) {
  9191. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9192. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9193. left += scaleW * this.view.offsetX;
  9194. right = left + scaleW * this.view.width;
  9195. top -= scaleH * this.view.offsetY;
  9196. bottom = top - scaleH * this.view.height;
  9197. }
  9198. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9199. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9200. }
  9201. toJSON( meta ) {
  9202. const data = super.toJSON( meta );
  9203. data.object.zoom = this.zoom;
  9204. data.object.left = this.left;
  9205. data.object.right = this.right;
  9206. data.object.top = this.top;
  9207. data.object.bottom = this.bottom;
  9208. data.object.near = this.near;
  9209. data.object.far = this.far;
  9210. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9211. return data;
  9212. }
  9213. }
  9214. OrthographicCamera.prototype.isOrthographicCamera = true;
  9215. const LOD_MIN = 4;
  9216. // The standard deviations (radians) associated with the extra mips. These are
  9217. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9218. // geometric shadowing function. These sigma values squared must match the
  9219. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9220. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9221. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9222. // samples and exit early, but not recompile the shader.
  9223. const MAX_SAMPLES = 20;
  9224. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9225. const _clearColor = /*@__PURE__*/ new Color();
  9226. let _oldTarget = null;
  9227. // Golden Ratio
  9228. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9229. const INV_PHI = 1 / PHI;
  9230. // Vertices of a dodecahedron (except the opposites, which represent the
  9231. // same axis), used as axis directions evenly spread on a sphere.
  9232. const _axisDirections = [
  9233. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9234. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9235. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9236. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9237. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9238. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9239. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9240. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9241. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9242. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9243. /**
  9244. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9245. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9246. * blur to be quickly accessed based on material roughness. It is packed into a
  9247. * special CubeUV format that allows us to perform custom interpolation so that
  9248. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9249. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9250. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9251. * higher roughness levels. In this way we maintain resolution to smoothly
  9252. * interpolate diffuse lighting while limiting sampling computation.
  9253. *
  9254. * Paper: Fast, Accurate Image-Based Lighting
  9255. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9256. */
  9257. class PMREMGenerator {
  9258. constructor( renderer ) {
  9259. this._renderer = renderer;
  9260. this._pingPongRenderTarget = null;
  9261. this._lodMax = 0;
  9262. this._cubeSize = 0;
  9263. this._lodPlanes = [];
  9264. this._sizeLods = [];
  9265. this._sigmas = [];
  9266. this._blurMaterial = null;
  9267. this._cubemapMaterial = null;
  9268. this._equirectMaterial = null;
  9269. this._compileMaterial( this._blurMaterial );
  9270. }
  9271. /**
  9272. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9273. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9274. * in radians to be applied to the scene before PMREM generation. Optional near
  9275. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9276. * is placed at the origin).
  9277. */
  9278. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9279. _oldTarget = this._renderer.getRenderTarget();
  9280. this._setSize( 256 );
  9281. const cubeUVRenderTarget = this._allocateTargets();
  9282. cubeUVRenderTarget.depthBuffer = true;
  9283. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9284. if ( sigma > 0 ) {
  9285. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9286. }
  9287. this._applyPMREM( cubeUVRenderTarget );
  9288. this._cleanup( cubeUVRenderTarget );
  9289. return cubeUVRenderTarget;
  9290. }
  9291. /**
  9292. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9293. * or HDR. The ideal input image size is 1k (1024 x 512),
  9294. * as this matches best with the 256 x 256 cubemap output.
  9295. */
  9296. fromEquirectangular( equirectangular, renderTarget = null ) {
  9297. return this._fromTexture( equirectangular, renderTarget );
  9298. }
  9299. /**
  9300. * Generates a PMREM from an cubemap texture, which can be either LDR
  9301. * or HDR. The ideal input cube size is 256 x 256,
  9302. * as this matches best with the 256 x 256 cubemap output.
  9303. */
  9304. fromCubemap( cubemap, renderTarget = null ) {
  9305. return this._fromTexture( cubemap, renderTarget );
  9306. }
  9307. /**
  9308. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9309. * your texture's network fetch for increased concurrency.
  9310. */
  9311. compileCubemapShader() {
  9312. if ( this._cubemapMaterial === null ) {
  9313. this._cubemapMaterial = _getCubemapMaterial();
  9314. this._compileMaterial( this._cubemapMaterial );
  9315. }
  9316. }
  9317. /**
  9318. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9319. * your texture's network fetch for increased concurrency.
  9320. */
  9321. compileEquirectangularShader() {
  9322. if ( this._equirectMaterial === null ) {
  9323. this._equirectMaterial = _getEquirectMaterial();
  9324. this._compileMaterial( this._equirectMaterial );
  9325. }
  9326. }
  9327. /**
  9328. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9329. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9330. * one of them will cause any others to also become unusable.
  9331. */
  9332. dispose() {
  9333. this._dispose();
  9334. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9335. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9336. }
  9337. // private interface
  9338. _setSize( cubeSize ) {
  9339. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9340. this._cubeSize = Math.pow( 2, this._lodMax );
  9341. }
  9342. _dispose() {
  9343. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9344. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9345. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9346. this._lodPlanes[ i ].dispose();
  9347. }
  9348. }
  9349. _cleanup( outputTarget ) {
  9350. this._renderer.setRenderTarget( _oldTarget );
  9351. outputTarget.scissorTest = false;
  9352. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9353. }
  9354. _fromTexture( texture, renderTarget ) {
  9355. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9356. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9357. } else { // Equirectangular
  9358. this._setSize( texture.image.width / 4 );
  9359. }
  9360. _oldTarget = this._renderer.getRenderTarget();
  9361. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9362. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9363. this._applyPMREM( cubeUVRenderTarget );
  9364. this._cleanup( cubeUVRenderTarget );
  9365. return cubeUVRenderTarget;
  9366. }
  9367. _allocateTargets() {
  9368. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9369. const height = 4 * this._cubeSize;
  9370. const params = {
  9371. magFilter: LinearFilter,
  9372. minFilter: LinearFilter,
  9373. generateMipmaps: false,
  9374. type: HalfFloatType,
  9375. format: RGBAFormat,
  9376. encoding: LinearEncoding,
  9377. depthBuffer: false
  9378. };
  9379. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9380. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width ) {
  9381. if ( this._pingPongRenderTarget !== null ) {
  9382. this._dispose();
  9383. }
  9384. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9385. const { _lodMax } = this;
  9386. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9387. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9388. }
  9389. return cubeUVRenderTarget;
  9390. }
  9391. _compileMaterial( material ) {
  9392. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9393. this._renderer.compile( tmpMesh, _flatCamera );
  9394. }
  9395. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9396. const fov = 90;
  9397. const aspect = 1;
  9398. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9399. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9400. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9401. const renderer = this._renderer;
  9402. const originalAutoClear = renderer.autoClear;
  9403. const toneMapping = renderer.toneMapping;
  9404. renderer.getClearColor( _clearColor );
  9405. renderer.toneMapping = NoToneMapping;
  9406. renderer.autoClear = false;
  9407. const backgroundMaterial = new MeshBasicMaterial( {
  9408. name: 'PMREM.Background',
  9409. side: BackSide,
  9410. depthWrite: false,
  9411. depthTest: false,
  9412. } );
  9413. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9414. let useSolidColor = false;
  9415. const background = scene.background;
  9416. if ( background ) {
  9417. if ( background.isColor ) {
  9418. backgroundMaterial.color.copy( background );
  9419. scene.background = null;
  9420. useSolidColor = true;
  9421. }
  9422. } else {
  9423. backgroundMaterial.color.copy( _clearColor );
  9424. useSolidColor = true;
  9425. }
  9426. for ( let i = 0; i < 6; i ++ ) {
  9427. const col = i % 3;
  9428. if ( col === 0 ) {
  9429. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9430. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9431. } else if ( col === 1 ) {
  9432. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9433. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9434. } else {
  9435. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9436. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9437. }
  9438. const size = this._cubeSize;
  9439. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9440. renderer.setRenderTarget( cubeUVRenderTarget );
  9441. if ( useSolidColor ) {
  9442. renderer.render( backgroundBox, cubeCamera );
  9443. }
  9444. renderer.render( scene, cubeCamera );
  9445. }
  9446. backgroundBox.geometry.dispose();
  9447. backgroundBox.material.dispose();
  9448. renderer.toneMapping = toneMapping;
  9449. renderer.autoClear = originalAutoClear;
  9450. scene.background = background;
  9451. }
  9452. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9453. const renderer = this._renderer;
  9454. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9455. if ( isCubeTexture ) {
  9456. if ( this._cubemapMaterial === null ) {
  9457. this._cubemapMaterial = _getCubemapMaterial();
  9458. }
  9459. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9460. } else {
  9461. if ( this._equirectMaterial === null ) {
  9462. this._equirectMaterial = _getEquirectMaterial();
  9463. }
  9464. }
  9465. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9466. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9467. const uniforms = material.uniforms;
  9468. uniforms[ 'envMap' ].value = texture;
  9469. const size = this._cubeSize;
  9470. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9471. renderer.setRenderTarget( cubeUVRenderTarget );
  9472. renderer.render( mesh, _flatCamera );
  9473. }
  9474. _applyPMREM( cubeUVRenderTarget ) {
  9475. const renderer = this._renderer;
  9476. const autoClear = renderer.autoClear;
  9477. renderer.autoClear = false;
  9478. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9479. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9480. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9481. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9482. }
  9483. renderer.autoClear = autoClear;
  9484. }
  9485. /**
  9486. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9487. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9488. * the blur latitudinally (around the poles), and then longitudinally (towards
  9489. * the poles) to approximate the orthogonally-separable blur. It is least
  9490. * accurate at the poles, but still does a decent job.
  9491. */
  9492. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9493. const pingPongRenderTarget = this._pingPongRenderTarget;
  9494. this._halfBlur(
  9495. cubeUVRenderTarget,
  9496. pingPongRenderTarget,
  9497. lodIn,
  9498. lodOut,
  9499. sigma,
  9500. 'latitudinal',
  9501. poleAxis );
  9502. this._halfBlur(
  9503. pingPongRenderTarget,
  9504. cubeUVRenderTarget,
  9505. lodOut,
  9506. lodOut,
  9507. sigma,
  9508. 'longitudinal',
  9509. poleAxis );
  9510. }
  9511. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9512. const renderer = this._renderer;
  9513. const blurMaterial = this._blurMaterial;
  9514. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9515. console.error(
  9516. 'blur direction must be either latitudinal or longitudinal!' );
  9517. }
  9518. // Number of standard deviations at which to cut off the discrete approximation.
  9519. const STANDARD_DEVIATIONS = 3;
  9520. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9521. const blurUniforms = blurMaterial.uniforms;
  9522. const pixels = this._sizeLods[ lodIn ] - 1;
  9523. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9524. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9525. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9526. if ( samples > MAX_SAMPLES ) {
  9527. console.warn( `sigmaRadians, ${
  9528. sigmaRadians}, is too large and will clip, as it requested ${
  9529. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9530. }
  9531. const weights = [];
  9532. let sum = 0;
  9533. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9534. const x = i / sigmaPixels;
  9535. const weight = Math.exp( - x * x / 2 );
  9536. weights.push( weight );
  9537. if ( i === 0 ) {
  9538. sum += weight;
  9539. } else if ( i < samples ) {
  9540. sum += 2 * weight;
  9541. }
  9542. }
  9543. for ( let i = 0; i < weights.length; i ++ ) {
  9544. weights[ i ] = weights[ i ] / sum;
  9545. }
  9546. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9547. blurUniforms[ 'samples' ].value = samples;
  9548. blurUniforms[ 'weights' ].value = weights;
  9549. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9550. if ( poleAxis ) {
  9551. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9552. }
  9553. const { _lodMax } = this;
  9554. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9555. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9556. const outputSize = this._sizeLods[ lodOut ];
  9557. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9558. const y = 4 * ( this._cubeSize - outputSize );
  9559. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9560. renderer.setRenderTarget( targetOut );
  9561. renderer.render( blurMesh, _flatCamera );
  9562. }
  9563. }
  9564. function _createPlanes( lodMax ) {
  9565. const lodPlanes = [];
  9566. const sizeLods = [];
  9567. const sigmas = [];
  9568. let lod = lodMax;
  9569. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9570. for ( let i = 0; i < totalLods; i ++ ) {
  9571. const sizeLod = Math.pow( 2, lod );
  9572. sizeLods.push( sizeLod );
  9573. let sigma = 1.0 / sizeLod;
  9574. if ( i > lodMax - LOD_MIN ) {
  9575. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9576. } else if ( i === 0 ) {
  9577. sigma = 0;
  9578. }
  9579. sigmas.push( sigma );
  9580. const texelSize = 1.0 / ( sizeLod - 2 );
  9581. const min = - texelSize;
  9582. const max = 1 + texelSize;
  9583. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9584. const cubeFaces = 6;
  9585. const vertices = 6;
  9586. const positionSize = 3;
  9587. const uvSize = 2;
  9588. const faceIndexSize = 1;
  9589. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9590. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9591. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9592. for ( let face = 0; face < cubeFaces; face ++ ) {
  9593. const x = ( face % 3 ) * 2 / 3 - 1;
  9594. const y = face > 2 ? 0 : - 1;
  9595. const coordinates = [
  9596. x, y, 0,
  9597. x + 2 / 3, y, 0,
  9598. x + 2 / 3, y + 1, 0,
  9599. x, y, 0,
  9600. x + 2 / 3, y + 1, 0,
  9601. x, y + 1, 0
  9602. ];
  9603. position.set( coordinates, positionSize * vertices * face );
  9604. uv.set( uv1, uvSize * vertices * face );
  9605. const fill = [ face, face, face, face, face, face ];
  9606. faceIndex.set( fill, faceIndexSize * vertices * face );
  9607. }
  9608. const planes = new BufferGeometry();
  9609. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9610. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9611. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9612. lodPlanes.push( planes );
  9613. if ( lod > LOD_MIN ) {
  9614. lod --;
  9615. }
  9616. }
  9617. return { lodPlanes, sizeLods, sigmas };
  9618. }
  9619. function _createRenderTarget( width, height, params ) {
  9620. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9621. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9622. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9623. cubeUVRenderTarget.scissorTest = true;
  9624. return cubeUVRenderTarget;
  9625. }
  9626. function _setViewport( target, x, y, width, height ) {
  9627. target.viewport.set( x, y, width, height );
  9628. target.scissor.set( x, y, width, height );
  9629. }
  9630. function _getBlurShader( lodMax, width, height ) {
  9631. const weights = new Float32Array( MAX_SAMPLES );
  9632. const poleAxis = new Vector3( 0, 1, 0 );
  9633. const shaderMaterial = new ShaderMaterial( {
  9634. name: 'SphericalGaussianBlur',
  9635. defines: {
  9636. 'n': MAX_SAMPLES,
  9637. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9638. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9639. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9640. },
  9641. uniforms: {
  9642. 'envMap': { value: null },
  9643. 'samples': { value: 1 },
  9644. 'weights': { value: weights },
  9645. 'latitudinal': { value: false },
  9646. 'dTheta': { value: 0 },
  9647. 'mipInt': { value: 0 },
  9648. 'poleAxis': { value: poleAxis }
  9649. },
  9650. vertexShader: _getCommonVertexShader(),
  9651. fragmentShader: /* glsl */`
  9652. precision mediump float;
  9653. precision mediump int;
  9654. varying vec3 vOutputDirection;
  9655. uniform sampler2D envMap;
  9656. uniform int samples;
  9657. uniform float weights[ n ];
  9658. uniform bool latitudinal;
  9659. uniform float dTheta;
  9660. uniform float mipInt;
  9661. uniform vec3 poleAxis;
  9662. #define ENVMAP_TYPE_CUBE_UV
  9663. #include <cube_uv_reflection_fragment>
  9664. vec3 getSample( float theta, vec3 axis ) {
  9665. float cosTheta = cos( theta );
  9666. // Rodrigues' axis-angle rotation
  9667. vec3 sampleDirection = vOutputDirection * cosTheta
  9668. + cross( axis, vOutputDirection ) * sin( theta )
  9669. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9670. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9671. }
  9672. void main() {
  9673. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9674. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9675. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9676. }
  9677. axis = normalize( axis );
  9678. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9679. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9680. for ( int i = 1; i < n; i++ ) {
  9681. if ( i >= samples ) {
  9682. break;
  9683. }
  9684. float theta = dTheta * float( i );
  9685. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9686. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9687. }
  9688. }
  9689. `,
  9690. blending: NoBlending,
  9691. depthTest: false,
  9692. depthWrite: false
  9693. } );
  9694. return shaderMaterial;
  9695. }
  9696. function _getEquirectMaterial() {
  9697. return new ShaderMaterial( {
  9698. name: 'EquirectangularToCubeUV',
  9699. uniforms: {
  9700. 'envMap': { value: null }
  9701. },
  9702. vertexShader: _getCommonVertexShader(),
  9703. fragmentShader: /* glsl */`
  9704. precision mediump float;
  9705. precision mediump int;
  9706. varying vec3 vOutputDirection;
  9707. uniform sampler2D envMap;
  9708. #include <common>
  9709. void main() {
  9710. vec3 outputDirection = normalize( vOutputDirection );
  9711. vec2 uv = equirectUv( outputDirection );
  9712. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9713. }
  9714. `,
  9715. blending: NoBlending,
  9716. depthTest: false,
  9717. depthWrite: false
  9718. } );
  9719. }
  9720. function _getCubemapMaterial() {
  9721. return new ShaderMaterial( {
  9722. name: 'CubemapToCubeUV',
  9723. uniforms: {
  9724. 'envMap': { value: null },
  9725. 'flipEnvMap': { value: - 1 }
  9726. },
  9727. vertexShader: _getCommonVertexShader(),
  9728. fragmentShader: /* glsl */`
  9729. precision mediump float;
  9730. precision mediump int;
  9731. uniform float flipEnvMap;
  9732. varying vec3 vOutputDirection;
  9733. uniform samplerCube envMap;
  9734. void main() {
  9735. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9736. }
  9737. `,
  9738. blending: NoBlending,
  9739. depthTest: false,
  9740. depthWrite: false
  9741. } );
  9742. }
  9743. function _getCommonVertexShader() {
  9744. return /* glsl */`
  9745. precision mediump float;
  9746. precision mediump int;
  9747. attribute float faceIndex;
  9748. varying vec3 vOutputDirection;
  9749. // RH coordinate system; PMREM face-indexing convention
  9750. vec3 getDirection( vec2 uv, float face ) {
  9751. uv = 2.0 * uv - 1.0;
  9752. vec3 direction = vec3( uv, 1.0 );
  9753. if ( face == 0.0 ) {
  9754. direction = direction.zyx; // ( 1, v, u ) pos x
  9755. } else if ( face == 1.0 ) {
  9756. direction = direction.xzy;
  9757. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9758. } else if ( face == 2.0 ) {
  9759. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9760. } else if ( face == 3.0 ) {
  9761. direction = direction.zyx;
  9762. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9763. } else if ( face == 4.0 ) {
  9764. direction = direction.xzy;
  9765. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9766. } else if ( face == 5.0 ) {
  9767. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9768. }
  9769. return direction;
  9770. }
  9771. void main() {
  9772. vOutputDirection = getDirection( uv, faceIndex );
  9773. gl_Position = vec4( position, 1.0 );
  9774. }
  9775. `;
  9776. }
  9777. function WebGLCubeUVMaps( renderer ) {
  9778. let cubeUVmaps = new WeakMap();
  9779. let pmremGenerator = null;
  9780. function get( texture ) {
  9781. if ( texture && texture.isTexture ) {
  9782. const mapping = texture.mapping;
  9783. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9784. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9785. // equirect/cube map to cubeUV conversion
  9786. if ( isEquirectMap || isCubeMap ) {
  9787. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9788. texture.needsPMREMUpdate = false;
  9789. let renderTarget = cubeUVmaps.get( texture );
  9790. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9791. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9792. cubeUVmaps.set( texture, renderTarget );
  9793. return renderTarget.texture;
  9794. } else {
  9795. if ( cubeUVmaps.has( texture ) ) {
  9796. return cubeUVmaps.get( texture ).texture;
  9797. } else {
  9798. const image = texture.image;
  9799. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9800. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9801. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9802. cubeUVmaps.set( texture, renderTarget );
  9803. texture.addEventListener( 'dispose', onTextureDispose );
  9804. return renderTarget.texture;
  9805. } else {
  9806. // image not yet ready. try the conversion next frame
  9807. return null;
  9808. }
  9809. }
  9810. }
  9811. }
  9812. }
  9813. return texture;
  9814. }
  9815. function isCubeTextureComplete( image ) {
  9816. let count = 0;
  9817. const length = 6;
  9818. for ( let i = 0; i < length; i ++ ) {
  9819. if ( image[ i ] !== undefined ) count ++;
  9820. }
  9821. return count === length;
  9822. }
  9823. function onTextureDispose( event ) {
  9824. const texture = event.target;
  9825. texture.removeEventListener( 'dispose', onTextureDispose );
  9826. const cubemapUV = cubeUVmaps.get( texture );
  9827. if ( cubemapUV !== undefined ) {
  9828. cubeUVmaps.delete( texture );
  9829. cubemapUV.dispose();
  9830. }
  9831. }
  9832. function dispose() {
  9833. cubeUVmaps = new WeakMap();
  9834. if ( pmremGenerator !== null ) {
  9835. pmremGenerator.dispose();
  9836. pmremGenerator = null;
  9837. }
  9838. }
  9839. return {
  9840. get: get,
  9841. dispose: dispose
  9842. };
  9843. }
  9844. function WebGLExtensions( gl ) {
  9845. const extensions = {};
  9846. function getExtension( name ) {
  9847. if ( extensions[ name ] !== undefined ) {
  9848. return extensions[ name ];
  9849. }
  9850. let extension;
  9851. switch ( name ) {
  9852. case 'WEBGL_depth_texture':
  9853. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9854. break;
  9855. case 'EXT_texture_filter_anisotropic':
  9856. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9857. break;
  9858. case 'WEBGL_compressed_texture_s3tc':
  9859. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9860. break;
  9861. case 'WEBGL_compressed_texture_pvrtc':
  9862. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9863. break;
  9864. default:
  9865. extension = gl.getExtension( name );
  9866. }
  9867. extensions[ name ] = extension;
  9868. return extension;
  9869. }
  9870. return {
  9871. has: function ( name ) {
  9872. return getExtension( name ) !== null;
  9873. },
  9874. init: function ( capabilities ) {
  9875. if ( capabilities.isWebGL2 ) {
  9876. getExtension( 'EXT_color_buffer_float' );
  9877. } else {
  9878. getExtension( 'WEBGL_depth_texture' );
  9879. getExtension( 'OES_texture_float' );
  9880. getExtension( 'OES_texture_half_float' );
  9881. getExtension( 'OES_texture_half_float_linear' );
  9882. getExtension( 'OES_standard_derivatives' );
  9883. getExtension( 'OES_element_index_uint' );
  9884. getExtension( 'OES_vertex_array_object' );
  9885. getExtension( 'ANGLE_instanced_arrays' );
  9886. }
  9887. getExtension( 'OES_texture_float_linear' );
  9888. getExtension( 'EXT_color_buffer_half_float' );
  9889. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9890. },
  9891. get: function ( name ) {
  9892. const extension = getExtension( name );
  9893. if ( extension === null ) {
  9894. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9895. }
  9896. return extension;
  9897. }
  9898. };
  9899. }
  9900. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9901. const geometries = {};
  9902. const wireframeAttributes = new WeakMap();
  9903. function onGeometryDispose( event ) {
  9904. const geometry = event.target;
  9905. if ( geometry.index !== null ) {
  9906. attributes.remove( geometry.index );
  9907. }
  9908. for ( const name in geometry.attributes ) {
  9909. attributes.remove( geometry.attributes[ name ] );
  9910. }
  9911. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9912. delete geometries[ geometry.id ];
  9913. const attribute = wireframeAttributes.get( geometry );
  9914. if ( attribute ) {
  9915. attributes.remove( attribute );
  9916. wireframeAttributes.delete( geometry );
  9917. }
  9918. bindingStates.releaseStatesOfGeometry( geometry );
  9919. if ( geometry.isInstancedBufferGeometry === true ) {
  9920. delete geometry._maxInstanceCount;
  9921. }
  9922. //
  9923. info.memory.geometries --;
  9924. }
  9925. function get( object, geometry ) {
  9926. if ( geometries[ geometry.id ] === true ) return geometry;
  9927. geometry.addEventListener( 'dispose', onGeometryDispose );
  9928. geometries[ geometry.id ] = true;
  9929. info.memory.geometries ++;
  9930. return geometry;
  9931. }
  9932. function update( geometry ) {
  9933. const geometryAttributes = geometry.attributes;
  9934. // Updating index buffer in VAO now. See WebGLBindingStates.
  9935. for ( const name in geometryAttributes ) {
  9936. attributes.update( geometryAttributes[ name ], 34962 );
  9937. }
  9938. // morph targets
  9939. const morphAttributes = geometry.morphAttributes;
  9940. for ( const name in morphAttributes ) {
  9941. const array = morphAttributes[ name ];
  9942. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9943. attributes.update( array[ i ], 34962 );
  9944. }
  9945. }
  9946. }
  9947. function updateWireframeAttribute( geometry ) {
  9948. const indices = [];
  9949. const geometryIndex = geometry.index;
  9950. const geometryPosition = geometry.attributes.position;
  9951. let version = 0;
  9952. if ( geometryIndex !== null ) {
  9953. const array = geometryIndex.array;
  9954. version = geometryIndex.version;
  9955. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9956. const a = array[ i + 0 ];
  9957. const b = array[ i + 1 ];
  9958. const c = array[ i + 2 ];
  9959. indices.push( a, b, b, c, c, a );
  9960. }
  9961. } else {
  9962. const array = geometryPosition.array;
  9963. version = geometryPosition.version;
  9964. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9965. const a = i + 0;
  9966. const b = i + 1;
  9967. const c = i + 2;
  9968. indices.push( a, b, b, c, c, a );
  9969. }
  9970. }
  9971. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9972. attribute.version = version;
  9973. // Updating index buffer in VAO now. See WebGLBindingStates
  9974. //
  9975. const previousAttribute = wireframeAttributes.get( geometry );
  9976. if ( previousAttribute ) attributes.remove( previousAttribute );
  9977. //
  9978. wireframeAttributes.set( geometry, attribute );
  9979. }
  9980. function getWireframeAttribute( geometry ) {
  9981. const currentAttribute = wireframeAttributes.get( geometry );
  9982. if ( currentAttribute ) {
  9983. const geometryIndex = geometry.index;
  9984. if ( geometryIndex !== null ) {
  9985. // if the attribute is obsolete, create a new one
  9986. if ( currentAttribute.version < geometryIndex.version ) {
  9987. updateWireframeAttribute( geometry );
  9988. }
  9989. }
  9990. } else {
  9991. updateWireframeAttribute( geometry );
  9992. }
  9993. return wireframeAttributes.get( geometry );
  9994. }
  9995. return {
  9996. get: get,
  9997. update: update,
  9998. getWireframeAttribute: getWireframeAttribute
  9999. };
  10000. }
  10001. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10002. const isWebGL2 = capabilities.isWebGL2;
  10003. let mode;
  10004. function setMode( value ) {
  10005. mode = value;
  10006. }
  10007. let type, bytesPerElement;
  10008. function setIndex( value ) {
  10009. type = value.type;
  10010. bytesPerElement = value.bytesPerElement;
  10011. }
  10012. function render( start, count ) {
  10013. gl.drawElements( mode, count, type, start * bytesPerElement );
  10014. info.update( count, mode, 1 );
  10015. }
  10016. function renderInstances( start, count, primcount ) {
  10017. if ( primcount === 0 ) return;
  10018. let extension, methodName;
  10019. if ( isWebGL2 ) {
  10020. extension = gl;
  10021. methodName = 'drawElementsInstanced';
  10022. } else {
  10023. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10024. methodName = 'drawElementsInstancedANGLE';
  10025. if ( extension === null ) {
  10026. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10027. return;
  10028. }
  10029. }
  10030. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10031. info.update( count, mode, primcount );
  10032. }
  10033. //
  10034. this.setMode = setMode;
  10035. this.setIndex = setIndex;
  10036. this.render = render;
  10037. this.renderInstances = renderInstances;
  10038. }
  10039. function WebGLInfo( gl ) {
  10040. const memory = {
  10041. geometries: 0,
  10042. textures: 0
  10043. };
  10044. const render = {
  10045. frame: 0,
  10046. calls: 0,
  10047. triangles: 0,
  10048. points: 0,
  10049. lines: 0
  10050. };
  10051. function update( count, mode, instanceCount ) {
  10052. render.calls ++;
  10053. switch ( mode ) {
  10054. case 4:
  10055. render.triangles += instanceCount * ( count / 3 );
  10056. break;
  10057. case 1:
  10058. render.lines += instanceCount * ( count / 2 );
  10059. break;
  10060. case 3:
  10061. render.lines += instanceCount * ( count - 1 );
  10062. break;
  10063. case 2:
  10064. render.lines += instanceCount * count;
  10065. break;
  10066. case 0:
  10067. render.points += instanceCount * count;
  10068. break;
  10069. default:
  10070. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10071. break;
  10072. }
  10073. }
  10074. function reset() {
  10075. render.frame ++;
  10076. render.calls = 0;
  10077. render.triangles = 0;
  10078. render.points = 0;
  10079. render.lines = 0;
  10080. }
  10081. return {
  10082. memory: memory,
  10083. render: render,
  10084. programs: null,
  10085. autoReset: true,
  10086. reset: reset,
  10087. update: update
  10088. };
  10089. }
  10090. function numericalSort( a, b ) {
  10091. return a[ 0 ] - b[ 0 ];
  10092. }
  10093. function absNumericalSort( a, b ) {
  10094. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10095. }
  10096. function denormalize( morph, attribute ) {
  10097. let denominator = 1;
  10098. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10099. if ( array instanceof Int8Array ) denominator = 127;
  10100. else if ( array instanceof Int16Array ) denominator = 32767;
  10101. else if ( array instanceof Int32Array ) denominator = 2147483647;
  10102. else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array );
  10103. morph.divideScalar( denominator );
  10104. }
  10105. function WebGLMorphtargets( gl, capabilities, textures ) {
  10106. const influencesList = {};
  10107. const morphInfluences = new Float32Array( 8 );
  10108. const morphTextures = new WeakMap();
  10109. const morph = new Vector4();
  10110. const workInfluences = [];
  10111. for ( let i = 0; i < 8; i ++ ) {
  10112. workInfluences[ i ] = [ i, 0 ];
  10113. }
  10114. function update( object, geometry, material, program ) {
  10115. const objectInfluences = object.morphTargetInfluences;
  10116. if ( capabilities.isWebGL2 === true ) {
  10117. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10118. // into an array of data textures. Each layer represents a single morph target.
  10119. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10120. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10121. let entry = morphTextures.get( geometry );
  10122. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10123. if ( entry !== undefined ) entry.texture.dispose();
  10124. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10125. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10126. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10127. const morphTargets = geometry.morphAttributes.position || [];
  10128. const morphNormals = geometry.morphAttributes.normal || [];
  10129. const morphColors = geometry.morphAttributes.color || [];
  10130. let vertexDataCount = 0;
  10131. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10132. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10133. if ( hasMorphColors === true ) vertexDataCount = 3;
  10134. let width = geometry.attributes.position.count * vertexDataCount;
  10135. let height = 1;
  10136. if ( width > capabilities.maxTextureSize ) {
  10137. height = Math.ceil( width / capabilities.maxTextureSize );
  10138. width = capabilities.maxTextureSize;
  10139. }
  10140. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10141. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10142. texture.type = FloatType;
  10143. texture.needsUpdate = true;
  10144. // fill buffer
  10145. const vertexDataStride = vertexDataCount * 4;
  10146. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10147. const morphTarget = morphTargets[ i ];
  10148. const morphNormal = morphNormals[ i ];
  10149. const morphColor = morphColors[ i ];
  10150. const offset = width * height * 4 * i;
  10151. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10152. const stride = j * vertexDataStride;
  10153. if ( hasMorphPosition === true ) {
  10154. morph.fromBufferAttribute( morphTarget, j );
  10155. if ( morphTarget.normalized === true ) denormalize( morph, morphTarget );
  10156. buffer[ offset + stride + 0 ] = morph.x;
  10157. buffer[ offset + stride + 1 ] = morph.y;
  10158. buffer[ offset + stride + 2 ] = morph.z;
  10159. buffer[ offset + stride + 3 ] = 0;
  10160. }
  10161. if ( hasMorphNormals === true ) {
  10162. morph.fromBufferAttribute( morphNormal, j );
  10163. if ( morphNormal.normalized === true ) denormalize( morph, morphNormal );
  10164. buffer[ offset + stride + 4 ] = morph.x;
  10165. buffer[ offset + stride + 5 ] = morph.y;
  10166. buffer[ offset + stride + 6 ] = morph.z;
  10167. buffer[ offset + stride + 7 ] = 0;
  10168. }
  10169. if ( hasMorphColors === true ) {
  10170. morph.fromBufferAttribute( morphColor, j );
  10171. if ( morphColor.normalized === true ) denormalize( morph, morphColor );
  10172. buffer[ offset + stride + 8 ] = morph.x;
  10173. buffer[ offset + stride + 9 ] = morph.y;
  10174. buffer[ offset + stride + 10 ] = morph.z;
  10175. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10176. }
  10177. }
  10178. }
  10179. entry = {
  10180. count: morphTargetsCount,
  10181. texture: texture,
  10182. size: new Vector2( width, height )
  10183. };
  10184. morphTextures.set( geometry, entry );
  10185. function disposeTexture() {
  10186. texture.dispose();
  10187. morphTextures.delete( geometry );
  10188. geometry.removeEventListener( 'dispose', disposeTexture );
  10189. }
  10190. geometry.addEventListener( 'dispose', disposeTexture );
  10191. }
  10192. //
  10193. let morphInfluencesSum = 0;
  10194. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10195. morphInfluencesSum += objectInfluences[ i ];
  10196. }
  10197. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10198. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10199. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10200. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10201. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10202. } else {
  10203. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10204. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10205. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10206. let influences = influencesList[ geometry.id ];
  10207. if ( influences === undefined || influences.length !== length ) {
  10208. // initialise list
  10209. influences = [];
  10210. for ( let i = 0; i < length; i ++ ) {
  10211. influences[ i ] = [ i, 0 ];
  10212. }
  10213. influencesList[ geometry.id ] = influences;
  10214. }
  10215. // Collect influences
  10216. for ( let i = 0; i < length; i ++ ) {
  10217. const influence = influences[ i ];
  10218. influence[ 0 ] = i;
  10219. influence[ 1 ] = objectInfluences[ i ];
  10220. }
  10221. influences.sort( absNumericalSort );
  10222. for ( let i = 0; i < 8; i ++ ) {
  10223. if ( i < length && influences[ i ][ 1 ] ) {
  10224. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10225. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10226. } else {
  10227. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10228. workInfluences[ i ][ 1 ] = 0;
  10229. }
  10230. }
  10231. workInfluences.sort( numericalSort );
  10232. const morphTargets = geometry.morphAttributes.position;
  10233. const morphNormals = geometry.morphAttributes.normal;
  10234. let morphInfluencesSum = 0;
  10235. for ( let i = 0; i < 8; i ++ ) {
  10236. const influence = workInfluences[ i ];
  10237. const index = influence[ 0 ];
  10238. const value = influence[ 1 ];
  10239. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10240. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10241. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10242. }
  10243. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10244. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10245. }
  10246. morphInfluences[ i ] = value;
  10247. morphInfluencesSum += value;
  10248. } else {
  10249. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10250. geometry.deleteAttribute( 'morphTarget' + i );
  10251. }
  10252. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10253. geometry.deleteAttribute( 'morphNormal' + i );
  10254. }
  10255. morphInfluences[ i ] = 0;
  10256. }
  10257. }
  10258. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10259. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10260. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10261. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10262. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10263. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10264. }
  10265. }
  10266. return {
  10267. update: update
  10268. };
  10269. }
  10270. function WebGLObjects( gl, geometries, attributes, info ) {
  10271. let updateMap = new WeakMap();
  10272. function update( object ) {
  10273. const frame = info.render.frame;
  10274. const geometry = object.geometry;
  10275. const buffergeometry = geometries.get( object, geometry );
  10276. // Update once per frame
  10277. if ( updateMap.get( buffergeometry ) !== frame ) {
  10278. geometries.update( buffergeometry );
  10279. updateMap.set( buffergeometry, frame );
  10280. }
  10281. if ( object.isInstancedMesh ) {
  10282. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10283. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10284. }
  10285. attributes.update( object.instanceMatrix, 34962 );
  10286. if ( object.instanceColor !== null ) {
  10287. attributes.update( object.instanceColor, 34962 );
  10288. }
  10289. }
  10290. return buffergeometry;
  10291. }
  10292. function dispose() {
  10293. updateMap = new WeakMap();
  10294. }
  10295. function onInstancedMeshDispose( event ) {
  10296. const instancedMesh = event.target;
  10297. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10298. attributes.remove( instancedMesh.instanceMatrix );
  10299. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10300. }
  10301. return {
  10302. update: update,
  10303. dispose: dispose
  10304. };
  10305. }
  10306. /**
  10307. * Uniforms of a program.
  10308. * Those form a tree structure with a special top-level container for the root,
  10309. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10310. *
  10311. *
  10312. * Properties of inner nodes including the top-level container:
  10313. *
  10314. * .seq - array of nested uniforms
  10315. * .map - nested uniforms by name
  10316. *
  10317. *
  10318. * Methods of all nodes except the top-level container:
  10319. *
  10320. * .setValue( gl, value, [textures] )
  10321. *
  10322. * uploads a uniform value(s)
  10323. * the 'textures' parameter is needed for sampler uniforms
  10324. *
  10325. *
  10326. * Static methods of the top-level container (textures factorizations):
  10327. *
  10328. * .upload( gl, seq, values, textures )
  10329. *
  10330. * sets uniforms in 'seq' to 'values[id].value'
  10331. *
  10332. * .seqWithValue( seq, values ) : filteredSeq
  10333. *
  10334. * filters 'seq' entries with corresponding entry in values
  10335. *
  10336. *
  10337. * Methods of the top-level container (textures factorizations):
  10338. *
  10339. * .setValue( gl, name, value, textures )
  10340. *
  10341. * sets uniform with name 'name' to 'value'
  10342. *
  10343. * .setOptional( gl, obj, prop )
  10344. *
  10345. * like .set for an optional property of the object
  10346. *
  10347. */
  10348. const emptyTexture = new Texture();
  10349. const emptyArrayTexture = new DataArrayTexture();
  10350. const empty3dTexture = new Data3DTexture();
  10351. const emptyCubeTexture = new CubeTexture();
  10352. // --- Utilities ---
  10353. // Array Caches (provide typed arrays for temporary by size)
  10354. const arrayCacheF32 = [];
  10355. const arrayCacheI32 = [];
  10356. // Float32Array caches used for uploading Matrix uniforms
  10357. const mat4array = new Float32Array( 16 );
  10358. const mat3array = new Float32Array( 9 );
  10359. const mat2array = new Float32Array( 4 );
  10360. // Flattening for arrays of vectors and matrices
  10361. function flatten( array, nBlocks, blockSize ) {
  10362. const firstElem = array[ 0 ];
  10363. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10364. // unoptimized: ! isNaN( firstElem )
  10365. // see http://jacksondunstan.com/articles/983
  10366. const n = nBlocks * blockSize;
  10367. let r = arrayCacheF32[ n ];
  10368. if ( r === undefined ) {
  10369. r = new Float32Array( n );
  10370. arrayCacheF32[ n ] = r;
  10371. }
  10372. if ( nBlocks !== 0 ) {
  10373. firstElem.toArray( r, 0 );
  10374. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10375. offset += blockSize;
  10376. array[ i ].toArray( r, offset );
  10377. }
  10378. }
  10379. return r;
  10380. }
  10381. function arraysEqual( a, b ) {
  10382. if ( a.length !== b.length ) return false;
  10383. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10384. if ( a[ i ] !== b[ i ] ) return false;
  10385. }
  10386. return true;
  10387. }
  10388. function copyArray( a, b ) {
  10389. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10390. a[ i ] = b[ i ];
  10391. }
  10392. }
  10393. // Texture unit allocation
  10394. function allocTexUnits( textures, n ) {
  10395. let r = arrayCacheI32[ n ];
  10396. if ( r === undefined ) {
  10397. r = new Int32Array( n );
  10398. arrayCacheI32[ n ] = r;
  10399. }
  10400. for ( let i = 0; i !== n; ++ i ) {
  10401. r[ i ] = textures.allocateTextureUnit();
  10402. }
  10403. return r;
  10404. }
  10405. // --- Setters ---
  10406. // Note: Defining these methods externally, because they come in a bunch
  10407. // and this way their names minify.
  10408. // Single scalar
  10409. function setValueV1f( gl, v ) {
  10410. const cache = this.cache;
  10411. if ( cache[ 0 ] === v ) return;
  10412. gl.uniform1f( this.addr, v );
  10413. cache[ 0 ] = v;
  10414. }
  10415. // Single float vector (from flat array or THREE.VectorN)
  10416. function setValueV2f( gl, v ) {
  10417. const cache = this.cache;
  10418. if ( v.x !== undefined ) {
  10419. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10420. gl.uniform2f( this.addr, v.x, v.y );
  10421. cache[ 0 ] = v.x;
  10422. cache[ 1 ] = v.y;
  10423. }
  10424. } else {
  10425. if ( arraysEqual( cache, v ) ) return;
  10426. gl.uniform2fv( this.addr, v );
  10427. copyArray( cache, v );
  10428. }
  10429. }
  10430. function setValueV3f( gl, v ) {
  10431. const cache = this.cache;
  10432. if ( v.x !== undefined ) {
  10433. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10434. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10435. cache[ 0 ] = v.x;
  10436. cache[ 1 ] = v.y;
  10437. cache[ 2 ] = v.z;
  10438. }
  10439. } else if ( v.r !== undefined ) {
  10440. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10441. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10442. cache[ 0 ] = v.r;
  10443. cache[ 1 ] = v.g;
  10444. cache[ 2 ] = v.b;
  10445. }
  10446. } else {
  10447. if ( arraysEqual( cache, v ) ) return;
  10448. gl.uniform3fv( this.addr, v );
  10449. copyArray( cache, v );
  10450. }
  10451. }
  10452. function setValueV4f( gl, v ) {
  10453. const cache = this.cache;
  10454. if ( v.x !== undefined ) {
  10455. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10456. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10457. cache[ 0 ] = v.x;
  10458. cache[ 1 ] = v.y;
  10459. cache[ 2 ] = v.z;
  10460. cache[ 3 ] = v.w;
  10461. }
  10462. } else {
  10463. if ( arraysEqual( cache, v ) ) return;
  10464. gl.uniform4fv( this.addr, v );
  10465. copyArray( cache, v );
  10466. }
  10467. }
  10468. // Single matrix (from flat array or THREE.MatrixN)
  10469. function setValueM2( gl, v ) {
  10470. const cache = this.cache;
  10471. const elements = v.elements;
  10472. if ( elements === undefined ) {
  10473. if ( arraysEqual( cache, v ) ) return;
  10474. gl.uniformMatrix2fv( this.addr, false, v );
  10475. copyArray( cache, v );
  10476. } else {
  10477. if ( arraysEqual( cache, elements ) ) return;
  10478. mat2array.set( elements );
  10479. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10480. copyArray( cache, elements );
  10481. }
  10482. }
  10483. function setValueM3( gl, v ) {
  10484. const cache = this.cache;
  10485. const elements = v.elements;
  10486. if ( elements === undefined ) {
  10487. if ( arraysEqual( cache, v ) ) return;
  10488. gl.uniformMatrix3fv( this.addr, false, v );
  10489. copyArray( cache, v );
  10490. } else {
  10491. if ( arraysEqual( cache, elements ) ) return;
  10492. mat3array.set( elements );
  10493. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10494. copyArray( cache, elements );
  10495. }
  10496. }
  10497. function setValueM4( gl, v ) {
  10498. const cache = this.cache;
  10499. const elements = v.elements;
  10500. if ( elements === undefined ) {
  10501. if ( arraysEqual( cache, v ) ) return;
  10502. gl.uniformMatrix4fv( this.addr, false, v );
  10503. copyArray( cache, v );
  10504. } else {
  10505. if ( arraysEqual( cache, elements ) ) return;
  10506. mat4array.set( elements );
  10507. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10508. copyArray( cache, elements );
  10509. }
  10510. }
  10511. // Single integer / boolean
  10512. function setValueV1i( gl, v ) {
  10513. const cache = this.cache;
  10514. if ( cache[ 0 ] === v ) return;
  10515. gl.uniform1i( this.addr, v );
  10516. cache[ 0 ] = v;
  10517. }
  10518. // Single integer / boolean vector (from flat array)
  10519. function setValueV2i( gl, v ) {
  10520. const cache = this.cache;
  10521. if ( arraysEqual( cache, v ) ) return;
  10522. gl.uniform2iv( this.addr, v );
  10523. copyArray( cache, v );
  10524. }
  10525. function setValueV3i( gl, v ) {
  10526. const cache = this.cache;
  10527. if ( arraysEqual( cache, v ) ) return;
  10528. gl.uniform3iv( this.addr, v );
  10529. copyArray( cache, v );
  10530. }
  10531. function setValueV4i( gl, v ) {
  10532. const cache = this.cache;
  10533. if ( arraysEqual( cache, v ) ) return;
  10534. gl.uniform4iv( this.addr, v );
  10535. copyArray( cache, v );
  10536. }
  10537. // Single unsigned integer
  10538. function setValueV1ui( gl, v ) {
  10539. const cache = this.cache;
  10540. if ( cache[ 0 ] === v ) return;
  10541. gl.uniform1ui( this.addr, v );
  10542. cache[ 0 ] = v;
  10543. }
  10544. // Single unsigned integer vector (from flat array)
  10545. function setValueV2ui( gl, v ) {
  10546. const cache = this.cache;
  10547. if ( arraysEqual( cache, v ) ) return;
  10548. gl.uniform2uiv( this.addr, v );
  10549. copyArray( cache, v );
  10550. }
  10551. function setValueV3ui( gl, v ) {
  10552. const cache = this.cache;
  10553. if ( arraysEqual( cache, v ) ) return;
  10554. gl.uniform3uiv( this.addr, v );
  10555. copyArray( cache, v );
  10556. }
  10557. function setValueV4ui( gl, v ) {
  10558. const cache = this.cache;
  10559. if ( arraysEqual( cache, v ) ) return;
  10560. gl.uniform4uiv( this.addr, v );
  10561. copyArray( cache, v );
  10562. }
  10563. // Single texture (2D / Cube)
  10564. function setValueT1( gl, v, textures ) {
  10565. const cache = this.cache;
  10566. const unit = textures.allocateTextureUnit();
  10567. if ( cache[ 0 ] !== unit ) {
  10568. gl.uniform1i( this.addr, unit );
  10569. cache[ 0 ] = unit;
  10570. }
  10571. textures.setTexture2D( v || emptyTexture, unit );
  10572. }
  10573. function setValueT3D1( gl, v, textures ) {
  10574. const cache = this.cache;
  10575. const unit = textures.allocateTextureUnit();
  10576. if ( cache[ 0 ] !== unit ) {
  10577. gl.uniform1i( this.addr, unit );
  10578. cache[ 0 ] = unit;
  10579. }
  10580. textures.setTexture3D( v || empty3dTexture, unit );
  10581. }
  10582. function setValueT6( gl, v, textures ) {
  10583. const cache = this.cache;
  10584. const unit = textures.allocateTextureUnit();
  10585. if ( cache[ 0 ] !== unit ) {
  10586. gl.uniform1i( this.addr, unit );
  10587. cache[ 0 ] = unit;
  10588. }
  10589. textures.setTextureCube( v || emptyCubeTexture, unit );
  10590. }
  10591. function setValueT2DArray1( gl, v, textures ) {
  10592. const cache = this.cache;
  10593. const unit = textures.allocateTextureUnit();
  10594. if ( cache[ 0 ] !== unit ) {
  10595. gl.uniform1i( this.addr, unit );
  10596. cache[ 0 ] = unit;
  10597. }
  10598. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10599. }
  10600. // Helper to pick the right setter for the singular case
  10601. function getSingularSetter( type ) {
  10602. switch ( type ) {
  10603. case 0x1406: return setValueV1f; // FLOAT
  10604. case 0x8b50: return setValueV2f; // _VEC2
  10605. case 0x8b51: return setValueV3f; // _VEC3
  10606. case 0x8b52: return setValueV4f; // _VEC4
  10607. case 0x8b5a: return setValueM2; // _MAT2
  10608. case 0x8b5b: return setValueM3; // _MAT3
  10609. case 0x8b5c: return setValueM4; // _MAT4
  10610. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10611. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10612. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10613. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10614. case 0x1405: return setValueV1ui; // UINT
  10615. case 0x8dc6: return setValueV2ui; // _VEC2
  10616. case 0x8dc7: return setValueV3ui; // _VEC3
  10617. case 0x8dc8: return setValueV4ui; // _VEC4
  10618. case 0x8b5e: // SAMPLER_2D
  10619. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10620. case 0x8dca: // INT_SAMPLER_2D
  10621. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10622. case 0x8b62: // SAMPLER_2D_SHADOW
  10623. return setValueT1;
  10624. case 0x8b5f: // SAMPLER_3D
  10625. case 0x8dcb: // INT_SAMPLER_3D
  10626. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10627. return setValueT3D1;
  10628. case 0x8b60: // SAMPLER_CUBE
  10629. case 0x8dcc: // INT_SAMPLER_CUBE
  10630. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10631. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10632. return setValueT6;
  10633. case 0x8dc1: // SAMPLER_2D_ARRAY
  10634. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10635. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10636. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10637. return setValueT2DArray1;
  10638. }
  10639. }
  10640. // Array of scalars
  10641. function setValueV1fArray( gl, v ) {
  10642. gl.uniform1fv( this.addr, v );
  10643. }
  10644. // Array of vectors (from flat array or array of THREE.VectorN)
  10645. function setValueV2fArray( gl, v ) {
  10646. const data = flatten( v, this.size, 2 );
  10647. gl.uniform2fv( this.addr, data );
  10648. }
  10649. function setValueV3fArray( gl, v ) {
  10650. const data = flatten( v, this.size, 3 );
  10651. gl.uniform3fv( this.addr, data );
  10652. }
  10653. function setValueV4fArray( gl, v ) {
  10654. const data = flatten( v, this.size, 4 );
  10655. gl.uniform4fv( this.addr, data );
  10656. }
  10657. // Array of matrices (from flat array or array of THREE.MatrixN)
  10658. function setValueM2Array( gl, v ) {
  10659. const data = flatten( v, this.size, 4 );
  10660. gl.uniformMatrix2fv( this.addr, false, data );
  10661. }
  10662. function setValueM3Array( gl, v ) {
  10663. const data = flatten( v, this.size, 9 );
  10664. gl.uniformMatrix3fv( this.addr, false, data );
  10665. }
  10666. function setValueM4Array( gl, v ) {
  10667. const data = flatten( v, this.size, 16 );
  10668. gl.uniformMatrix4fv( this.addr, false, data );
  10669. }
  10670. // Array of integer / boolean
  10671. function setValueV1iArray( gl, v ) {
  10672. gl.uniform1iv( this.addr, v );
  10673. }
  10674. // Array of integer / boolean vectors (from flat array)
  10675. function setValueV2iArray( gl, v ) {
  10676. gl.uniform2iv( this.addr, v );
  10677. }
  10678. function setValueV3iArray( gl, v ) {
  10679. gl.uniform3iv( this.addr, v );
  10680. }
  10681. function setValueV4iArray( gl, v ) {
  10682. gl.uniform4iv( this.addr, v );
  10683. }
  10684. // Array of unsigned integer
  10685. function setValueV1uiArray( gl, v ) {
  10686. gl.uniform1uiv( this.addr, v );
  10687. }
  10688. // Array of unsigned integer vectors (from flat array)
  10689. function setValueV2uiArray( gl, v ) {
  10690. gl.uniform2uiv( this.addr, v );
  10691. }
  10692. function setValueV3uiArray( gl, v ) {
  10693. gl.uniform3uiv( this.addr, v );
  10694. }
  10695. function setValueV4uiArray( gl, v ) {
  10696. gl.uniform4uiv( this.addr, v );
  10697. }
  10698. // Array of textures (2D / 3D / Cube / 2DArray)
  10699. function setValueT1Array( gl, v, textures ) {
  10700. const n = v.length;
  10701. const units = allocTexUnits( textures, n );
  10702. gl.uniform1iv( this.addr, units );
  10703. for ( let i = 0; i !== n; ++ i ) {
  10704. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10705. }
  10706. }
  10707. function setValueT3DArray( gl, v, textures ) {
  10708. const n = v.length;
  10709. const units = allocTexUnits( textures, n );
  10710. gl.uniform1iv( this.addr, units );
  10711. for ( let i = 0; i !== n; ++ i ) {
  10712. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10713. }
  10714. }
  10715. function setValueT6Array( gl, v, textures ) {
  10716. const n = v.length;
  10717. const units = allocTexUnits( textures, n );
  10718. gl.uniform1iv( this.addr, units );
  10719. for ( let i = 0; i !== n; ++ i ) {
  10720. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10721. }
  10722. }
  10723. function setValueT2DArrayArray( gl, v, textures ) {
  10724. const n = v.length;
  10725. const units = allocTexUnits( textures, n );
  10726. gl.uniform1iv( this.addr, units );
  10727. for ( let i = 0; i !== n; ++ i ) {
  10728. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10729. }
  10730. }
  10731. // Helper to pick the right setter for a pure (bottom-level) array
  10732. function getPureArraySetter( type ) {
  10733. switch ( type ) {
  10734. case 0x1406: return setValueV1fArray; // FLOAT
  10735. case 0x8b50: return setValueV2fArray; // _VEC2
  10736. case 0x8b51: return setValueV3fArray; // _VEC3
  10737. case 0x8b52: return setValueV4fArray; // _VEC4
  10738. case 0x8b5a: return setValueM2Array; // _MAT2
  10739. case 0x8b5b: return setValueM3Array; // _MAT3
  10740. case 0x8b5c: return setValueM4Array; // _MAT4
  10741. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10742. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10743. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10744. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10745. case 0x1405: return setValueV1uiArray; // UINT
  10746. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10747. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10748. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10749. case 0x8b5e: // SAMPLER_2D
  10750. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10751. case 0x8dca: // INT_SAMPLER_2D
  10752. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10753. case 0x8b62: // SAMPLER_2D_SHADOW
  10754. return setValueT1Array;
  10755. case 0x8b5f: // SAMPLER_3D
  10756. case 0x8dcb: // INT_SAMPLER_3D
  10757. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10758. return setValueT3DArray;
  10759. case 0x8b60: // SAMPLER_CUBE
  10760. case 0x8dcc: // INT_SAMPLER_CUBE
  10761. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10762. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10763. return setValueT6Array;
  10764. case 0x8dc1: // SAMPLER_2D_ARRAY
  10765. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10766. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10767. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10768. return setValueT2DArrayArray;
  10769. }
  10770. }
  10771. // --- Uniform Classes ---
  10772. function SingleUniform( id, activeInfo, addr ) {
  10773. this.id = id;
  10774. this.addr = addr;
  10775. this.cache = [];
  10776. this.setValue = getSingularSetter( activeInfo.type );
  10777. // this.path = activeInfo.name; // DEBUG
  10778. }
  10779. function PureArrayUniform( id, activeInfo, addr ) {
  10780. this.id = id;
  10781. this.addr = addr;
  10782. this.cache = [];
  10783. this.size = activeInfo.size;
  10784. this.setValue = getPureArraySetter( activeInfo.type );
  10785. // this.path = activeInfo.name; // DEBUG
  10786. }
  10787. function StructuredUniform( id ) {
  10788. this.id = id;
  10789. this.seq = [];
  10790. this.map = {};
  10791. }
  10792. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10793. const seq = this.seq;
  10794. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10795. const u = seq[ i ];
  10796. u.setValue( gl, value[ u.id ], textures );
  10797. }
  10798. };
  10799. // --- Top-level ---
  10800. // Parser - builds up the property tree from the path strings
  10801. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10802. // extracts
  10803. // - the identifier (member name or array index)
  10804. // - followed by an optional right bracket (found when array index)
  10805. // - followed by an optional left bracket or dot (type of subscript)
  10806. //
  10807. // Note: These portions can be read in a non-overlapping fashion and
  10808. // allow straightforward parsing of the hierarchy that WebGL encodes
  10809. // in the uniform names.
  10810. function addUniform( container, uniformObject ) {
  10811. container.seq.push( uniformObject );
  10812. container.map[ uniformObject.id ] = uniformObject;
  10813. }
  10814. function parseUniform( activeInfo, addr, container ) {
  10815. const path = activeInfo.name,
  10816. pathLength = path.length;
  10817. // reset RegExp object, because of the early exit of a previous run
  10818. RePathPart.lastIndex = 0;
  10819. while ( true ) {
  10820. const match = RePathPart.exec( path ),
  10821. matchEnd = RePathPart.lastIndex;
  10822. let id = match[ 1 ];
  10823. const idIsIndex = match[ 2 ] === ']',
  10824. subscript = match[ 3 ];
  10825. if ( idIsIndex ) id = id | 0; // convert to integer
  10826. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10827. // bare name or "pure" bottom-level array "[0]" suffix
  10828. addUniform( container, subscript === undefined ?
  10829. new SingleUniform( id, activeInfo, addr ) :
  10830. new PureArrayUniform( id, activeInfo, addr ) );
  10831. break;
  10832. } else {
  10833. // step into inner node / create it in case it doesn't exist
  10834. const map = container.map;
  10835. let next = map[ id ];
  10836. if ( next === undefined ) {
  10837. next = new StructuredUniform( id );
  10838. addUniform( container, next );
  10839. }
  10840. container = next;
  10841. }
  10842. }
  10843. }
  10844. // Root Container
  10845. function WebGLUniforms( gl, program ) {
  10846. this.seq = [];
  10847. this.map = {};
  10848. const n = gl.getProgramParameter( program, 35718 );
  10849. for ( let i = 0; i < n; ++ i ) {
  10850. const info = gl.getActiveUniform( program, i ),
  10851. addr = gl.getUniformLocation( program, info.name );
  10852. parseUniform( info, addr, this );
  10853. }
  10854. }
  10855. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10856. const u = this.map[ name ];
  10857. if ( u !== undefined ) u.setValue( gl, value, textures );
  10858. };
  10859. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10860. const v = object[ name ];
  10861. if ( v !== undefined ) this.setValue( gl, name, v );
  10862. };
  10863. // Static interface
  10864. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10865. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10866. const u = seq[ i ],
  10867. v = values[ u.id ];
  10868. if ( v.needsUpdate !== false ) {
  10869. // note: always updating when .needsUpdate is undefined
  10870. u.setValue( gl, v.value, textures );
  10871. }
  10872. }
  10873. };
  10874. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10875. const r = [];
  10876. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10877. const u = seq[ i ];
  10878. if ( u.id in values ) r.push( u );
  10879. }
  10880. return r;
  10881. };
  10882. function WebGLShader( gl, type, string ) {
  10883. const shader = gl.createShader( type );
  10884. gl.shaderSource( shader, string );
  10885. gl.compileShader( shader );
  10886. return shader;
  10887. }
  10888. let programIdCount = 0;
  10889. function handleSource( string, errorLine ) {
  10890. const lines = string.split( '\n' );
  10891. const lines2 = [];
  10892. const from = Math.max( errorLine - 6, 0 );
  10893. const to = Math.min( errorLine + 6, lines.length );
  10894. for ( let i = from; i < to; i ++ ) {
  10895. lines2.push( ( i + 1 ) + ': ' + lines[ i ] );
  10896. }
  10897. return lines2.join( '\n' );
  10898. }
  10899. function getEncodingComponents( encoding ) {
  10900. switch ( encoding ) {
  10901. case LinearEncoding:
  10902. return [ 'Linear', '( value )' ];
  10903. case sRGBEncoding:
  10904. return [ 'sRGB', '( value )' ];
  10905. default:
  10906. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10907. return [ 'Linear', '( value )' ];
  10908. }
  10909. }
  10910. function getShaderErrors( gl, shader, type ) {
  10911. const status = gl.getShaderParameter( shader, 35713 );
  10912. const errors = gl.getShaderInfoLog( shader ).trim();
  10913. if ( status && errors === '' ) return '';
  10914. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10915. if ( errorMatches ) {
  10916. // --enable-privileged-webgl-extension
  10917. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10918. const errorLine = parseInt( errorMatches[ 0 ] );
  10919. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10920. } else {
  10921. return errors;
  10922. }
  10923. }
  10924. function getTexelEncodingFunction( functionName, encoding ) {
  10925. const components = getEncodingComponents( encoding );
  10926. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10927. }
  10928. function getToneMappingFunction( functionName, toneMapping ) {
  10929. let toneMappingName;
  10930. switch ( toneMapping ) {
  10931. case LinearToneMapping:
  10932. toneMappingName = 'Linear';
  10933. break;
  10934. case ReinhardToneMapping:
  10935. toneMappingName = 'Reinhard';
  10936. break;
  10937. case CineonToneMapping:
  10938. toneMappingName = 'OptimizedCineon';
  10939. break;
  10940. case ACESFilmicToneMapping:
  10941. toneMappingName = 'ACESFilmic';
  10942. break;
  10943. case CustomToneMapping:
  10944. toneMappingName = 'Custom';
  10945. break;
  10946. default:
  10947. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10948. toneMappingName = 'Linear';
  10949. }
  10950. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10951. }
  10952. function generateExtensions( parameters ) {
  10953. const chunks = [
  10954. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10955. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10956. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10957. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10958. ];
  10959. return chunks.filter( filterEmptyLine ).join( '\n' );
  10960. }
  10961. function generateDefines( defines ) {
  10962. const chunks = [];
  10963. for ( const name in defines ) {
  10964. const value = defines[ name ];
  10965. if ( value === false ) continue;
  10966. chunks.push( '#define ' + name + ' ' + value );
  10967. }
  10968. return chunks.join( '\n' );
  10969. }
  10970. function fetchAttributeLocations( gl, program ) {
  10971. const attributes = {};
  10972. const n = gl.getProgramParameter( program, 35721 );
  10973. for ( let i = 0; i < n; i ++ ) {
  10974. const info = gl.getActiveAttrib( program, i );
  10975. const name = info.name;
  10976. let locationSize = 1;
  10977. if ( info.type === 35674 ) locationSize = 2;
  10978. if ( info.type === 35675 ) locationSize = 3;
  10979. if ( info.type === 35676 ) locationSize = 4;
  10980. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10981. attributes[ name ] = {
  10982. type: info.type,
  10983. location: gl.getAttribLocation( program, name ),
  10984. locationSize: locationSize
  10985. };
  10986. }
  10987. return attributes;
  10988. }
  10989. function filterEmptyLine( string ) {
  10990. return string !== '';
  10991. }
  10992. function replaceLightNums( string, parameters ) {
  10993. return string
  10994. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10995. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10996. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10997. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10998. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10999. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11000. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11001. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11002. }
  11003. function replaceClippingPlaneNums( string, parameters ) {
  11004. return string
  11005. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11006. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11007. }
  11008. // Resolve Includes
  11009. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11010. function resolveIncludes( string ) {
  11011. return string.replace( includePattern, includeReplacer );
  11012. }
  11013. function includeReplacer( match, include ) {
  11014. const string = ShaderChunk[ include ];
  11015. if ( string === undefined ) {
  11016. throw new Error( 'Can not resolve #include <' + include + '>' );
  11017. }
  11018. return resolveIncludes( string );
  11019. }
  11020. // Unroll Loops
  11021. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11022. 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;
  11023. function unrollLoops( string ) {
  11024. return string
  11025. .replace( unrollLoopPattern, loopReplacer )
  11026. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  11027. }
  11028. function deprecatedLoopReplacer( match, start, end, snippet ) {
  11029. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  11030. return loopReplacer( match, start, end, snippet );
  11031. }
  11032. function loopReplacer( match, start, end, snippet ) {
  11033. let string = '';
  11034. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11035. string += snippet
  11036. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11037. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11038. }
  11039. return string;
  11040. }
  11041. //
  11042. function generatePrecision( parameters ) {
  11043. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11044. if ( parameters.precision === 'highp' ) {
  11045. precisionstring += '\n#define HIGH_PRECISION';
  11046. } else if ( parameters.precision === 'mediump' ) {
  11047. precisionstring += '\n#define MEDIUM_PRECISION';
  11048. } else if ( parameters.precision === 'lowp' ) {
  11049. precisionstring += '\n#define LOW_PRECISION';
  11050. }
  11051. return precisionstring;
  11052. }
  11053. function generateShadowMapTypeDefine( parameters ) {
  11054. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11055. if ( parameters.shadowMapType === PCFShadowMap ) {
  11056. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11057. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11058. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11059. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11060. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11061. }
  11062. return shadowMapTypeDefine;
  11063. }
  11064. function generateEnvMapTypeDefine( parameters ) {
  11065. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11066. if ( parameters.envMap ) {
  11067. switch ( parameters.envMapMode ) {
  11068. case CubeReflectionMapping:
  11069. case CubeRefractionMapping:
  11070. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11071. break;
  11072. case CubeUVReflectionMapping:
  11073. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11074. break;
  11075. }
  11076. }
  11077. return envMapTypeDefine;
  11078. }
  11079. function generateEnvMapModeDefine( parameters ) {
  11080. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11081. if ( parameters.envMap ) {
  11082. switch ( parameters.envMapMode ) {
  11083. case CubeRefractionMapping:
  11084. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11085. break;
  11086. }
  11087. }
  11088. return envMapModeDefine;
  11089. }
  11090. function generateEnvMapBlendingDefine( parameters ) {
  11091. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11092. if ( parameters.envMap ) {
  11093. switch ( parameters.combine ) {
  11094. case MultiplyOperation:
  11095. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11096. break;
  11097. case MixOperation:
  11098. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11099. break;
  11100. case AddOperation:
  11101. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11102. break;
  11103. }
  11104. }
  11105. return envMapBlendingDefine;
  11106. }
  11107. function generateCubeUVSize( parameters ) {
  11108. const imageHeight = parameters.envMapCubeUVHeight;
  11109. if ( imageHeight === null ) return null;
  11110. const maxMip = Math.log2( imageHeight ) - 2;
  11111. const texelHeight = 1.0 / imageHeight;
  11112. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11113. return { texelWidth, texelHeight, maxMip };
  11114. }
  11115. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11116. // TODO Send this event to Three.js DevTools
  11117. // console.log( 'WebGLProgram', cacheKey );
  11118. const gl = renderer.getContext();
  11119. const defines = parameters.defines;
  11120. let vertexShader = parameters.vertexShader;
  11121. let fragmentShader = parameters.fragmentShader;
  11122. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11123. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11124. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11125. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11126. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11127. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11128. const customDefines = generateDefines( defines );
  11129. const program = gl.createProgram();
  11130. let prefixVertex, prefixFragment;
  11131. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11132. if ( parameters.isRawShaderMaterial ) {
  11133. prefixVertex = [
  11134. customDefines
  11135. ].filter( filterEmptyLine ).join( '\n' );
  11136. if ( prefixVertex.length > 0 ) {
  11137. prefixVertex += '\n';
  11138. }
  11139. prefixFragment = [
  11140. customExtensions,
  11141. customDefines
  11142. ].filter( filterEmptyLine ).join( '\n' );
  11143. if ( prefixFragment.length > 0 ) {
  11144. prefixFragment += '\n';
  11145. }
  11146. } else {
  11147. prefixVertex = [
  11148. generatePrecision( parameters ),
  11149. '#define SHADER_NAME ' + parameters.shaderName,
  11150. customDefines,
  11151. parameters.instancing ? '#define USE_INSTANCING' : '',
  11152. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11153. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11154. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11155. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11156. parameters.map ? '#define USE_MAP' : '',
  11157. parameters.envMap ? '#define USE_ENVMAP' : '',
  11158. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11159. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11160. parameters.aoMap ? '#define USE_AOMAP' : '',
  11161. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11162. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11163. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11164. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11165. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11166. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11167. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11168. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11169. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11170. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11171. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11172. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11173. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11174. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11175. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11176. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11177. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11178. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11179. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11180. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11181. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11182. parameters.vertexColors ? '#define USE_COLOR' : '',
  11183. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11184. parameters.vertexUvs ? '#define USE_UV' : '',
  11185. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11186. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11187. parameters.skinning ? '#define USE_SKINNING' : '',
  11188. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11189. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11190. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11191. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11192. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11193. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11194. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11195. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11196. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11197. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11198. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11199. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11200. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11201. 'uniform mat4 modelMatrix;',
  11202. 'uniform mat4 modelViewMatrix;',
  11203. 'uniform mat4 projectionMatrix;',
  11204. 'uniform mat4 viewMatrix;',
  11205. 'uniform mat3 normalMatrix;',
  11206. 'uniform vec3 cameraPosition;',
  11207. 'uniform bool isOrthographic;',
  11208. '#ifdef USE_INSTANCING',
  11209. ' attribute mat4 instanceMatrix;',
  11210. '#endif',
  11211. '#ifdef USE_INSTANCING_COLOR',
  11212. ' attribute vec3 instanceColor;',
  11213. '#endif',
  11214. 'attribute vec3 position;',
  11215. 'attribute vec3 normal;',
  11216. 'attribute vec2 uv;',
  11217. '#ifdef USE_TANGENT',
  11218. ' attribute vec4 tangent;',
  11219. '#endif',
  11220. '#if defined( USE_COLOR_ALPHA )',
  11221. ' attribute vec4 color;',
  11222. '#elif defined( USE_COLOR )',
  11223. ' attribute vec3 color;',
  11224. '#endif',
  11225. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11226. ' attribute vec3 morphTarget0;',
  11227. ' attribute vec3 morphTarget1;',
  11228. ' attribute vec3 morphTarget2;',
  11229. ' attribute vec3 morphTarget3;',
  11230. ' #ifdef USE_MORPHNORMALS',
  11231. ' attribute vec3 morphNormal0;',
  11232. ' attribute vec3 morphNormal1;',
  11233. ' attribute vec3 morphNormal2;',
  11234. ' attribute vec3 morphNormal3;',
  11235. ' #else',
  11236. ' attribute vec3 morphTarget4;',
  11237. ' attribute vec3 morphTarget5;',
  11238. ' attribute vec3 morphTarget6;',
  11239. ' attribute vec3 morphTarget7;',
  11240. ' #endif',
  11241. '#endif',
  11242. '#ifdef USE_SKINNING',
  11243. ' attribute vec4 skinIndex;',
  11244. ' attribute vec4 skinWeight;',
  11245. '#endif',
  11246. '\n'
  11247. ].filter( filterEmptyLine ).join( '\n' );
  11248. prefixFragment = [
  11249. customExtensions,
  11250. generatePrecision( parameters ),
  11251. '#define SHADER_NAME ' + parameters.shaderName,
  11252. customDefines,
  11253. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11254. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11255. parameters.map ? '#define USE_MAP' : '',
  11256. parameters.matcap ? '#define USE_MATCAP' : '',
  11257. parameters.envMap ? '#define USE_ENVMAP' : '',
  11258. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11259. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11260. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11261. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11262. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11263. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11264. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11265. parameters.aoMap ? '#define USE_AOMAP' : '',
  11266. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11267. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11268. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11269. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11270. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11271. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11272. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11273. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11274. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11275. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11276. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11277. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11278. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11279. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11280. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11281. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11282. parameters.sheen ? '#define USE_SHEEN' : '',
  11283. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11284. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11285. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11286. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11287. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11288. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11289. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11290. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11291. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11292. parameters.vertexUvs ? '#define USE_UV' : '',
  11293. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11294. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11295. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11296. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11297. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11298. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11299. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11300. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11301. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11302. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11303. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11304. 'uniform mat4 viewMatrix;',
  11305. 'uniform vec3 cameraPosition;',
  11306. 'uniform bool isOrthographic;',
  11307. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11308. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11309. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11310. parameters.dithering ? '#define DITHERING' : '',
  11311. parameters.opaque ? '#define OPAQUE' : '',
  11312. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11313. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11314. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11315. '\n'
  11316. ].filter( filterEmptyLine ).join( '\n' );
  11317. }
  11318. vertexShader = resolveIncludes( vertexShader );
  11319. vertexShader = replaceLightNums( vertexShader, parameters );
  11320. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11321. fragmentShader = resolveIncludes( fragmentShader );
  11322. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11323. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11324. vertexShader = unrollLoops( vertexShader );
  11325. fragmentShader = unrollLoops( fragmentShader );
  11326. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11327. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11328. versionString = '#version 300 es\n';
  11329. prefixVertex = [
  11330. 'precision mediump sampler2DArray;',
  11331. '#define attribute in',
  11332. '#define varying out',
  11333. '#define texture2D texture'
  11334. ].join( '\n' ) + '\n' + prefixVertex;
  11335. prefixFragment = [
  11336. '#define varying in',
  11337. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11338. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11339. '#define gl_FragDepthEXT gl_FragDepth',
  11340. '#define texture2D texture',
  11341. '#define textureCube texture',
  11342. '#define texture2DProj textureProj',
  11343. '#define texture2DLodEXT textureLod',
  11344. '#define texture2DProjLodEXT textureProjLod',
  11345. '#define textureCubeLodEXT textureLod',
  11346. '#define texture2DGradEXT textureGrad',
  11347. '#define texture2DProjGradEXT textureProjGrad',
  11348. '#define textureCubeGradEXT textureGrad'
  11349. ].join( '\n' ) + '\n' + prefixFragment;
  11350. }
  11351. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11352. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11353. // console.log( '*VERTEX*', vertexGlsl );
  11354. // console.log( '*FRAGMENT*', fragmentGlsl );
  11355. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11356. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11357. gl.attachShader( program, glVertexShader );
  11358. gl.attachShader( program, glFragmentShader );
  11359. // Force a particular attribute to index 0.
  11360. if ( parameters.index0AttributeName !== undefined ) {
  11361. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11362. } else if ( parameters.morphTargets === true ) {
  11363. // programs with morphTargets displace position out of attribute 0
  11364. gl.bindAttribLocation( program, 0, 'position' );
  11365. }
  11366. gl.linkProgram( program );
  11367. // check for link errors
  11368. if ( renderer.debug.checkShaderErrors ) {
  11369. const programLog = gl.getProgramInfoLog( program ).trim();
  11370. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11371. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11372. let runnable = true;
  11373. let haveDiagnostics = true;
  11374. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11375. runnable = false;
  11376. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11377. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11378. console.error(
  11379. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11380. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11381. 'Program Info Log: ' + programLog + '\n' +
  11382. vertexErrors + '\n' +
  11383. fragmentErrors
  11384. );
  11385. } else if ( programLog !== '' ) {
  11386. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11387. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11388. haveDiagnostics = false;
  11389. }
  11390. if ( haveDiagnostics ) {
  11391. this.diagnostics = {
  11392. runnable: runnable,
  11393. programLog: programLog,
  11394. vertexShader: {
  11395. log: vertexLog,
  11396. prefix: prefixVertex
  11397. },
  11398. fragmentShader: {
  11399. log: fragmentLog,
  11400. prefix: prefixFragment
  11401. }
  11402. };
  11403. }
  11404. }
  11405. // Clean up
  11406. // Crashes in iOS9 and iOS10. #18402
  11407. // gl.detachShader( program, glVertexShader );
  11408. // gl.detachShader( program, glFragmentShader );
  11409. gl.deleteShader( glVertexShader );
  11410. gl.deleteShader( glFragmentShader );
  11411. // set up caching for uniform locations
  11412. let cachedUniforms;
  11413. this.getUniforms = function () {
  11414. if ( cachedUniforms === undefined ) {
  11415. cachedUniforms = new WebGLUniforms( gl, program );
  11416. }
  11417. return cachedUniforms;
  11418. };
  11419. // set up caching for attribute locations
  11420. let cachedAttributes;
  11421. this.getAttributes = function () {
  11422. if ( cachedAttributes === undefined ) {
  11423. cachedAttributes = fetchAttributeLocations( gl, program );
  11424. }
  11425. return cachedAttributes;
  11426. };
  11427. // free resource
  11428. this.destroy = function () {
  11429. bindingStates.releaseStatesOfProgram( this );
  11430. gl.deleteProgram( program );
  11431. this.program = undefined;
  11432. };
  11433. //
  11434. this.name = parameters.shaderName;
  11435. this.id = programIdCount ++;
  11436. this.cacheKey = cacheKey;
  11437. this.usedTimes = 1;
  11438. this.program = program;
  11439. this.vertexShader = glVertexShader;
  11440. this.fragmentShader = glFragmentShader;
  11441. return this;
  11442. }
  11443. let _id = 0;
  11444. class WebGLShaderCache {
  11445. constructor() {
  11446. this.shaderCache = new Map();
  11447. this.materialCache = new Map();
  11448. }
  11449. update( material ) {
  11450. const vertexShader = material.vertexShader;
  11451. const fragmentShader = material.fragmentShader;
  11452. const vertexShaderStage = this._getShaderStage( vertexShader );
  11453. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11454. const materialShaders = this._getShaderCacheForMaterial( material );
  11455. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11456. materialShaders.add( vertexShaderStage );
  11457. vertexShaderStage.usedTimes ++;
  11458. }
  11459. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11460. materialShaders.add( fragmentShaderStage );
  11461. fragmentShaderStage.usedTimes ++;
  11462. }
  11463. return this;
  11464. }
  11465. remove( material ) {
  11466. const materialShaders = this.materialCache.get( material );
  11467. for ( const shaderStage of materialShaders ) {
  11468. shaderStage.usedTimes --;
  11469. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11470. }
  11471. this.materialCache.delete( material );
  11472. return this;
  11473. }
  11474. getVertexShaderID( material ) {
  11475. return this._getShaderStage( material.vertexShader ).id;
  11476. }
  11477. getFragmentShaderID( material ) {
  11478. return this._getShaderStage( material.fragmentShader ).id;
  11479. }
  11480. dispose() {
  11481. this.shaderCache.clear();
  11482. this.materialCache.clear();
  11483. }
  11484. _getShaderCacheForMaterial( material ) {
  11485. const cache = this.materialCache;
  11486. if ( cache.has( material ) === false ) {
  11487. cache.set( material, new Set() );
  11488. }
  11489. return cache.get( material );
  11490. }
  11491. _getShaderStage( code ) {
  11492. const cache = this.shaderCache;
  11493. if ( cache.has( code ) === false ) {
  11494. const stage = new WebGLShaderStage( code );
  11495. cache.set( code, stage );
  11496. }
  11497. return cache.get( code );
  11498. }
  11499. }
  11500. class WebGLShaderStage {
  11501. constructor( code ) {
  11502. this.id = _id ++;
  11503. this.code = code;
  11504. this.usedTimes = 0;
  11505. }
  11506. }
  11507. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11508. const _programLayers = new Layers();
  11509. const _customShaders = new WebGLShaderCache();
  11510. const programs = [];
  11511. const isWebGL2 = capabilities.isWebGL2;
  11512. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11513. const vertexTextures = capabilities.vertexTextures;
  11514. let precision = capabilities.precision;
  11515. const shaderIDs = {
  11516. MeshDepthMaterial: 'depth',
  11517. MeshDistanceMaterial: 'distanceRGBA',
  11518. MeshNormalMaterial: 'normal',
  11519. MeshBasicMaterial: 'basic',
  11520. MeshLambertMaterial: 'lambert',
  11521. MeshPhongMaterial: 'phong',
  11522. MeshToonMaterial: 'toon',
  11523. MeshStandardMaterial: 'physical',
  11524. MeshPhysicalMaterial: 'physical',
  11525. MeshMatcapMaterial: 'matcap',
  11526. LineBasicMaterial: 'basic',
  11527. LineDashedMaterial: 'dashed',
  11528. PointsMaterial: 'points',
  11529. ShadowMaterial: 'shadow',
  11530. SpriteMaterial: 'sprite'
  11531. };
  11532. function getParameters( material, lights, shadows, scene, object ) {
  11533. const fog = scene.fog;
  11534. const geometry = object.geometry;
  11535. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11536. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11537. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11538. const shaderID = shaderIDs[ material.type ];
  11539. // heuristics to create shader parameters according to lights in the scene
  11540. // (not to blow over maxLights budget)
  11541. if ( material.precision !== null ) {
  11542. precision = capabilities.getMaxPrecision( material.precision );
  11543. if ( precision !== material.precision ) {
  11544. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11545. }
  11546. }
  11547. //
  11548. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11549. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11550. let morphTextureStride = 0;
  11551. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11552. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11553. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11554. //
  11555. let vertexShader, fragmentShader;
  11556. let customVertexShaderID, customFragmentShaderID;
  11557. if ( shaderID ) {
  11558. const shader = ShaderLib[ shaderID ];
  11559. vertexShader = shader.vertexShader;
  11560. fragmentShader = shader.fragmentShader;
  11561. } else {
  11562. vertexShader = material.vertexShader;
  11563. fragmentShader = material.fragmentShader;
  11564. _customShaders.update( material );
  11565. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11566. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11567. }
  11568. const currentRenderTarget = renderer.getRenderTarget();
  11569. const useAlphaTest = material.alphaTest > 0;
  11570. const useClearcoat = material.clearcoat > 0;
  11571. const parameters = {
  11572. isWebGL2: isWebGL2,
  11573. shaderID: shaderID,
  11574. shaderName: material.type,
  11575. vertexShader: vertexShader,
  11576. fragmentShader: fragmentShader,
  11577. defines: material.defines,
  11578. customVertexShaderID: customVertexShaderID,
  11579. customFragmentShaderID: customFragmentShaderID,
  11580. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11581. glslVersion: material.glslVersion,
  11582. precision: precision,
  11583. instancing: object.isInstancedMesh === true,
  11584. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11585. supportsVertexTextures: vertexTextures,
  11586. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11587. map: !! material.map,
  11588. matcap: !! material.matcap,
  11589. envMap: !! envMap,
  11590. envMapMode: envMap && envMap.mapping,
  11591. envMapCubeUVHeight: envMapCubeUVHeight,
  11592. lightMap: !! material.lightMap,
  11593. aoMap: !! material.aoMap,
  11594. emissiveMap: !! material.emissiveMap,
  11595. bumpMap: !! material.bumpMap,
  11596. normalMap: !! material.normalMap,
  11597. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11598. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11599. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11600. clearcoat: useClearcoat,
  11601. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11602. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11603. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11604. displacementMap: !! material.displacementMap,
  11605. roughnessMap: !! material.roughnessMap,
  11606. metalnessMap: !! material.metalnessMap,
  11607. specularMap: !! material.specularMap,
  11608. specularIntensityMap: !! material.specularIntensityMap,
  11609. specularColorMap: !! material.specularColorMap,
  11610. opaque: material.transparent === false && material.blending === NormalBlending,
  11611. alphaMap: !! material.alphaMap,
  11612. alphaTest: useAlphaTest,
  11613. gradientMap: !! material.gradientMap,
  11614. sheen: material.sheen > 0,
  11615. sheenColorMap: !! material.sheenColorMap,
  11616. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11617. transmission: material.transmission > 0,
  11618. transmissionMap: !! material.transmissionMap,
  11619. thicknessMap: !! material.thicknessMap,
  11620. combine: material.combine,
  11621. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11622. vertexColors: material.vertexColors,
  11623. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11624. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap,
  11625. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap,
  11626. fog: !! fog,
  11627. useFog: material.fog === true,
  11628. fogExp2: ( fog && fog.isFogExp2 ),
  11629. flatShading: !! material.flatShading,
  11630. sizeAttenuation: material.sizeAttenuation,
  11631. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11632. skinning: object.isSkinnedMesh === true,
  11633. morphTargets: geometry.morphAttributes.position !== undefined,
  11634. morphNormals: geometry.morphAttributes.normal !== undefined,
  11635. morphColors: geometry.morphAttributes.color !== undefined,
  11636. morphTargetsCount: morphTargetsCount,
  11637. morphTextureStride: morphTextureStride,
  11638. numDirLights: lights.directional.length,
  11639. numPointLights: lights.point.length,
  11640. numSpotLights: lights.spot.length,
  11641. numRectAreaLights: lights.rectArea.length,
  11642. numHemiLights: lights.hemi.length,
  11643. numDirLightShadows: lights.directionalShadowMap.length,
  11644. numPointLightShadows: lights.pointShadowMap.length,
  11645. numSpotLightShadows: lights.spotShadowMap.length,
  11646. numClippingPlanes: clipping.numPlanes,
  11647. numClipIntersection: clipping.numIntersection,
  11648. dithering: material.dithering,
  11649. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11650. shadowMapType: renderer.shadowMap.type,
  11651. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11652. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11653. premultipliedAlpha: material.premultipliedAlpha,
  11654. doubleSided: material.side === DoubleSide,
  11655. flipSided: material.side === BackSide,
  11656. useDepthPacking: !! material.depthPacking,
  11657. depthPacking: material.depthPacking || 0,
  11658. index0AttributeName: material.index0AttributeName,
  11659. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11660. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11661. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11662. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11663. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11664. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11665. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11666. customProgramCacheKey: material.customProgramCacheKey()
  11667. };
  11668. return parameters;
  11669. }
  11670. function getProgramCacheKey( parameters ) {
  11671. const array = [];
  11672. if ( parameters.shaderID ) {
  11673. array.push( parameters.shaderID );
  11674. } else {
  11675. array.push( parameters.customVertexShaderID );
  11676. array.push( parameters.customFragmentShaderID );
  11677. }
  11678. if ( parameters.defines !== undefined ) {
  11679. for ( const name in parameters.defines ) {
  11680. array.push( name );
  11681. array.push( parameters.defines[ name ] );
  11682. }
  11683. }
  11684. if ( parameters.isRawShaderMaterial === false ) {
  11685. getProgramCacheKeyParameters( array, parameters );
  11686. getProgramCacheKeyBooleans( array, parameters );
  11687. array.push( renderer.outputEncoding );
  11688. }
  11689. array.push( parameters.customProgramCacheKey );
  11690. return array.join();
  11691. }
  11692. function getProgramCacheKeyParameters( array, parameters ) {
  11693. array.push( parameters.precision );
  11694. array.push( parameters.outputEncoding );
  11695. array.push( parameters.envMapMode );
  11696. array.push( parameters.envMapCubeUVHeight );
  11697. array.push( parameters.combine );
  11698. array.push( parameters.vertexUvs );
  11699. array.push( parameters.fogExp2 );
  11700. array.push( parameters.sizeAttenuation );
  11701. array.push( parameters.morphTargetsCount );
  11702. array.push( parameters.morphAttributeCount );
  11703. array.push( parameters.numDirLights );
  11704. array.push( parameters.numPointLights );
  11705. array.push( parameters.numSpotLights );
  11706. array.push( parameters.numHemiLights );
  11707. array.push( parameters.numRectAreaLights );
  11708. array.push( parameters.numDirLightShadows );
  11709. array.push( parameters.numPointLightShadows );
  11710. array.push( parameters.numSpotLightShadows );
  11711. array.push( parameters.shadowMapType );
  11712. array.push( parameters.toneMapping );
  11713. array.push( parameters.numClippingPlanes );
  11714. array.push( parameters.numClipIntersection );
  11715. array.push( parameters.depthPacking );
  11716. }
  11717. function getProgramCacheKeyBooleans( array, parameters ) {
  11718. _programLayers.disableAll();
  11719. if ( parameters.isWebGL2 )
  11720. _programLayers.enable( 0 );
  11721. if ( parameters.supportsVertexTextures )
  11722. _programLayers.enable( 1 );
  11723. if ( parameters.instancing )
  11724. _programLayers.enable( 2 );
  11725. if ( parameters.instancingColor )
  11726. _programLayers.enable( 3 );
  11727. if ( parameters.map )
  11728. _programLayers.enable( 4 );
  11729. if ( parameters.matcap )
  11730. _programLayers.enable( 5 );
  11731. if ( parameters.envMap )
  11732. _programLayers.enable( 6 );
  11733. if ( parameters.lightMap )
  11734. _programLayers.enable( 7 );
  11735. if ( parameters.aoMap )
  11736. _programLayers.enable( 8 );
  11737. if ( parameters.emissiveMap )
  11738. _programLayers.enable( 9 );
  11739. if ( parameters.bumpMap )
  11740. _programLayers.enable( 10 );
  11741. if ( parameters.normalMap )
  11742. _programLayers.enable( 11 );
  11743. if ( parameters.objectSpaceNormalMap )
  11744. _programLayers.enable( 12 );
  11745. if ( parameters.tangentSpaceNormalMap )
  11746. _programLayers.enable( 13 );
  11747. if ( parameters.clearcoat )
  11748. _programLayers.enable( 14 );
  11749. if ( parameters.clearcoatMap )
  11750. _programLayers.enable( 15 );
  11751. if ( parameters.clearcoatRoughnessMap )
  11752. _programLayers.enable( 16 );
  11753. if ( parameters.clearcoatNormalMap )
  11754. _programLayers.enable( 17 );
  11755. if ( parameters.displacementMap )
  11756. _programLayers.enable( 18 );
  11757. if ( parameters.specularMap )
  11758. _programLayers.enable( 19 );
  11759. if ( parameters.roughnessMap )
  11760. _programLayers.enable( 20 );
  11761. if ( parameters.metalnessMap )
  11762. _programLayers.enable( 21 );
  11763. if ( parameters.gradientMap )
  11764. _programLayers.enable( 22 );
  11765. if ( parameters.alphaMap )
  11766. _programLayers.enable( 23 );
  11767. if ( parameters.alphaTest )
  11768. _programLayers.enable( 24 );
  11769. if ( parameters.vertexColors )
  11770. _programLayers.enable( 25 );
  11771. if ( parameters.vertexAlphas )
  11772. _programLayers.enable( 26 );
  11773. if ( parameters.vertexUvs )
  11774. _programLayers.enable( 27 );
  11775. if ( parameters.vertexTangents )
  11776. _programLayers.enable( 28 );
  11777. if ( parameters.uvsVertexOnly )
  11778. _programLayers.enable( 29 );
  11779. if ( parameters.fog )
  11780. _programLayers.enable( 30 );
  11781. array.push( _programLayers.mask );
  11782. _programLayers.disableAll();
  11783. if ( parameters.useFog )
  11784. _programLayers.enable( 0 );
  11785. if ( parameters.flatShading )
  11786. _programLayers.enable( 1 );
  11787. if ( parameters.logarithmicDepthBuffer )
  11788. _programLayers.enable( 2 );
  11789. if ( parameters.skinning )
  11790. _programLayers.enable( 3 );
  11791. if ( parameters.morphTargets )
  11792. _programLayers.enable( 4 );
  11793. if ( parameters.morphNormals )
  11794. _programLayers.enable( 5 );
  11795. if ( parameters.morphColors )
  11796. _programLayers.enable( 6 );
  11797. if ( parameters.premultipliedAlpha )
  11798. _programLayers.enable( 7 );
  11799. if ( parameters.shadowMapEnabled )
  11800. _programLayers.enable( 8 );
  11801. if ( parameters.physicallyCorrectLights )
  11802. _programLayers.enable( 9 );
  11803. if ( parameters.doubleSided )
  11804. _programLayers.enable( 10 );
  11805. if ( parameters.flipSided )
  11806. _programLayers.enable( 11 );
  11807. if ( parameters.useDepthPacking )
  11808. _programLayers.enable( 12 );
  11809. if ( parameters.dithering )
  11810. _programLayers.enable( 13 );
  11811. if ( parameters.specularIntensityMap )
  11812. _programLayers.enable( 14 );
  11813. if ( parameters.specularColorMap )
  11814. _programLayers.enable( 15 );
  11815. if ( parameters.transmission )
  11816. _programLayers.enable( 16 );
  11817. if ( parameters.transmissionMap )
  11818. _programLayers.enable( 17 );
  11819. if ( parameters.thicknessMap )
  11820. _programLayers.enable( 18 );
  11821. if ( parameters.sheen )
  11822. _programLayers.enable( 19 );
  11823. if ( parameters.sheenColorMap )
  11824. _programLayers.enable( 20 );
  11825. if ( parameters.sheenRoughnessMap )
  11826. _programLayers.enable( 21 );
  11827. if ( parameters.decodeVideoTexture )
  11828. _programLayers.enable( 22 );
  11829. if ( parameters.opaque )
  11830. _programLayers.enable( 23 );
  11831. array.push( _programLayers.mask );
  11832. }
  11833. function getUniforms( material ) {
  11834. const shaderID = shaderIDs[ material.type ];
  11835. let uniforms;
  11836. if ( shaderID ) {
  11837. const shader = ShaderLib[ shaderID ];
  11838. uniforms = UniformsUtils.clone( shader.uniforms );
  11839. } else {
  11840. uniforms = material.uniforms;
  11841. }
  11842. return uniforms;
  11843. }
  11844. function acquireProgram( parameters, cacheKey ) {
  11845. let program;
  11846. // Check if code has been already compiled
  11847. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11848. const preexistingProgram = programs[ p ];
  11849. if ( preexistingProgram.cacheKey === cacheKey ) {
  11850. program = preexistingProgram;
  11851. ++ program.usedTimes;
  11852. break;
  11853. }
  11854. }
  11855. if ( program === undefined ) {
  11856. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11857. programs.push( program );
  11858. }
  11859. return program;
  11860. }
  11861. function releaseProgram( program ) {
  11862. if ( -- program.usedTimes === 0 ) {
  11863. // Remove from unordered set
  11864. const i = programs.indexOf( program );
  11865. programs[ i ] = programs[ programs.length - 1 ];
  11866. programs.pop();
  11867. // Free WebGL resources
  11868. program.destroy();
  11869. }
  11870. }
  11871. function releaseShaderCache( material ) {
  11872. _customShaders.remove( material );
  11873. }
  11874. function dispose() {
  11875. _customShaders.dispose();
  11876. }
  11877. return {
  11878. getParameters: getParameters,
  11879. getProgramCacheKey: getProgramCacheKey,
  11880. getUniforms: getUniforms,
  11881. acquireProgram: acquireProgram,
  11882. releaseProgram: releaseProgram,
  11883. releaseShaderCache: releaseShaderCache,
  11884. // Exposed for resource monitoring & error feedback via renderer.info:
  11885. programs: programs,
  11886. dispose: dispose
  11887. };
  11888. }
  11889. function WebGLProperties() {
  11890. let properties = new WeakMap();
  11891. function get( object ) {
  11892. let map = properties.get( object );
  11893. if ( map === undefined ) {
  11894. map = {};
  11895. properties.set( object, map );
  11896. }
  11897. return map;
  11898. }
  11899. function remove( object ) {
  11900. properties.delete( object );
  11901. }
  11902. function update( object, key, value ) {
  11903. properties.get( object )[ key ] = value;
  11904. }
  11905. function dispose() {
  11906. properties = new WeakMap();
  11907. }
  11908. return {
  11909. get: get,
  11910. remove: remove,
  11911. update: update,
  11912. dispose: dispose
  11913. };
  11914. }
  11915. function painterSortStable( a, b ) {
  11916. if ( a.groupOrder !== b.groupOrder ) {
  11917. return a.groupOrder - b.groupOrder;
  11918. } else if ( a.renderOrder !== b.renderOrder ) {
  11919. return a.renderOrder - b.renderOrder;
  11920. } else if ( a.material.id !== b.material.id ) {
  11921. return a.material.id - b.material.id;
  11922. } else if ( a.z !== b.z ) {
  11923. return a.z - b.z;
  11924. } else {
  11925. return a.id - b.id;
  11926. }
  11927. }
  11928. function reversePainterSortStable( a, b ) {
  11929. if ( a.groupOrder !== b.groupOrder ) {
  11930. return a.groupOrder - b.groupOrder;
  11931. } else if ( a.renderOrder !== b.renderOrder ) {
  11932. return a.renderOrder - b.renderOrder;
  11933. } else if ( a.z !== b.z ) {
  11934. return b.z - a.z;
  11935. } else {
  11936. return a.id - b.id;
  11937. }
  11938. }
  11939. function WebGLRenderList() {
  11940. const renderItems = [];
  11941. let renderItemsIndex = 0;
  11942. const opaque = [];
  11943. const transmissive = [];
  11944. const transparent = [];
  11945. function init() {
  11946. renderItemsIndex = 0;
  11947. opaque.length = 0;
  11948. transmissive.length = 0;
  11949. transparent.length = 0;
  11950. }
  11951. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11952. let renderItem = renderItems[ renderItemsIndex ];
  11953. if ( renderItem === undefined ) {
  11954. renderItem = {
  11955. id: object.id,
  11956. object: object,
  11957. geometry: geometry,
  11958. material: material,
  11959. groupOrder: groupOrder,
  11960. renderOrder: object.renderOrder,
  11961. z: z,
  11962. group: group
  11963. };
  11964. renderItems[ renderItemsIndex ] = renderItem;
  11965. } else {
  11966. renderItem.id = object.id;
  11967. renderItem.object = object;
  11968. renderItem.geometry = geometry;
  11969. renderItem.material = material;
  11970. renderItem.groupOrder = groupOrder;
  11971. renderItem.renderOrder = object.renderOrder;
  11972. renderItem.z = z;
  11973. renderItem.group = group;
  11974. }
  11975. renderItemsIndex ++;
  11976. return renderItem;
  11977. }
  11978. function push( object, geometry, material, groupOrder, z, group ) {
  11979. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11980. if ( material.transmission > 0.0 ) {
  11981. transmissive.push( renderItem );
  11982. } else if ( material.transparent === true ) {
  11983. transparent.push( renderItem );
  11984. } else {
  11985. opaque.push( renderItem );
  11986. }
  11987. }
  11988. function unshift( object, geometry, material, groupOrder, z, group ) {
  11989. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11990. if ( material.transmission > 0.0 ) {
  11991. transmissive.unshift( renderItem );
  11992. } else if ( material.transparent === true ) {
  11993. transparent.unshift( renderItem );
  11994. } else {
  11995. opaque.unshift( renderItem );
  11996. }
  11997. }
  11998. function sort( customOpaqueSort, customTransparentSort ) {
  11999. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12000. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12001. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12002. }
  12003. function finish() {
  12004. // Clear references from inactive renderItems in the list
  12005. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12006. const renderItem = renderItems[ i ];
  12007. if ( renderItem.id === null ) break;
  12008. renderItem.id = null;
  12009. renderItem.object = null;
  12010. renderItem.geometry = null;
  12011. renderItem.material = null;
  12012. renderItem.group = null;
  12013. }
  12014. }
  12015. return {
  12016. opaque: opaque,
  12017. transmissive: transmissive,
  12018. transparent: transparent,
  12019. init: init,
  12020. push: push,
  12021. unshift: unshift,
  12022. finish: finish,
  12023. sort: sort
  12024. };
  12025. }
  12026. function WebGLRenderLists() {
  12027. let lists = new WeakMap();
  12028. function get( scene, renderCallDepth ) {
  12029. let list;
  12030. if ( lists.has( scene ) === false ) {
  12031. list = new WebGLRenderList();
  12032. lists.set( scene, [ list ] );
  12033. } else {
  12034. if ( renderCallDepth >= lists.get( scene ).length ) {
  12035. list = new WebGLRenderList();
  12036. lists.get( scene ).push( list );
  12037. } else {
  12038. list = lists.get( scene )[ renderCallDepth ];
  12039. }
  12040. }
  12041. return list;
  12042. }
  12043. function dispose() {
  12044. lists = new WeakMap();
  12045. }
  12046. return {
  12047. get: get,
  12048. dispose: dispose
  12049. };
  12050. }
  12051. function UniformsCache() {
  12052. const lights = {};
  12053. return {
  12054. get: function ( light ) {
  12055. if ( lights[ light.id ] !== undefined ) {
  12056. return lights[ light.id ];
  12057. }
  12058. let uniforms;
  12059. switch ( light.type ) {
  12060. case 'DirectionalLight':
  12061. uniforms = {
  12062. direction: new Vector3(),
  12063. color: new Color()
  12064. };
  12065. break;
  12066. case 'SpotLight':
  12067. uniforms = {
  12068. position: new Vector3(),
  12069. direction: new Vector3(),
  12070. color: new Color(),
  12071. distance: 0,
  12072. coneCos: 0,
  12073. penumbraCos: 0,
  12074. decay: 0
  12075. };
  12076. break;
  12077. case 'PointLight':
  12078. uniforms = {
  12079. position: new Vector3(),
  12080. color: new Color(),
  12081. distance: 0,
  12082. decay: 0
  12083. };
  12084. break;
  12085. case 'HemisphereLight':
  12086. uniforms = {
  12087. direction: new Vector3(),
  12088. skyColor: new Color(),
  12089. groundColor: new Color()
  12090. };
  12091. break;
  12092. case 'RectAreaLight':
  12093. uniforms = {
  12094. color: new Color(),
  12095. position: new Vector3(),
  12096. halfWidth: new Vector3(),
  12097. halfHeight: new Vector3()
  12098. };
  12099. break;
  12100. }
  12101. lights[ light.id ] = uniforms;
  12102. return uniforms;
  12103. }
  12104. };
  12105. }
  12106. function ShadowUniformsCache() {
  12107. const lights = {};
  12108. return {
  12109. get: function ( light ) {
  12110. if ( lights[ light.id ] !== undefined ) {
  12111. return lights[ light.id ];
  12112. }
  12113. let uniforms;
  12114. switch ( light.type ) {
  12115. case 'DirectionalLight':
  12116. uniforms = {
  12117. shadowBias: 0,
  12118. shadowNormalBias: 0,
  12119. shadowRadius: 1,
  12120. shadowMapSize: new Vector2()
  12121. };
  12122. break;
  12123. case 'SpotLight':
  12124. uniforms = {
  12125. shadowBias: 0,
  12126. shadowNormalBias: 0,
  12127. shadowRadius: 1,
  12128. shadowMapSize: new Vector2()
  12129. };
  12130. break;
  12131. case 'PointLight':
  12132. uniforms = {
  12133. shadowBias: 0,
  12134. shadowNormalBias: 0,
  12135. shadowRadius: 1,
  12136. shadowMapSize: new Vector2(),
  12137. shadowCameraNear: 1,
  12138. shadowCameraFar: 1000
  12139. };
  12140. break;
  12141. // TODO (abelnation): set RectAreaLight shadow uniforms
  12142. }
  12143. lights[ light.id ] = uniforms;
  12144. return uniforms;
  12145. }
  12146. };
  12147. }
  12148. let nextVersion = 0;
  12149. function shadowCastingLightsFirst( lightA, lightB ) {
  12150. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  12151. }
  12152. function WebGLLights( extensions, capabilities ) {
  12153. const cache = new UniformsCache();
  12154. const shadowCache = ShadowUniformsCache();
  12155. const state = {
  12156. version: 0,
  12157. hash: {
  12158. directionalLength: - 1,
  12159. pointLength: - 1,
  12160. spotLength: - 1,
  12161. rectAreaLength: - 1,
  12162. hemiLength: - 1,
  12163. numDirectionalShadows: - 1,
  12164. numPointShadows: - 1,
  12165. numSpotShadows: - 1
  12166. },
  12167. ambient: [ 0, 0, 0 ],
  12168. probe: [],
  12169. directional: [],
  12170. directionalShadow: [],
  12171. directionalShadowMap: [],
  12172. directionalShadowMatrix: [],
  12173. spot: [],
  12174. spotShadow: [],
  12175. spotShadowMap: [],
  12176. spotShadowMatrix: [],
  12177. rectArea: [],
  12178. rectAreaLTC1: null,
  12179. rectAreaLTC2: null,
  12180. point: [],
  12181. pointShadow: [],
  12182. pointShadowMap: [],
  12183. pointShadowMatrix: [],
  12184. hemi: []
  12185. };
  12186. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12187. const vector3 = new Vector3();
  12188. const matrix4 = new Matrix4();
  12189. const matrix42 = new Matrix4();
  12190. function setup( lights, physicallyCorrectLights ) {
  12191. let r = 0, g = 0, b = 0;
  12192. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12193. let directionalLength = 0;
  12194. let pointLength = 0;
  12195. let spotLength = 0;
  12196. let rectAreaLength = 0;
  12197. let hemiLength = 0;
  12198. let numDirectionalShadows = 0;
  12199. let numPointShadows = 0;
  12200. let numSpotShadows = 0;
  12201. lights.sort( shadowCastingLightsFirst );
  12202. // artist-friendly light intensity scaling factor
  12203. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12204. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12205. const light = lights[ i ];
  12206. const color = light.color;
  12207. const intensity = light.intensity;
  12208. const distance = light.distance;
  12209. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12210. if ( light.isAmbientLight ) {
  12211. r += color.r * intensity * scaleFactor;
  12212. g += color.g * intensity * scaleFactor;
  12213. b += color.b * intensity * scaleFactor;
  12214. } else if ( light.isLightProbe ) {
  12215. for ( let j = 0; j < 9; j ++ ) {
  12216. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12217. }
  12218. } else if ( light.isDirectionalLight ) {
  12219. const uniforms = cache.get( light );
  12220. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12221. if ( light.castShadow ) {
  12222. const shadow = light.shadow;
  12223. const shadowUniforms = shadowCache.get( light );
  12224. shadowUniforms.shadowBias = shadow.bias;
  12225. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12226. shadowUniforms.shadowRadius = shadow.radius;
  12227. shadowUniforms.shadowMapSize = shadow.mapSize;
  12228. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12229. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12230. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12231. numDirectionalShadows ++;
  12232. }
  12233. state.directional[ directionalLength ] = uniforms;
  12234. directionalLength ++;
  12235. } else if ( light.isSpotLight ) {
  12236. const uniforms = cache.get( light );
  12237. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12238. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12239. uniforms.distance = distance;
  12240. uniforms.coneCos = Math.cos( light.angle );
  12241. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12242. uniforms.decay = light.decay;
  12243. if ( light.castShadow ) {
  12244. const shadow = light.shadow;
  12245. const shadowUniforms = shadowCache.get( light );
  12246. shadowUniforms.shadowBias = shadow.bias;
  12247. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12248. shadowUniforms.shadowRadius = shadow.radius;
  12249. shadowUniforms.shadowMapSize = shadow.mapSize;
  12250. state.spotShadow[ spotLength ] = shadowUniforms;
  12251. state.spotShadowMap[ spotLength ] = shadowMap;
  12252. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12253. numSpotShadows ++;
  12254. }
  12255. state.spot[ spotLength ] = uniforms;
  12256. spotLength ++;
  12257. } else if ( light.isRectAreaLight ) {
  12258. const uniforms = cache.get( light );
  12259. // (a) intensity is the total visible light emitted
  12260. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12261. // (b) intensity is the brightness of the light
  12262. uniforms.color.copy( color ).multiplyScalar( intensity );
  12263. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12264. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12265. state.rectArea[ rectAreaLength ] = uniforms;
  12266. rectAreaLength ++;
  12267. } else if ( light.isPointLight ) {
  12268. const uniforms = cache.get( light );
  12269. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12270. uniforms.distance = light.distance;
  12271. uniforms.decay = light.decay;
  12272. if ( light.castShadow ) {
  12273. const shadow = light.shadow;
  12274. const shadowUniforms = shadowCache.get( light );
  12275. shadowUniforms.shadowBias = shadow.bias;
  12276. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12277. shadowUniforms.shadowRadius = shadow.radius;
  12278. shadowUniforms.shadowMapSize = shadow.mapSize;
  12279. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12280. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12281. state.pointShadow[ pointLength ] = shadowUniforms;
  12282. state.pointShadowMap[ pointLength ] = shadowMap;
  12283. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12284. numPointShadows ++;
  12285. }
  12286. state.point[ pointLength ] = uniforms;
  12287. pointLength ++;
  12288. } else if ( light.isHemisphereLight ) {
  12289. const uniforms = cache.get( light );
  12290. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12291. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12292. state.hemi[ hemiLength ] = uniforms;
  12293. hemiLength ++;
  12294. }
  12295. }
  12296. if ( rectAreaLength > 0 ) {
  12297. if ( capabilities.isWebGL2 ) {
  12298. // WebGL 2
  12299. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12300. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12301. } else {
  12302. // WebGL 1
  12303. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12304. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12305. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12306. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12307. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12308. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12309. } else {
  12310. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12311. }
  12312. }
  12313. }
  12314. state.ambient[ 0 ] = r;
  12315. state.ambient[ 1 ] = g;
  12316. state.ambient[ 2 ] = b;
  12317. const hash = state.hash;
  12318. if ( hash.directionalLength !== directionalLength ||
  12319. hash.pointLength !== pointLength ||
  12320. hash.spotLength !== spotLength ||
  12321. hash.rectAreaLength !== rectAreaLength ||
  12322. hash.hemiLength !== hemiLength ||
  12323. hash.numDirectionalShadows !== numDirectionalShadows ||
  12324. hash.numPointShadows !== numPointShadows ||
  12325. hash.numSpotShadows !== numSpotShadows ) {
  12326. state.directional.length = directionalLength;
  12327. state.spot.length = spotLength;
  12328. state.rectArea.length = rectAreaLength;
  12329. state.point.length = pointLength;
  12330. state.hemi.length = hemiLength;
  12331. state.directionalShadow.length = numDirectionalShadows;
  12332. state.directionalShadowMap.length = numDirectionalShadows;
  12333. state.pointShadow.length = numPointShadows;
  12334. state.pointShadowMap.length = numPointShadows;
  12335. state.spotShadow.length = numSpotShadows;
  12336. state.spotShadowMap.length = numSpotShadows;
  12337. state.directionalShadowMatrix.length = numDirectionalShadows;
  12338. state.pointShadowMatrix.length = numPointShadows;
  12339. state.spotShadowMatrix.length = numSpotShadows;
  12340. hash.directionalLength = directionalLength;
  12341. hash.pointLength = pointLength;
  12342. hash.spotLength = spotLength;
  12343. hash.rectAreaLength = rectAreaLength;
  12344. hash.hemiLength = hemiLength;
  12345. hash.numDirectionalShadows = numDirectionalShadows;
  12346. hash.numPointShadows = numPointShadows;
  12347. hash.numSpotShadows = numSpotShadows;
  12348. state.version = nextVersion ++;
  12349. }
  12350. }
  12351. function setupView( lights, camera ) {
  12352. let directionalLength = 0;
  12353. let pointLength = 0;
  12354. let spotLength = 0;
  12355. let rectAreaLength = 0;
  12356. let hemiLength = 0;
  12357. const viewMatrix = camera.matrixWorldInverse;
  12358. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12359. const light = lights[ i ];
  12360. if ( light.isDirectionalLight ) {
  12361. const uniforms = state.directional[ directionalLength ];
  12362. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12363. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12364. uniforms.direction.sub( vector3 );
  12365. uniforms.direction.transformDirection( viewMatrix );
  12366. directionalLength ++;
  12367. } else if ( light.isSpotLight ) {
  12368. const uniforms = state.spot[ spotLength ];
  12369. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12370. uniforms.position.applyMatrix4( viewMatrix );
  12371. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12372. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12373. uniforms.direction.sub( vector3 );
  12374. uniforms.direction.transformDirection( viewMatrix );
  12375. spotLength ++;
  12376. } else if ( light.isRectAreaLight ) {
  12377. const uniforms = state.rectArea[ rectAreaLength ];
  12378. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12379. uniforms.position.applyMatrix4( viewMatrix );
  12380. // extract local rotation of light to derive width/height half vectors
  12381. matrix42.identity();
  12382. matrix4.copy( light.matrixWorld );
  12383. matrix4.premultiply( viewMatrix );
  12384. matrix42.extractRotation( matrix4 );
  12385. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12386. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12387. uniforms.halfWidth.applyMatrix4( matrix42 );
  12388. uniforms.halfHeight.applyMatrix4( matrix42 );
  12389. rectAreaLength ++;
  12390. } else if ( light.isPointLight ) {
  12391. const uniforms = state.point[ pointLength ];
  12392. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12393. uniforms.position.applyMatrix4( viewMatrix );
  12394. pointLength ++;
  12395. } else if ( light.isHemisphereLight ) {
  12396. const uniforms = state.hemi[ hemiLength ];
  12397. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12398. uniforms.direction.transformDirection( viewMatrix );
  12399. hemiLength ++;
  12400. }
  12401. }
  12402. }
  12403. return {
  12404. setup: setup,
  12405. setupView: setupView,
  12406. state: state
  12407. };
  12408. }
  12409. function WebGLRenderState( extensions, capabilities ) {
  12410. const lights = new WebGLLights( extensions, capabilities );
  12411. const lightsArray = [];
  12412. const shadowsArray = [];
  12413. function init() {
  12414. lightsArray.length = 0;
  12415. shadowsArray.length = 0;
  12416. }
  12417. function pushLight( light ) {
  12418. lightsArray.push( light );
  12419. }
  12420. function pushShadow( shadowLight ) {
  12421. shadowsArray.push( shadowLight );
  12422. }
  12423. function setupLights( physicallyCorrectLights ) {
  12424. lights.setup( lightsArray, physicallyCorrectLights );
  12425. }
  12426. function setupLightsView( camera ) {
  12427. lights.setupView( lightsArray, camera );
  12428. }
  12429. const state = {
  12430. lightsArray: lightsArray,
  12431. shadowsArray: shadowsArray,
  12432. lights: lights
  12433. };
  12434. return {
  12435. init: init,
  12436. state: state,
  12437. setupLights: setupLights,
  12438. setupLightsView: setupLightsView,
  12439. pushLight: pushLight,
  12440. pushShadow: pushShadow
  12441. };
  12442. }
  12443. function WebGLRenderStates( extensions, capabilities ) {
  12444. let renderStates = new WeakMap();
  12445. function get( scene, renderCallDepth = 0 ) {
  12446. let renderState;
  12447. if ( renderStates.has( scene ) === false ) {
  12448. renderState = new WebGLRenderState( extensions, capabilities );
  12449. renderStates.set( scene, [ renderState ] );
  12450. } else {
  12451. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12452. renderState = new WebGLRenderState( extensions, capabilities );
  12453. renderStates.get( scene ).push( renderState );
  12454. } else {
  12455. renderState = renderStates.get( scene )[ renderCallDepth ];
  12456. }
  12457. }
  12458. return renderState;
  12459. }
  12460. function dispose() {
  12461. renderStates = new WeakMap();
  12462. }
  12463. return {
  12464. get: get,
  12465. dispose: dispose
  12466. };
  12467. }
  12468. class MeshDepthMaterial extends Material {
  12469. constructor( parameters ) {
  12470. super();
  12471. this.type = 'MeshDepthMaterial';
  12472. this.depthPacking = BasicDepthPacking;
  12473. this.map = null;
  12474. this.alphaMap = null;
  12475. this.displacementMap = null;
  12476. this.displacementScale = 1;
  12477. this.displacementBias = 0;
  12478. this.wireframe = false;
  12479. this.wireframeLinewidth = 1;
  12480. this.setValues( parameters );
  12481. }
  12482. copy( source ) {
  12483. super.copy( source );
  12484. this.depthPacking = source.depthPacking;
  12485. this.map = source.map;
  12486. this.alphaMap = source.alphaMap;
  12487. this.displacementMap = source.displacementMap;
  12488. this.displacementScale = source.displacementScale;
  12489. this.displacementBias = source.displacementBias;
  12490. this.wireframe = source.wireframe;
  12491. this.wireframeLinewidth = source.wireframeLinewidth;
  12492. return this;
  12493. }
  12494. }
  12495. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12496. class MeshDistanceMaterial extends Material {
  12497. constructor( parameters ) {
  12498. super();
  12499. this.type = 'MeshDistanceMaterial';
  12500. this.referencePosition = new Vector3();
  12501. this.nearDistance = 1;
  12502. this.farDistance = 1000;
  12503. this.map = null;
  12504. this.alphaMap = null;
  12505. this.displacementMap = null;
  12506. this.displacementScale = 1;
  12507. this.displacementBias = 0;
  12508. this.setValues( parameters );
  12509. }
  12510. copy( source ) {
  12511. super.copy( source );
  12512. this.referencePosition.copy( source.referencePosition );
  12513. this.nearDistance = source.nearDistance;
  12514. this.farDistance = source.farDistance;
  12515. this.map = source.map;
  12516. this.alphaMap = source.alphaMap;
  12517. this.displacementMap = source.displacementMap;
  12518. this.displacementScale = source.displacementScale;
  12519. this.displacementBias = source.displacementBias;
  12520. return this;
  12521. }
  12522. }
  12523. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12524. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12525. 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}";
  12526. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12527. let _frustum = new Frustum();
  12528. const _shadowMapSize = new Vector2(),
  12529. _viewportSize = new Vector2(),
  12530. _viewport = new Vector4(),
  12531. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12532. _distanceMaterial = new MeshDistanceMaterial(),
  12533. _materialCache = {},
  12534. _maxTextureSize = _capabilities.maxTextureSize;
  12535. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12536. const shadowMaterialVertical = new ShaderMaterial( {
  12537. defines: {
  12538. VSM_SAMPLES: 8
  12539. },
  12540. uniforms: {
  12541. shadow_pass: { value: null },
  12542. resolution: { value: new Vector2() },
  12543. radius: { value: 4.0 }
  12544. },
  12545. vertexShader: vertex,
  12546. fragmentShader: fragment
  12547. } );
  12548. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12549. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12550. const fullScreenTri = new BufferGeometry();
  12551. fullScreenTri.setAttribute(
  12552. 'position',
  12553. new BufferAttribute(
  12554. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12555. 3
  12556. )
  12557. );
  12558. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12559. const scope = this;
  12560. this.enabled = false;
  12561. this.autoUpdate = true;
  12562. this.needsUpdate = false;
  12563. this.type = PCFShadowMap;
  12564. this.render = function ( lights, scene, camera ) {
  12565. if ( scope.enabled === false ) return;
  12566. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12567. if ( lights.length === 0 ) return;
  12568. const currentRenderTarget = _renderer.getRenderTarget();
  12569. const activeCubeFace = _renderer.getActiveCubeFace();
  12570. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12571. const _state = _renderer.state;
  12572. // Set GL state for depth map.
  12573. _state.setBlending( NoBlending );
  12574. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12575. _state.buffers.depth.setTest( true );
  12576. _state.setScissorTest( false );
  12577. // render depth map
  12578. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12579. const light = lights[ i ];
  12580. const shadow = light.shadow;
  12581. if ( shadow === undefined ) {
  12582. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12583. continue;
  12584. }
  12585. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12586. _shadowMapSize.copy( shadow.mapSize );
  12587. const shadowFrameExtents = shadow.getFrameExtents();
  12588. _shadowMapSize.multiply( shadowFrameExtents );
  12589. _viewportSize.copy( shadow.mapSize );
  12590. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12591. if ( _shadowMapSize.x > _maxTextureSize ) {
  12592. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12593. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12594. shadow.mapSize.x = _viewportSize.x;
  12595. }
  12596. if ( _shadowMapSize.y > _maxTextureSize ) {
  12597. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12598. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12599. shadow.mapSize.y = _viewportSize.y;
  12600. }
  12601. }
  12602. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12603. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12604. shadow.map.texture.name = light.name + '.shadowMap';
  12605. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12606. shadow.camera.updateProjectionMatrix();
  12607. }
  12608. if ( shadow.map === null ) {
  12609. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12610. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12611. shadow.map.texture.name = light.name + '.shadowMap';
  12612. shadow.camera.updateProjectionMatrix();
  12613. }
  12614. _renderer.setRenderTarget( shadow.map );
  12615. _renderer.clear();
  12616. const viewportCount = shadow.getViewportCount();
  12617. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12618. const viewport = shadow.getViewport( vp );
  12619. _viewport.set(
  12620. _viewportSize.x * viewport.x,
  12621. _viewportSize.y * viewport.y,
  12622. _viewportSize.x * viewport.z,
  12623. _viewportSize.y * viewport.w
  12624. );
  12625. _state.viewport( _viewport );
  12626. shadow.updateMatrices( light, vp );
  12627. _frustum = shadow.getFrustum();
  12628. renderObject( scene, camera, shadow.camera, light, this.type );
  12629. }
  12630. // do blur pass for VSM
  12631. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12632. VSMPass( shadow, camera );
  12633. }
  12634. shadow.needsUpdate = false;
  12635. }
  12636. scope.needsUpdate = false;
  12637. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12638. };
  12639. function VSMPass( shadow, camera ) {
  12640. const geometry = _objects.update( fullScreenMesh );
  12641. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12642. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12643. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12644. shadowMaterialVertical.needsUpdate = true;
  12645. shadowMaterialHorizontal.needsUpdate = true;
  12646. }
  12647. // vertical pass
  12648. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12649. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12650. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12651. _renderer.setRenderTarget( shadow.mapPass );
  12652. _renderer.clear();
  12653. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12654. // horizontal pass
  12655. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12656. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12657. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12658. _renderer.setRenderTarget( shadow.map );
  12659. _renderer.clear();
  12660. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12661. }
  12662. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12663. let result = null;
  12664. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12665. if ( customMaterial !== undefined ) {
  12666. result = customMaterial;
  12667. } else {
  12668. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12669. }
  12670. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  12671. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12672. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12673. // in this case we need a unique material instance reflecting the
  12674. // appropriate state
  12675. const keyA = result.uuid, keyB = material.uuid;
  12676. let materialsForVariant = _materialCache[ keyA ];
  12677. if ( materialsForVariant === undefined ) {
  12678. materialsForVariant = {};
  12679. _materialCache[ keyA ] = materialsForVariant;
  12680. }
  12681. let cachedMaterial = materialsForVariant[ keyB ];
  12682. if ( cachedMaterial === undefined ) {
  12683. cachedMaterial = result.clone();
  12684. materialsForVariant[ keyB ] = cachedMaterial;
  12685. }
  12686. result = cachedMaterial;
  12687. }
  12688. result.visible = material.visible;
  12689. result.wireframe = material.wireframe;
  12690. if ( type === VSMShadowMap ) {
  12691. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12692. } else {
  12693. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12694. }
  12695. result.alphaMap = material.alphaMap;
  12696. result.alphaTest = material.alphaTest;
  12697. result.clipShadows = material.clipShadows;
  12698. result.clippingPlanes = material.clippingPlanes;
  12699. result.clipIntersection = material.clipIntersection;
  12700. result.displacementMap = material.displacementMap;
  12701. result.displacementScale = material.displacementScale;
  12702. result.displacementBias = material.displacementBias;
  12703. result.wireframeLinewidth = material.wireframeLinewidth;
  12704. result.linewidth = material.linewidth;
  12705. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12706. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12707. result.nearDistance = shadowCameraNear;
  12708. result.farDistance = shadowCameraFar;
  12709. }
  12710. return result;
  12711. }
  12712. function renderObject( object, camera, shadowCamera, light, type ) {
  12713. if ( object.visible === false ) return;
  12714. const visible = object.layers.test( camera.layers );
  12715. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12716. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12717. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12718. const geometry = _objects.update( object );
  12719. const material = object.material;
  12720. if ( Array.isArray( material ) ) {
  12721. const groups = geometry.groups;
  12722. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12723. const group = groups[ k ];
  12724. const groupMaterial = material[ group.materialIndex ];
  12725. if ( groupMaterial && groupMaterial.visible ) {
  12726. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12727. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12728. }
  12729. }
  12730. } else if ( material.visible ) {
  12731. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12732. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12733. }
  12734. }
  12735. }
  12736. const children = object.children;
  12737. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12738. renderObject( children[ i ], camera, shadowCamera, light, type );
  12739. }
  12740. }
  12741. }
  12742. function WebGLState( gl, extensions, capabilities ) {
  12743. const isWebGL2 = capabilities.isWebGL2;
  12744. function ColorBuffer() {
  12745. let locked = false;
  12746. const color = new Vector4();
  12747. let currentColorMask = null;
  12748. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12749. return {
  12750. setMask: function ( colorMask ) {
  12751. if ( currentColorMask !== colorMask && ! locked ) {
  12752. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12753. currentColorMask = colorMask;
  12754. }
  12755. },
  12756. setLocked: function ( lock ) {
  12757. locked = lock;
  12758. },
  12759. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12760. if ( premultipliedAlpha === true ) {
  12761. r *= a; g *= a; b *= a;
  12762. }
  12763. color.set( r, g, b, a );
  12764. if ( currentColorClear.equals( color ) === false ) {
  12765. gl.clearColor( r, g, b, a );
  12766. currentColorClear.copy( color );
  12767. }
  12768. },
  12769. reset: function () {
  12770. locked = false;
  12771. currentColorMask = null;
  12772. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12773. }
  12774. };
  12775. }
  12776. function DepthBuffer() {
  12777. let locked = false;
  12778. let currentDepthMask = null;
  12779. let currentDepthFunc = null;
  12780. let currentDepthClear = null;
  12781. return {
  12782. setTest: function ( depthTest ) {
  12783. if ( depthTest ) {
  12784. enable( 2929 );
  12785. } else {
  12786. disable( 2929 );
  12787. }
  12788. },
  12789. setMask: function ( depthMask ) {
  12790. if ( currentDepthMask !== depthMask && ! locked ) {
  12791. gl.depthMask( depthMask );
  12792. currentDepthMask = depthMask;
  12793. }
  12794. },
  12795. setFunc: function ( depthFunc ) {
  12796. if ( currentDepthFunc !== depthFunc ) {
  12797. if ( depthFunc ) {
  12798. switch ( depthFunc ) {
  12799. case NeverDepth:
  12800. gl.depthFunc( 512 );
  12801. break;
  12802. case AlwaysDepth:
  12803. gl.depthFunc( 519 );
  12804. break;
  12805. case LessDepth:
  12806. gl.depthFunc( 513 );
  12807. break;
  12808. case LessEqualDepth:
  12809. gl.depthFunc( 515 );
  12810. break;
  12811. case EqualDepth:
  12812. gl.depthFunc( 514 );
  12813. break;
  12814. case GreaterEqualDepth:
  12815. gl.depthFunc( 518 );
  12816. break;
  12817. case GreaterDepth:
  12818. gl.depthFunc( 516 );
  12819. break;
  12820. case NotEqualDepth:
  12821. gl.depthFunc( 517 );
  12822. break;
  12823. default:
  12824. gl.depthFunc( 515 );
  12825. }
  12826. } else {
  12827. gl.depthFunc( 515 );
  12828. }
  12829. currentDepthFunc = depthFunc;
  12830. }
  12831. },
  12832. setLocked: function ( lock ) {
  12833. locked = lock;
  12834. },
  12835. setClear: function ( depth ) {
  12836. if ( currentDepthClear !== depth ) {
  12837. gl.clearDepth( depth );
  12838. currentDepthClear = depth;
  12839. }
  12840. },
  12841. reset: function () {
  12842. locked = false;
  12843. currentDepthMask = null;
  12844. currentDepthFunc = null;
  12845. currentDepthClear = null;
  12846. }
  12847. };
  12848. }
  12849. function StencilBuffer() {
  12850. let locked = false;
  12851. let currentStencilMask = null;
  12852. let currentStencilFunc = null;
  12853. let currentStencilRef = null;
  12854. let currentStencilFuncMask = null;
  12855. let currentStencilFail = null;
  12856. let currentStencilZFail = null;
  12857. let currentStencilZPass = null;
  12858. let currentStencilClear = null;
  12859. return {
  12860. setTest: function ( stencilTest ) {
  12861. if ( ! locked ) {
  12862. if ( stencilTest ) {
  12863. enable( 2960 );
  12864. } else {
  12865. disable( 2960 );
  12866. }
  12867. }
  12868. },
  12869. setMask: function ( stencilMask ) {
  12870. if ( currentStencilMask !== stencilMask && ! locked ) {
  12871. gl.stencilMask( stencilMask );
  12872. currentStencilMask = stencilMask;
  12873. }
  12874. },
  12875. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12876. if ( currentStencilFunc !== stencilFunc ||
  12877. currentStencilRef !== stencilRef ||
  12878. currentStencilFuncMask !== stencilMask ) {
  12879. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12880. currentStencilFunc = stencilFunc;
  12881. currentStencilRef = stencilRef;
  12882. currentStencilFuncMask = stencilMask;
  12883. }
  12884. },
  12885. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12886. if ( currentStencilFail !== stencilFail ||
  12887. currentStencilZFail !== stencilZFail ||
  12888. currentStencilZPass !== stencilZPass ) {
  12889. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12890. currentStencilFail = stencilFail;
  12891. currentStencilZFail = stencilZFail;
  12892. currentStencilZPass = stencilZPass;
  12893. }
  12894. },
  12895. setLocked: function ( lock ) {
  12896. locked = lock;
  12897. },
  12898. setClear: function ( stencil ) {
  12899. if ( currentStencilClear !== stencil ) {
  12900. gl.clearStencil( stencil );
  12901. currentStencilClear = stencil;
  12902. }
  12903. },
  12904. reset: function () {
  12905. locked = false;
  12906. currentStencilMask = null;
  12907. currentStencilFunc = null;
  12908. currentStencilRef = null;
  12909. currentStencilFuncMask = null;
  12910. currentStencilFail = null;
  12911. currentStencilZFail = null;
  12912. currentStencilZPass = null;
  12913. currentStencilClear = null;
  12914. }
  12915. };
  12916. }
  12917. //
  12918. const colorBuffer = new ColorBuffer();
  12919. const depthBuffer = new DepthBuffer();
  12920. const stencilBuffer = new StencilBuffer();
  12921. let enabledCapabilities = {};
  12922. let currentBoundFramebuffers = {};
  12923. let currentDrawbuffers = new WeakMap();
  12924. let defaultDrawbuffers = [];
  12925. let currentProgram = null;
  12926. let currentBlendingEnabled = false;
  12927. let currentBlending = null;
  12928. let currentBlendEquation = null;
  12929. let currentBlendSrc = null;
  12930. let currentBlendDst = null;
  12931. let currentBlendEquationAlpha = null;
  12932. let currentBlendSrcAlpha = null;
  12933. let currentBlendDstAlpha = null;
  12934. let currentPremultipledAlpha = false;
  12935. let currentFlipSided = null;
  12936. let currentCullFace = null;
  12937. let currentLineWidth = null;
  12938. let currentPolygonOffsetFactor = null;
  12939. let currentPolygonOffsetUnits = null;
  12940. const maxTextures = gl.getParameter( 35661 );
  12941. let lineWidthAvailable = false;
  12942. let version = 0;
  12943. const glVersion = gl.getParameter( 7938 );
  12944. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12945. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12946. lineWidthAvailable = ( version >= 1.0 );
  12947. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12948. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12949. lineWidthAvailable = ( version >= 2.0 );
  12950. }
  12951. let currentTextureSlot = null;
  12952. let currentBoundTextures = {};
  12953. const scissorParam = gl.getParameter( 3088 );
  12954. const viewportParam = gl.getParameter( 2978 );
  12955. const currentScissor = new Vector4().fromArray( scissorParam );
  12956. const currentViewport = new Vector4().fromArray( viewportParam );
  12957. function createTexture( type, target, count ) {
  12958. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12959. const texture = gl.createTexture();
  12960. gl.bindTexture( type, texture );
  12961. gl.texParameteri( type, 10241, 9728 );
  12962. gl.texParameteri( type, 10240, 9728 );
  12963. for ( let i = 0; i < count; i ++ ) {
  12964. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12965. }
  12966. return texture;
  12967. }
  12968. const emptyTextures = {};
  12969. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12970. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12971. // init
  12972. colorBuffer.setClear( 0, 0, 0, 1 );
  12973. depthBuffer.setClear( 1 );
  12974. stencilBuffer.setClear( 0 );
  12975. enable( 2929 );
  12976. depthBuffer.setFunc( LessEqualDepth );
  12977. setFlipSided( false );
  12978. setCullFace( CullFaceBack );
  12979. enable( 2884 );
  12980. setBlending( NoBlending );
  12981. //
  12982. function enable( id ) {
  12983. if ( enabledCapabilities[ id ] !== true ) {
  12984. gl.enable( id );
  12985. enabledCapabilities[ id ] = true;
  12986. }
  12987. }
  12988. function disable( id ) {
  12989. if ( enabledCapabilities[ id ] !== false ) {
  12990. gl.disable( id );
  12991. enabledCapabilities[ id ] = false;
  12992. }
  12993. }
  12994. function bindFramebuffer( target, framebuffer ) {
  12995. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12996. gl.bindFramebuffer( target, framebuffer );
  12997. currentBoundFramebuffers[ target ] = framebuffer;
  12998. if ( isWebGL2 ) {
  12999. // 36009 is equivalent to 36160
  13000. if ( target === 36009 ) {
  13001. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13002. }
  13003. if ( target === 36160 ) {
  13004. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13005. }
  13006. }
  13007. return true;
  13008. }
  13009. return false;
  13010. }
  13011. function drawBuffers( renderTarget, framebuffer ) {
  13012. let drawBuffers = defaultDrawbuffers;
  13013. let needsUpdate = false;
  13014. if ( renderTarget ) {
  13015. drawBuffers = currentDrawbuffers.get( framebuffer );
  13016. if ( drawBuffers === undefined ) {
  13017. drawBuffers = [];
  13018. currentDrawbuffers.set( framebuffer, drawBuffers );
  13019. }
  13020. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13021. const textures = renderTarget.texture;
  13022. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13023. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13024. drawBuffers[ i ] = 36064 + i;
  13025. }
  13026. drawBuffers.length = textures.length;
  13027. needsUpdate = true;
  13028. }
  13029. } else {
  13030. if ( drawBuffers[ 0 ] !== 36064 ) {
  13031. drawBuffers[ 0 ] = 36064;
  13032. needsUpdate = true;
  13033. }
  13034. }
  13035. } else {
  13036. if ( drawBuffers[ 0 ] !== 1029 ) {
  13037. drawBuffers[ 0 ] = 1029;
  13038. needsUpdate = true;
  13039. }
  13040. }
  13041. if ( needsUpdate ) {
  13042. if ( capabilities.isWebGL2 ) {
  13043. gl.drawBuffers( drawBuffers );
  13044. } else {
  13045. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13046. }
  13047. }
  13048. }
  13049. function useProgram( program ) {
  13050. if ( currentProgram !== program ) {
  13051. gl.useProgram( program );
  13052. currentProgram = program;
  13053. return true;
  13054. }
  13055. return false;
  13056. }
  13057. const equationToGL = {
  13058. [ AddEquation ]: 32774,
  13059. [ SubtractEquation ]: 32778,
  13060. [ ReverseSubtractEquation ]: 32779
  13061. };
  13062. if ( isWebGL2 ) {
  13063. equationToGL[ MinEquation ] = 32775;
  13064. equationToGL[ MaxEquation ] = 32776;
  13065. } else {
  13066. const extension = extensions.get( 'EXT_blend_minmax' );
  13067. if ( extension !== null ) {
  13068. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13069. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13070. }
  13071. }
  13072. const factorToGL = {
  13073. [ ZeroFactor ]: 0,
  13074. [ OneFactor ]: 1,
  13075. [ SrcColorFactor ]: 768,
  13076. [ SrcAlphaFactor ]: 770,
  13077. [ SrcAlphaSaturateFactor ]: 776,
  13078. [ DstColorFactor ]: 774,
  13079. [ DstAlphaFactor ]: 772,
  13080. [ OneMinusSrcColorFactor ]: 769,
  13081. [ OneMinusSrcAlphaFactor ]: 771,
  13082. [ OneMinusDstColorFactor ]: 775,
  13083. [ OneMinusDstAlphaFactor ]: 773
  13084. };
  13085. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13086. if ( blending === NoBlending ) {
  13087. if ( currentBlendingEnabled === true ) {
  13088. disable( 3042 );
  13089. currentBlendingEnabled = false;
  13090. }
  13091. return;
  13092. }
  13093. if ( currentBlendingEnabled === false ) {
  13094. enable( 3042 );
  13095. currentBlendingEnabled = true;
  13096. }
  13097. if ( blending !== CustomBlending ) {
  13098. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13099. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13100. gl.blendEquation( 32774 );
  13101. currentBlendEquation = AddEquation;
  13102. currentBlendEquationAlpha = AddEquation;
  13103. }
  13104. if ( premultipliedAlpha ) {
  13105. switch ( blending ) {
  13106. case NormalBlending:
  13107. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13108. break;
  13109. case AdditiveBlending:
  13110. gl.blendFunc( 1, 1 );
  13111. break;
  13112. case SubtractiveBlending:
  13113. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13114. break;
  13115. case MultiplyBlending:
  13116. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13117. break;
  13118. default:
  13119. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13120. break;
  13121. }
  13122. } else {
  13123. switch ( blending ) {
  13124. case NormalBlending:
  13125. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13126. break;
  13127. case AdditiveBlending:
  13128. gl.blendFunc( 770, 1 );
  13129. break;
  13130. case SubtractiveBlending:
  13131. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13132. break;
  13133. case MultiplyBlending:
  13134. gl.blendFunc( 0, 768 );
  13135. break;
  13136. default:
  13137. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13138. break;
  13139. }
  13140. }
  13141. currentBlendSrc = null;
  13142. currentBlendDst = null;
  13143. currentBlendSrcAlpha = null;
  13144. currentBlendDstAlpha = null;
  13145. currentBlending = blending;
  13146. currentPremultipledAlpha = premultipliedAlpha;
  13147. }
  13148. return;
  13149. }
  13150. // custom blending
  13151. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13152. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13153. blendDstAlpha = blendDstAlpha || blendDst;
  13154. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13155. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13156. currentBlendEquation = blendEquation;
  13157. currentBlendEquationAlpha = blendEquationAlpha;
  13158. }
  13159. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13160. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13161. currentBlendSrc = blendSrc;
  13162. currentBlendDst = blendDst;
  13163. currentBlendSrcAlpha = blendSrcAlpha;
  13164. currentBlendDstAlpha = blendDstAlpha;
  13165. }
  13166. currentBlending = blending;
  13167. currentPremultipledAlpha = null;
  13168. }
  13169. function setMaterial( material, frontFaceCW ) {
  13170. material.side === DoubleSide
  13171. ? disable( 2884 )
  13172. : enable( 2884 );
  13173. let flipSided = ( material.side === BackSide );
  13174. if ( frontFaceCW ) flipSided = ! flipSided;
  13175. setFlipSided( flipSided );
  13176. ( material.blending === NormalBlending && material.transparent === false )
  13177. ? setBlending( NoBlending )
  13178. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13179. depthBuffer.setFunc( material.depthFunc );
  13180. depthBuffer.setTest( material.depthTest );
  13181. depthBuffer.setMask( material.depthWrite );
  13182. colorBuffer.setMask( material.colorWrite );
  13183. const stencilWrite = material.stencilWrite;
  13184. stencilBuffer.setTest( stencilWrite );
  13185. if ( stencilWrite ) {
  13186. stencilBuffer.setMask( material.stencilWriteMask );
  13187. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13188. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13189. }
  13190. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13191. material.alphaToCoverage === true
  13192. ? enable( 32926 )
  13193. : disable( 32926 );
  13194. }
  13195. //
  13196. function setFlipSided( flipSided ) {
  13197. if ( currentFlipSided !== flipSided ) {
  13198. if ( flipSided ) {
  13199. gl.frontFace( 2304 );
  13200. } else {
  13201. gl.frontFace( 2305 );
  13202. }
  13203. currentFlipSided = flipSided;
  13204. }
  13205. }
  13206. function setCullFace( cullFace ) {
  13207. if ( cullFace !== CullFaceNone ) {
  13208. enable( 2884 );
  13209. if ( cullFace !== currentCullFace ) {
  13210. if ( cullFace === CullFaceBack ) {
  13211. gl.cullFace( 1029 );
  13212. } else if ( cullFace === CullFaceFront ) {
  13213. gl.cullFace( 1028 );
  13214. } else {
  13215. gl.cullFace( 1032 );
  13216. }
  13217. }
  13218. } else {
  13219. disable( 2884 );
  13220. }
  13221. currentCullFace = cullFace;
  13222. }
  13223. function setLineWidth( width ) {
  13224. if ( width !== currentLineWidth ) {
  13225. if ( lineWidthAvailable ) gl.lineWidth( width );
  13226. currentLineWidth = width;
  13227. }
  13228. }
  13229. function setPolygonOffset( polygonOffset, factor, units ) {
  13230. if ( polygonOffset ) {
  13231. enable( 32823 );
  13232. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13233. gl.polygonOffset( factor, units );
  13234. currentPolygonOffsetFactor = factor;
  13235. currentPolygonOffsetUnits = units;
  13236. }
  13237. } else {
  13238. disable( 32823 );
  13239. }
  13240. }
  13241. function setScissorTest( scissorTest ) {
  13242. if ( scissorTest ) {
  13243. enable( 3089 );
  13244. } else {
  13245. disable( 3089 );
  13246. }
  13247. }
  13248. // texture
  13249. function activeTexture( webglSlot ) {
  13250. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13251. if ( currentTextureSlot !== webglSlot ) {
  13252. gl.activeTexture( webglSlot );
  13253. currentTextureSlot = webglSlot;
  13254. }
  13255. }
  13256. function bindTexture( webglType, webglTexture ) {
  13257. if ( currentTextureSlot === null ) {
  13258. activeTexture();
  13259. }
  13260. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  13261. if ( boundTexture === undefined ) {
  13262. boundTexture = { type: undefined, texture: undefined };
  13263. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  13264. }
  13265. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13266. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13267. boundTexture.type = webglType;
  13268. boundTexture.texture = webglTexture;
  13269. }
  13270. }
  13271. function unbindTexture() {
  13272. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13273. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13274. gl.bindTexture( boundTexture.type, null );
  13275. boundTexture.type = undefined;
  13276. boundTexture.texture = undefined;
  13277. }
  13278. }
  13279. function compressedTexImage2D() {
  13280. try {
  13281. gl.compressedTexImage2D.apply( gl, arguments );
  13282. } catch ( error ) {
  13283. console.error( 'THREE.WebGLState:', error );
  13284. }
  13285. }
  13286. function texSubImage2D() {
  13287. try {
  13288. gl.texSubImage2D.apply( gl, arguments );
  13289. } catch ( error ) {
  13290. console.error( 'THREE.WebGLState:', error );
  13291. }
  13292. }
  13293. function texSubImage3D() {
  13294. try {
  13295. gl.texSubImage3D.apply( gl, arguments );
  13296. } catch ( error ) {
  13297. console.error( 'THREE.WebGLState:', error );
  13298. }
  13299. }
  13300. function compressedTexSubImage2D() {
  13301. try {
  13302. gl.compressedTexSubImage2D.apply( gl, arguments );
  13303. } catch ( error ) {
  13304. console.error( 'THREE.WebGLState:', error );
  13305. }
  13306. }
  13307. function texStorage2D() {
  13308. try {
  13309. gl.texStorage2D.apply( gl, arguments );
  13310. } catch ( error ) {
  13311. console.error( 'THREE.WebGLState:', error );
  13312. }
  13313. }
  13314. function texStorage3D() {
  13315. try {
  13316. gl.texStorage3D.apply( gl, arguments );
  13317. } catch ( error ) {
  13318. console.error( 'THREE.WebGLState:', error );
  13319. }
  13320. }
  13321. function texImage2D() {
  13322. try {
  13323. gl.texImage2D.apply( gl, arguments );
  13324. } catch ( error ) {
  13325. console.error( 'THREE.WebGLState:', error );
  13326. }
  13327. }
  13328. function texImage3D() {
  13329. try {
  13330. gl.texImage3D.apply( gl, arguments );
  13331. } catch ( error ) {
  13332. console.error( 'THREE.WebGLState:', error );
  13333. }
  13334. }
  13335. //
  13336. function scissor( scissor ) {
  13337. if ( currentScissor.equals( scissor ) === false ) {
  13338. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13339. currentScissor.copy( scissor );
  13340. }
  13341. }
  13342. function viewport( viewport ) {
  13343. if ( currentViewport.equals( viewport ) === false ) {
  13344. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13345. currentViewport.copy( viewport );
  13346. }
  13347. }
  13348. //
  13349. function reset() {
  13350. // reset state
  13351. gl.disable( 3042 );
  13352. gl.disable( 2884 );
  13353. gl.disable( 2929 );
  13354. gl.disable( 32823 );
  13355. gl.disable( 3089 );
  13356. gl.disable( 2960 );
  13357. gl.disable( 32926 );
  13358. gl.blendEquation( 32774 );
  13359. gl.blendFunc( 1, 0 );
  13360. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13361. gl.colorMask( true, true, true, true );
  13362. gl.clearColor( 0, 0, 0, 0 );
  13363. gl.depthMask( true );
  13364. gl.depthFunc( 513 );
  13365. gl.clearDepth( 1 );
  13366. gl.stencilMask( 0xffffffff );
  13367. gl.stencilFunc( 519, 0, 0xffffffff );
  13368. gl.stencilOp( 7680, 7680, 7680 );
  13369. gl.clearStencil( 0 );
  13370. gl.cullFace( 1029 );
  13371. gl.frontFace( 2305 );
  13372. gl.polygonOffset( 0, 0 );
  13373. gl.activeTexture( 33984 );
  13374. gl.bindFramebuffer( 36160, null );
  13375. if ( isWebGL2 === true ) {
  13376. gl.bindFramebuffer( 36009, null );
  13377. gl.bindFramebuffer( 36008, null );
  13378. }
  13379. gl.useProgram( null );
  13380. gl.lineWidth( 1 );
  13381. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13382. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13383. // reset internals
  13384. enabledCapabilities = {};
  13385. currentTextureSlot = null;
  13386. currentBoundTextures = {};
  13387. currentBoundFramebuffers = {};
  13388. currentDrawbuffers = new WeakMap();
  13389. defaultDrawbuffers = [];
  13390. currentProgram = null;
  13391. currentBlendingEnabled = false;
  13392. currentBlending = null;
  13393. currentBlendEquation = null;
  13394. currentBlendSrc = null;
  13395. currentBlendDst = null;
  13396. currentBlendEquationAlpha = null;
  13397. currentBlendSrcAlpha = null;
  13398. currentBlendDstAlpha = null;
  13399. currentPremultipledAlpha = false;
  13400. currentFlipSided = null;
  13401. currentCullFace = null;
  13402. currentLineWidth = null;
  13403. currentPolygonOffsetFactor = null;
  13404. currentPolygonOffsetUnits = null;
  13405. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13406. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13407. colorBuffer.reset();
  13408. depthBuffer.reset();
  13409. stencilBuffer.reset();
  13410. }
  13411. return {
  13412. buffers: {
  13413. color: colorBuffer,
  13414. depth: depthBuffer,
  13415. stencil: stencilBuffer
  13416. },
  13417. enable: enable,
  13418. disable: disable,
  13419. bindFramebuffer: bindFramebuffer,
  13420. drawBuffers: drawBuffers,
  13421. useProgram: useProgram,
  13422. setBlending: setBlending,
  13423. setMaterial: setMaterial,
  13424. setFlipSided: setFlipSided,
  13425. setCullFace: setCullFace,
  13426. setLineWidth: setLineWidth,
  13427. setPolygonOffset: setPolygonOffset,
  13428. setScissorTest: setScissorTest,
  13429. activeTexture: activeTexture,
  13430. bindTexture: bindTexture,
  13431. unbindTexture: unbindTexture,
  13432. compressedTexImage2D: compressedTexImage2D,
  13433. texImage2D: texImage2D,
  13434. texImage3D: texImage3D,
  13435. texStorage2D: texStorage2D,
  13436. texStorage3D: texStorage3D,
  13437. texSubImage2D: texSubImage2D,
  13438. texSubImage3D: texSubImage3D,
  13439. compressedTexSubImage2D: compressedTexSubImage2D,
  13440. scissor: scissor,
  13441. viewport: viewport,
  13442. reset: reset
  13443. };
  13444. }
  13445. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13446. const isWebGL2 = capabilities.isWebGL2;
  13447. const maxTextures = capabilities.maxTextures;
  13448. const maxCubemapSize = capabilities.maxCubemapSize;
  13449. const maxTextureSize = capabilities.maxTextureSize;
  13450. const maxSamples = capabilities.maxSamples;
  13451. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13452. const supportsInvalidateFramebuffer = /OculusBrowser/g.test( navigator.userAgent );
  13453. const _videoTextures = new WeakMap();
  13454. let _canvas;
  13455. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13456. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13457. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13458. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13459. let useOffscreenCanvas = false;
  13460. try {
  13461. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13462. // eslint-disable-next-line compat/compat
  13463. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13464. } catch ( err ) {
  13465. // Ignore any errors
  13466. }
  13467. function createCanvas( width, height ) {
  13468. // Use OffscreenCanvas when available. Specially needed in web workers
  13469. return useOffscreenCanvas ?
  13470. // eslint-disable-next-line compat/compat
  13471. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13472. }
  13473. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13474. let scale = 1;
  13475. // handle case if texture exceeds max size
  13476. if ( image.width > maxSize || image.height > maxSize ) {
  13477. scale = maxSize / Math.max( image.width, image.height );
  13478. }
  13479. // only perform resize if necessary
  13480. if ( scale < 1 || needsPowerOfTwo === true ) {
  13481. // only perform resize for certain image types
  13482. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13483. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13484. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13485. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13486. const width = floor( scale * image.width );
  13487. const height = floor( scale * image.height );
  13488. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13489. // cube textures can't reuse the same canvas
  13490. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13491. canvas.width = width;
  13492. canvas.height = height;
  13493. const context = canvas.getContext( '2d' );
  13494. context.drawImage( image, 0, 0, width, height );
  13495. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13496. return canvas;
  13497. } else {
  13498. if ( 'data' in image ) {
  13499. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13500. }
  13501. return image;
  13502. }
  13503. }
  13504. return image;
  13505. }
  13506. function isPowerOfTwo$1( image ) {
  13507. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13508. }
  13509. function textureNeedsPowerOfTwo( texture ) {
  13510. if ( isWebGL2 ) return false;
  13511. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13512. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13513. }
  13514. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13515. return texture.generateMipmaps && supportsMips &&
  13516. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13517. }
  13518. function generateMipmap( target ) {
  13519. _gl.generateMipmap( target );
  13520. }
  13521. function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) {
  13522. if ( isWebGL2 === false ) return glFormat;
  13523. if ( internalFormatName !== null ) {
  13524. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13525. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13526. }
  13527. let internalFormat = glFormat;
  13528. if ( glFormat === 6403 ) {
  13529. if ( glType === 5126 ) internalFormat = 33326;
  13530. if ( glType === 5131 ) internalFormat = 33325;
  13531. if ( glType === 5121 ) internalFormat = 33321;
  13532. }
  13533. if ( glFormat === 33319 ) {
  13534. if ( glType === 5126 ) internalFormat = 33328;
  13535. if ( glType === 5131 ) internalFormat = 33327;
  13536. if ( glType === 5121 ) internalFormat = 33323;
  13537. }
  13538. if ( glFormat === 6408 ) {
  13539. if ( glType === 5126 ) internalFormat = 34836;
  13540. if ( glType === 5131 ) internalFormat = 34842;
  13541. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856;
  13542. if ( glType === 32819 ) internalFormat = 32854;
  13543. if ( glType === 32820 ) internalFormat = 32855;
  13544. }
  13545. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13546. internalFormat === 33327 || internalFormat === 33328 ||
  13547. internalFormat === 34842 || internalFormat === 34836 ) {
  13548. extensions.get( 'EXT_color_buffer_float' );
  13549. }
  13550. return internalFormat;
  13551. }
  13552. function getMipLevels( texture, image, supportsMips ) {
  13553. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13554. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13555. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13556. // user-defined mipmaps
  13557. return texture.mipmaps.length;
  13558. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13559. return image.mipmaps.length;
  13560. } else {
  13561. // texture without mipmaps (only base level)
  13562. return 1;
  13563. }
  13564. }
  13565. // Fallback filters for non-power-of-2 textures
  13566. function filterFallback( f ) {
  13567. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13568. return 9728;
  13569. }
  13570. return 9729;
  13571. }
  13572. //
  13573. function onTextureDispose( event ) {
  13574. const texture = event.target;
  13575. texture.removeEventListener( 'dispose', onTextureDispose );
  13576. deallocateTexture( texture );
  13577. if ( texture.isVideoTexture ) {
  13578. _videoTextures.delete( texture );
  13579. }
  13580. }
  13581. function onRenderTargetDispose( event ) {
  13582. const renderTarget = event.target;
  13583. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13584. deallocateRenderTarget( renderTarget );
  13585. }
  13586. //
  13587. function deallocateTexture( texture ) {
  13588. const textureProperties = properties.get( texture );
  13589. if ( textureProperties.__webglInit === undefined ) return;
  13590. // check if it's necessary to remove the WebGLTexture object
  13591. const source = texture.source;
  13592. const webglTextures = _sources.get( source );
  13593. if ( webglTextures ) {
  13594. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13595. webglTexture.usedTimes --;
  13596. // the WebGLTexture object is not used anymore, remove it
  13597. if ( webglTexture.usedTimes === 0 ) {
  13598. deleteTexture( texture );
  13599. }
  13600. // remove the weak map entry if no WebGLTexture uses the source anymore
  13601. if ( Object.keys( webglTextures ).length === 0 ) {
  13602. _sources.delete( source );
  13603. }
  13604. }
  13605. properties.remove( texture );
  13606. }
  13607. function deleteTexture( texture ) {
  13608. const textureProperties = properties.get( texture );
  13609. _gl.deleteTexture( textureProperties.__webglTexture );
  13610. const source = texture.source;
  13611. const webglTextures = _sources.get( source );
  13612. delete webglTextures[ textureProperties.__cacheKey ];
  13613. info.memory.textures --;
  13614. }
  13615. function deallocateRenderTarget( renderTarget ) {
  13616. const texture = renderTarget.texture;
  13617. const renderTargetProperties = properties.get( renderTarget );
  13618. const textureProperties = properties.get( texture );
  13619. if ( textureProperties.__webglTexture !== undefined ) {
  13620. _gl.deleteTexture( textureProperties.__webglTexture );
  13621. info.memory.textures --;
  13622. }
  13623. if ( renderTarget.depthTexture ) {
  13624. renderTarget.depthTexture.dispose();
  13625. }
  13626. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13627. for ( let i = 0; i < 6; i ++ ) {
  13628. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13629. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13630. }
  13631. } else {
  13632. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13633. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13634. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13635. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13636. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13637. }
  13638. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13639. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13640. const attachmentProperties = properties.get( texture[ i ] );
  13641. if ( attachmentProperties.__webglTexture ) {
  13642. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13643. info.memory.textures --;
  13644. }
  13645. properties.remove( texture[ i ] );
  13646. }
  13647. }
  13648. properties.remove( texture );
  13649. properties.remove( renderTarget );
  13650. }
  13651. //
  13652. let textureUnits = 0;
  13653. function resetTextureUnits() {
  13654. textureUnits = 0;
  13655. }
  13656. function allocateTextureUnit() {
  13657. const textureUnit = textureUnits;
  13658. if ( textureUnit >= maxTextures ) {
  13659. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13660. }
  13661. textureUnits += 1;
  13662. return textureUnit;
  13663. }
  13664. function getTextureCacheKey( texture ) {
  13665. const array = [];
  13666. array.push( texture.wrapS );
  13667. array.push( texture.wrapT );
  13668. array.push( texture.magFilter );
  13669. array.push( texture.minFilter );
  13670. array.push( texture.anisotropy );
  13671. array.push( texture.internalFormat );
  13672. array.push( texture.format );
  13673. array.push( texture.type );
  13674. array.push( texture.generateMipmaps );
  13675. array.push( texture.premultiplyAlpha );
  13676. array.push( texture.flipY );
  13677. array.push( texture.unpackAlignment );
  13678. array.push( texture.encoding );
  13679. return array.join();
  13680. }
  13681. //
  13682. function setTexture2D( texture, slot ) {
  13683. const textureProperties = properties.get( texture );
  13684. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13685. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13686. const image = texture.image;
  13687. if ( image === null ) {
  13688. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13689. } else if ( image.complete === false ) {
  13690. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13691. } else {
  13692. uploadTexture( textureProperties, texture, slot );
  13693. return;
  13694. }
  13695. }
  13696. state.activeTexture( 33984 + slot );
  13697. state.bindTexture( 3553, textureProperties.__webglTexture );
  13698. }
  13699. function setTexture2DArray( texture, slot ) {
  13700. const textureProperties = properties.get( texture );
  13701. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13702. uploadTexture( textureProperties, texture, slot );
  13703. return;
  13704. }
  13705. state.activeTexture( 33984 + slot );
  13706. state.bindTexture( 35866, textureProperties.__webglTexture );
  13707. }
  13708. function setTexture3D( texture, slot ) {
  13709. const textureProperties = properties.get( texture );
  13710. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13711. uploadTexture( textureProperties, texture, slot );
  13712. return;
  13713. }
  13714. state.activeTexture( 33984 + slot );
  13715. state.bindTexture( 32879, textureProperties.__webglTexture );
  13716. }
  13717. function setTextureCube( texture, slot ) {
  13718. const textureProperties = properties.get( texture );
  13719. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13720. uploadCubeTexture( textureProperties, texture, slot );
  13721. return;
  13722. }
  13723. state.activeTexture( 33984 + slot );
  13724. state.bindTexture( 34067, textureProperties.__webglTexture );
  13725. }
  13726. const wrappingToGL = {
  13727. [ RepeatWrapping ]: 10497,
  13728. [ ClampToEdgeWrapping ]: 33071,
  13729. [ MirroredRepeatWrapping ]: 33648
  13730. };
  13731. const filterToGL = {
  13732. [ NearestFilter ]: 9728,
  13733. [ NearestMipmapNearestFilter ]: 9984,
  13734. [ NearestMipmapLinearFilter ]: 9986,
  13735. [ LinearFilter ]: 9729,
  13736. [ LinearMipmapNearestFilter ]: 9985,
  13737. [ LinearMipmapLinearFilter ]: 9987
  13738. };
  13739. function setTextureParameters( textureType, texture, supportsMips ) {
  13740. if ( supportsMips ) {
  13741. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13742. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13743. if ( textureType === 32879 || textureType === 35866 ) {
  13744. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13745. }
  13746. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13747. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13748. } else {
  13749. _gl.texParameteri( textureType, 10242, 33071 );
  13750. _gl.texParameteri( textureType, 10243, 33071 );
  13751. if ( textureType === 32879 || textureType === 35866 ) {
  13752. _gl.texParameteri( textureType, 32882, 33071 );
  13753. }
  13754. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13755. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13756. }
  13757. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13758. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13759. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13760. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13761. }
  13762. }
  13763. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13764. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13765. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13766. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13767. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13768. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13769. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13770. }
  13771. }
  13772. }
  13773. function initTexture( textureProperties, texture ) {
  13774. let forceUpload = false;
  13775. if ( textureProperties.__webglInit === undefined ) {
  13776. textureProperties.__webglInit = true;
  13777. texture.addEventListener( 'dispose', onTextureDispose );
  13778. }
  13779. // create Source <-> WebGLTextures mapping if necessary
  13780. const source = texture.source;
  13781. let webglTextures = _sources.get( source );
  13782. if ( webglTextures === undefined ) {
  13783. webglTextures = {};
  13784. _sources.set( source, webglTextures );
  13785. }
  13786. // check if there is already a WebGLTexture object for the given texture parameters
  13787. const textureCacheKey = getTextureCacheKey( texture );
  13788. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13789. // if not, create a new instance of WebGLTexture
  13790. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13791. // create new entry
  13792. webglTextures[ textureCacheKey ] = {
  13793. texture: _gl.createTexture(),
  13794. usedTimes: 0
  13795. };
  13796. info.memory.textures ++;
  13797. // when a new instance of WebGLTexture was created, a texture upload is required
  13798. // even if the image contents are identical
  13799. forceUpload = true;
  13800. }
  13801. webglTextures[ textureCacheKey ].usedTimes ++;
  13802. // every time the texture cache key changes, it's necessary to check if an instance of
  13803. // WebGLTexture can be deleted in order to avoid a memory leak.
  13804. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13805. if ( webglTexture !== undefined ) {
  13806. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13807. if ( webglTexture.usedTimes === 0 ) {
  13808. deleteTexture( texture );
  13809. }
  13810. }
  13811. // store references to cache key and WebGLTexture object
  13812. textureProperties.__cacheKey = textureCacheKey;
  13813. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13814. }
  13815. return forceUpload;
  13816. }
  13817. function uploadTexture( textureProperties, texture, slot ) {
  13818. let textureType = 3553;
  13819. if ( texture.isDataArrayTexture ) textureType = 35866;
  13820. if ( texture.isData3DTexture ) textureType = 32879;
  13821. const forceUpload = initTexture( textureProperties, texture );
  13822. const source = texture.source;
  13823. state.activeTexture( 33984 + slot );
  13824. state.bindTexture( textureType, textureProperties.__webglTexture );
  13825. if ( source.version !== source.__currentVersion || forceUpload === true ) {
  13826. _gl.pixelStorei( 37440, texture.flipY );
  13827. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13828. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13829. _gl.pixelStorei( 37443, 0 );
  13830. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13831. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13832. image = verifyColorSpace( texture, image );
  13833. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13834. glFormat = utils.convert( texture.format, texture.encoding );
  13835. let glType = utils.convert( texture.type ),
  13836. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13837. setTextureParameters( textureType, texture, supportsMips );
  13838. let mipmap;
  13839. const mipmaps = texture.mipmaps;
  13840. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13841. const allocateMemory = ( textureProperties.__version === undefined ) || ( forceUpload === true );
  13842. const levels = getMipLevels( texture, image, supportsMips );
  13843. if ( texture.isDepthTexture ) {
  13844. // populate depth texture with dummy data
  13845. glInternalFormat = 6402;
  13846. if ( isWebGL2 ) {
  13847. if ( texture.type === FloatType ) {
  13848. glInternalFormat = 36012;
  13849. } else if ( texture.type === UnsignedIntType ) {
  13850. glInternalFormat = 33190;
  13851. } else if ( texture.type === UnsignedInt248Type ) {
  13852. glInternalFormat = 35056;
  13853. } else {
  13854. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13855. }
  13856. } else {
  13857. if ( texture.type === FloatType ) {
  13858. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13859. }
  13860. }
  13861. // validation checks for WebGL 1
  13862. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13863. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13864. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13865. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13866. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13867. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13868. texture.type = UnsignedShortType;
  13869. glType = utils.convert( texture.type );
  13870. }
  13871. }
  13872. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13873. // Depth stencil textures need the DEPTH_STENCIL internal format
  13874. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13875. glInternalFormat = 34041;
  13876. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13877. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13878. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13879. if ( texture.type !== UnsignedInt248Type ) {
  13880. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13881. texture.type = UnsignedInt248Type;
  13882. glType = utils.convert( texture.type );
  13883. }
  13884. }
  13885. //
  13886. if ( allocateMemory ) {
  13887. if ( useTexStorage ) {
  13888. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  13889. } else {
  13890. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13891. }
  13892. }
  13893. } else if ( texture.isDataTexture ) {
  13894. // use manually created mipmaps if available
  13895. // if there are no manual mipmaps
  13896. // set 0 level mipmap and then use GL to generate other mipmap levels
  13897. if ( mipmaps.length > 0 && supportsMips ) {
  13898. if ( useTexStorage && allocateMemory ) {
  13899. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13900. }
  13901. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13902. mipmap = mipmaps[ i ];
  13903. if ( useTexStorage ) {
  13904. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13905. } else {
  13906. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13907. }
  13908. }
  13909. texture.generateMipmaps = false;
  13910. } else {
  13911. if ( useTexStorage ) {
  13912. if ( allocateMemory ) {
  13913. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13914. }
  13915. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  13916. } else {
  13917. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13918. }
  13919. }
  13920. } else if ( texture.isCompressedTexture ) {
  13921. if ( useTexStorage && allocateMemory ) {
  13922. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13923. }
  13924. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13925. mipmap = mipmaps[ i ];
  13926. if ( texture.format !== RGBAFormat ) {
  13927. if ( glFormat !== null ) {
  13928. if ( useTexStorage ) {
  13929. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  13930. } else {
  13931. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13932. }
  13933. } else {
  13934. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13935. }
  13936. } else {
  13937. if ( useTexStorage ) {
  13938. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13939. } else {
  13940. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13941. }
  13942. }
  13943. }
  13944. } else if ( texture.isDataArrayTexture ) {
  13945. if ( useTexStorage ) {
  13946. if ( allocateMemory ) {
  13947. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  13948. }
  13949. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13950. } else {
  13951. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13952. }
  13953. } else if ( texture.isData3DTexture ) {
  13954. if ( useTexStorage ) {
  13955. if ( allocateMemory ) {
  13956. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  13957. }
  13958. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13959. } else {
  13960. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13961. }
  13962. } else if ( texture.isFramebufferTexture ) {
  13963. if ( allocateMemory ) {
  13964. if ( useTexStorage ) {
  13965. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13966. } else {
  13967. let width = image.width, height = image.height;
  13968. for ( let i = 0; i < levels; i ++ ) {
  13969. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  13970. width >>= 1;
  13971. height >>= 1;
  13972. }
  13973. }
  13974. }
  13975. } else {
  13976. // regular Texture (image, video, canvas)
  13977. // use manually created mipmaps if available
  13978. // if there are no manual mipmaps
  13979. // set 0 level mipmap and then use GL to generate other mipmap levels
  13980. if ( mipmaps.length > 0 && supportsMips ) {
  13981. if ( useTexStorage && allocateMemory ) {
  13982. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13983. }
  13984. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13985. mipmap = mipmaps[ i ];
  13986. if ( useTexStorage ) {
  13987. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  13988. } else {
  13989. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13990. }
  13991. }
  13992. texture.generateMipmaps = false;
  13993. } else {
  13994. if ( useTexStorage ) {
  13995. if ( allocateMemory ) {
  13996. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13997. }
  13998. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  13999. } else {
  14000. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14001. }
  14002. }
  14003. }
  14004. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14005. generateMipmap( textureType );
  14006. }
  14007. source.__currentVersion = source.version;
  14008. if ( texture.onUpdate ) texture.onUpdate( texture );
  14009. }
  14010. textureProperties.__version = texture.version;
  14011. }
  14012. function uploadCubeTexture( textureProperties, texture, slot ) {
  14013. if ( texture.image.length !== 6 ) return;
  14014. const forceUpload = initTexture( textureProperties, texture );
  14015. const source = texture.source;
  14016. state.activeTexture( 33984 + slot );
  14017. state.bindTexture( 34067, textureProperties.__webglTexture );
  14018. if ( source.version !== source.__currentVersion || forceUpload === true ) {
  14019. _gl.pixelStorei( 37440, texture.flipY );
  14020. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14021. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14022. _gl.pixelStorei( 37443, 0 );
  14023. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14024. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14025. const cubeImage = [];
  14026. for ( let i = 0; i < 6; i ++ ) {
  14027. if ( ! isCompressed && ! isDataTexture ) {
  14028. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14029. } else {
  14030. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14031. }
  14032. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14033. }
  14034. const image = cubeImage[ 0 ],
  14035. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14036. glFormat = utils.convert( texture.format, texture.encoding ),
  14037. glType = utils.convert( texture.type ),
  14038. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14039. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14040. const allocateMemory = ( textureProperties.__version === undefined );
  14041. let levels = getMipLevels( texture, image, supportsMips );
  14042. setTextureParameters( 34067, texture, supportsMips );
  14043. let mipmaps;
  14044. if ( isCompressed ) {
  14045. if ( useTexStorage && allocateMemory ) {
  14046. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14047. }
  14048. for ( let i = 0; i < 6; i ++ ) {
  14049. mipmaps = cubeImage[ i ].mipmaps;
  14050. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14051. const mipmap = mipmaps[ j ];
  14052. if ( texture.format !== RGBAFormat ) {
  14053. if ( glFormat !== null ) {
  14054. if ( useTexStorage ) {
  14055. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14056. } else {
  14057. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14058. }
  14059. } else {
  14060. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14061. }
  14062. } else {
  14063. if ( useTexStorage ) {
  14064. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14065. } else {
  14066. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14067. }
  14068. }
  14069. }
  14070. }
  14071. } else {
  14072. mipmaps = texture.mipmaps;
  14073. if ( useTexStorage && allocateMemory ) {
  14074. // TODO: Uniformly handle mipmap definitions
  14075. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14076. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14077. if ( mipmaps.length > 0 ) levels ++;
  14078. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14079. }
  14080. for ( let i = 0; i < 6; i ++ ) {
  14081. if ( isDataTexture ) {
  14082. if ( useTexStorage ) {
  14083. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14084. } else {
  14085. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14086. }
  14087. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14088. const mipmap = mipmaps[ j ];
  14089. const mipmapImage = mipmap.image[ i ].image;
  14090. if ( useTexStorage ) {
  14091. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14092. } else {
  14093. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14094. }
  14095. }
  14096. } else {
  14097. if ( useTexStorage ) {
  14098. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14099. } else {
  14100. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14101. }
  14102. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14103. const mipmap = mipmaps[ j ];
  14104. if ( useTexStorage ) {
  14105. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14106. } else {
  14107. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14108. }
  14109. }
  14110. }
  14111. }
  14112. }
  14113. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14114. // We assume images for cube map have the same size.
  14115. generateMipmap( 34067 );
  14116. }
  14117. source.__currentVersion = source.version;
  14118. if ( texture.onUpdate ) texture.onUpdate( texture );
  14119. }
  14120. textureProperties.__version = texture.version;
  14121. }
  14122. // Render targets
  14123. // Setup storage for target texture and bind it to correct framebuffer
  14124. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14125. const glFormat = utils.convert( texture.format, texture.encoding );
  14126. const glType = utils.convert( texture.type );
  14127. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14128. const renderTargetProperties = properties.get( renderTarget );
  14129. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14130. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14131. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14132. } else {
  14133. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14134. }
  14135. }
  14136. state.bindFramebuffer( 36160, framebuffer );
  14137. if ( useMultisampledRTT( renderTarget ) ) {
  14138. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14139. } else {
  14140. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14141. }
  14142. state.bindFramebuffer( 36160, null );
  14143. }
  14144. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14145. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14146. _gl.bindRenderbuffer( 36161, renderbuffer );
  14147. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14148. let glInternalFormat = 33189;
  14149. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14150. const depthTexture = renderTarget.depthTexture;
  14151. if ( depthTexture && depthTexture.isDepthTexture ) {
  14152. if ( depthTexture.type === FloatType ) {
  14153. glInternalFormat = 36012;
  14154. } else if ( depthTexture.type === UnsignedIntType ) {
  14155. glInternalFormat = 33190;
  14156. }
  14157. }
  14158. const samples = getRenderTargetSamples( renderTarget );
  14159. if ( useMultisampledRTT( renderTarget ) ) {
  14160. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14161. } else {
  14162. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14163. }
  14164. } else {
  14165. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14166. }
  14167. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14168. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14169. const samples = getRenderTargetSamples( renderTarget );
  14170. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14171. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14172. } else if ( useMultisampledRTT( renderTarget ) ) {
  14173. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14174. } else {
  14175. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14176. }
  14177. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14178. } else {
  14179. // Use the first texture for MRT so far
  14180. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  14181. const glFormat = utils.convert( texture.format, texture.encoding );
  14182. const glType = utils.convert( texture.type );
  14183. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14184. const samples = getRenderTargetSamples( renderTarget );
  14185. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14186. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14187. } else if ( useMultisampledRTT( renderTarget ) ) {
  14188. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14189. } else {
  14190. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14191. }
  14192. }
  14193. _gl.bindRenderbuffer( 36161, null );
  14194. }
  14195. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14196. function setupDepthTexture( framebuffer, renderTarget ) {
  14197. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14198. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14199. state.bindFramebuffer( 36160, framebuffer );
  14200. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14201. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14202. }
  14203. // upload an empty depth texture with framebuffer size
  14204. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14205. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14206. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14207. renderTarget.depthTexture.image.width = renderTarget.width;
  14208. renderTarget.depthTexture.image.height = renderTarget.height;
  14209. renderTarget.depthTexture.needsUpdate = true;
  14210. }
  14211. setTexture2D( renderTarget.depthTexture, 0 );
  14212. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14213. const samples = getRenderTargetSamples( renderTarget );
  14214. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14215. if ( useMultisampledRTT( renderTarget ) ) {
  14216. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14217. } else {
  14218. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14219. }
  14220. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14221. if ( useMultisampledRTT( renderTarget ) ) {
  14222. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14223. } else {
  14224. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14225. }
  14226. } else {
  14227. throw new Error( 'Unknown depthTexture format' );
  14228. }
  14229. }
  14230. // Setup GL resources for a non-texture depth buffer
  14231. function setupDepthRenderbuffer( renderTarget ) {
  14232. const renderTargetProperties = properties.get( renderTarget );
  14233. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14234. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14235. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14236. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14237. } else {
  14238. if ( isCube ) {
  14239. renderTargetProperties.__webglDepthbuffer = [];
  14240. for ( let i = 0; i < 6; i ++ ) {
  14241. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14242. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14243. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14244. }
  14245. } else {
  14246. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14247. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14248. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14249. }
  14250. }
  14251. state.bindFramebuffer( 36160, null );
  14252. }
  14253. // rebind framebuffer with external textures
  14254. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14255. const renderTargetProperties = properties.get( renderTarget );
  14256. if ( colorTexture !== undefined ) {
  14257. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14258. }
  14259. if ( depthTexture !== undefined ) {
  14260. setupDepthRenderbuffer( renderTarget );
  14261. }
  14262. }
  14263. // Set up GL resources for the render target
  14264. function setupRenderTarget( renderTarget ) {
  14265. const texture = renderTarget.texture;
  14266. const renderTargetProperties = properties.get( renderTarget );
  14267. const textureProperties = properties.get( texture );
  14268. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14269. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14270. if ( textureProperties.__webglTexture === undefined ) {
  14271. textureProperties.__webglTexture = _gl.createTexture();
  14272. }
  14273. textureProperties.__version = texture.version;
  14274. info.memory.textures ++;
  14275. }
  14276. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14277. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14278. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14279. // Setup framebuffer
  14280. if ( isCube ) {
  14281. renderTargetProperties.__webglFramebuffer = [];
  14282. for ( let i = 0; i < 6; i ++ ) {
  14283. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14284. }
  14285. } else {
  14286. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14287. if ( isMultipleRenderTargets ) {
  14288. if ( capabilities.drawBuffers ) {
  14289. const textures = renderTarget.texture;
  14290. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14291. const attachmentProperties = properties.get( textures[ i ] );
  14292. if ( attachmentProperties.__webglTexture === undefined ) {
  14293. attachmentProperties.__webglTexture = _gl.createTexture();
  14294. info.memory.textures ++;
  14295. }
  14296. }
  14297. } else {
  14298. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14299. }
  14300. } else if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14301. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14302. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14303. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  14304. const glFormat = utils.convert( texture.format, texture.encoding );
  14305. const glType = utils.convert( texture.type );
  14306. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14307. const samples = getRenderTargetSamples( renderTarget );
  14308. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14309. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14310. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  14311. _gl.bindRenderbuffer( 36161, null );
  14312. if ( renderTarget.depthBuffer ) {
  14313. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14314. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14315. }
  14316. state.bindFramebuffer( 36160, null );
  14317. }
  14318. }
  14319. // Setup color buffer
  14320. if ( isCube ) {
  14321. state.bindTexture( 34067, textureProperties.__webglTexture );
  14322. setTextureParameters( 34067, texture, supportsMips );
  14323. for ( let i = 0; i < 6; i ++ ) {
  14324. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14325. }
  14326. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14327. generateMipmap( 34067 );
  14328. }
  14329. state.unbindTexture();
  14330. } else if ( isMultipleRenderTargets ) {
  14331. const textures = renderTarget.texture;
  14332. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14333. const attachment = textures[ i ];
  14334. const attachmentProperties = properties.get( attachment );
  14335. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14336. setTextureParameters( 3553, attachment, supportsMips );
  14337. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14338. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14339. generateMipmap( 3553 );
  14340. }
  14341. }
  14342. state.unbindTexture();
  14343. } else {
  14344. let glTextureType = 3553;
  14345. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14346. if ( isWebGL2 ) {
  14347. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14348. } else {
  14349. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14350. }
  14351. }
  14352. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14353. setTextureParameters( glTextureType, texture, supportsMips );
  14354. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14355. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14356. generateMipmap( glTextureType );
  14357. }
  14358. state.unbindTexture();
  14359. }
  14360. // Setup depth and stencil buffers
  14361. if ( renderTarget.depthBuffer ) {
  14362. setupDepthRenderbuffer( renderTarget );
  14363. }
  14364. }
  14365. function updateRenderTargetMipmap( renderTarget ) {
  14366. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14367. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14368. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14369. const texture = textures[ i ];
  14370. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14371. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14372. const webglTexture = properties.get( texture ).__webglTexture;
  14373. state.bindTexture( target, webglTexture );
  14374. generateMipmap( target );
  14375. state.unbindTexture();
  14376. }
  14377. }
  14378. }
  14379. function updateMultisampleRenderTarget( renderTarget ) {
  14380. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14381. const width = renderTarget.width;
  14382. const height = renderTarget.height;
  14383. let mask = 16384;
  14384. const invalidationArray = [ 36064 ];
  14385. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14386. if ( renderTarget.depthBuffer ) {
  14387. invalidationArray.push( depthStyle );
  14388. }
  14389. const renderTargetProperties = properties.get( renderTarget );
  14390. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14391. if ( ignoreDepthValues === false ) {
  14392. if ( renderTarget.depthBuffer ) mask |= 256;
  14393. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14394. }
  14395. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14396. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14397. if ( ignoreDepthValues === true ) {
  14398. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14399. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14400. }
  14401. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14402. if ( supportsInvalidateFramebuffer ) {
  14403. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14404. }
  14405. state.bindFramebuffer( 36008, null );
  14406. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14407. }
  14408. }
  14409. function getRenderTargetSamples( renderTarget ) {
  14410. return Math.min( maxSamples, renderTarget.samples );
  14411. }
  14412. function useMultisampledRTT( renderTarget ) {
  14413. const renderTargetProperties = properties.get( renderTarget );
  14414. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14415. }
  14416. function updateVideoTexture( texture ) {
  14417. const frame = info.render.frame;
  14418. // Check the last frame we updated the VideoTexture
  14419. if ( _videoTextures.get( texture ) !== frame ) {
  14420. _videoTextures.set( texture, frame );
  14421. texture.update();
  14422. }
  14423. }
  14424. function verifyColorSpace( texture, image ) {
  14425. const encoding = texture.encoding;
  14426. const format = texture.format;
  14427. const type = texture.type;
  14428. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14429. if ( encoding !== LinearEncoding ) {
  14430. // sRGB
  14431. if ( encoding === sRGBEncoding ) {
  14432. if ( isWebGL2 === false ) {
  14433. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14434. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14435. texture.format = _SRGBAFormat;
  14436. // it's not possible to generate mips in WebGL 1 with this extension
  14437. texture.minFilter = LinearFilter;
  14438. texture.generateMipmaps = false;
  14439. } else {
  14440. // slow fallback (CPU decode)
  14441. image = ImageUtils.sRGBToLinear( image );
  14442. }
  14443. } else {
  14444. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14445. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14446. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14447. }
  14448. }
  14449. } else {
  14450. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14451. }
  14452. }
  14453. return image;
  14454. }
  14455. //
  14456. this.allocateTextureUnit = allocateTextureUnit;
  14457. this.resetTextureUnits = resetTextureUnits;
  14458. this.setTexture2D = setTexture2D;
  14459. this.setTexture2DArray = setTexture2DArray;
  14460. this.setTexture3D = setTexture3D;
  14461. this.setTextureCube = setTextureCube;
  14462. this.rebindTextures = rebindTextures;
  14463. this.setupRenderTarget = setupRenderTarget;
  14464. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14465. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14466. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14467. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14468. this.useMultisampledRTT = useMultisampledRTT;
  14469. }
  14470. function WebGLUtils( gl, extensions, capabilities ) {
  14471. const isWebGL2 = capabilities.isWebGL2;
  14472. function convert( p, encoding = null ) {
  14473. let extension;
  14474. if ( p === UnsignedByteType ) return 5121;
  14475. if ( p === UnsignedShort4444Type ) return 32819;
  14476. if ( p === UnsignedShort5551Type ) return 32820;
  14477. if ( p === ByteType ) return 5120;
  14478. if ( p === ShortType ) return 5122;
  14479. if ( p === UnsignedShortType ) return 5123;
  14480. if ( p === IntType ) return 5124;
  14481. if ( p === UnsignedIntType ) return 5125;
  14482. if ( p === FloatType ) return 5126;
  14483. if ( p === HalfFloatType ) {
  14484. if ( isWebGL2 ) return 5131;
  14485. extension = extensions.get( 'OES_texture_half_float' );
  14486. if ( extension !== null ) {
  14487. return extension.HALF_FLOAT_OES;
  14488. } else {
  14489. return null;
  14490. }
  14491. }
  14492. if ( p === AlphaFormat ) return 6406;
  14493. if ( p === RGBAFormat ) return 6408;
  14494. if ( p === LuminanceFormat ) return 6409;
  14495. if ( p === LuminanceAlphaFormat ) return 6410;
  14496. if ( p === DepthFormat ) return 6402;
  14497. if ( p === DepthStencilFormat ) return 34041;
  14498. if ( p === RedFormat ) return 6403;
  14499. if ( p === RGBFormat ) {
  14500. console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' );
  14501. return 6408;
  14502. }
  14503. // WebGL 1 sRGB fallback
  14504. if ( p === _SRGBAFormat ) {
  14505. extension = extensions.get( 'EXT_sRGB' );
  14506. if ( extension !== null ) {
  14507. return extension.SRGB_ALPHA_EXT;
  14508. } else {
  14509. return null;
  14510. }
  14511. }
  14512. // WebGL2 formats.
  14513. if ( p === RedIntegerFormat ) return 36244;
  14514. if ( p === RGFormat ) return 33319;
  14515. if ( p === RGIntegerFormat ) return 33320;
  14516. if ( p === RGBAIntegerFormat ) return 36249;
  14517. // S3TC
  14518. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14519. if ( encoding === sRGBEncoding ) {
  14520. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14521. if ( extension !== null ) {
  14522. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14523. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14524. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14525. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14526. } else {
  14527. return null;
  14528. }
  14529. } else {
  14530. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14531. if ( extension !== null ) {
  14532. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14533. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14534. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14535. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14536. } else {
  14537. return null;
  14538. }
  14539. }
  14540. }
  14541. // PVRTC
  14542. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14543. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14544. if ( extension !== null ) {
  14545. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14546. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14547. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14548. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14549. } else {
  14550. return null;
  14551. }
  14552. }
  14553. // ETC1
  14554. if ( p === RGB_ETC1_Format ) {
  14555. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14556. if ( extension !== null ) {
  14557. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14558. } else {
  14559. return null;
  14560. }
  14561. }
  14562. // ETC2
  14563. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14564. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14565. if ( extension !== null ) {
  14566. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14567. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14568. } else {
  14569. return null;
  14570. }
  14571. }
  14572. // ASTC
  14573. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14574. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14575. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14576. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14577. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14578. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14579. if ( extension !== null ) {
  14580. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14581. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14582. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14583. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14584. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14585. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14586. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14587. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14588. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14589. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14590. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14591. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14592. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14593. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14594. } else {
  14595. return null;
  14596. }
  14597. }
  14598. // BPTC
  14599. if ( p === RGBA_BPTC_Format ) {
  14600. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14601. if ( extension !== null ) {
  14602. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14603. } else {
  14604. return null;
  14605. }
  14606. }
  14607. //
  14608. if ( p === UnsignedInt248Type ) {
  14609. if ( isWebGL2 ) return 34042;
  14610. extension = extensions.get( 'WEBGL_depth_texture' );
  14611. if ( extension !== null ) {
  14612. return extension.UNSIGNED_INT_24_8_WEBGL;
  14613. } else {
  14614. return null;
  14615. }
  14616. }
  14617. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14618. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14619. }
  14620. return { convert: convert };
  14621. }
  14622. class ArrayCamera extends PerspectiveCamera {
  14623. constructor( array = [] ) {
  14624. super();
  14625. this.cameras = array;
  14626. }
  14627. }
  14628. ArrayCamera.prototype.isArrayCamera = true;
  14629. class Group extends Object3D {
  14630. constructor() {
  14631. super();
  14632. this.type = 'Group';
  14633. }
  14634. }
  14635. Group.prototype.isGroup = true;
  14636. const _moveEvent = { type: 'move' };
  14637. class WebXRController {
  14638. constructor() {
  14639. this._targetRay = null;
  14640. this._grip = null;
  14641. this._hand = null;
  14642. }
  14643. getHandSpace() {
  14644. if ( this._hand === null ) {
  14645. this._hand = new Group();
  14646. this._hand.matrixAutoUpdate = false;
  14647. this._hand.visible = false;
  14648. this._hand.joints = {};
  14649. this._hand.inputState = { pinching: false };
  14650. }
  14651. return this._hand;
  14652. }
  14653. getTargetRaySpace() {
  14654. if ( this._targetRay === null ) {
  14655. this._targetRay = new Group();
  14656. this._targetRay.matrixAutoUpdate = false;
  14657. this._targetRay.visible = false;
  14658. this._targetRay.hasLinearVelocity = false;
  14659. this._targetRay.linearVelocity = new Vector3();
  14660. this._targetRay.hasAngularVelocity = false;
  14661. this._targetRay.angularVelocity = new Vector3();
  14662. }
  14663. return this._targetRay;
  14664. }
  14665. getGripSpace() {
  14666. if ( this._grip === null ) {
  14667. this._grip = new Group();
  14668. this._grip.matrixAutoUpdate = false;
  14669. this._grip.visible = false;
  14670. this._grip.hasLinearVelocity = false;
  14671. this._grip.linearVelocity = new Vector3();
  14672. this._grip.hasAngularVelocity = false;
  14673. this._grip.angularVelocity = new Vector3();
  14674. }
  14675. return this._grip;
  14676. }
  14677. dispatchEvent( event ) {
  14678. if ( this._targetRay !== null ) {
  14679. this._targetRay.dispatchEvent( event );
  14680. }
  14681. if ( this._grip !== null ) {
  14682. this._grip.dispatchEvent( event );
  14683. }
  14684. if ( this._hand !== null ) {
  14685. this._hand.dispatchEvent( event );
  14686. }
  14687. return this;
  14688. }
  14689. disconnect( inputSource ) {
  14690. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14691. if ( this._targetRay !== null ) {
  14692. this._targetRay.visible = false;
  14693. }
  14694. if ( this._grip !== null ) {
  14695. this._grip.visible = false;
  14696. }
  14697. if ( this._hand !== null ) {
  14698. this._hand.visible = false;
  14699. }
  14700. return this;
  14701. }
  14702. update( inputSource, frame, referenceSpace ) {
  14703. let inputPose = null;
  14704. let gripPose = null;
  14705. let handPose = null;
  14706. const targetRay = this._targetRay;
  14707. const grip = this._grip;
  14708. const hand = this._hand;
  14709. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14710. if ( targetRay !== null ) {
  14711. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14712. if ( inputPose !== null ) {
  14713. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14714. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14715. if ( inputPose.linearVelocity ) {
  14716. targetRay.hasLinearVelocity = true;
  14717. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14718. } else {
  14719. targetRay.hasLinearVelocity = false;
  14720. }
  14721. if ( inputPose.angularVelocity ) {
  14722. targetRay.hasAngularVelocity = true;
  14723. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14724. } else {
  14725. targetRay.hasAngularVelocity = false;
  14726. }
  14727. this.dispatchEvent( _moveEvent );
  14728. }
  14729. }
  14730. if ( hand && inputSource.hand ) {
  14731. handPose = true;
  14732. for ( const inputjoint of inputSource.hand.values() ) {
  14733. // Update the joints groups with the XRJoint poses
  14734. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14735. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14736. // The transform of this joint will be updated with the joint pose on each frame
  14737. const joint = new Group();
  14738. joint.matrixAutoUpdate = false;
  14739. joint.visible = false;
  14740. hand.joints[ inputjoint.jointName ] = joint;
  14741. // ??
  14742. hand.add( joint );
  14743. }
  14744. const joint = hand.joints[ inputjoint.jointName ];
  14745. if ( jointPose !== null ) {
  14746. joint.matrix.fromArray( jointPose.transform.matrix );
  14747. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14748. joint.jointRadius = jointPose.radius;
  14749. }
  14750. joint.visible = jointPose !== null;
  14751. }
  14752. // Custom events
  14753. // Check pinchz
  14754. const indexTip = hand.joints[ 'index-finger-tip' ];
  14755. const thumbTip = hand.joints[ 'thumb-tip' ];
  14756. const distance = indexTip.position.distanceTo( thumbTip.position );
  14757. const distanceToPinch = 0.02;
  14758. const threshold = 0.005;
  14759. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14760. hand.inputState.pinching = false;
  14761. this.dispatchEvent( {
  14762. type: 'pinchend',
  14763. handedness: inputSource.handedness,
  14764. target: this
  14765. } );
  14766. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14767. hand.inputState.pinching = true;
  14768. this.dispatchEvent( {
  14769. type: 'pinchstart',
  14770. handedness: inputSource.handedness,
  14771. target: this
  14772. } );
  14773. }
  14774. } else {
  14775. if ( grip !== null && inputSource.gripSpace ) {
  14776. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14777. if ( gripPose !== null ) {
  14778. grip.matrix.fromArray( gripPose.transform.matrix );
  14779. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14780. if ( gripPose.linearVelocity ) {
  14781. grip.hasLinearVelocity = true;
  14782. grip.linearVelocity.copy( gripPose.linearVelocity );
  14783. } else {
  14784. grip.hasLinearVelocity = false;
  14785. }
  14786. if ( gripPose.angularVelocity ) {
  14787. grip.hasAngularVelocity = true;
  14788. grip.angularVelocity.copy( gripPose.angularVelocity );
  14789. } else {
  14790. grip.hasAngularVelocity = false;
  14791. }
  14792. }
  14793. }
  14794. }
  14795. }
  14796. if ( targetRay !== null ) {
  14797. targetRay.visible = ( inputPose !== null );
  14798. }
  14799. if ( grip !== null ) {
  14800. grip.visible = ( gripPose !== null );
  14801. }
  14802. if ( hand !== null ) {
  14803. hand.visible = ( handPose !== null );
  14804. }
  14805. return this;
  14806. }
  14807. }
  14808. class DepthTexture extends Texture {
  14809. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14810. format = format !== undefined ? format : DepthFormat;
  14811. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14812. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14813. }
  14814. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14815. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14816. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14817. this.image = { width: width, height: height };
  14818. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14819. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14820. this.flipY = false;
  14821. this.generateMipmaps = false;
  14822. }
  14823. }
  14824. DepthTexture.prototype.isDepthTexture = true;
  14825. class WebXRManager extends EventDispatcher {
  14826. constructor( renderer, gl ) {
  14827. super();
  14828. const scope = this;
  14829. let session = null;
  14830. let framebufferScaleFactor = 1.0;
  14831. let referenceSpace = null;
  14832. let referenceSpaceType = 'local-floor';
  14833. let customReferenceSpace = null;
  14834. let pose = null;
  14835. let glBinding = null;
  14836. let glProjLayer = null;
  14837. let glBaseLayer = null;
  14838. let xrFrame = null;
  14839. const attributes = gl.getContextAttributes();
  14840. let initialRenderTarget = null;
  14841. let newRenderTarget = null;
  14842. const controllers = [];
  14843. const inputSourcesMap = new Map();
  14844. //
  14845. const cameraL = new PerspectiveCamera();
  14846. cameraL.layers.enable( 1 );
  14847. cameraL.viewport = new Vector4();
  14848. const cameraR = new PerspectiveCamera();
  14849. cameraR.layers.enable( 2 );
  14850. cameraR.viewport = new Vector4();
  14851. const cameras = [ cameraL, cameraR ];
  14852. const cameraVR = new ArrayCamera();
  14853. cameraVR.layers.enable( 1 );
  14854. cameraVR.layers.enable( 2 );
  14855. let _currentDepthNear = null;
  14856. let _currentDepthFar = null;
  14857. //
  14858. this.cameraAutoUpdate = true;
  14859. this.enabled = false;
  14860. this.isPresenting = false;
  14861. this.getController = function ( index ) {
  14862. let controller = controllers[ index ];
  14863. if ( controller === undefined ) {
  14864. controller = new WebXRController();
  14865. controllers[ index ] = controller;
  14866. }
  14867. return controller.getTargetRaySpace();
  14868. };
  14869. this.getControllerGrip = function ( index ) {
  14870. let controller = controllers[ index ];
  14871. if ( controller === undefined ) {
  14872. controller = new WebXRController();
  14873. controllers[ index ] = controller;
  14874. }
  14875. return controller.getGripSpace();
  14876. };
  14877. this.getHand = function ( index ) {
  14878. let controller = controllers[ index ];
  14879. if ( controller === undefined ) {
  14880. controller = new WebXRController();
  14881. controllers[ index ] = controller;
  14882. }
  14883. return controller.getHandSpace();
  14884. };
  14885. //
  14886. function onSessionEvent( event ) {
  14887. const controller = inputSourcesMap.get( event.inputSource );
  14888. if ( controller ) {
  14889. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14890. }
  14891. }
  14892. function onSessionEnd() {
  14893. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14894. controller.disconnect( inputSource );
  14895. } );
  14896. inputSourcesMap.clear();
  14897. _currentDepthNear = null;
  14898. _currentDepthFar = null;
  14899. // restore framebuffer/rendering state
  14900. renderer.setRenderTarget( initialRenderTarget );
  14901. glBaseLayer = null;
  14902. glProjLayer = null;
  14903. glBinding = null;
  14904. session = null;
  14905. newRenderTarget = null;
  14906. //
  14907. animation.stop();
  14908. scope.isPresenting = false;
  14909. scope.dispatchEvent( { type: 'sessionend' } );
  14910. }
  14911. this.setFramebufferScaleFactor = function ( value ) {
  14912. framebufferScaleFactor = value;
  14913. if ( scope.isPresenting === true ) {
  14914. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14915. }
  14916. };
  14917. this.setReferenceSpaceType = function ( value ) {
  14918. referenceSpaceType = value;
  14919. if ( scope.isPresenting === true ) {
  14920. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14921. }
  14922. };
  14923. this.getReferenceSpace = function () {
  14924. return customReferenceSpace || referenceSpace;
  14925. };
  14926. this.setReferenceSpace = function ( space ) {
  14927. customReferenceSpace = space;
  14928. };
  14929. this.getBaseLayer = function () {
  14930. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14931. };
  14932. this.getBinding = function () {
  14933. return glBinding;
  14934. };
  14935. this.getFrame = function () {
  14936. return xrFrame;
  14937. };
  14938. this.getSession = function () {
  14939. return session;
  14940. };
  14941. this.setSession = async function ( value ) {
  14942. session = value;
  14943. if ( session !== null ) {
  14944. initialRenderTarget = renderer.getRenderTarget();
  14945. session.addEventListener( 'select', onSessionEvent );
  14946. session.addEventListener( 'selectstart', onSessionEvent );
  14947. session.addEventListener( 'selectend', onSessionEvent );
  14948. session.addEventListener( 'squeeze', onSessionEvent );
  14949. session.addEventListener( 'squeezestart', onSessionEvent );
  14950. session.addEventListener( 'squeezeend', onSessionEvent );
  14951. session.addEventListener( 'end', onSessionEnd );
  14952. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14953. if ( attributes.xrCompatible !== true ) {
  14954. await gl.makeXRCompatible();
  14955. }
  14956. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  14957. const layerInit = {
  14958. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  14959. alpha: attributes.alpha,
  14960. depth: attributes.depth,
  14961. stencil: attributes.stencil,
  14962. framebufferScaleFactor: framebufferScaleFactor
  14963. };
  14964. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14965. session.updateRenderState( { baseLayer: glBaseLayer } );
  14966. newRenderTarget = new WebGLRenderTarget(
  14967. glBaseLayer.framebufferWidth,
  14968. glBaseLayer.framebufferHeight,
  14969. {
  14970. format: RGBAFormat,
  14971. type: UnsignedByteType,
  14972. encoding: renderer.outputEncoding
  14973. }
  14974. );
  14975. } else {
  14976. let depthFormat = null;
  14977. let depthType = null;
  14978. let glDepthFormat = null;
  14979. if ( attributes.depth ) {
  14980. glDepthFormat = attributes.stencil ? 35056 : 33190;
  14981. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14982. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  14983. }
  14984. const projectionlayerInit = {
  14985. colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? 35907 : 32856,
  14986. depthFormat: glDepthFormat,
  14987. scaleFactor: framebufferScaleFactor
  14988. };
  14989. glBinding = new XRWebGLBinding( session, gl );
  14990. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  14991. session.updateRenderState( { layers: [ glProjLayer ] } );
  14992. newRenderTarget = new WebGLRenderTarget(
  14993. glProjLayer.textureWidth,
  14994. glProjLayer.textureHeight,
  14995. {
  14996. format: RGBAFormat,
  14997. type: UnsignedByteType,
  14998. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  14999. stencilBuffer: attributes.stencil,
  15000. encoding: renderer.outputEncoding,
  15001. samples: attributes.antialias ? 4 : 0
  15002. } );
  15003. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15004. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15005. }
  15006. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15007. // Set foveation to maximum.
  15008. this.setFoveation( 1.0 );
  15009. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15010. animation.setContext( session );
  15011. animation.start();
  15012. scope.isPresenting = true;
  15013. scope.dispatchEvent( { type: 'sessionstart' } );
  15014. }
  15015. };
  15016. function onInputSourcesChange( event ) {
  15017. const inputSources = session.inputSources;
  15018. // Assign controllers to available inputSources
  15019. for ( let i = 0; i < inputSources.length; i ++ ) {
  15020. const index = inputSources[ i ].handedness === 'right' ? 1 : 0;
  15021. inputSourcesMap.set( inputSources[ i ], controllers[ index ] );
  15022. }
  15023. // Notify disconnected
  15024. for ( let i = 0; i < event.removed.length; i ++ ) {
  15025. const inputSource = event.removed[ i ];
  15026. const controller = inputSourcesMap.get( inputSource );
  15027. if ( controller ) {
  15028. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15029. inputSourcesMap.delete( inputSource );
  15030. }
  15031. }
  15032. // Notify connected
  15033. for ( let i = 0; i < event.added.length; i ++ ) {
  15034. const inputSource = event.added[ i ];
  15035. const controller = inputSourcesMap.get( inputSource );
  15036. if ( controller ) {
  15037. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  15038. }
  15039. }
  15040. }
  15041. //
  15042. const cameraLPos = new Vector3();
  15043. const cameraRPos = new Vector3();
  15044. /**
  15045. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15046. * the cameras' projection and world matrices have already been set.
  15047. * And that near and far planes are identical for both cameras.
  15048. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15049. */
  15050. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15051. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15052. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15053. const ipd = cameraLPos.distanceTo( cameraRPos );
  15054. const projL = cameraL.projectionMatrix.elements;
  15055. const projR = cameraR.projectionMatrix.elements;
  15056. // VR systems will have identical far and near planes, and
  15057. // most likely identical top and bottom frustum extents.
  15058. // Use the left camera for these values.
  15059. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15060. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15061. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15062. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15063. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15064. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15065. const left = near * leftFov;
  15066. const right = near * rightFov;
  15067. // Calculate the new camera's position offset from the
  15068. // left camera. xOffset should be roughly half `ipd`.
  15069. const zOffset = ipd / ( - leftFov + rightFov );
  15070. const xOffset = zOffset * - leftFov;
  15071. // TODO: Better way to apply this offset?
  15072. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15073. camera.translateX( xOffset );
  15074. camera.translateZ( zOffset );
  15075. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15076. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15077. // Find the union of the frustum values of the cameras and scale
  15078. // the values so that the near plane's position does not change in world space,
  15079. // although must now be relative to the new union camera.
  15080. const near2 = near + zOffset;
  15081. const far2 = far + zOffset;
  15082. const left2 = left - xOffset;
  15083. const right2 = right + ( ipd - xOffset );
  15084. const top2 = topFov * far / far2 * near2;
  15085. const bottom2 = bottomFov * far / far2 * near2;
  15086. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15087. }
  15088. function updateCamera( camera, parent ) {
  15089. if ( parent === null ) {
  15090. camera.matrixWorld.copy( camera.matrix );
  15091. } else {
  15092. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15093. }
  15094. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15095. }
  15096. this.updateCamera = function ( camera ) {
  15097. if ( session === null ) return;
  15098. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15099. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15100. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15101. // Note that the new renderState won't apply until the next frame. See #18320
  15102. session.updateRenderState( {
  15103. depthNear: cameraVR.near,
  15104. depthFar: cameraVR.far
  15105. } );
  15106. _currentDepthNear = cameraVR.near;
  15107. _currentDepthFar = cameraVR.far;
  15108. }
  15109. const parent = camera.parent;
  15110. const cameras = cameraVR.cameras;
  15111. updateCamera( cameraVR, parent );
  15112. for ( let i = 0; i < cameras.length; i ++ ) {
  15113. updateCamera( cameras[ i ], parent );
  15114. }
  15115. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15116. // update user camera and its children
  15117. camera.position.copy( cameraVR.position );
  15118. camera.quaternion.copy( cameraVR.quaternion );
  15119. camera.scale.copy( cameraVR.scale );
  15120. camera.matrix.copy( cameraVR.matrix );
  15121. camera.matrixWorld.copy( cameraVR.matrixWorld );
  15122. const children = camera.children;
  15123. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15124. children[ i ].updateMatrixWorld( true );
  15125. }
  15126. // update projection matrix for proper view frustum culling
  15127. if ( cameras.length === 2 ) {
  15128. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15129. } else {
  15130. // assume single camera setup (AR)
  15131. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15132. }
  15133. };
  15134. this.getCamera = function () {
  15135. return cameraVR;
  15136. };
  15137. this.getFoveation = function () {
  15138. if ( glProjLayer !== null ) {
  15139. return glProjLayer.fixedFoveation;
  15140. }
  15141. if ( glBaseLayer !== null ) {
  15142. return glBaseLayer.fixedFoveation;
  15143. }
  15144. return undefined;
  15145. };
  15146. this.setFoveation = function ( foveation ) {
  15147. // 0 = no foveation = full resolution
  15148. // 1 = maximum foveation = the edges render at lower resolution
  15149. if ( glProjLayer !== null ) {
  15150. glProjLayer.fixedFoveation = foveation;
  15151. }
  15152. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15153. glBaseLayer.fixedFoveation = foveation;
  15154. }
  15155. };
  15156. // Animation Loop
  15157. let onAnimationFrameCallback = null;
  15158. function onAnimationFrame( time, frame ) {
  15159. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15160. xrFrame = frame;
  15161. if ( pose !== null ) {
  15162. const views = pose.views;
  15163. if ( glBaseLayer !== null ) {
  15164. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15165. renderer.setRenderTarget( newRenderTarget );
  15166. }
  15167. let cameraVRNeedsUpdate = false;
  15168. // check if it's necessary to rebuild cameraVR's camera list
  15169. if ( views.length !== cameraVR.cameras.length ) {
  15170. cameraVR.cameras.length = 0;
  15171. cameraVRNeedsUpdate = true;
  15172. }
  15173. for ( let i = 0; i < views.length; i ++ ) {
  15174. const view = views[ i ];
  15175. let viewport = null;
  15176. if ( glBaseLayer !== null ) {
  15177. viewport = glBaseLayer.getViewport( view );
  15178. } else {
  15179. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15180. viewport = glSubImage.viewport;
  15181. // For side-by-side projection, we only produce a single texture for both eyes.
  15182. if ( i === 0 ) {
  15183. renderer.setRenderTargetTextures(
  15184. newRenderTarget,
  15185. glSubImage.colorTexture,
  15186. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15187. renderer.setRenderTarget( newRenderTarget );
  15188. }
  15189. }
  15190. const camera = cameras[ i ];
  15191. camera.matrix.fromArray( view.transform.matrix );
  15192. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15193. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15194. if ( i === 0 ) {
  15195. cameraVR.matrix.copy( camera.matrix );
  15196. }
  15197. if ( cameraVRNeedsUpdate === true ) {
  15198. cameraVR.cameras.push( camera );
  15199. }
  15200. }
  15201. }
  15202. //
  15203. const inputSources = session.inputSources;
  15204. for ( let i = 0; i < controllers.length; i ++ ) {
  15205. const inputSource = inputSources[ i ];
  15206. const controller = inputSourcesMap.get( inputSource );
  15207. if ( controller !== undefined ) {
  15208. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15209. }
  15210. }
  15211. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15212. xrFrame = null;
  15213. }
  15214. const animation = new WebGLAnimation();
  15215. animation.setAnimationLoop( onAnimationFrame );
  15216. this.setAnimationLoop = function ( callback ) {
  15217. onAnimationFrameCallback = callback;
  15218. };
  15219. this.dispose = function () {};
  15220. }
  15221. }
  15222. function WebGLMaterials( renderer, properties ) {
  15223. function refreshFogUniforms( uniforms, fog ) {
  15224. uniforms.fogColor.value.copy( fog.color );
  15225. if ( fog.isFog ) {
  15226. uniforms.fogNear.value = fog.near;
  15227. uniforms.fogFar.value = fog.far;
  15228. } else if ( fog.isFogExp2 ) {
  15229. uniforms.fogDensity.value = fog.density;
  15230. }
  15231. }
  15232. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15233. if ( material.isMeshBasicMaterial ) {
  15234. refreshUniformsCommon( uniforms, material );
  15235. } else if ( material.isMeshLambertMaterial ) {
  15236. refreshUniformsCommon( uniforms, material );
  15237. } else if ( material.isMeshToonMaterial ) {
  15238. refreshUniformsCommon( uniforms, material );
  15239. refreshUniformsToon( uniforms, material );
  15240. } else if ( material.isMeshPhongMaterial ) {
  15241. refreshUniformsCommon( uniforms, material );
  15242. refreshUniformsPhong( uniforms, material );
  15243. } else if ( material.isMeshStandardMaterial ) {
  15244. refreshUniformsCommon( uniforms, material );
  15245. refreshUniformsStandard( uniforms, material );
  15246. if ( material.isMeshPhysicalMaterial ) {
  15247. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15248. }
  15249. } else if ( material.isMeshMatcapMaterial ) {
  15250. refreshUniformsCommon( uniforms, material );
  15251. refreshUniformsMatcap( uniforms, material );
  15252. } else if ( material.isMeshDepthMaterial ) {
  15253. refreshUniformsCommon( uniforms, material );
  15254. } else if ( material.isMeshDistanceMaterial ) {
  15255. refreshUniformsCommon( uniforms, material );
  15256. refreshUniformsDistance( uniforms, material );
  15257. } else if ( material.isMeshNormalMaterial ) {
  15258. refreshUniformsCommon( uniforms, material );
  15259. } else if ( material.isLineBasicMaterial ) {
  15260. refreshUniformsLine( uniforms, material );
  15261. if ( material.isLineDashedMaterial ) {
  15262. refreshUniformsDash( uniforms, material );
  15263. }
  15264. } else if ( material.isPointsMaterial ) {
  15265. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15266. } else if ( material.isSpriteMaterial ) {
  15267. refreshUniformsSprites( uniforms, material );
  15268. } else if ( material.isShadowMaterial ) {
  15269. uniforms.color.value.copy( material.color );
  15270. uniforms.opacity.value = material.opacity;
  15271. } else if ( material.isShaderMaterial ) {
  15272. material.uniformsNeedUpdate = false; // #15581
  15273. }
  15274. }
  15275. function refreshUniformsCommon( uniforms, material ) {
  15276. uniforms.opacity.value = material.opacity;
  15277. if ( material.color ) {
  15278. uniforms.diffuse.value.copy( material.color );
  15279. }
  15280. if ( material.emissive ) {
  15281. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15282. }
  15283. if ( material.map ) {
  15284. uniforms.map.value = material.map;
  15285. }
  15286. if ( material.alphaMap ) {
  15287. uniforms.alphaMap.value = material.alphaMap;
  15288. }
  15289. if ( material.bumpMap ) {
  15290. uniforms.bumpMap.value = material.bumpMap;
  15291. uniforms.bumpScale.value = material.bumpScale;
  15292. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15293. }
  15294. if ( material.displacementMap ) {
  15295. uniforms.displacementMap.value = material.displacementMap;
  15296. uniforms.displacementScale.value = material.displacementScale;
  15297. uniforms.displacementBias.value = material.displacementBias;
  15298. }
  15299. if ( material.emissiveMap ) {
  15300. uniforms.emissiveMap.value = material.emissiveMap;
  15301. }
  15302. if ( material.normalMap ) {
  15303. uniforms.normalMap.value = material.normalMap;
  15304. uniforms.normalScale.value.copy( material.normalScale );
  15305. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15306. }
  15307. if ( material.specularMap ) {
  15308. uniforms.specularMap.value = material.specularMap;
  15309. }
  15310. if ( material.alphaTest > 0 ) {
  15311. uniforms.alphaTest.value = material.alphaTest;
  15312. }
  15313. const envMap = properties.get( material ).envMap;
  15314. if ( envMap ) {
  15315. uniforms.envMap.value = envMap;
  15316. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15317. uniforms.reflectivity.value = material.reflectivity;
  15318. uniforms.ior.value = material.ior;
  15319. uniforms.refractionRatio.value = material.refractionRatio;
  15320. }
  15321. if ( material.lightMap ) {
  15322. uniforms.lightMap.value = material.lightMap;
  15323. // artist-friendly light intensity scaling factor
  15324. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15325. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15326. }
  15327. if ( material.aoMap ) {
  15328. uniforms.aoMap.value = material.aoMap;
  15329. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15330. }
  15331. // uv repeat and offset setting priorities
  15332. // 1. color map
  15333. // 2. specular map
  15334. // 3. displacementMap map
  15335. // 4. normal map
  15336. // 5. bump map
  15337. // 6. roughnessMap map
  15338. // 7. metalnessMap map
  15339. // 8. alphaMap map
  15340. // 9. emissiveMap map
  15341. // 10. clearcoat map
  15342. // 11. clearcoat normal map
  15343. // 12. clearcoat roughnessMap map
  15344. // 13. specular intensity map
  15345. // 14. specular tint map
  15346. // 15. transmission map
  15347. // 16. thickness map
  15348. let uvScaleMap;
  15349. if ( material.map ) {
  15350. uvScaleMap = material.map;
  15351. } else if ( material.specularMap ) {
  15352. uvScaleMap = material.specularMap;
  15353. } else if ( material.displacementMap ) {
  15354. uvScaleMap = material.displacementMap;
  15355. } else if ( material.normalMap ) {
  15356. uvScaleMap = material.normalMap;
  15357. } else if ( material.bumpMap ) {
  15358. uvScaleMap = material.bumpMap;
  15359. } else if ( material.roughnessMap ) {
  15360. uvScaleMap = material.roughnessMap;
  15361. } else if ( material.metalnessMap ) {
  15362. uvScaleMap = material.metalnessMap;
  15363. } else if ( material.alphaMap ) {
  15364. uvScaleMap = material.alphaMap;
  15365. } else if ( material.emissiveMap ) {
  15366. uvScaleMap = material.emissiveMap;
  15367. } else if ( material.clearcoatMap ) {
  15368. uvScaleMap = material.clearcoatMap;
  15369. } else if ( material.clearcoatNormalMap ) {
  15370. uvScaleMap = material.clearcoatNormalMap;
  15371. } else if ( material.clearcoatRoughnessMap ) {
  15372. uvScaleMap = material.clearcoatRoughnessMap;
  15373. } else if ( material.specularIntensityMap ) {
  15374. uvScaleMap = material.specularIntensityMap;
  15375. } else if ( material.specularColorMap ) {
  15376. uvScaleMap = material.specularColorMap;
  15377. } else if ( material.transmissionMap ) {
  15378. uvScaleMap = material.transmissionMap;
  15379. } else if ( material.thicknessMap ) {
  15380. uvScaleMap = material.thicknessMap;
  15381. } else if ( material.sheenColorMap ) {
  15382. uvScaleMap = material.sheenColorMap;
  15383. } else if ( material.sheenRoughnessMap ) {
  15384. uvScaleMap = material.sheenRoughnessMap;
  15385. }
  15386. if ( uvScaleMap !== undefined ) {
  15387. // backwards compatibility
  15388. if ( uvScaleMap.isWebGLRenderTarget ) {
  15389. uvScaleMap = uvScaleMap.texture;
  15390. }
  15391. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15392. uvScaleMap.updateMatrix();
  15393. }
  15394. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15395. }
  15396. // uv repeat and offset setting priorities for uv2
  15397. // 1. ao map
  15398. // 2. light map
  15399. let uv2ScaleMap;
  15400. if ( material.aoMap ) {
  15401. uv2ScaleMap = material.aoMap;
  15402. } else if ( material.lightMap ) {
  15403. uv2ScaleMap = material.lightMap;
  15404. }
  15405. if ( uv2ScaleMap !== undefined ) {
  15406. // backwards compatibility
  15407. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15408. uv2ScaleMap = uv2ScaleMap.texture;
  15409. }
  15410. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15411. uv2ScaleMap.updateMatrix();
  15412. }
  15413. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15414. }
  15415. }
  15416. function refreshUniformsLine( uniforms, material ) {
  15417. uniforms.diffuse.value.copy( material.color );
  15418. uniforms.opacity.value = material.opacity;
  15419. }
  15420. function refreshUniformsDash( uniforms, material ) {
  15421. uniforms.dashSize.value = material.dashSize;
  15422. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15423. uniforms.scale.value = material.scale;
  15424. }
  15425. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15426. uniforms.diffuse.value.copy( material.color );
  15427. uniforms.opacity.value = material.opacity;
  15428. uniforms.size.value = material.size * pixelRatio;
  15429. uniforms.scale.value = height * 0.5;
  15430. if ( material.map ) {
  15431. uniforms.map.value = material.map;
  15432. }
  15433. if ( material.alphaMap ) {
  15434. uniforms.alphaMap.value = material.alphaMap;
  15435. }
  15436. if ( material.alphaTest > 0 ) {
  15437. uniforms.alphaTest.value = material.alphaTest;
  15438. }
  15439. // uv repeat and offset setting priorities
  15440. // 1. color map
  15441. // 2. alpha map
  15442. let uvScaleMap;
  15443. if ( material.map ) {
  15444. uvScaleMap = material.map;
  15445. } else if ( material.alphaMap ) {
  15446. uvScaleMap = material.alphaMap;
  15447. }
  15448. if ( uvScaleMap !== undefined ) {
  15449. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15450. uvScaleMap.updateMatrix();
  15451. }
  15452. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15453. }
  15454. }
  15455. function refreshUniformsSprites( uniforms, material ) {
  15456. uniforms.diffuse.value.copy( material.color );
  15457. uniforms.opacity.value = material.opacity;
  15458. uniforms.rotation.value = material.rotation;
  15459. if ( material.map ) {
  15460. uniforms.map.value = material.map;
  15461. }
  15462. if ( material.alphaMap ) {
  15463. uniforms.alphaMap.value = material.alphaMap;
  15464. }
  15465. if ( material.alphaTest > 0 ) {
  15466. uniforms.alphaTest.value = material.alphaTest;
  15467. }
  15468. // uv repeat and offset setting priorities
  15469. // 1. color map
  15470. // 2. alpha map
  15471. let uvScaleMap;
  15472. if ( material.map ) {
  15473. uvScaleMap = material.map;
  15474. } else if ( material.alphaMap ) {
  15475. uvScaleMap = material.alphaMap;
  15476. }
  15477. if ( uvScaleMap !== undefined ) {
  15478. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15479. uvScaleMap.updateMatrix();
  15480. }
  15481. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15482. }
  15483. }
  15484. function refreshUniformsPhong( uniforms, material ) {
  15485. uniforms.specular.value.copy( material.specular );
  15486. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15487. }
  15488. function refreshUniformsToon( uniforms, material ) {
  15489. if ( material.gradientMap ) {
  15490. uniforms.gradientMap.value = material.gradientMap;
  15491. }
  15492. }
  15493. function refreshUniformsStandard( uniforms, material ) {
  15494. uniforms.roughness.value = material.roughness;
  15495. uniforms.metalness.value = material.metalness;
  15496. if ( material.roughnessMap ) {
  15497. uniforms.roughnessMap.value = material.roughnessMap;
  15498. }
  15499. if ( material.metalnessMap ) {
  15500. uniforms.metalnessMap.value = material.metalnessMap;
  15501. }
  15502. const envMap = properties.get( material ).envMap;
  15503. if ( envMap ) {
  15504. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15505. uniforms.envMapIntensity.value = material.envMapIntensity;
  15506. }
  15507. }
  15508. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15509. uniforms.ior.value = material.ior; // also part of uniforms common
  15510. if ( material.sheen > 0 ) {
  15511. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15512. uniforms.sheenRoughness.value = material.sheenRoughness;
  15513. if ( material.sheenColorMap ) {
  15514. uniforms.sheenColorMap.value = material.sheenColorMap;
  15515. }
  15516. if ( material.sheenRoughnessMap ) {
  15517. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15518. }
  15519. }
  15520. if ( material.clearcoat > 0 ) {
  15521. uniforms.clearcoat.value = material.clearcoat;
  15522. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15523. if ( material.clearcoatMap ) {
  15524. uniforms.clearcoatMap.value = material.clearcoatMap;
  15525. }
  15526. if ( material.clearcoatRoughnessMap ) {
  15527. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15528. }
  15529. if ( material.clearcoatNormalMap ) {
  15530. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15531. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15532. if ( material.side === BackSide ) {
  15533. uniforms.clearcoatNormalScale.value.negate();
  15534. }
  15535. }
  15536. }
  15537. if ( material.transmission > 0 ) {
  15538. uniforms.transmission.value = material.transmission;
  15539. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15540. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15541. if ( material.transmissionMap ) {
  15542. uniforms.transmissionMap.value = material.transmissionMap;
  15543. }
  15544. uniforms.thickness.value = material.thickness;
  15545. if ( material.thicknessMap ) {
  15546. uniforms.thicknessMap.value = material.thicknessMap;
  15547. }
  15548. uniforms.attenuationDistance.value = material.attenuationDistance;
  15549. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15550. }
  15551. uniforms.specularIntensity.value = material.specularIntensity;
  15552. uniforms.specularColor.value.copy( material.specularColor );
  15553. if ( material.specularIntensityMap ) {
  15554. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15555. }
  15556. if ( material.specularColorMap ) {
  15557. uniforms.specularColorMap.value = material.specularColorMap;
  15558. }
  15559. }
  15560. function refreshUniformsMatcap( uniforms, material ) {
  15561. if ( material.matcap ) {
  15562. uniforms.matcap.value = material.matcap;
  15563. }
  15564. }
  15565. function refreshUniformsDistance( uniforms, material ) {
  15566. uniforms.referencePosition.value.copy( material.referencePosition );
  15567. uniforms.nearDistance.value = material.nearDistance;
  15568. uniforms.farDistance.value = material.farDistance;
  15569. }
  15570. return {
  15571. refreshFogUniforms: refreshFogUniforms,
  15572. refreshMaterialUniforms: refreshMaterialUniforms
  15573. };
  15574. }
  15575. function createCanvasElement() {
  15576. const canvas = createElementNS( 'canvas' );
  15577. canvas.style.display = 'block';
  15578. return canvas;
  15579. }
  15580. function WebGLRenderer( parameters = {} ) {
  15581. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15582. _context = parameters.context !== undefined ? parameters.context : null,
  15583. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15584. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15585. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15586. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15587. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15588. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15589. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15590. let _alpha;
  15591. if ( _context !== null ) {
  15592. _alpha = _context.getContextAttributes().alpha;
  15593. } else {
  15594. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15595. }
  15596. let currentRenderList = null;
  15597. let currentRenderState = null;
  15598. // render() can be called from within a callback triggered by another render.
  15599. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15600. const renderListStack = [];
  15601. const renderStateStack = [];
  15602. // public properties
  15603. this.domElement = _canvas;
  15604. // Debug configuration container
  15605. this.debug = {
  15606. /**
  15607. * Enables error checking and reporting when shader programs are being compiled
  15608. * @type {boolean}
  15609. */
  15610. checkShaderErrors: true
  15611. };
  15612. // clearing
  15613. this.autoClear = true;
  15614. this.autoClearColor = true;
  15615. this.autoClearDepth = true;
  15616. this.autoClearStencil = true;
  15617. // scene graph
  15618. this.sortObjects = true;
  15619. // user-defined clipping
  15620. this.clippingPlanes = [];
  15621. this.localClippingEnabled = false;
  15622. // physically based shading
  15623. this.outputEncoding = LinearEncoding;
  15624. // physical lights
  15625. this.physicallyCorrectLights = false;
  15626. // tone mapping
  15627. this.toneMapping = NoToneMapping;
  15628. this.toneMappingExposure = 1.0;
  15629. // internal properties
  15630. const _this = this;
  15631. let _isContextLost = false;
  15632. // internal state cache
  15633. let _currentActiveCubeFace = 0;
  15634. let _currentActiveMipmapLevel = 0;
  15635. let _currentRenderTarget = null;
  15636. let _currentMaterialId = - 1;
  15637. let _currentCamera = null;
  15638. const _currentViewport = new Vector4();
  15639. const _currentScissor = new Vector4();
  15640. let _currentScissorTest = null;
  15641. //
  15642. let _width = _canvas.width;
  15643. let _height = _canvas.height;
  15644. let _pixelRatio = 1;
  15645. let _opaqueSort = null;
  15646. let _transparentSort = null;
  15647. const _viewport = new Vector4( 0, 0, _width, _height );
  15648. const _scissor = new Vector4( 0, 0, _width, _height );
  15649. let _scissorTest = false;
  15650. // frustum
  15651. const _frustum = new Frustum();
  15652. // clipping
  15653. let _clippingEnabled = false;
  15654. let _localClippingEnabled = false;
  15655. // transmission
  15656. let _transmissionRenderTarget = null;
  15657. // camera matrices cache
  15658. const _projScreenMatrix = new Matrix4();
  15659. const _vector2 = new Vector2();
  15660. const _vector3 = new Vector3();
  15661. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15662. function getTargetPixelRatio() {
  15663. return _currentRenderTarget === null ? _pixelRatio : 1;
  15664. }
  15665. // initialize
  15666. let _gl = _context;
  15667. function getContext( contextNames, contextAttributes ) {
  15668. for ( let i = 0; i < contextNames.length; i ++ ) {
  15669. const contextName = contextNames[ i ];
  15670. const context = _canvas.getContext( contextName, contextAttributes );
  15671. if ( context !== null ) return context;
  15672. }
  15673. return null;
  15674. }
  15675. try {
  15676. const contextAttributes = {
  15677. alpha: true,
  15678. depth: _depth,
  15679. stencil: _stencil,
  15680. antialias: _antialias,
  15681. premultipliedAlpha: _premultipliedAlpha,
  15682. preserveDrawingBuffer: _preserveDrawingBuffer,
  15683. powerPreference: _powerPreference,
  15684. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15685. };
  15686. // OffscreenCanvas does not have setAttribute, see #22811
  15687. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  15688. // event listeners must be registered before WebGL context is created, see #12753
  15689. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15690. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15691. if ( _gl === null ) {
  15692. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15693. if ( _this.isWebGL1Renderer === true ) {
  15694. contextNames.shift();
  15695. }
  15696. _gl = getContext( contextNames, contextAttributes );
  15697. if ( _gl === null ) {
  15698. if ( getContext( contextNames ) ) {
  15699. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  15700. } else {
  15701. throw new Error( 'Error creating WebGL context.' );
  15702. }
  15703. }
  15704. }
  15705. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15706. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15707. _gl.getShaderPrecisionFormat = function () {
  15708. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15709. };
  15710. }
  15711. } catch ( error ) {
  15712. console.error( 'THREE.WebGLRenderer: ' + error.message );
  15713. throw error;
  15714. }
  15715. let extensions, capabilities, state, info;
  15716. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15717. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15718. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15719. let utils, bindingStates;
  15720. function initGLContext() {
  15721. extensions = new WebGLExtensions( _gl );
  15722. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15723. extensions.init( capabilities );
  15724. utils = new WebGLUtils( _gl, extensions, capabilities );
  15725. state = new WebGLState( _gl, extensions, capabilities );
  15726. info = new WebGLInfo( _gl );
  15727. properties = new WebGLProperties();
  15728. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  15729. cubemaps = new WebGLCubeMaps( _this );
  15730. cubeuvmaps = new WebGLCubeUVMaps( _this );
  15731. attributes = new WebGLAttributes( _gl, capabilities );
  15732. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  15733. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  15734. objects = new WebGLObjects( _gl, geometries, attributes, info );
  15735. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  15736. clipping = new WebGLClipping( properties );
  15737. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  15738. materials = new WebGLMaterials( _this, properties );
  15739. renderLists = new WebGLRenderLists();
  15740. renderStates = new WebGLRenderStates( extensions, capabilities );
  15741. background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
  15742. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  15743. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  15744. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  15745. info.programs = programCache.programs;
  15746. _this.capabilities = capabilities;
  15747. _this.extensions = extensions;
  15748. _this.properties = properties;
  15749. _this.renderLists = renderLists;
  15750. _this.shadowMap = shadowMap;
  15751. _this.state = state;
  15752. _this.info = info;
  15753. }
  15754. initGLContext();
  15755. // xr
  15756. const xr = new WebXRManager( _this, _gl );
  15757. this.xr = xr;
  15758. // API
  15759. this.getContext = function () {
  15760. return _gl;
  15761. };
  15762. this.getContextAttributes = function () {
  15763. return _gl.getContextAttributes();
  15764. };
  15765. this.forceContextLoss = function () {
  15766. const extension = extensions.get( 'WEBGL_lose_context' );
  15767. if ( extension ) extension.loseContext();
  15768. };
  15769. this.forceContextRestore = function () {
  15770. const extension = extensions.get( 'WEBGL_lose_context' );
  15771. if ( extension ) extension.restoreContext();
  15772. };
  15773. this.getPixelRatio = function () {
  15774. return _pixelRatio;
  15775. };
  15776. this.setPixelRatio = function ( value ) {
  15777. if ( value === undefined ) return;
  15778. _pixelRatio = value;
  15779. this.setSize( _width, _height, false );
  15780. };
  15781. this.getSize = function ( target ) {
  15782. return target.set( _width, _height );
  15783. };
  15784. this.setSize = function ( width, height, updateStyle ) {
  15785. if ( xr.isPresenting ) {
  15786. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  15787. return;
  15788. }
  15789. _width = width;
  15790. _height = height;
  15791. _canvas.width = Math.floor( width * _pixelRatio );
  15792. _canvas.height = Math.floor( height * _pixelRatio );
  15793. if ( updateStyle !== false ) {
  15794. _canvas.style.width = width + 'px';
  15795. _canvas.style.height = height + 'px';
  15796. }
  15797. this.setViewport( 0, 0, width, height );
  15798. };
  15799. this.getDrawingBufferSize = function ( target ) {
  15800. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  15801. };
  15802. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  15803. _width = width;
  15804. _height = height;
  15805. _pixelRatio = pixelRatio;
  15806. _canvas.width = Math.floor( width * pixelRatio );
  15807. _canvas.height = Math.floor( height * pixelRatio );
  15808. this.setViewport( 0, 0, width, height );
  15809. };
  15810. this.getCurrentViewport = function ( target ) {
  15811. return target.copy( _currentViewport );
  15812. };
  15813. this.getViewport = function ( target ) {
  15814. return target.copy( _viewport );
  15815. };
  15816. this.setViewport = function ( x, y, width, height ) {
  15817. if ( x.isVector4 ) {
  15818. _viewport.set( x.x, x.y, x.z, x.w );
  15819. } else {
  15820. _viewport.set( x, y, width, height );
  15821. }
  15822. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  15823. };
  15824. this.getScissor = function ( target ) {
  15825. return target.copy( _scissor );
  15826. };
  15827. this.setScissor = function ( x, y, width, height ) {
  15828. if ( x.isVector4 ) {
  15829. _scissor.set( x.x, x.y, x.z, x.w );
  15830. } else {
  15831. _scissor.set( x, y, width, height );
  15832. }
  15833. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  15834. };
  15835. this.getScissorTest = function () {
  15836. return _scissorTest;
  15837. };
  15838. this.setScissorTest = function ( boolean ) {
  15839. state.setScissorTest( _scissorTest = boolean );
  15840. };
  15841. this.setOpaqueSort = function ( method ) {
  15842. _opaqueSort = method;
  15843. };
  15844. this.setTransparentSort = function ( method ) {
  15845. _transparentSort = method;
  15846. };
  15847. // Clearing
  15848. this.getClearColor = function ( target ) {
  15849. return target.copy( background.getClearColor() );
  15850. };
  15851. this.setClearColor = function () {
  15852. background.setClearColor.apply( background, arguments );
  15853. };
  15854. this.getClearAlpha = function () {
  15855. return background.getClearAlpha();
  15856. };
  15857. this.setClearAlpha = function () {
  15858. background.setClearAlpha.apply( background, arguments );
  15859. };
  15860. this.clear = function ( color = true, depth = true, stencil = true ) {
  15861. let bits = 0;
  15862. if ( color ) bits |= 16384;
  15863. if ( depth ) bits |= 256;
  15864. if ( stencil ) bits |= 1024;
  15865. _gl.clear( bits );
  15866. };
  15867. this.clearColor = function () {
  15868. this.clear( true, false, false );
  15869. };
  15870. this.clearDepth = function () {
  15871. this.clear( false, true, false );
  15872. };
  15873. this.clearStencil = function () {
  15874. this.clear( false, false, true );
  15875. };
  15876. //
  15877. this.dispose = function () {
  15878. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  15879. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  15880. renderLists.dispose();
  15881. renderStates.dispose();
  15882. properties.dispose();
  15883. cubemaps.dispose();
  15884. cubeuvmaps.dispose();
  15885. objects.dispose();
  15886. bindingStates.dispose();
  15887. programCache.dispose();
  15888. xr.dispose();
  15889. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  15890. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  15891. if ( _transmissionRenderTarget ) {
  15892. _transmissionRenderTarget.dispose();
  15893. _transmissionRenderTarget = null;
  15894. }
  15895. animation.stop();
  15896. };
  15897. // Events
  15898. function onContextLost( event ) {
  15899. event.preventDefault();
  15900. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  15901. _isContextLost = true;
  15902. }
  15903. function onContextRestore( /* event */ ) {
  15904. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  15905. _isContextLost = false;
  15906. const infoAutoReset = info.autoReset;
  15907. const shadowMapEnabled = shadowMap.enabled;
  15908. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15909. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15910. const shadowMapType = shadowMap.type;
  15911. initGLContext();
  15912. info.autoReset = infoAutoReset;
  15913. shadowMap.enabled = shadowMapEnabled;
  15914. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15915. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15916. shadowMap.type = shadowMapType;
  15917. }
  15918. function onMaterialDispose( event ) {
  15919. const material = event.target;
  15920. material.removeEventListener( 'dispose', onMaterialDispose );
  15921. deallocateMaterial( material );
  15922. }
  15923. // Buffer deallocation
  15924. function deallocateMaterial( material ) {
  15925. releaseMaterialProgramReferences( material );
  15926. properties.remove( material );
  15927. }
  15928. function releaseMaterialProgramReferences( material ) {
  15929. const programs = properties.get( material ).programs;
  15930. if ( programs !== undefined ) {
  15931. programs.forEach( function ( program ) {
  15932. programCache.releaseProgram( program );
  15933. } );
  15934. if ( material.isShaderMaterial ) {
  15935. programCache.releaseShaderCache( material );
  15936. }
  15937. }
  15938. }
  15939. // Buffer rendering
  15940. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15941. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15942. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15943. const program = setProgram( camera, scene, geometry, material, object );
  15944. state.setMaterial( material, frontFaceCW );
  15945. //
  15946. let index = geometry.index;
  15947. const position = geometry.attributes.position;
  15948. //
  15949. if ( index === null ) {
  15950. if ( position === undefined || position.count === 0 ) return;
  15951. } else if ( index.count === 0 ) {
  15952. return;
  15953. }
  15954. //
  15955. let rangeFactor = 1;
  15956. if ( material.wireframe === true ) {
  15957. index = geometries.getWireframeAttribute( geometry );
  15958. rangeFactor = 2;
  15959. }
  15960. bindingStates.setup( object, material, program, geometry, index );
  15961. let attribute;
  15962. let renderer = bufferRenderer;
  15963. if ( index !== null ) {
  15964. attribute = attributes.get( index );
  15965. renderer = indexedBufferRenderer;
  15966. renderer.setIndex( attribute );
  15967. }
  15968. //
  15969. const dataCount = ( index !== null ) ? index.count : position.count;
  15970. const rangeStart = geometry.drawRange.start * rangeFactor;
  15971. const rangeCount = geometry.drawRange.count * rangeFactor;
  15972. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15973. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15974. const drawStart = Math.max( rangeStart, groupStart );
  15975. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15976. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15977. if ( drawCount === 0 ) return;
  15978. //
  15979. if ( object.isMesh ) {
  15980. if ( material.wireframe === true ) {
  15981. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15982. renderer.setMode( 1 );
  15983. } else {
  15984. renderer.setMode( 4 );
  15985. }
  15986. } else if ( object.isLine ) {
  15987. let lineWidth = material.linewidth;
  15988. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15989. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15990. if ( object.isLineSegments ) {
  15991. renderer.setMode( 1 );
  15992. } else if ( object.isLineLoop ) {
  15993. renderer.setMode( 2 );
  15994. } else {
  15995. renderer.setMode( 3 );
  15996. }
  15997. } else if ( object.isPoints ) {
  15998. renderer.setMode( 0 );
  15999. } else if ( object.isSprite ) {
  16000. renderer.setMode( 4 );
  16001. }
  16002. if ( object.isInstancedMesh ) {
  16003. renderer.renderInstances( drawStart, drawCount, object.count );
  16004. } else if ( geometry.isInstancedBufferGeometry ) {
  16005. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  16006. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16007. } else {
  16008. renderer.render( drawStart, drawCount );
  16009. }
  16010. };
  16011. // Compile
  16012. this.compile = function ( scene, camera ) {
  16013. currentRenderState = renderStates.get( scene );
  16014. currentRenderState.init();
  16015. renderStateStack.push( currentRenderState );
  16016. scene.traverseVisible( function ( object ) {
  16017. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16018. currentRenderState.pushLight( object );
  16019. if ( object.castShadow ) {
  16020. currentRenderState.pushShadow( object );
  16021. }
  16022. }
  16023. } );
  16024. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16025. scene.traverse( function ( object ) {
  16026. const material = object.material;
  16027. if ( material ) {
  16028. if ( Array.isArray( material ) ) {
  16029. for ( let i = 0; i < material.length; i ++ ) {
  16030. const material2 = material[ i ];
  16031. getProgram( material2, scene, object );
  16032. }
  16033. } else {
  16034. getProgram( material, scene, object );
  16035. }
  16036. }
  16037. } );
  16038. renderStateStack.pop();
  16039. currentRenderState = null;
  16040. };
  16041. // Animation Loop
  16042. let onAnimationFrameCallback = null;
  16043. function onAnimationFrame( time ) {
  16044. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16045. }
  16046. function onXRSessionStart() {
  16047. animation.stop();
  16048. }
  16049. function onXRSessionEnd() {
  16050. animation.start();
  16051. }
  16052. const animation = new WebGLAnimation();
  16053. animation.setAnimationLoop( onAnimationFrame );
  16054. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16055. this.setAnimationLoop = function ( callback ) {
  16056. onAnimationFrameCallback = callback;
  16057. xr.setAnimationLoop( callback );
  16058. ( callback === null ) ? animation.stop() : animation.start();
  16059. };
  16060. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16061. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16062. // Rendering
  16063. this.render = function ( scene, camera ) {
  16064. if ( camera !== undefined && camera.isCamera !== true ) {
  16065. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16066. return;
  16067. }
  16068. if ( _isContextLost === true ) return;
  16069. // update scene graph
  16070. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16071. // update camera matrices and frustum
  16072. if ( camera.parent === null ) camera.updateMatrixWorld();
  16073. if ( xr.enabled === true && xr.isPresenting === true ) {
  16074. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16075. camera = xr.getCamera(); // use XR camera for rendering
  16076. }
  16077. //
  16078. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16079. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16080. currentRenderState.init();
  16081. renderStateStack.push( currentRenderState );
  16082. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16083. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16084. _localClippingEnabled = this.localClippingEnabled;
  16085. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16086. currentRenderList = renderLists.get( scene, renderListStack.length );
  16087. currentRenderList.init();
  16088. renderListStack.push( currentRenderList );
  16089. projectObject( scene, camera, 0, _this.sortObjects );
  16090. currentRenderList.finish();
  16091. if ( _this.sortObjects === true ) {
  16092. currentRenderList.sort( _opaqueSort, _transparentSort );
  16093. }
  16094. //
  16095. if ( _clippingEnabled === true ) clipping.beginShadows();
  16096. const shadowsArray = currentRenderState.state.shadowsArray;
  16097. shadowMap.render( shadowsArray, scene, camera );
  16098. if ( _clippingEnabled === true ) clipping.endShadows();
  16099. //
  16100. if ( this.info.autoReset === true ) this.info.reset();
  16101. //
  16102. background.render( currentRenderList, scene );
  16103. // render scene
  16104. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16105. if ( camera.isArrayCamera ) {
  16106. const cameras = camera.cameras;
  16107. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16108. const camera2 = cameras[ i ];
  16109. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16110. }
  16111. } else {
  16112. renderScene( currentRenderList, scene, camera );
  16113. }
  16114. //
  16115. if ( _currentRenderTarget !== null ) {
  16116. // resolve multisample renderbuffers to a single-sample texture if necessary
  16117. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16118. // Generate mipmap if we're using any kind of mipmap filtering
  16119. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16120. }
  16121. //
  16122. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16123. // _gl.finish();
  16124. bindingStates.resetDefaultState();
  16125. _currentMaterialId = - 1;
  16126. _currentCamera = null;
  16127. renderStateStack.pop();
  16128. if ( renderStateStack.length > 0 ) {
  16129. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16130. } else {
  16131. currentRenderState = null;
  16132. }
  16133. renderListStack.pop();
  16134. if ( renderListStack.length > 0 ) {
  16135. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16136. } else {
  16137. currentRenderList = null;
  16138. }
  16139. };
  16140. function projectObject( object, camera, groupOrder, sortObjects ) {
  16141. if ( object.visible === false ) return;
  16142. const visible = object.layers.test( camera.layers );
  16143. if ( visible ) {
  16144. if ( object.isGroup ) {
  16145. groupOrder = object.renderOrder;
  16146. } else if ( object.isLOD ) {
  16147. if ( object.autoUpdate === true ) object.update( camera );
  16148. } else if ( object.isLight ) {
  16149. currentRenderState.pushLight( object );
  16150. if ( object.castShadow ) {
  16151. currentRenderState.pushShadow( object );
  16152. }
  16153. } else if ( object.isSprite ) {
  16154. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16155. if ( sortObjects ) {
  16156. _vector3.setFromMatrixPosition( object.matrixWorld )
  16157. .applyMatrix4( _projScreenMatrix );
  16158. }
  16159. const geometry = objects.update( object );
  16160. const material = object.material;
  16161. if ( material.visible ) {
  16162. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16163. }
  16164. }
  16165. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16166. if ( object.isSkinnedMesh ) {
  16167. // update skeleton only once in a frame
  16168. if ( object.skeleton.frame !== info.render.frame ) {
  16169. object.skeleton.update();
  16170. object.skeleton.frame = info.render.frame;
  16171. }
  16172. }
  16173. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16174. if ( sortObjects ) {
  16175. _vector3.setFromMatrixPosition( object.matrixWorld )
  16176. .applyMatrix4( _projScreenMatrix );
  16177. }
  16178. const geometry = objects.update( object );
  16179. const material = object.material;
  16180. if ( Array.isArray( material ) ) {
  16181. const groups = geometry.groups;
  16182. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16183. const group = groups[ i ];
  16184. const groupMaterial = material[ group.materialIndex ];
  16185. if ( groupMaterial && groupMaterial.visible ) {
  16186. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16187. }
  16188. }
  16189. } else if ( material.visible ) {
  16190. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16191. }
  16192. }
  16193. }
  16194. }
  16195. const children = object.children;
  16196. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16197. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16198. }
  16199. }
  16200. function renderScene( currentRenderList, scene, camera, viewport ) {
  16201. const opaqueObjects = currentRenderList.opaque;
  16202. const transmissiveObjects = currentRenderList.transmissive;
  16203. const transparentObjects = currentRenderList.transparent;
  16204. currentRenderState.setupLightsView( camera );
  16205. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16206. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16207. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16208. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16209. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16210. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16211. state.buffers.depth.setTest( true );
  16212. state.buffers.depth.setMask( true );
  16213. state.buffers.color.setMask( true );
  16214. state.setPolygonOffset( false );
  16215. }
  16216. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16217. const isWebGL2 = capabilities.isWebGL2;
  16218. if ( _transmissionRenderTarget === null ) {
  16219. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16220. generateMipmaps: true,
  16221. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16222. minFilter: LinearMipmapLinearFilter,
  16223. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16224. } );
  16225. }
  16226. _this.getDrawingBufferSize( _vector2 );
  16227. if ( isWebGL2 ) {
  16228. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16229. } else {
  16230. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16231. }
  16232. //
  16233. const currentRenderTarget = _this.getRenderTarget();
  16234. _this.setRenderTarget( _transmissionRenderTarget );
  16235. _this.clear();
  16236. // Turn off the features which can affect the frag color for opaque objects pass.
  16237. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16238. const currentToneMapping = _this.toneMapping;
  16239. _this.toneMapping = NoToneMapping;
  16240. renderObjects( opaqueObjects, scene, camera );
  16241. _this.toneMapping = currentToneMapping;
  16242. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16243. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16244. _this.setRenderTarget( currentRenderTarget );
  16245. }
  16246. function renderObjects( renderList, scene, camera ) {
  16247. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16248. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16249. const renderItem = renderList[ i ];
  16250. const object = renderItem.object;
  16251. const geometry = renderItem.geometry;
  16252. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16253. const group = renderItem.group;
  16254. if ( object.layers.test( camera.layers ) ) {
  16255. renderObject( object, scene, camera, geometry, material, group );
  16256. }
  16257. }
  16258. }
  16259. function renderObject( object, scene, camera, geometry, material, group ) {
  16260. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16261. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16262. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16263. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16264. if ( material.transparent === true && material.side === DoubleSide ) {
  16265. material.side = BackSide;
  16266. material.needsUpdate = true;
  16267. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16268. material.side = FrontSide;
  16269. material.needsUpdate = true;
  16270. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16271. material.side = DoubleSide;
  16272. } else {
  16273. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16274. }
  16275. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16276. }
  16277. function getProgram( material, scene, object ) {
  16278. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16279. const materialProperties = properties.get( material );
  16280. const lights = currentRenderState.state.lights;
  16281. const shadowsArray = currentRenderState.state.shadowsArray;
  16282. const lightsStateVersion = lights.state.version;
  16283. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16284. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16285. let programs = materialProperties.programs;
  16286. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16287. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16288. materialProperties.fog = scene.fog;
  16289. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16290. if ( programs === undefined ) {
  16291. // new material
  16292. material.addEventListener( 'dispose', onMaterialDispose );
  16293. programs = new Map();
  16294. materialProperties.programs = programs;
  16295. }
  16296. let program = programs.get( programCacheKey );
  16297. if ( program !== undefined ) {
  16298. // early out if program and light state is identical
  16299. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16300. updateCommonMaterialProperties( material, parameters );
  16301. return program;
  16302. }
  16303. } else {
  16304. parameters.uniforms = programCache.getUniforms( material );
  16305. material.onBuild( object, parameters, _this );
  16306. material.onBeforeCompile( parameters, _this );
  16307. program = programCache.acquireProgram( parameters, programCacheKey );
  16308. programs.set( programCacheKey, program );
  16309. materialProperties.uniforms = parameters.uniforms;
  16310. }
  16311. const uniforms = materialProperties.uniforms;
  16312. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16313. uniforms.clippingPlanes = clipping.uniform;
  16314. }
  16315. updateCommonMaterialProperties( material, parameters );
  16316. // store the light setup it was created for
  16317. materialProperties.needsLights = materialNeedsLights( material );
  16318. materialProperties.lightsStateVersion = lightsStateVersion;
  16319. if ( materialProperties.needsLights ) {
  16320. // wire up the material to this renderer's lighting state
  16321. uniforms.ambientLightColor.value = lights.state.ambient;
  16322. uniforms.lightProbe.value = lights.state.probe;
  16323. uniforms.directionalLights.value = lights.state.directional;
  16324. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16325. uniforms.spotLights.value = lights.state.spot;
  16326. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16327. uniforms.rectAreaLights.value = lights.state.rectArea;
  16328. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16329. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16330. uniforms.pointLights.value = lights.state.point;
  16331. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16332. uniforms.hemisphereLights.value = lights.state.hemi;
  16333. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16334. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16335. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16336. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16337. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16338. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16339. // TODO (abelnation): add area lights shadow info to uniforms
  16340. }
  16341. const progUniforms = program.getUniforms();
  16342. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16343. materialProperties.currentProgram = program;
  16344. materialProperties.uniformsList = uniformsList;
  16345. return program;
  16346. }
  16347. function updateCommonMaterialProperties( material, parameters ) {
  16348. const materialProperties = properties.get( material );
  16349. materialProperties.outputEncoding = parameters.outputEncoding;
  16350. materialProperties.instancing = parameters.instancing;
  16351. materialProperties.skinning = parameters.skinning;
  16352. materialProperties.morphTargets = parameters.morphTargets;
  16353. materialProperties.morphNormals = parameters.morphNormals;
  16354. materialProperties.morphColors = parameters.morphColors;
  16355. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16356. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16357. materialProperties.numIntersection = parameters.numClipIntersection;
  16358. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16359. materialProperties.vertexTangents = parameters.vertexTangents;
  16360. materialProperties.toneMapping = parameters.toneMapping;
  16361. }
  16362. function setProgram( camera, scene, geometry, material, object ) {
  16363. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16364. textures.resetTextureUnits();
  16365. const fog = scene.fog;
  16366. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16367. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16368. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16369. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16370. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16371. const morphTargets = !! geometry.morphAttributes.position;
  16372. const morphNormals = !! geometry.morphAttributes.normal;
  16373. const morphColors = !! geometry.morphAttributes.color;
  16374. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16375. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16376. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16377. const materialProperties = properties.get( material );
  16378. const lights = currentRenderState.state.lights;
  16379. if ( _clippingEnabled === true ) {
  16380. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16381. const useCache =
  16382. camera === _currentCamera &&
  16383. material.id === _currentMaterialId;
  16384. // we might want to call this function with some ClippingGroup
  16385. // object instead of the material, once it becomes feasible
  16386. // (#8465, #8379)
  16387. clipping.setState( material, camera, useCache );
  16388. }
  16389. }
  16390. //
  16391. let needsProgramChange = false;
  16392. if ( material.version === materialProperties.__version ) {
  16393. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16394. needsProgramChange = true;
  16395. } else if ( materialProperties.outputEncoding !== encoding ) {
  16396. needsProgramChange = true;
  16397. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16398. needsProgramChange = true;
  16399. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16400. needsProgramChange = true;
  16401. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16402. needsProgramChange = true;
  16403. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16404. needsProgramChange = true;
  16405. } else if ( materialProperties.envMap !== envMap ) {
  16406. needsProgramChange = true;
  16407. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16408. needsProgramChange = true;
  16409. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16410. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16411. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16412. needsProgramChange = true;
  16413. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16414. needsProgramChange = true;
  16415. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16416. needsProgramChange = true;
  16417. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16418. needsProgramChange = true;
  16419. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16420. needsProgramChange = true;
  16421. } else if ( materialProperties.morphColors !== morphColors ) {
  16422. needsProgramChange = true;
  16423. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16424. needsProgramChange = true;
  16425. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16426. needsProgramChange = true;
  16427. }
  16428. } else {
  16429. needsProgramChange = true;
  16430. materialProperties.__version = material.version;
  16431. }
  16432. //
  16433. let program = materialProperties.currentProgram;
  16434. if ( needsProgramChange === true ) {
  16435. program = getProgram( material, scene, object );
  16436. }
  16437. let refreshProgram = false;
  16438. let refreshMaterial = false;
  16439. let refreshLights = false;
  16440. const p_uniforms = program.getUniforms(),
  16441. m_uniforms = materialProperties.uniforms;
  16442. if ( state.useProgram( program.program ) ) {
  16443. refreshProgram = true;
  16444. refreshMaterial = true;
  16445. refreshLights = true;
  16446. }
  16447. if ( material.id !== _currentMaterialId ) {
  16448. _currentMaterialId = material.id;
  16449. refreshMaterial = true;
  16450. }
  16451. if ( refreshProgram || _currentCamera !== camera ) {
  16452. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16453. if ( capabilities.logarithmicDepthBuffer ) {
  16454. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16455. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16456. }
  16457. if ( _currentCamera !== camera ) {
  16458. _currentCamera = camera;
  16459. // lighting uniforms depend on the camera so enforce an update
  16460. // now, in case this material supports lights - or later, when
  16461. // the next material that does gets activated:
  16462. refreshMaterial = true; // set to true on material change
  16463. refreshLights = true; // remains set until update done
  16464. }
  16465. // load material specific uniforms
  16466. // (shader material also gets them for the sake of genericity)
  16467. if ( material.isShaderMaterial ||
  16468. material.isMeshPhongMaterial ||
  16469. material.isMeshToonMaterial ||
  16470. material.isMeshStandardMaterial ||
  16471. material.envMap ) {
  16472. const uCamPos = p_uniforms.map.cameraPosition;
  16473. if ( uCamPos !== undefined ) {
  16474. uCamPos.setValue( _gl,
  16475. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16476. }
  16477. }
  16478. if ( material.isMeshPhongMaterial ||
  16479. material.isMeshToonMaterial ||
  16480. material.isMeshLambertMaterial ||
  16481. material.isMeshBasicMaterial ||
  16482. material.isMeshStandardMaterial ||
  16483. material.isShaderMaterial ) {
  16484. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  16485. }
  16486. if ( material.isMeshPhongMaterial ||
  16487. material.isMeshToonMaterial ||
  16488. material.isMeshLambertMaterial ||
  16489. material.isMeshBasicMaterial ||
  16490. material.isMeshStandardMaterial ||
  16491. material.isShaderMaterial ||
  16492. material.isShadowMaterial ||
  16493. object.isSkinnedMesh ) {
  16494. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16495. }
  16496. }
  16497. // skinning and morph target uniforms must be set even if material didn't change
  16498. // auto-setting of texture unit for bone and morph texture must go before other textures
  16499. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16500. if ( object.isSkinnedMesh ) {
  16501. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16502. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16503. const skeleton = object.skeleton;
  16504. if ( skeleton ) {
  16505. if ( capabilities.floatVertexTextures ) {
  16506. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  16507. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  16508. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  16509. } else {
  16510. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  16511. }
  16512. }
  16513. }
  16514. const morphAttributes = geometry.morphAttributes;
  16515. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  16516. morphtargets.update( object, geometry, material, program );
  16517. }
  16518. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  16519. materialProperties.receiveShadow = object.receiveShadow;
  16520. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  16521. }
  16522. if ( refreshMaterial ) {
  16523. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  16524. if ( materialProperties.needsLights ) {
  16525. // the current material requires lighting info
  16526. // note: all lighting uniforms are always set correctly
  16527. // they simply reference the renderer's state for their
  16528. // values
  16529. //
  16530. // use the current material's .needsUpdate flags to set
  16531. // the GL state when required
  16532. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16533. }
  16534. // refresh uniforms common to several materials
  16535. if ( fog && material.fog === true ) {
  16536. materials.refreshFogUniforms( m_uniforms, fog );
  16537. }
  16538. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  16539. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16540. }
  16541. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  16542. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16543. material.uniformsNeedUpdate = false;
  16544. }
  16545. if ( material.isSpriteMaterial ) {
  16546. p_uniforms.setValue( _gl, 'center', object.center );
  16547. }
  16548. // common matrices
  16549. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  16550. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  16551. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16552. return program;
  16553. }
  16554. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16555. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  16556. uniforms.ambientLightColor.needsUpdate = value;
  16557. uniforms.lightProbe.needsUpdate = value;
  16558. uniforms.directionalLights.needsUpdate = value;
  16559. uniforms.directionalLightShadows.needsUpdate = value;
  16560. uniforms.pointLights.needsUpdate = value;
  16561. uniforms.pointLightShadows.needsUpdate = value;
  16562. uniforms.spotLights.needsUpdate = value;
  16563. uniforms.spotLightShadows.needsUpdate = value;
  16564. uniforms.rectAreaLights.needsUpdate = value;
  16565. uniforms.hemisphereLights.needsUpdate = value;
  16566. }
  16567. function materialNeedsLights( material ) {
  16568. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  16569. material.isMeshStandardMaterial || material.isShadowMaterial ||
  16570. ( material.isShaderMaterial && material.lights === true );
  16571. }
  16572. this.getActiveCubeFace = function () {
  16573. return _currentActiveCubeFace;
  16574. };
  16575. this.getActiveMipmapLevel = function () {
  16576. return _currentActiveMipmapLevel;
  16577. };
  16578. this.getRenderTarget = function () {
  16579. return _currentRenderTarget;
  16580. };
  16581. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  16582. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  16583. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  16584. const renderTargetProperties = properties.get( renderTarget );
  16585. renderTargetProperties.__hasExternalTextures = true;
  16586. if ( renderTargetProperties.__hasExternalTextures ) {
  16587. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16588. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  16589. // The multisample_render_to_texture extension doesn't work properly if there
  16590. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16591. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  16592. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  16593. renderTargetProperties.__useRenderToTexture = false;
  16594. }
  16595. }
  16596. }
  16597. };
  16598. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  16599. const renderTargetProperties = properties.get( renderTarget );
  16600. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16601. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16602. };
  16603. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16604. _currentRenderTarget = renderTarget;
  16605. _currentActiveCubeFace = activeCubeFace;
  16606. _currentActiveMipmapLevel = activeMipmapLevel;
  16607. let useDefaultFramebuffer = true;
  16608. if ( renderTarget ) {
  16609. const renderTargetProperties = properties.get( renderTarget );
  16610. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  16611. // We need to make sure to rebind the framebuffer.
  16612. state.bindFramebuffer( 36160, null );
  16613. useDefaultFramebuffer = false;
  16614. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  16615. textures.setupRenderTarget( renderTarget );
  16616. } else if ( renderTargetProperties.__hasExternalTextures ) {
  16617. // Color and depth texture must be rebound in order for the swapchain to update.
  16618. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  16619. }
  16620. }
  16621. let framebuffer = null;
  16622. let isCube = false;
  16623. let isRenderTarget3D = false;
  16624. if ( renderTarget ) {
  16625. const texture = renderTarget.texture;
  16626. if ( texture.isData3DTexture || texture.isDataArrayTexture ) {
  16627. isRenderTarget3D = true;
  16628. }
  16629. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16630. if ( renderTarget.isWebGLCubeRenderTarget ) {
  16631. framebuffer = __webglFramebuffer[ activeCubeFace ];
  16632. isCube = true;
  16633. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  16634. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  16635. } else {
  16636. framebuffer = __webglFramebuffer;
  16637. }
  16638. _currentViewport.copy( renderTarget.viewport );
  16639. _currentScissor.copy( renderTarget.scissor );
  16640. _currentScissorTest = renderTarget.scissorTest;
  16641. } else {
  16642. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16643. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16644. _currentScissorTest = _scissorTest;
  16645. }
  16646. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16647. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  16648. state.drawBuffers( renderTarget, framebuffer );
  16649. }
  16650. state.viewport( _currentViewport );
  16651. state.scissor( _currentScissor );
  16652. state.setScissorTest( _currentScissorTest );
  16653. if ( isCube ) {
  16654. const textureProperties = properties.get( renderTarget.texture );
  16655. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16656. } else if ( isRenderTarget3D ) {
  16657. const textureProperties = properties.get( renderTarget.texture );
  16658. const layer = activeCubeFace || 0;
  16659. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16660. }
  16661. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  16662. };
  16663. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  16664. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  16665. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16666. return;
  16667. }
  16668. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16669. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  16670. framebuffer = framebuffer[ activeCubeFaceIndex ];
  16671. }
  16672. if ( framebuffer ) {
  16673. state.bindFramebuffer( 36160, framebuffer );
  16674. try {
  16675. const texture = renderTarget.texture;
  16676. const textureFormat = texture.format;
  16677. const textureType = texture.type;
  16678. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  16679. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16680. return;
  16681. }
  16682. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  16683. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  16684. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16685. ! halfFloatSupportedByExt ) {
  16686. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16687. return;
  16688. }
  16689. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16690. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16691. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  16692. }
  16693. } finally {
  16694. // restore framebuffer of current render target if necessary
  16695. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  16696. state.bindFramebuffer( 36160, framebuffer );
  16697. }
  16698. }
  16699. };
  16700. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  16701. if ( texture.isFramebufferTexture !== true ) {
  16702. console.error( 'THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.' );
  16703. return;
  16704. }
  16705. const levelScale = Math.pow( 2, - level );
  16706. const width = Math.floor( texture.image.width * levelScale );
  16707. const height = Math.floor( texture.image.height * levelScale );
  16708. textures.setTexture2D( texture, 0 );
  16709. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  16710. state.unbindTexture();
  16711. };
  16712. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  16713. const width = srcTexture.image.width;
  16714. const height = srcTexture.image.height;
  16715. const glFormat = utils.convert( dstTexture.format );
  16716. const glType = utils.convert( dstTexture.type );
  16717. textures.setTexture2D( dstTexture, 0 );
  16718. // As another texture upload may have changed pixelStorei
  16719. // parameters, make sure they are correct for the dstTexture
  16720. _gl.pixelStorei( 37440, dstTexture.flipY );
  16721. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16722. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16723. if ( srcTexture.isDataTexture ) {
  16724. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  16725. } else {
  16726. if ( srcTexture.isCompressedTexture ) {
  16727. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  16728. } else {
  16729. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  16730. }
  16731. }
  16732. // Generate mipmaps only when copying level 0
  16733. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  16734. state.unbindTexture();
  16735. };
  16736. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  16737. if ( _this.isWebGL1Renderer ) {
  16738. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  16739. return;
  16740. }
  16741. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16742. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16743. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16744. const glFormat = utils.convert( dstTexture.format );
  16745. const glType = utils.convert( dstTexture.type );
  16746. let glTarget;
  16747. if ( dstTexture.isData3DTexture ) {
  16748. textures.setTexture3D( dstTexture, 0 );
  16749. glTarget = 32879;
  16750. } else if ( dstTexture.isDataArrayTexture ) {
  16751. textures.setTexture2DArray( dstTexture, 0 );
  16752. glTarget = 35866;
  16753. } else {
  16754. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  16755. return;
  16756. }
  16757. _gl.pixelStorei( 37440, dstTexture.flipY );
  16758. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16759. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16760. const unpackRowLen = _gl.getParameter( 3314 );
  16761. const unpackImageHeight = _gl.getParameter( 32878 );
  16762. const unpackSkipPixels = _gl.getParameter( 3316 );
  16763. const unpackSkipRows = _gl.getParameter( 3315 );
  16764. const unpackSkipImages = _gl.getParameter( 32877 );
  16765. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  16766. _gl.pixelStorei( 3314, image.width );
  16767. _gl.pixelStorei( 32878, image.height );
  16768. _gl.pixelStorei( 3316, sourceBox.min.x );
  16769. _gl.pixelStorei( 3315, sourceBox.min.y );
  16770. _gl.pixelStorei( 32877, sourceBox.min.z );
  16771. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  16772. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  16773. } else {
  16774. if ( srcTexture.isCompressedTexture ) {
  16775. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  16776. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  16777. } else {
  16778. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  16779. }
  16780. }
  16781. _gl.pixelStorei( 3314, unpackRowLen );
  16782. _gl.pixelStorei( 32878, unpackImageHeight );
  16783. _gl.pixelStorei( 3316, unpackSkipPixels );
  16784. _gl.pixelStorei( 3315, unpackSkipRows );
  16785. _gl.pixelStorei( 32877, unpackSkipImages );
  16786. // Generate mipmaps only when copying level 0
  16787. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  16788. state.unbindTexture();
  16789. };
  16790. this.initTexture = function ( texture ) {
  16791. textures.setTexture2D( texture, 0 );
  16792. state.unbindTexture();
  16793. };
  16794. this.resetState = function () {
  16795. _currentActiveCubeFace = 0;
  16796. _currentActiveMipmapLevel = 0;
  16797. _currentRenderTarget = null;
  16798. state.reset();
  16799. bindingStates.reset();
  16800. };
  16801. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16802. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  16803. }
  16804. }
  16805. WebGLRenderer.prototype.isWebGLRenderer = true;
  16806. class WebGL1Renderer extends WebGLRenderer {}
  16807. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16808. class FogExp2 {
  16809. constructor( color, density = 0.00025 ) {
  16810. this.name = '';
  16811. this.color = new Color( color );
  16812. this.density = density;
  16813. }
  16814. clone() {
  16815. return new FogExp2( this.color, this.density );
  16816. }
  16817. toJSON( /* meta */ ) {
  16818. return {
  16819. type: 'FogExp2',
  16820. color: this.color.getHex(),
  16821. density: this.density
  16822. };
  16823. }
  16824. }
  16825. FogExp2.prototype.isFogExp2 = true;
  16826. class Fog {
  16827. constructor( color, near = 1, far = 1000 ) {
  16828. this.name = '';
  16829. this.color = new Color( color );
  16830. this.near = near;
  16831. this.far = far;
  16832. }
  16833. clone() {
  16834. return new Fog( this.color, this.near, this.far );
  16835. }
  16836. toJSON( /* meta */ ) {
  16837. return {
  16838. type: 'Fog',
  16839. color: this.color.getHex(),
  16840. near: this.near,
  16841. far: this.far
  16842. };
  16843. }
  16844. }
  16845. Fog.prototype.isFog = true;
  16846. class Scene extends Object3D {
  16847. constructor() {
  16848. super();
  16849. this.type = 'Scene';
  16850. this.background = null;
  16851. this.environment = null;
  16852. this.fog = null;
  16853. this.overrideMaterial = null;
  16854. this.autoUpdate = true; // checked by the renderer
  16855. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16856. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  16857. }
  16858. }
  16859. copy( source, recursive ) {
  16860. super.copy( source, recursive );
  16861. if ( source.background !== null ) this.background = source.background.clone();
  16862. if ( source.environment !== null ) this.environment = source.environment.clone();
  16863. if ( source.fog !== null ) this.fog = source.fog.clone();
  16864. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16865. this.autoUpdate = source.autoUpdate;
  16866. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16867. return this;
  16868. }
  16869. toJSON( meta ) {
  16870. const data = super.toJSON( meta );
  16871. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16872. return data;
  16873. }
  16874. }
  16875. Scene.prototype.isScene = true;
  16876. class InterleavedBuffer {
  16877. constructor( array, stride ) {
  16878. this.array = array;
  16879. this.stride = stride;
  16880. this.count = array !== undefined ? array.length / stride : 0;
  16881. this.usage = StaticDrawUsage;
  16882. this.updateRange = { offset: 0, count: - 1 };
  16883. this.version = 0;
  16884. this.uuid = generateUUID();
  16885. }
  16886. onUploadCallback() {}
  16887. set needsUpdate( value ) {
  16888. if ( value === true ) this.version ++;
  16889. }
  16890. setUsage( value ) {
  16891. this.usage = value;
  16892. return this;
  16893. }
  16894. copy( source ) {
  16895. this.array = new source.array.constructor( source.array );
  16896. this.count = source.count;
  16897. this.stride = source.stride;
  16898. this.usage = source.usage;
  16899. return this;
  16900. }
  16901. copyAt( index1, attribute, index2 ) {
  16902. index1 *= this.stride;
  16903. index2 *= attribute.stride;
  16904. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  16905. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  16906. }
  16907. return this;
  16908. }
  16909. set( value, offset = 0 ) {
  16910. this.array.set( value, offset );
  16911. return this;
  16912. }
  16913. clone( data ) {
  16914. if ( data.arrayBuffers === undefined ) {
  16915. data.arrayBuffers = {};
  16916. }
  16917. if ( this.array.buffer._uuid === undefined ) {
  16918. this.array.buffer._uuid = generateUUID();
  16919. }
  16920. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16921. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  16922. }
  16923. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  16924. const ib = new this.constructor( array, this.stride );
  16925. ib.setUsage( this.usage );
  16926. return ib;
  16927. }
  16928. onUpload( callback ) {
  16929. this.onUploadCallback = callback;
  16930. return this;
  16931. }
  16932. toJSON( data ) {
  16933. if ( data.arrayBuffers === undefined ) {
  16934. data.arrayBuffers = {};
  16935. }
  16936. // generate UUID for array buffer if necessary
  16937. if ( this.array.buffer._uuid === undefined ) {
  16938. this.array.buffer._uuid = generateUUID();
  16939. }
  16940. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16941. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  16942. }
  16943. //
  16944. return {
  16945. uuid: this.uuid,
  16946. buffer: this.array.buffer._uuid,
  16947. type: this.array.constructor.name,
  16948. stride: this.stride
  16949. };
  16950. }
  16951. }
  16952. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16953. const _vector$6 = /*@__PURE__*/ new Vector3();
  16954. class InterleavedBufferAttribute {
  16955. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  16956. this.name = '';
  16957. this.data = interleavedBuffer;
  16958. this.itemSize = itemSize;
  16959. this.offset = offset;
  16960. this.normalized = normalized === true;
  16961. }
  16962. get count() {
  16963. return this.data.count;
  16964. }
  16965. get array() {
  16966. return this.data.array;
  16967. }
  16968. set needsUpdate( value ) {
  16969. this.data.needsUpdate = value;
  16970. }
  16971. applyMatrix4( m ) {
  16972. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  16973. _vector$6.fromBufferAttribute( this, i );
  16974. _vector$6.applyMatrix4( m );
  16975. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16976. }
  16977. return this;
  16978. }
  16979. applyNormalMatrix( m ) {
  16980. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16981. _vector$6.fromBufferAttribute( this, i );
  16982. _vector$6.applyNormalMatrix( m );
  16983. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16984. }
  16985. return this;
  16986. }
  16987. transformDirection( m ) {
  16988. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16989. _vector$6.fromBufferAttribute( this, i );
  16990. _vector$6.transformDirection( m );
  16991. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16992. }
  16993. return this;
  16994. }
  16995. setX( index, x ) {
  16996. this.data.array[ index * this.data.stride + this.offset ] = x;
  16997. return this;
  16998. }
  16999. setY( index, y ) {
  17000. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17001. return this;
  17002. }
  17003. setZ( index, z ) {
  17004. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17005. return this;
  17006. }
  17007. setW( index, w ) {
  17008. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17009. return this;
  17010. }
  17011. getX( index ) {
  17012. return this.data.array[ index * this.data.stride + this.offset ];
  17013. }
  17014. getY( index ) {
  17015. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  17016. }
  17017. getZ( index ) {
  17018. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  17019. }
  17020. getW( index ) {
  17021. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  17022. }
  17023. setXY( index, x, y ) {
  17024. index = index * this.data.stride + this.offset;
  17025. this.data.array[ index + 0 ] = x;
  17026. this.data.array[ index + 1 ] = y;
  17027. return this;
  17028. }
  17029. setXYZ( index, x, y, z ) {
  17030. index = index * this.data.stride + this.offset;
  17031. this.data.array[ index + 0 ] = x;
  17032. this.data.array[ index + 1 ] = y;
  17033. this.data.array[ index + 2 ] = z;
  17034. return this;
  17035. }
  17036. setXYZW( index, x, y, z, w ) {
  17037. index = index * this.data.stride + this.offset;
  17038. this.data.array[ index + 0 ] = x;
  17039. this.data.array[ index + 1 ] = y;
  17040. this.data.array[ index + 2 ] = z;
  17041. this.data.array[ index + 3 ] = w;
  17042. return this;
  17043. }
  17044. clone( data ) {
  17045. if ( data === undefined ) {
  17046. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  17047. const array = [];
  17048. for ( let i = 0; i < this.count; i ++ ) {
  17049. const index = i * this.data.stride + this.offset;
  17050. for ( let j = 0; j < this.itemSize; j ++ ) {
  17051. array.push( this.data.array[ index + j ] );
  17052. }
  17053. }
  17054. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17055. } else {
  17056. if ( data.interleavedBuffers === undefined ) {
  17057. data.interleavedBuffers = {};
  17058. }
  17059. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17060. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17061. }
  17062. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17063. }
  17064. }
  17065. toJSON( data ) {
  17066. if ( data === undefined ) {
  17067. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  17068. const array = [];
  17069. for ( let i = 0; i < this.count; i ++ ) {
  17070. const index = i * this.data.stride + this.offset;
  17071. for ( let j = 0; j < this.itemSize; j ++ ) {
  17072. array.push( this.data.array[ index + j ] );
  17073. }
  17074. }
  17075. // deinterleave data and save it as an ordinary buffer attribute for now
  17076. return {
  17077. itemSize: this.itemSize,
  17078. type: this.array.constructor.name,
  17079. array: array,
  17080. normalized: this.normalized
  17081. };
  17082. } else {
  17083. // save as true interlaved attribtue
  17084. if ( data.interleavedBuffers === undefined ) {
  17085. data.interleavedBuffers = {};
  17086. }
  17087. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17088. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17089. }
  17090. return {
  17091. isInterleavedBufferAttribute: true,
  17092. itemSize: this.itemSize,
  17093. data: this.data.uuid,
  17094. offset: this.offset,
  17095. normalized: this.normalized
  17096. };
  17097. }
  17098. }
  17099. }
  17100. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  17101. class SpriteMaterial extends Material {
  17102. constructor( parameters ) {
  17103. super();
  17104. this.type = 'SpriteMaterial';
  17105. this.color = new Color( 0xffffff );
  17106. this.map = null;
  17107. this.alphaMap = null;
  17108. this.rotation = 0;
  17109. this.sizeAttenuation = true;
  17110. this.transparent = true;
  17111. this.fog = true;
  17112. this.setValues( parameters );
  17113. }
  17114. copy( source ) {
  17115. super.copy( source );
  17116. this.color.copy( source.color );
  17117. this.map = source.map;
  17118. this.alphaMap = source.alphaMap;
  17119. this.rotation = source.rotation;
  17120. this.sizeAttenuation = source.sizeAttenuation;
  17121. this.fog = source.fog;
  17122. return this;
  17123. }
  17124. }
  17125. SpriteMaterial.prototype.isSpriteMaterial = true;
  17126. let _geometry;
  17127. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17128. const _worldScale = /*@__PURE__*/ new Vector3();
  17129. const _mvPosition = /*@__PURE__*/ new Vector3();
  17130. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17131. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17132. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17133. const _vA = /*@__PURE__*/ new Vector3();
  17134. const _vB = /*@__PURE__*/ new Vector3();
  17135. const _vC = /*@__PURE__*/ new Vector3();
  17136. const _uvA = /*@__PURE__*/ new Vector2();
  17137. const _uvB = /*@__PURE__*/ new Vector2();
  17138. const _uvC = /*@__PURE__*/ new Vector2();
  17139. class Sprite extends Object3D {
  17140. constructor( material ) {
  17141. super();
  17142. this.type = 'Sprite';
  17143. if ( _geometry === undefined ) {
  17144. _geometry = new BufferGeometry();
  17145. const float32Array = new Float32Array( [
  17146. - 0.5, - 0.5, 0, 0, 0,
  17147. 0.5, - 0.5, 0, 1, 0,
  17148. 0.5, 0.5, 0, 1, 1,
  17149. - 0.5, 0.5, 0, 0, 1
  17150. ] );
  17151. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17152. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17153. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17154. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17155. }
  17156. this.geometry = _geometry;
  17157. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17158. this.center = new Vector2( 0.5, 0.5 );
  17159. }
  17160. raycast( raycaster, intersects ) {
  17161. if ( raycaster.camera === null ) {
  17162. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17163. }
  17164. _worldScale.setFromMatrixScale( this.matrixWorld );
  17165. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17166. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17167. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17168. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17169. _worldScale.multiplyScalar( - _mvPosition.z );
  17170. }
  17171. const rotation = this.material.rotation;
  17172. let sin, cos;
  17173. if ( rotation !== 0 ) {
  17174. cos = Math.cos( rotation );
  17175. sin = Math.sin( rotation );
  17176. }
  17177. const center = this.center;
  17178. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17179. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17180. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17181. _uvA.set( 0, 0 );
  17182. _uvB.set( 1, 0 );
  17183. _uvC.set( 1, 1 );
  17184. // check first triangle
  17185. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17186. if ( intersect === null ) {
  17187. // check second triangle
  17188. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17189. _uvB.set( 0, 1 );
  17190. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17191. if ( intersect === null ) {
  17192. return;
  17193. }
  17194. }
  17195. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17196. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17197. intersects.push( {
  17198. distance: distance,
  17199. point: _intersectPoint.clone(),
  17200. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17201. face: null,
  17202. object: this
  17203. } );
  17204. }
  17205. copy( source ) {
  17206. super.copy( source );
  17207. if ( source.center !== undefined ) this.center.copy( source.center );
  17208. this.material = source.material;
  17209. return this;
  17210. }
  17211. }
  17212. Sprite.prototype.isSprite = true;
  17213. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17214. // compute position in camera space
  17215. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17216. // to check if rotation is not zero
  17217. if ( sin !== undefined ) {
  17218. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17219. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17220. } else {
  17221. _rotatedPosition.copy( _alignedPosition );
  17222. }
  17223. vertexPosition.copy( mvPosition );
  17224. vertexPosition.x += _rotatedPosition.x;
  17225. vertexPosition.y += _rotatedPosition.y;
  17226. // transform to world space
  17227. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17228. }
  17229. const _v1$2 = /*@__PURE__*/ new Vector3();
  17230. const _v2$1 = /*@__PURE__*/ new Vector3();
  17231. class LOD extends Object3D {
  17232. constructor() {
  17233. super();
  17234. this._currentLevel = 0;
  17235. this.type = 'LOD';
  17236. Object.defineProperties( this, {
  17237. levels: {
  17238. enumerable: true,
  17239. value: []
  17240. },
  17241. isLOD: {
  17242. value: true,
  17243. }
  17244. } );
  17245. this.autoUpdate = true;
  17246. }
  17247. copy( source ) {
  17248. super.copy( source, false );
  17249. const levels = source.levels;
  17250. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17251. const level = levels[ i ];
  17252. this.addLevel( level.object.clone(), level.distance );
  17253. }
  17254. this.autoUpdate = source.autoUpdate;
  17255. return this;
  17256. }
  17257. addLevel( object, distance = 0 ) {
  17258. distance = Math.abs( distance );
  17259. const levels = this.levels;
  17260. let l;
  17261. for ( l = 0; l < levels.length; l ++ ) {
  17262. if ( distance < levels[ l ].distance ) {
  17263. break;
  17264. }
  17265. }
  17266. levels.splice( l, 0, { distance: distance, object: object } );
  17267. this.add( object );
  17268. return this;
  17269. }
  17270. getCurrentLevel() {
  17271. return this._currentLevel;
  17272. }
  17273. getObjectForDistance( distance ) {
  17274. const levels = this.levels;
  17275. if ( levels.length > 0 ) {
  17276. let i, l;
  17277. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17278. if ( distance < levels[ i ].distance ) {
  17279. break;
  17280. }
  17281. }
  17282. return levels[ i - 1 ].object;
  17283. }
  17284. return null;
  17285. }
  17286. raycast( raycaster, intersects ) {
  17287. const levels = this.levels;
  17288. if ( levels.length > 0 ) {
  17289. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17290. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17291. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17292. }
  17293. }
  17294. update( camera ) {
  17295. const levels = this.levels;
  17296. if ( levels.length > 1 ) {
  17297. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17298. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17299. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17300. levels[ 0 ].object.visible = true;
  17301. let i, l;
  17302. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17303. if ( distance >= levels[ i ].distance ) {
  17304. levels[ i - 1 ].object.visible = false;
  17305. levels[ i ].object.visible = true;
  17306. } else {
  17307. break;
  17308. }
  17309. }
  17310. this._currentLevel = i - 1;
  17311. for ( ; i < l; i ++ ) {
  17312. levels[ i ].object.visible = false;
  17313. }
  17314. }
  17315. }
  17316. toJSON( meta ) {
  17317. const data = super.toJSON( meta );
  17318. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17319. data.object.levels = [];
  17320. const levels = this.levels;
  17321. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17322. const level = levels[ i ];
  17323. data.object.levels.push( {
  17324. object: level.object.uuid,
  17325. distance: level.distance
  17326. } );
  17327. }
  17328. return data;
  17329. }
  17330. }
  17331. const _basePosition = /*@__PURE__*/ new Vector3();
  17332. const _skinIndex = /*@__PURE__*/ new Vector4();
  17333. const _skinWeight = /*@__PURE__*/ new Vector4();
  17334. const _vector$5 = /*@__PURE__*/ new Vector3();
  17335. const _matrix = /*@__PURE__*/ new Matrix4();
  17336. class SkinnedMesh extends Mesh {
  17337. constructor( geometry, material ) {
  17338. super( geometry, material );
  17339. this.type = 'SkinnedMesh';
  17340. this.bindMode = 'attached';
  17341. this.bindMatrix = new Matrix4();
  17342. this.bindMatrixInverse = new Matrix4();
  17343. }
  17344. copy( source ) {
  17345. super.copy( source );
  17346. this.bindMode = source.bindMode;
  17347. this.bindMatrix.copy( source.bindMatrix );
  17348. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17349. this.skeleton = source.skeleton;
  17350. return this;
  17351. }
  17352. bind( skeleton, bindMatrix ) {
  17353. this.skeleton = skeleton;
  17354. if ( bindMatrix === undefined ) {
  17355. this.updateMatrixWorld( true );
  17356. this.skeleton.calculateInverses();
  17357. bindMatrix = this.matrixWorld;
  17358. }
  17359. this.bindMatrix.copy( bindMatrix );
  17360. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17361. }
  17362. pose() {
  17363. this.skeleton.pose();
  17364. }
  17365. normalizeSkinWeights() {
  17366. const vector = new Vector4();
  17367. const skinWeight = this.geometry.attributes.skinWeight;
  17368. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17369. vector.fromBufferAttribute( skinWeight, i );
  17370. const scale = 1.0 / vector.manhattanLength();
  17371. if ( scale !== Infinity ) {
  17372. vector.multiplyScalar( scale );
  17373. } else {
  17374. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17375. }
  17376. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17377. }
  17378. }
  17379. updateMatrixWorld( force ) {
  17380. super.updateMatrixWorld( force );
  17381. if ( this.bindMode === 'attached' ) {
  17382. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17383. } else if ( this.bindMode === 'detached' ) {
  17384. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17385. } else {
  17386. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17387. }
  17388. }
  17389. boneTransform( index, target ) {
  17390. const skeleton = this.skeleton;
  17391. const geometry = this.geometry;
  17392. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17393. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17394. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17395. target.set( 0, 0, 0 );
  17396. for ( let i = 0; i < 4; i ++ ) {
  17397. const weight = _skinWeight.getComponent( i );
  17398. if ( weight !== 0 ) {
  17399. const boneIndex = _skinIndex.getComponent( i );
  17400. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17401. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  17402. }
  17403. }
  17404. return target.applyMatrix4( this.bindMatrixInverse );
  17405. }
  17406. }
  17407. SkinnedMesh.prototype.isSkinnedMesh = true;
  17408. class Bone extends Object3D {
  17409. constructor() {
  17410. super();
  17411. this.type = 'Bone';
  17412. }
  17413. }
  17414. Bone.prototype.isBone = true;
  17415. class DataTexture extends Texture {
  17416. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  17417. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17418. this.image = { data: data, width: width, height: height };
  17419. this.generateMipmaps = false;
  17420. this.flipY = false;
  17421. this.unpackAlignment = 1;
  17422. }
  17423. }
  17424. DataTexture.prototype.isDataTexture = true;
  17425. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17426. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17427. class Skeleton {
  17428. constructor( bones = [], boneInverses = [] ) {
  17429. this.uuid = generateUUID();
  17430. this.bones = bones.slice( 0 );
  17431. this.boneInverses = boneInverses;
  17432. this.boneMatrices = null;
  17433. this.boneTexture = null;
  17434. this.boneTextureSize = 0;
  17435. this.frame = - 1;
  17436. this.init();
  17437. }
  17438. init() {
  17439. const bones = this.bones;
  17440. const boneInverses = this.boneInverses;
  17441. this.boneMatrices = new Float32Array( bones.length * 16 );
  17442. // calculate inverse bone matrices if necessary
  17443. if ( boneInverses.length === 0 ) {
  17444. this.calculateInverses();
  17445. } else {
  17446. // handle special case
  17447. if ( bones.length !== boneInverses.length ) {
  17448. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17449. this.boneInverses = [];
  17450. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17451. this.boneInverses.push( new Matrix4() );
  17452. }
  17453. }
  17454. }
  17455. }
  17456. calculateInverses() {
  17457. this.boneInverses.length = 0;
  17458. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17459. const inverse = new Matrix4();
  17460. if ( this.bones[ i ] ) {
  17461. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17462. }
  17463. this.boneInverses.push( inverse );
  17464. }
  17465. }
  17466. pose() {
  17467. // recover the bind-time world matrices
  17468. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17469. const bone = this.bones[ i ];
  17470. if ( bone ) {
  17471. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17472. }
  17473. }
  17474. // compute the local matrices, positions, rotations and scales
  17475. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17476. const bone = this.bones[ i ];
  17477. if ( bone ) {
  17478. if ( bone.parent && bone.parent.isBone ) {
  17479. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17480. bone.matrix.multiply( bone.matrixWorld );
  17481. } else {
  17482. bone.matrix.copy( bone.matrixWorld );
  17483. }
  17484. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17485. }
  17486. }
  17487. }
  17488. update() {
  17489. const bones = this.bones;
  17490. const boneInverses = this.boneInverses;
  17491. const boneMatrices = this.boneMatrices;
  17492. const boneTexture = this.boneTexture;
  17493. // flatten bone matrices to array
  17494. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17495. // compute the offset between the current and the original transform
  17496. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17497. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17498. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17499. }
  17500. if ( boneTexture !== null ) {
  17501. boneTexture.needsUpdate = true;
  17502. }
  17503. }
  17504. clone() {
  17505. return new Skeleton( this.bones, this.boneInverses );
  17506. }
  17507. computeBoneTexture() {
  17508. // layout (1 matrix = 4 pixels)
  17509. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17510. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17511. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17512. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17513. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17514. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17515. size = ceilPowerOfTwo( size );
  17516. size = Math.max( size, 4 );
  17517. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17518. boneMatrices.set( this.boneMatrices ); // copy current values
  17519. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17520. boneTexture.needsUpdate = true;
  17521. this.boneMatrices = boneMatrices;
  17522. this.boneTexture = boneTexture;
  17523. this.boneTextureSize = size;
  17524. return this;
  17525. }
  17526. getBoneByName( name ) {
  17527. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17528. const bone = this.bones[ i ];
  17529. if ( bone.name === name ) {
  17530. return bone;
  17531. }
  17532. }
  17533. return undefined;
  17534. }
  17535. dispose( ) {
  17536. if ( this.boneTexture !== null ) {
  17537. this.boneTexture.dispose();
  17538. this.boneTexture = null;
  17539. }
  17540. }
  17541. fromJSON( json, bones ) {
  17542. this.uuid = json.uuid;
  17543. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17544. const uuid = json.bones[ i ];
  17545. let bone = bones[ uuid ];
  17546. if ( bone === undefined ) {
  17547. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  17548. bone = new Bone();
  17549. }
  17550. this.bones.push( bone );
  17551. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17552. }
  17553. this.init();
  17554. return this;
  17555. }
  17556. toJSON() {
  17557. const data = {
  17558. metadata: {
  17559. version: 4.5,
  17560. type: 'Skeleton',
  17561. generator: 'Skeleton.toJSON'
  17562. },
  17563. bones: [],
  17564. boneInverses: []
  17565. };
  17566. data.uuid = this.uuid;
  17567. const bones = this.bones;
  17568. const boneInverses = this.boneInverses;
  17569. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17570. const bone = bones[ i ];
  17571. data.bones.push( bone.uuid );
  17572. const boneInverse = boneInverses[ i ];
  17573. data.boneInverses.push( boneInverse.toArray() );
  17574. }
  17575. return data;
  17576. }
  17577. }
  17578. class InstancedBufferAttribute extends BufferAttribute {
  17579. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17580. if ( typeof normalized === 'number' ) {
  17581. meshPerAttribute = normalized;
  17582. normalized = false;
  17583. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  17584. }
  17585. super( array, itemSize, normalized );
  17586. this.meshPerAttribute = meshPerAttribute;
  17587. }
  17588. copy( source ) {
  17589. super.copy( source );
  17590. this.meshPerAttribute = source.meshPerAttribute;
  17591. return this;
  17592. }
  17593. toJSON() {
  17594. const data = super.toJSON();
  17595. data.meshPerAttribute = this.meshPerAttribute;
  17596. data.isInstancedBufferAttribute = true;
  17597. return data;
  17598. }
  17599. }
  17600. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17601. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17602. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17603. const _instanceIntersects = [];
  17604. const _mesh = /*@__PURE__*/ new Mesh();
  17605. class InstancedMesh extends Mesh {
  17606. constructor( geometry, material, count ) {
  17607. super( geometry, material );
  17608. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17609. this.instanceColor = null;
  17610. this.count = count;
  17611. this.frustumCulled = false;
  17612. }
  17613. copy( source ) {
  17614. super.copy( source );
  17615. this.instanceMatrix.copy( source.instanceMatrix );
  17616. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17617. this.count = source.count;
  17618. return this;
  17619. }
  17620. getColorAt( index, color ) {
  17621. color.fromArray( this.instanceColor.array, index * 3 );
  17622. }
  17623. getMatrixAt( index, matrix ) {
  17624. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17625. }
  17626. raycast( raycaster, intersects ) {
  17627. const matrixWorld = this.matrixWorld;
  17628. const raycastTimes = this.count;
  17629. _mesh.geometry = this.geometry;
  17630. _mesh.material = this.material;
  17631. if ( _mesh.material === undefined ) return;
  17632. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  17633. // calculate the world matrix for each instance
  17634. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  17635. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  17636. // the mesh represents this single instance
  17637. _mesh.matrixWorld = _instanceWorldMatrix;
  17638. _mesh.raycast( raycaster, _instanceIntersects );
  17639. // process the result of raycast
  17640. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  17641. const intersect = _instanceIntersects[ i ];
  17642. intersect.instanceId = instanceId;
  17643. intersect.object = this;
  17644. intersects.push( intersect );
  17645. }
  17646. _instanceIntersects.length = 0;
  17647. }
  17648. }
  17649. setColorAt( index, color ) {
  17650. if ( this.instanceColor === null ) {
  17651. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  17652. }
  17653. color.toArray( this.instanceColor.array, index * 3 );
  17654. }
  17655. setMatrixAt( index, matrix ) {
  17656. matrix.toArray( this.instanceMatrix.array, index * 16 );
  17657. }
  17658. updateMorphTargets() {
  17659. }
  17660. dispose() {
  17661. this.dispatchEvent( { type: 'dispose' } );
  17662. }
  17663. }
  17664. InstancedMesh.prototype.isInstancedMesh = true;
  17665. class LineBasicMaterial extends Material {
  17666. constructor( parameters ) {
  17667. super();
  17668. this.type = 'LineBasicMaterial';
  17669. this.color = new Color( 0xffffff );
  17670. this.linewidth = 1;
  17671. this.linecap = 'round';
  17672. this.linejoin = 'round';
  17673. this.fog = true;
  17674. this.setValues( parameters );
  17675. }
  17676. copy( source ) {
  17677. super.copy( source );
  17678. this.color.copy( source.color );
  17679. this.linewidth = source.linewidth;
  17680. this.linecap = source.linecap;
  17681. this.linejoin = source.linejoin;
  17682. this.fog = source.fog;
  17683. return this;
  17684. }
  17685. }
  17686. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17687. const _start$1 = /*@__PURE__*/ new Vector3();
  17688. const _end$1 = /*@__PURE__*/ new Vector3();
  17689. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  17690. const _ray$1 = /*@__PURE__*/ new Ray();
  17691. const _sphere$1 = /*@__PURE__*/ new Sphere();
  17692. class Line extends Object3D {
  17693. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  17694. super();
  17695. this.type = 'Line';
  17696. this.geometry = geometry;
  17697. this.material = material;
  17698. this.updateMorphTargets();
  17699. }
  17700. copy( source ) {
  17701. super.copy( source );
  17702. this.material = source.material;
  17703. this.geometry = source.geometry;
  17704. return this;
  17705. }
  17706. computeLineDistances() {
  17707. const geometry = this.geometry;
  17708. if ( geometry.isBufferGeometry ) {
  17709. // we assume non-indexed geometry
  17710. if ( geometry.index === null ) {
  17711. const positionAttribute = geometry.attributes.position;
  17712. const lineDistances = [ 0 ];
  17713. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  17714. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  17715. _end$1.fromBufferAttribute( positionAttribute, i );
  17716. lineDistances[ i ] = lineDistances[ i - 1 ];
  17717. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  17718. }
  17719. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17720. } else {
  17721. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17722. }
  17723. } else if ( geometry.isGeometry ) {
  17724. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17725. }
  17726. return this;
  17727. }
  17728. raycast( raycaster, intersects ) {
  17729. const geometry = this.geometry;
  17730. const matrixWorld = this.matrixWorld;
  17731. const threshold = raycaster.params.Line.threshold;
  17732. const drawRange = geometry.drawRange;
  17733. // Checking boundingSphere distance to ray
  17734. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17735. _sphere$1.copy( geometry.boundingSphere );
  17736. _sphere$1.applyMatrix4( matrixWorld );
  17737. _sphere$1.radius += threshold;
  17738. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  17739. //
  17740. _inverseMatrix$1.copy( matrixWorld ).invert();
  17741. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  17742. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17743. const localThresholdSq = localThreshold * localThreshold;
  17744. const vStart = new Vector3();
  17745. const vEnd = new Vector3();
  17746. const interSegment = new Vector3();
  17747. const interRay = new Vector3();
  17748. const step = this.isLineSegments ? 2 : 1;
  17749. if ( geometry.isBufferGeometry ) {
  17750. const index = geometry.index;
  17751. const attributes = geometry.attributes;
  17752. const positionAttribute = attributes.position;
  17753. if ( index !== null ) {
  17754. const start = Math.max( 0, drawRange.start );
  17755. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17756. for ( let i = start, l = end - 1; i < l; i += step ) {
  17757. const a = index.getX( i );
  17758. const b = index.getX( i + 1 );
  17759. vStart.fromBufferAttribute( positionAttribute, a );
  17760. vEnd.fromBufferAttribute( positionAttribute, b );
  17761. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17762. if ( distSq > localThresholdSq ) continue;
  17763. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17764. const distance = raycaster.ray.origin.distanceTo( interRay );
  17765. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17766. intersects.push( {
  17767. distance: distance,
  17768. // What do we want? intersection point on the ray or on the segment??
  17769. // point: raycaster.ray.at( distance ),
  17770. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17771. index: i,
  17772. face: null,
  17773. faceIndex: null,
  17774. object: this
  17775. } );
  17776. }
  17777. } else {
  17778. const start = Math.max( 0, drawRange.start );
  17779. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17780. for ( let i = start, l = end - 1; i < l; i += step ) {
  17781. vStart.fromBufferAttribute( positionAttribute, i );
  17782. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  17783. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17784. if ( distSq > localThresholdSq ) continue;
  17785. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17786. const distance = raycaster.ray.origin.distanceTo( interRay );
  17787. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17788. intersects.push( {
  17789. distance: distance,
  17790. // What do we want? intersection point on the ray or on the segment??
  17791. // point: raycaster.ray.at( distance ),
  17792. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17793. index: i,
  17794. face: null,
  17795. faceIndex: null,
  17796. object: this
  17797. } );
  17798. }
  17799. }
  17800. } else if ( geometry.isGeometry ) {
  17801. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17802. }
  17803. }
  17804. updateMorphTargets() {
  17805. const geometry = this.geometry;
  17806. if ( geometry.isBufferGeometry ) {
  17807. const morphAttributes = geometry.morphAttributes;
  17808. const keys = Object.keys( morphAttributes );
  17809. if ( keys.length > 0 ) {
  17810. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17811. if ( morphAttribute !== undefined ) {
  17812. this.morphTargetInfluences = [];
  17813. this.morphTargetDictionary = {};
  17814. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17815. const name = morphAttribute[ m ].name || String( m );
  17816. this.morphTargetInfluences.push( 0 );
  17817. this.morphTargetDictionary[ name ] = m;
  17818. }
  17819. }
  17820. }
  17821. } else {
  17822. const morphTargets = geometry.morphTargets;
  17823. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17824. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17825. }
  17826. }
  17827. }
  17828. }
  17829. Line.prototype.isLine = true;
  17830. const _start = /*@__PURE__*/ new Vector3();
  17831. const _end = /*@__PURE__*/ new Vector3();
  17832. class LineSegments extends Line {
  17833. constructor( geometry, material ) {
  17834. super( geometry, material );
  17835. this.type = 'LineSegments';
  17836. }
  17837. computeLineDistances() {
  17838. const geometry = this.geometry;
  17839. if ( geometry.isBufferGeometry ) {
  17840. // we assume non-indexed geometry
  17841. if ( geometry.index === null ) {
  17842. const positionAttribute = geometry.attributes.position;
  17843. const lineDistances = [];
  17844. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17845. _start.fromBufferAttribute( positionAttribute, i );
  17846. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17847. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17848. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17849. }
  17850. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17851. } else {
  17852. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17853. }
  17854. } else if ( geometry.isGeometry ) {
  17855. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17856. }
  17857. return this;
  17858. }
  17859. }
  17860. LineSegments.prototype.isLineSegments = true;
  17861. class LineLoop extends Line {
  17862. constructor( geometry, material ) {
  17863. super( geometry, material );
  17864. this.type = 'LineLoop';
  17865. }
  17866. }
  17867. LineLoop.prototype.isLineLoop = true;
  17868. class PointsMaterial extends Material {
  17869. constructor( parameters ) {
  17870. super();
  17871. this.type = 'PointsMaterial';
  17872. this.color = new Color( 0xffffff );
  17873. this.map = null;
  17874. this.alphaMap = null;
  17875. this.size = 1;
  17876. this.sizeAttenuation = true;
  17877. this.fog = true;
  17878. this.setValues( parameters );
  17879. }
  17880. copy( source ) {
  17881. super.copy( source );
  17882. this.color.copy( source.color );
  17883. this.map = source.map;
  17884. this.alphaMap = source.alphaMap;
  17885. this.size = source.size;
  17886. this.sizeAttenuation = source.sizeAttenuation;
  17887. this.fog = source.fog;
  17888. return this;
  17889. }
  17890. }
  17891. PointsMaterial.prototype.isPointsMaterial = true;
  17892. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17893. const _ray = /*@__PURE__*/ new Ray();
  17894. const _sphere = /*@__PURE__*/ new Sphere();
  17895. const _position$2 = /*@__PURE__*/ new Vector3();
  17896. class Points extends Object3D {
  17897. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17898. super();
  17899. this.type = 'Points';
  17900. this.geometry = geometry;
  17901. this.material = material;
  17902. this.updateMorphTargets();
  17903. }
  17904. copy( source ) {
  17905. super.copy( source );
  17906. this.material = source.material;
  17907. this.geometry = source.geometry;
  17908. return this;
  17909. }
  17910. raycast( raycaster, intersects ) {
  17911. const geometry = this.geometry;
  17912. const matrixWorld = this.matrixWorld;
  17913. const threshold = raycaster.params.Points.threshold;
  17914. const drawRange = geometry.drawRange;
  17915. // Checking boundingSphere distance to ray
  17916. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17917. _sphere.copy( geometry.boundingSphere );
  17918. _sphere.applyMatrix4( matrixWorld );
  17919. _sphere.radius += threshold;
  17920. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17921. //
  17922. _inverseMatrix.copy( matrixWorld ).invert();
  17923. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17924. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17925. const localThresholdSq = localThreshold * localThreshold;
  17926. if ( geometry.isBufferGeometry ) {
  17927. const index = geometry.index;
  17928. const attributes = geometry.attributes;
  17929. const positionAttribute = attributes.position;
  17930. if ( index !== null ) {
  17931. const start = Math.max( 0, drawRange.start );
  17932. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17933. for ( let i = start, il = end; i < il; i ++ ) {
  17934. const a = index.getX( i );
  17935. _position$2.fromBufferAttribute( positionAttribute, a );
  17936. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17937. }
  17938. } else {
  17939. const start = Math.max( 0, drawRange.start );
  17940. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17941. for ( let i = start, l = end; i < l; i ++ ) {
  17942. _position$2.fromBufferAttribute( positionAttribute, i );
  17943. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17944. }
  17945. }
  17946. } else {
  17947. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17948. }
  17949. }
  17950. updateMorphTargets() {
  17951. const geometry = this.geometry;
  17952. if ( geometry.isBufferGeometry ) {
  17953. const morphAttributes = geometry.morphAttributes;
  17954. const keys = Object.keys( morphAttributes );
  17955. if ( keys.length > 0 ) {
  17956. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17957. if ( morphAttribute !== undefined ) {
  17958. this.morphTargetInfluences = [];
  17959. this.morphTargetDictionary = {};
  17960. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17961. const name = morphAttribute[ m ].name || String( m );
  17962. this.morphTargetInfluences.push( 0 );
  17963. this.morphTargetDictionary[ name ] = m;
  17964. }
  17965. }
  17966. }
  17967. } else {
  17968. const morphTargets = geometry.morphTargets;
  17969. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17970. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17971. }
  17972. }
  17973. }
  17974. }
  17975. Points.prototype.isPoints = true;
  17976. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17977. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17978. if ( rayPointDistanceSq < localThresholdSq ) {
  17979. const intersectPoint = new Vector3();
  17980. _ray.closestPointToPoint( point, intersectPoint );
  17981. intersectPoint.applyMatrix4( matrixWorld );
  17982. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17983. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17984. intersects.push( {
  17985. distance: distance,
  17986. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17987. point: intersectPoint,
  17988. index: index,
  17989. face: null,
  17990. object: object
  17991. } );
  17992. }
  17993. }
  17994. class VideoTexture extends Texture {
  17995. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17996. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17997. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17998. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17999. this.generateMipmaps = false;
  18000. const scope = this;
  18001. function updateVideo() {
  18002. scope.needsUpdate = true;
  18003. video.requestVideoFrameCallback( updateVideo );
  18004. }
  18005. if ( 'requestVideoFrameCallback' in video ) {
  18006. video.requestVideoFrameCallback( updateVideo );
  18007. }
  18008. }
  18009. clone() {
  18010. return new this.constructor( this.image ).copy( this );
  18011. }
  18012. update() {
  18013. const video = this.image;
  18014. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18015. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18016. this.needsUpdate = true;
  18017. }
  18018. }
  18019. }
  18020. VideoTexture.prototype.isVideoTexture = true;
  18021. class FramebufferTexture extends Texture {
  18022. constructor( width, height, format ) {
  18023. super( { width, height } );
  18024. this.format = format;
  18025. this.magFilter = NearestFilter;
  18026. this.minFilter = NearestFilter;
  18027. this.generateMipmaps = false;
  18028. this.needsUpdate = true;
  18029. }
  18030. }
  18031. FramebufferTexture.prototype.isFramebufferTexture = true;
  18032. class CompressedTexture extends Texture {
  18033. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18034. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18035. this.image = { width: width, height: height };
  18036. this.mipmaps = mipmaps;
  18037. // no flipping for cube textures
  18038. // (also flipping doesn't work for compressed textures )
  18039. this.flipY = false;
  18040. // can't generate mipmaps for compressed textures
  18041. // mips must be embedded in DDS files
  18042. this.generateMipmaps = false;
  18043. }
  18044. }
  18045. CompressedTexture.prototype.isCompressedTexture = true;
  18046. class CanvasTexture extends Texture {
  18047. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18048. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18049. this.needsUpdate = true;
  18050. }
  18051. }
  18052. CanvasTexture.prototype.isCanvasTexture = true;
  18053. /**
  18054. * Extensible curve object.
  18055. *
  18056. * Some common of curve methods:
  18057. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18058. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18059. * .getPoints(), .getSpacedPoints()
  18060. * .getLength()
  18061. * .updateArcLengths()
  18062. *
  18063. * This following curves inherit from THREE.Curve:
  18064. *
  18065. * -- 2D curves --
  18066. * THREE.ArcCurve
  18067. * THREE.CubicBezierCurve
  18068. * THREE.EllipseCurve
  18069. * THREE.LineCurve
  18070. * THREE.QuadraticBezierCurve
  18071. * THREE.SplineCurve
  18072. *
  18073. * -- 3D curves --
  18074. * THREE.CatmullRomCurve3
  18075. * THREE.CubicBezierCurve3
  18076. * THREE.LineCurve3
  18077. * THREE.QuadraticBezierCurve3
  18078. *
  18079. * A series of curves can be represented as a THREE.CurvePath.
  18080. *
  18081. **/
  18082. class Curve {
  18083. constructor() {
  18084. this.type = 'Curve';
  18085. this.arcLengthDivisions = 200;
  18086. }
  18087. // Virtual base class method to overwrite and implement in subclasses
  18088. // - t [0 .. 1]
  18089. getPoint( /* t, optionalTarget */ ) {
  18090. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18091. return null;
  18092. }
  18093. // Get point at relative position in curve according to arc length
  18094. // - u [0 .. 1]
  18095. getPointAt( u, optionalTarget ) {
  18096. const t = this.getUtoTmapping( u );
  18097. return this.getPoint( t, optionalTarget );
  18098. }
  18099. // Get sequence of points using getPoint( t )
  18100. getPoints( divisions = 5 ) {
  18101. const points = [];
  18102. for ( let d = 0; d <= divisions; d ++ ) {
  18103. points.push( this.getPoint( d / divisions ) );
  18104. }
  18105. return points;
  18106. }
  18107. // Get sequence of points using getPointAt( u )
  18108. getSpacedPoints( divisions = 5 ) {
  18109. const points = [];
  18110. for ( let d = 0; d <= divisions; d ++ ) {
  18111. points.push( this.getPointAt( d / divisions ) );
  18112. }
  18113. return points;
  18114. }
  18115. // Get total curve arc length
  18116. getLength() {
  18117. const lengths = this.getLengths();
  18118. return lengths[ lengths.length - 1 ];
  18119. }
  18120. // Get list of cumulative segment lengths
  18121. getLengths( divisions = this.arcLengthDivisions ) {
  18122. if ( this.cacheArcLengths &&
  18123. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18124. ! this.needsUpdate ) {
  18125. return this.cacheArcLengths;
  18126. }
  18127. this.needsUpdate = false;
  18128. const cache = [];
  18129. let current, last = this.getPoint( 0 );
  18130. let sum = 0;
  18131. cache.push( 0 );
  18132. for ( let p = 1; p <= divisions; p ++ ) {
  18133. current = this.getPoint( p / divisions );
  18134. sum += current.distanceTo( last );
  18135. cache.push( sum );
  18136. last = current;
  18137. }
  18138. this.cacheArcLengths = cache;
  18139. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18140. }
  18141. updateArcLengths() {
  18142. this.needsUpdate = true;
  18143. this.getLengths();
  18144. }
  18145. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18146. getUtoTmapping( u, distance ) {
  18147. const arcLengths = this.getLengths();
  18148. let i = 0;
  18149. const il = arcLengths.length;
  18150. let targetArcLength; // The targeted u distance value to get
  18151. if ( distance ) {
  18152. targetArcLength = distance;
  18153. } else {
  18154. targetArcLength = u * arcLengths[ il - 1 ];
  18155. }
  18156. // binary search for the index with largest value smaller than target u distance
  18157. let low = 0, high = il - 1, comparison;
  18158. while ( low <= high ) {
  18159. 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
  18160. comparison = arcLengths[ i ] - targetArcLength;
  18161. if ( comparison < 0 ) {
  18162. low = i + 1;
  18163. } else if ( comparison > 0 ) {
  18164. high = i - 1;
  18165. } else {
  18166. high = i;
  18167. break;
  18168. // DONE
  18169. }
  18170. }
  18171. i = high;
  18172. if ( arcLengths[ i ] === targetArcLength ) {
  18173. return i / ( il - 1 );
  18174. }
  18175. // we could get finer grain at lengths, or use simple interpolation between two points
  18176. const lengthBefore = arcLengths[ i ];
  18177. const lengthAfter = arcLengths[ i + 1 ];
  18178. const segmentLength = lengthAfter - lengthBefore;
  18179. // determine where we are between the 'before' and 'after' points
  18180. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18181. // add that fractional amount to t
  18182. const t = ( i + segmentFraction ) / ( il - 1 );
  18183. return t;
  18184. }
  18185. // Returns a unit vector tangent at t
  18186. // In case any sub curve does not implement its tangent derivation,
  18187. // 2 points a small delta apart will be used to find its gradient
  18188. // which seems to give a reasonable approximation
  18189. getTangent( t, optionalTarget ) {
  18190. const delta = 0.0001;
  18191. let t1 = t - delta;
  18192. let t2 = t + delta;
  18193. // Capping in case of danger
  18194. if ( t1 < 0 ) t1 = 0;
  18195. if ( t2 > 1 ) t2 = 1;
  18196. const pt1 = this.getPoint( t1 );
  18197. const pt2 = this.getPoint( t2 );
  18198. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18199. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18200. return tangent;
  18201. }
  18202. getTangentAt( u, optionalTarget ) {
  18203. const t = this.getUtoTmapping( u );
  18204. return this.getTangent( t, optionalTarget );
  18205. }
  18206. computeFrenetFrames( segments, closed ) {
  18207. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18208. const normal = new Vector3();
  18209. const tangents = [];
  18210. const normals = [];
  18211. const binormals = [];
  18212. const vec = new Vector3();
  18213. const mat = new Matrix4();
  18214. // compute the tangent vectors for each segment on the curve
  18215. for ( let i = 0; i <= segments; i ++ ) {
  18216. const u = i / segments;
  18217. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18218. }
  18219. // select an initial normal vector perpendicular to the first tangent vector,
  18220. // and in the direction of the minimum tangent xyz component
  18221. normals[ 0 ] = new Vector3();
  18222. binormals[ 0 ] = new Vector3();
  18223. let min = Number.MAX_VALUE;
  18224. const tx = Math.abs( tangents[ 0 ].x );
  18225. const ty = Math.abs( tangents[ 0 ].y );
  18226. const tz = Math.abs( tangents[ 0 ].z );
  18227. if ( tx <= min ) {
  18228. min = tx;
  18229. normal.set( 1, 0, 0 );
  18230. }
  18231. if ( ty <= min ) {
  18232. min = ty;
  18233. normal.set( 0, 1, 0 );
  18234. }
  18235. if ( tz <= min ) {
  18236. normal.set( 0, 0, 1 );
  18237. }
  18238. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18239. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18240. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18241. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18242. for ( let i = 1; i <= segments; i ++ ) {
  18243. normals[ i ] = normals[ i - 1 ].clone();
  18244. binormals[ i ] = binormals[ i - 1 ].clone();
  18245. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18246. if ( vec.length() > Number.EPSILON ) {
  18247. vec.normalize();
  18248. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18249. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18250. }
  18251. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18252. }
  18253. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18254. if ( closed === true ) {
  18255. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18256. theta /= segments;
  18257. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18258. theta = - theta;
  18259. }
  18260. for ( let i = 1; i <= segments; i ++ ) {
  18261. // twist a little...
  18262. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18263. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18264. }
  18265. }
  18266. return {
  18267. tangents: tangents,
  18268. normals: normals,
  18269. binormals: binormals
  18270. };
  18271. }
  18272. clone() {
  18273. return new this.constructor().copy( this );
  18274. }
  18275. copy( source ) {
  18276. this.arcLengthDivisions = source.arcLengthDivisions;
  18277. return this;
  18278. }
  18279. toJSON() {
  18280. const data = {
  18281. metadata: {
  18282. version: 4.5,
  18283. type: 'Curve',
  18284. generator: 'Curve.toJSON'
  18285. }
  18286. };
  18287. data.arcLengthDivisions = this.arcLengthDivisions;
  18288. data.type = this.type;
  18289. return data;
  18290. }
  18291. fromJSON( json ) {
  18292. this.arcLengthDivisions = json.arcLengthDivisions;
  18293. return this;
  18294. }
  18295. }
  18296. class EllipseCurve extends Curve {
  18297. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18298. super();
  18299. this.type = 'EllipseCurve';
  18300. this.aX = aX;
  18301. this.aY = aY;
  18302. this.xRadius = xRadius;
  18303. this.yRadius = yRadius;
  18304. this.aStartAngle = aStartAngle;
  18305. this.aEndAngle = aEndAngle;
  18306. this.aClockwise = aClockwise;
  18307. this.aRotation = aRotation;
  18308. }
  18309. getPoint( t, optionalTarget ) {
  18310. const point = optionalTarget || new Vector2();
  18311. const twoPi = Math.PI * 2;
  18312. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18313. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18314. // ensures that deltaAngle is 0 .. 2 PI
  18315. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18316. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18317. if ( deltaAngle < Number.EPSILON ) {
  18318. if ( samePoints ) {
  18319. deltaAngle = 0;
  18320. } else {
  18321. deltaAngle = twoPi;
  18322. }
  18323. }
  18324. if ( this.aClockwise === true && ! samePoints ) {
  18325. if ( deltaAngle === twoPi ) {
  18326. deltaAngle = - twoPi;
  18327. } else {
  18328. deltaAngle = deltaAngle - twoPi;
  18329. }
  18330. }
  18331. const angle = this.aStartAngle + t * deltaAngle;
  18332. let x = this.aX + this.xRadius * Math.cos( angle );
  18333. let y = this.aY + this.yRadius * Math.sin( angle );
  18334. if ( this.aRotation !== 0 ) {
  18335. const cos = Math.cos( this.aRotation );
  18336. const sin = Math.sin( this.aRotation );
  18337. const tx = x - this.aX;
  18338. const ty = y - this.aY;
  18339. // Rotate the point about the center of the ellipse.
  18340. x = tx * cos - ty * sin + this.aX;
  18341. y = tx * sin + ty * cos + this.aY;
  18342. }
  18343. return point.set( x, y );
  18344. }
  18345. copy( source ) {
  18346. super.copy( source );
  18347. this.aX = source.aX;
  18348. this.aY = source.aY;
  18349. this.xRadius = source.xRadius;
  18350. this.yRadius = source.yRadius;
  18351. this.aStartAngle = source.aStartAngle;
  18352. this.aEndAngle = source.aEndAngle;
  18353. this.aClockwise = source.aClockwise;
  18354. this.aRotation = source.aRotation;
  18355. return this;
  18356. }
  18357. toJSON() {
  18358. const data = super.toJSON();
  18359. data.aX = this.aX;
  18360. data.aY = this.aY;
  18361. data.xRadius = this.xRadius;
  18362. data.yRadius = this.yRadius;
  18363. data.aStartAngle = this.aStartAngle;
  18364. data.aEndAngle = this.aEndAngle;
  18365. data.aClockwise = this.aClockwise;
  18366. data.aRotation = this.aRotation;
  18367. return data;
  18368. }
  18369. fromJSON( json ) {
  18370. super.fromJSON( json );
  18371. this.aX = json.aX;
  18372. this.aY = json.aY;
  18373. this.xRadius = json.xRadius;
  18374. this.yRadius = json.yRadius;
  18375. this.aStartAngle = json.aStartAngle;
  18376. this.aEndAngle = json.aEndAngle;
  18377. this.aClockwise = json.aClockwise;
  18378. this.aRotation = json.aRotation;
  18379. return this;
  18380. }
  18381. }
  18382. EllipseCurve.prototype.isEllipseCurve = true;
  18383. class ArcCurve extends EllipseCurve {
  18384. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18385. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18386. this.type = 'ArcCurve';
  18387. }
  18388. }
  18389. ArcCurve.prototype.isArcCurve = true;
  18390. /**
  18391. * Centripetal CatmullRom Curve - which is useful for avoiding
  18392. * cusps and self-intersections in non-uniform catmull rom curves.
  18393. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18394. *
  18395. * curve.type accepts centripetal(default), chordal and catmullrom
  18396. * curve.tension is used for catmullrom which defaults to 0.5
  18397. */
  18398. /*
  18399. Based on an optimized c++ solution in
  18400. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18401. - http://ideone.com/NoEbVM
  18402. This CubicPoly class could be used for reusing some variables and calculations,
  18403. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18404. which can be placed in CurveUtils.
  18405. */
  18406. function CubicPoly() {
  18407. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18408. /*
  18409. * Compute coefficients for a cubic polynomial
  18410. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18411. * such that
  18412. * p(0) = x0, p(1) = x1
  18413. * and
  18414. * p'(0) = t0, p'(1) = t1.
  18415. */
  18416. function init( x0, x1, t0, t1 ) {
  18417. c0 = x0;
  18418. c1 = t0;
  18419. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18420. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18421. }
  18422. return {
  18423. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18424. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18425. },
  18426. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18427. // compute tangents when parameterized in [t1,t2]
  18428. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18429. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18430. // rescale tangents for parametrization in [0,1]
  18431. t1 *= dt1;
  18432. t2 *= dt1;
  18433. init( x1, x2, t1, t2 );
  18434. },
  18435. calc: function ( t ) {
  18436. const t2 = t * t;
  18437. const t3 = t2 * t;
  18438. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18439. }
  18440. };
  18441. }
  18442. //
  18443. const tmp = new Vector3();
  18444. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  18445. class CatmullRomCurve3 extends Curve {
  18446. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18447. super();
  18448. this.type = 'CatmullRomCurve3';
  18449. this.points = points;
  18450. this.closed = closed;
  18451. this.curveType = curveType;
  18452. this.tension = tension;
  18453. }
  18454. getPoint( t, optionalTarget = new Vector3() ) {
  18455. const point = optionalTarget;
  18456. const points = this.points;
  18457. const l = points.length;
  18458. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18459. let intPoint = Math.floor( p );
  18460. let weight = p - intPoint;
  18461. if ( this.closed ) {
  18462. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18463. } else if ( weight === 0 && intPoint === l - 1 ) {
  18464. intPoint = l - 2;
  18465. weight = 1;
  18466. }
  18467. let p0, p3; // 4 points (p1 & p2 defined below)
  18468. if ( this.closed || intPoint > 0 ) {
  18469. p0 = points[ ( intPoint - 1 ) % l ];
  18470. } else {
  18471. // extrapolate first point
  18472. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18473. p0 = tmp;
  18474. }
  18475. const p1 = points[ intPoint % l ];
  18476. const p2 = points[ ( intPoint + 1 ) % l ];
  18477. if ( this.closed || intPoint + 2 < l ) {
  18478. p3 = points[ ( intPoint + 2 ) % l ];
  18479. } else {
  18480. // extrapolate last point
  18481. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18482. p3 = tmp;
  18483. }
  18484. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18485. // init Centripetal / Chordal Catmull-Rom
  18486. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18487. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18488. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18489. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18490. // safety check for repeated points
  18491. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18492. if ( dt0 < 1e-4 ) dt0 = dt1;
  18493. if ( dt2 < 1e-4 ) dt2 = dt1;
  18494. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18495. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18496. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18497. } else if ( this.curveType === 'catmullrom' ) {
  18498. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18499. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18500. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18501. }
  18502. point.set(
  18503. px.calc( weight ),
  18504. py.calc( weight ),
  18505. pz.calc( weight )
  18506. );
  18507. return point;
  18508. }
  18509. copy( source ) {
  18510. super.copy( source );
  18511. this.points = [];
  18512. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18513. const point = source.points[ i ];
  18514. this.points.push( point.clone() );
  18515. }
  18516. this.closed = source.closed;
  18517. this.curveType = source.curveType;
  18518. this.tension = source.tension;
  18519. return this;
  18520. }
  18521. toJSON() {
  18522. const data = super.toJSON();
  18523. data.points = [];
  18524. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18525. const point = this.points[ i ];
  18526. data.points.push( point.toArray() );
  18527. }
  18528. data.closed = this.closed;
  18529. data.curveType = this.curveType;
  18530. data.tension = this.tension;
  18531. return data;
  18532. }
  18533. fromJSON( json ) {
  18534. super.fromJSON( json );
  18535. this.points = [];
  18536. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18537. const point = json.points[ i ];
  18538. this.points.push( new Vector3().fromArray( point ) );
  18539. }
  18540. this.closed = json.closed;
  18541. this.curveType = json.curveType;
  18542. this.tension = json.tension;
  18543. return this;
  18544. }
  18545. }
  18546. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18547. /**
  18548. * Bezier Curves formulas obtained from
  18549. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18550. */
  18551. function CatmullRom( t, p0, p1, p2, p3 ) {
  18552. const v0 = ( p2 - p0 ) * 0.5;
  18553. const v1 = ( p3 - p1 ) * 0.5;
  18554. const t2 = t * t;
  18555. const t3 = t * t2;
  18556. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18557. }
  18558. //
  18559. function QuadraticBezierP0( t, p ) {
  18560. const k = 1 - t;
  18561. return k * k * p;
  18562. }
  18563. function QuadraticBezierP1( t, p ) {
  18564. return 2 * ( 1 - t ) * t * p;
  18565. }
  18566. function QuadraticBezierP2( t, p ) {
  18567. return t * t * p;
  18568. }
  18569. function QuadraticBezier( t, p0, p1, p2 ) {
  18570. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18571. QuadraticBezierP2( t, p2 );
  18572. }
  18573. //
  18574. function CubicBezierP0( t, p ) {
  18575. const k = 1 - t;
  18576. return k * k * k * p;
  18577. }
  18578. function CubicBezierP1( t, p ) {
  18579. const k = 1 - t;
  18580. return 3 * k * k * t * p;
  18581. }
  18582. function CubicBezierP2( t, p ) {
  18583. return 3 * ( 1 - t ) * t * t * p;
  18584. }
  18585. function CubicBezierP3( t, p ) {
  18586. return t * t * t * p;
  18587. }
  18588. function CubicBezier( t, p0, p1, p2, p3 ) {
  18589. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18590. CubicBezierP3( t, p3 );
  18591. }
  18592. class CubicBezierCurve extends Curve {
  18593. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18594. super();
  18595. this.type = 'CubicBezierCurve';
  18596. this.v0 = v0;
  18597. this.v1 = v1;
  18598. this.v2 = v2;
  18599. this.v3 = v3;
  18600. }
  18601. getPoint( t, optionalTarget = new Vector2() ) {
  18602. const point = optionalTarget;
  18603. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18604. point.set(
  18605. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18606. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18607. );
  18608. return point;
  18609. }
  18610. copy( source ) {
  18611. super.copy( source );
  18612. this.v0.copy( source.v0 );
  18613. this.v1.copy( source.v1 );
  18614. this.v2.copy( source.v2 );
  18615. this.v3.copy( source.v3 );
  18616. return this;
  18617. }
  18618. toJSON() {
  18619. const data = super.toJSON();
  18620. data.v0 = this.v0.toArray();
  18621. data.v1 = this.v1.toArray();
  18622. data.v2 = this.v2.toArray();
  18623. data.v3 = this.v3.toArray();
  18624. return data;
  18625. }
  18626. fromJSON( json ) {
  18627. super.fromJSON( json );
  18628. this.v0.fromArray( json.v0 );
  18629. this.v1.fromArray( json.v1 );
  18630. this.v2.fromArray( json.v2 );
  18631. this.v3.fromArray( json.v3 );
  18632. return this;
  18633. }
  18634. }
  18635. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18636. class CubicBezierCurve3 extends Curve {
  18637. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18638. super();
  18639. this.type = 'CubicBezierCurve3';
  18640. this.v0 = v0;
  18641. this.v1 = v1;
  18642. this.v2 = v2;
  18643. this.v3 = v3;
  18644. }
  18645. getPoint( t, optionalTarget = new Vector3() ) {
  18646. const point = optionalTarget;
  18647. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18648. point.set(
  18649. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18650. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18651. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18652. );
  18653. return point;
  18654. }
  18655. copy( source ) {
  18656. super.copy( source );
  18657. this.v0.copy( source.v0 );
  18658. this.v1.copy( source.v1 );
  18659. this.v2.copy( source.v2 );
  18660. this.v3.copy( source.v3 );
  18661. return this;
  18662. }
  18663. toJSON() {
  18664. const data = super.toJSON();
  18665. data.v0 = this.v0.toArray();
  18666. data.v1 = this.v1.toArray();
  18667. data.v2 = this.v2.toArray();
  18668. data.v3 = this.v3.toArray();
  18669. return data;
  18670. }
  18671. fromJSON( json ) {
  18672. super.fromJSON( json );
  18673. this.v0.fromArray( json.v0 );
  18674. this.v1.fromArray( json.v1 );
  18675. this.v2.fromArray( json.v2 );
  18676. this.v3.fromArray( json.v3 );
  18677. return this;
  18678. }
  18679. }
  18680. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18681. class LineCurve extends Curve {
  18682. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18683. super();
  18684. this.type = 'LineCurve';
  18685. this.v1 = v1;
  18686. this.v2 = v2;
  18687. }
  18688. getPoint( t, optionalTarget = new Vector2() ) {
  18689. const point = optionalTarget;
  18690. if ( t === 1 ) {
  18691. point.copy( this.v2 );
  18692. } else {
  18693. point.copy( this.v2 ).sub( this.v1 );
  18694. point.multiplyScalar( t ).add( this.v1 );
  18695. }
  18696. return point;
  18697. }
  18698. // Line curve is linear, so we can overwrite default getPointAt
  18699. getPointAt( u, optionalTarget ) {
  18700. return this.getPoint( u, optionalTarget );
  18701. }
  18702. getTangent( t, optionalTarget ) {
  18703. const tangent = optionalTarget || new Vector2();
  18704. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  18705. return tangent;
  18706. }
  18707. copy( source ) {
  18708. super.copy( source );
  18709. this.v1.copy( source.v1 );
  18710. this.v2.copy( source.v2 );
  18711. return this;
  18712. }
  18713. toJSON() {
  18714. const data = super.toJSON();
  18715. data.v1 = this.v1.toArray();
  18716. data.v2 = this.v2.toArray();
  18717. return data;
  18718. }
  18719. fromJSON( json ) {
  18720. super.fromJSON( json );
  18721. this.v1.fromArray( json.v1 );
  18722. this.v2.fromArray( json.v2 );
  18723. return this;
  18724. }
  18725. }
  18726. LineCurve.prototype.isLineCurve = true;
  18727. class LineCurve3 extends Curve {
  18728. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18729. super();
  18730. this.type = 'LineCurve3';
  18731. this.isLineCurve3 = true;
  18732. this.v1 = v1;
  18733. this.v2 = v2;
  18734. }
  18735. getPoint( t, optionalTarget = new Vector3() ) {
  18736. const point = optionalTarget;
  18737. if ( t === 1 ) {
  18738. point.copy( this.v2 );
  18739. } else {
  18740. point.copy( this.v2 ).sub( this.v1 );
  18741. point.multiplyScalar( t ).add( this.v1 );
  18742. }
  18743. return point;
  18744. }
  18745. // Line curve is linear, so we can overwrite default getPointAt
  18746. getPointAt( u, optionalTarget ) {
  18747. return this.getPoint( u, optionalTarget );
  18748. }
  18749. copy( source ) {
  18750. super.copy( source );
  18751. this.v1.copy( source.v1 );
  18752. this.v2.copy( source.v2 );
  18753. return this;
  18754. }
  18755. toJSON() {
  18756. const data = super.toJSON();
  18757. data.v1 = this.v1.toArray();
  18758. data.v2 = this.v2.toArray();
  18759. return data;
  18760. }
  18761. fromJSON( json ) {
  18762. super.fromJSON( json );
  18763. this.v1.fromArray( json.v1 );
  18764. this.v2.fromArray( json.v2 );
  18765. return this;
  18766. }
  18767. }
  18768. class QuadraticBezierCurve extends Curve {
  18769. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  18770. super();
  18771. this.type = 'QuadraticBezierCurve';
  18772. this.v0 = v0;
  18773. this.v1 = v1;
  18774. this.v2 = v2;
  18775. }
  18776. getPoint( t, optionalTarget = new Vector2() ) {
  18777. const point = optionalTarget;
  18778. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18779. point.set(
  18780. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18781. QuadraticBezier( t, v0.y, v1.y, v2.y )
  18782. );
  18783. return point;
  18784. }
  18785. copy( source ) {
  18786. super.copy( source );
  18787. this.v0.copy( source.v0 );
  18788. this.v1.copy( source.v1 );
  18789. this.v2.copy( source.v2 );
  18790. return this;
  18791. }
  18792. toJSON() {
  18793. const data = super.toJSON();
  18794. data.v0 = this.v0.toArray();
  18795. data.v1 = this.v1.toArray();
  18796. data.v2 = this.v2.toArray();
  18797. return data;
  18798. }
  18799. fromJSON( json ) {
  18800. super.fromJSON( json );
  18801. this.v0.fromArray( json.v0 );
  18802. this.v1.fromArray( json.v1 );
  18803. this.v2.fromArray( json.v2 );
  18804. return this;
  18805. }
  18806. }
  18807. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18808. class QuadraticBezierCurve3 extends Curve {
  18809. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  18810. super();
  18811. this.type = 'QuadraticBezierCurve3';
  18812. this.v0 = v0;
  18813. this.v1 = v1;
  18814. this.v2 = v2;
  18815. }
  18816. getPoint( t, optionalTarget = new Vector3() ) {
  18817. const point = optionalTarget;
  18818. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18819. point.set(
  18820. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18821. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  18822. QuadraticBezier( t, v0.z, v1.z, v2.z )
  18823. );
  18824. return point;
  18825. }
  18826. copy( source ) {
  18827. super.copy( source );
  18828. this.v0.copy( source.v0 );
  18829. this.v1.copy( source.v1 );
  18830. this.v2.copy( source.v2 );
  18831. return this;
  18832. }
  18833. toJSON() {
  18834. const data = super.toJSON();
  18835. data.v0 = this.v0.toArray();
  18836. data.v1 = this.v1.toArray();
  18837. data.v2 = this.v2.toArray();
  18838. return data;
  18839. }
  18840. fromJSON( json ) {
  18841. super.fromJSON( json );
  18842. this.v0.fromArray( json.v0 );
  18843. this.v1.fromArray( json.v1 );
  18844. this.v2.fromArray( json.v2 );
  18845. return this;
  18846. }
  18847. }
  18848. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18849. class SplineCurve extends Curve {
  18850. constructor( points = [] ) {
  18851. super();
  18852. this.type = 'SplineCurve';
  18853. this.points = points;
  18854. }
  18855. getPoint( t, optionalTarget = new Vector2() ) {
  18856. const point = optionalTarget;
  18857. const points = this.points;
  18858. const p = ( points.length - 1 ) * t;
  18859. const intPoint = Math.floor( p );
  18860. const weight = p - intPoint;
  18861. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18862. const p1 = points[ intPoint ];
  18863. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18864. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18865. point.set(
  18866. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  18867. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  18868. );
  18869. return point;
  18870. }
  18871. copy( source ) {
  18872. super.copy( source );
  18873. this.points = [];
  18874. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18875. const point = source.points[ i ];
  18876. this.points.push( point.clone() );
  18877. }
  18878. return this;
  18879. }
  18880. toJSON() {
  18881. const data = super.toJSON();
  18882. data.points = [];
  18883. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18884. const point = this.points[ i ];
  18885. data.points.push( point.toArray() );
  18886. }
  18887. return data;
  18888. }
  18889. fromJSON( json ) {
  18890. super.fromJSON( json );
  18891. this.points = [];
  18892. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18893. const point = json.points[ i ];
  18894. this.points.push( new Vector2().fromArray( point ) );
  18895. }
  18896. return this;
  18897. }
  18898. }
  18899. SplineCurve.prototype.isSplineCurve = true;
  18900. var Curves = /*#__PURE__*/Object.freeze({
  18901. __proto__: null,
  18902. ArcCurve: ArcCurve,
  18903. CatmullRomCurve3: CatmullRomCurve3,
  18904. CubicBezierCurve: CubicBezierCurve,
  18905. CubicBezierCurve3: CubicBezierCurve3,
  18906. EllipseCurve: EllipseCurve,
  18907. LineCurve: LineCurve,
  18908. LineCurve3: LineCurve3,
  18909. QuadraticBezierCurve: QuadraticBezierCurve,
  18910. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18911. SplineCurve: SplineCurve
  18912. });
  18913. /**************************************************************
  18914. * Curved Path - a curve path is simply a array of connected
  18915. * curves, but retains the api of a curve
  18916. **************************************************************/
  18917. class CurvePath extends Curve {
  18918. constructor() {
  18919. super();
  18920. this.type = 'CurvePath';
  18921. this.curves = [];
  18922. this.autoClose = false; // Automatically closes the path
  18923. }
  18924. add( curve ) {
  18925. this.curves.push( curve );
  18926. }
  18927. closePath() {
  18928. // Add a line curve if start and end of lines are not connected
  18929. const startPoint = this.curves[ 0 ].getPoint( 0 );
  18930. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  18931. if ( ! startPoint.equals( endPoint ) ) {
  18932. this.curves.push( new LineCurve( endPoint, startPoint ) );
  18933. }
  18934. }
  18935. // To get accurate point with reference to
  18936. // entire path distance at time t,
  18937. // following has to be done:
  18938. // 1. Length of each sub path have to be known
  18939. // 2. Locate and identify type of curve
  18940. // 3. Get t for the curve
  18941. // 4. Return curve.getPointAt(t')
  18942. getPoint( t, optionalTarget ) {
  18943. const d = t * this.getLength();
  18944. const curveLengths = this.getCurveLengths();
  18945. let i = 0;
  18946. // To think about boundaries points.
  18947. while ( i < curveLengths.length ) {
  18948. if ( curveLengths[ i ] >= d ) {
  18949. const diff = curveLengths[ i ] - d;
  18950. const curve = this.curves[ i ];
  18951. const segmentLength = curve.getLength();
  18952. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  18953. return curve.getPointAt( u, optionalTarget );
  18954. }
  18955. i ++;
  18956. }
  18957. return null;
  18958. // loop where sum != 0, sum > d , sum+1 <d
  18959. }
  18960. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  18961. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  18962. // getPoint() depends on getLength
  18963. getLength() {
  18964. const lens = this.getCurveLengths();
  18965. return lens[ lens.length - 1 ];
  18966. }
  18967. // cacheLengths must be recalculated.
  18968. updateArcLengths() {
  18969. this.needsUpdate = true;
  18970. this.cacheLengths = null;
  18971. this.getCurveLengths();
  18972. }
  18973. // Compute lengths and cache them
  18974. // We cannot overwrite getLengths() because UtoT mapping uses it.
  18975. getCurveLengths() {
  18976. // We use cache values if curves and cache array are same length
  18977. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  18978. return this.cacheLengths;
  18979. }
  18980. // Get length of sub-curve
  18981. // Push sums into cached array
  18982. const lengths = [];
  18983. let sums = 0;
  18984. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  18985. sums += this.curves[ i ].getLength();
  18986. lengths.push( sums );
  18987. }
  18988. this.cacheLengths = lengths;
  18989. return lengths;
  18990. }
  18991. getSpacedPoints( divisions = 40 ) {
  18992. const points = [];
  18993. for ( let i = 0; i <= divisions; i ++ ) {
  18994. points.push( this.getPoint( i / divisions ) );
  18995. }
  18996. if ( this.autoClose ) {
  18997. points.push( points[ 0 ] );
  18998. }
  18999. return points;
  19000. }
  19001. getPoints( divisions = 12 ) {
  19002. const points = [];
  19003. let last;
  19004. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19005. const curve = curves[ i ];
  19006. const resolution = curve.isEllipseCurve ? divisions * 2
  19007. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19008. : curve.isSplineCurve ? divisions * curve.points.length
  19009. : divisions;
  19010. const pts = curve.getPoints( resolution );
  19011. for ( let j = 0; j < pts.length; j ++ ) {
  19012. const point = pts[ j ];
  19013. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19014. points.push( point );
  19015. last = point;
  19016. }
  19017. }
  19018. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19019. points.push( points[ 0 ] );
  19020. }
  19021. return points;
  19022. }
  19023. copy( source ) {
  19024. super.copy( source );
  19025. this.curves = [];
  19026. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19027. const curve = source.curves[ i ];
  19028. this.curves.push( curve.clone() );
  19029. }
  19030. this.autoClose = source.autoClose;
  19031. return this;
  19032. }
  19033. toJSON() {
  19034. const data = super.toJSON();
  19035. data.autoClose = this.autoClose;
  19036. data.curves = [];
  19037. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19038. const curve = this.curves[ i ];
  19039. data.curves.push( curve.toJSON() );
  19040. }
  19041. return data;
  19042. }
  19043. fromJSON( json ) {
  19044. super.fromJSON( json );
  19045. this.autoClose = json.autoClose;
  19046. this.curves = [];
  19047. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19048. const curve = json.curves[ i ];
  19049. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19050. }
  19051. return this;
  19052. }
  19053. }
  19054. class Path extends CurvePath {
  19055. constructor( points ) {
  19056. super();
  19057. this.type = 'Path';
  19058. this.currentPoint = new Vector2();
  19059. if ( points ) {
  19060. this.setFromPoints( points );
  19061. }
  19062. }
  19063. setFromPoints( points ) {
  19064. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19065. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19066. this.lineTo( points[ i ].x, points[ i ].y );
  19067. }
  19068. return this;
  19069. }
  19070. moveTo( x, y ) {
  19071. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19072. return this;
  19073. }
  19074. lineTo( x, y ) {
  19075. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19076. this.curves.push( curve );
  19077. this.currentPoint.set( x, y );
  19078. return this;
  19079. }
  19080. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19081. const curve = new QuadraticBezierCurve(
  19082. this.currentPoint.clone(),
  19083. new Vector2( aCPx, aCPy ),
  19084. new Vector2( aX, aY )
  19085. );
  19086. this.curves.push( curve );
  19087. this.currentPoint.set( aX, aY );
  19088. return this;
  19089. }
  19090. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19091. const curve = new CubicBezierCurve(
  19092. this.currentPoint.clone(),
  19093. new Vector2( aCP1x, aCP1y ),
  19094. new Vector2( aCP2x, aCP2y ),
  19095. new Vector2( aX, aY )
  19096. );
  19097. this.curves.push( curve );
  19098. this.currentPoint.set( aX, aY );
  19099. return this;
  19100. }
  19101. splineThru( pts /*Array of Vector*/ ) {
  19102. const npts = [ this.currentPoint.clone() ].concat( pts );
  19103. const curve = new SplineCurve( npts );
  19104. this.curves.push( curve );
  19105. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19106. return this;
  19107. }
  19108. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19109. const x0 = this.currentPoint.x;
  19110. const y0 = this.currentPoint.y;
  19111. this.absarc( aX + x0, aY + y0, aRadius,
  19112. aStartAngle, aEndAngle, aClockwise );
  19113. return this;
  19114. }
  19115. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19116. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19117. return this;
  19118. }
  19119. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19120. const x0 = this.currentPoint.x;
  19121. const y0 = this.currentPoint.y;
  19122. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19123. return this;
  19124. }
  19125. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19126. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19127. if ( this.curves.length > 0 ) {
  19128. // if a previous curve is present, attempt to join
  19129. const firstPoint = curve.getPoint( 0 );
  19130. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19131. this.lineTo( firstPoint.x, firstPoint.y );
  19132. }
  19133. }
  19134. this.curves.push( curve );
  19135. const lastPoint = curve.getPoint( 1 );
  19136. this.currentPoint.copy( lastPoint );
  19137. return this;
  19138. }
  19139. copy( source ) {
  19140. super.copy( source );
  19141. this.currentPoint.copy( source.currentPoint );
  19142. return this;
  19143. }
  19144. toJSON() {
  19145. const data = super.toJSON();
  19146. data.currentPoint = this.currentPoint.toArray();
  19147. return data;
  19148. }
  19149. fromJSON( json ) {
  19150. super.fromJSON( json );
  19151. this.currentPoint.fromArray( json.currentPoint );
  19152. return this;
  19153. }
  19154. }
  19155. class LatheGeometry extends BufferGeometry {
  19156. 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 ) {
  19157. super();
  19158. this.type = 'LatheGeometry';
  19159. this.parameters = {
  19160. points: points,
  19161. segments: segments,
  19162. phiStart: phiStart,
  19163. phiLength: phiLength
  19164. };
  19165. segments = Math.floor( segments );
  19166. // clamp phiLength so it's in range of [ 0, 2PI ]
  19167. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19168. // buffers
  19169. const indices = [];
  19170. const vertices = [];
  19171. const uvs = [];
  19172. const initNormals = [];
  19173. const normals = [];
  19174. // helper variables
  19175. const inverseSegments = 1.0 / segments;
  19176. const vertex = new Vector3();
  19177. const uv = new Vector2();
  19178. const normal = new Vector3();
  19179. const curNormal = new Vector3();
  19180. const prevNormal = new Vector3();
  19181. let dx = 0;
  19182. let dy = 0;
  19183. // pre-compute normals for initial "meridian"
  19184. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19185. switch ( j ) {
  19186. case 0: // special handling for 1st vertex on path
  19187. dx = points[ j + 1 ].x - points[ j ].x;
  19188. dy = points[ j + 1 ].y - points[ j ].y;
  19189. normal.x = dy * 1.0;
  19190. normal.y = - dx;
  19191. normal.z = dy * 0.0;
  19192. prevNormal.copy( normal );
  19193. normal.normalize();
  19194. initNormals.push( normal.x, normal.y, normal.z );
  19195. break;
  19196. case ( points.length - 1 ): // special handling for last Vertex on path
  19197. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19198. break;
  19199. default: // default handling for all vertices in between
  19200. dx = points[ j + 1 ].x - points[ j ].x;
  19201. dy = points[ j + 1 ].y - points[ j ].y;
  19202. normal.x = dy * 1.0;
  19203. normal.y = - dx;
  19204. normal.z = dy * 0.0;
  19205. curNormal.copy( normal );
  19206. normal.x += prevNormal.x;
  19207. normal.y += prevNormal.y;
  19208. normal.z += prevNormal.z;
  19209. normal.normalize();
  19210. initNormals.push( normal.x, normal.y, normal.z );
  19211. prevNormal.copy( curNormal );
  19212. }
  19213. }
  19214. // generate vertices, uvs and normals
  19215. for ( let i = 0; i <= segments; i ++ ) {
  19216. const phi = phiStart + i * inverseSegments * phiLength;
  19217. const sin = Math.sin( phi );
  19218. const cos = Math.cos( phi );
  19219. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19220. // vertex
  19221. vertex.x = points[ j ].x * sin;
  19222. vertex.y = points[ j ].y;
  19223. vertex.z = points[ j ].x * cos;
  19224. vertices.push( vertex.x, vertex.y, vertex.z );
  19225. // uv
  19226. uv.x = i / segments;
  19227. uv.y = j / ( points.length - 1 );
  19228. uvs.push( uv.x, uv.y );
  19229. // normal
  19230. const x = initNormals[ 3 * j + 0 ] * sin;
  19231. const y = initNormals[ 3 * j + 1 ];
  19232. const z = initNormals[ 3 * j + 0 ] * cos;
  19233. normals.push( x, y, z );
  19234. }
  19235. }
  19236. // indices
  19237. for ( let i = 0; i < segments; i ++ ) {
  19238. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19239. const base = j + i * points.length;
  19240. const a = base;
  19241. const b = base + points.length;
  19242. const c = base + points.length + 1;
  19243. const d = base + 1;
  19244. // faces
  19245. indices.push( a, b, d );
  19246. indices.push( c, d, b );
  19247. }
  19248. }
  19249. // build geometry
  19250. this.setIndex( indices );
  19251. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19252. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19253. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19254. }
  19255. static fromJSON( data ) {
  19256. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19257. }
  19258. }
  19259. class CapsuleGeometry extends LatheGeometry {
  19260. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19261. const path = new Path();
  19262. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19263. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19264. super( path.getPoints( capSegments ), radialSegments );
  19265. this.type = 'CapsuleGeometry';
  19266. this.parameters = {
  19267. radius: radius,
  19268. height: length,
  19269. capSegments: capSegments,
  19270. radialSegments: radialSegments,
  19271. };
  19272. }
  19273. static fromJSON( data ) {
  19274. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19275. }
  19276. }
  19277. class CircleGeometry extends BufferGeometry {
  19278. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19279. super();
  19280. this.type = 'CircleGeometry';
  19281. this.parameters = {
  19282. radius: radius,
  19283. segments: segments,
  19284. thetaStart: thetaStart,
  19285. thetaLength: thetaLength
  19286. };
  19287. segments = Math.max( 3, segments );
  19288. // buffers
  19289. const indices = [];
  19290. const vertices = [];
  19291. const normals = [];
  19292. const uvs = [];
  19293. // helper variables
  19294. const vertex = new Vector3();
  19295. const uv = new Vector2();
  19296. // center point
  19297. vertices.push( 0, 0, 0 );
  19298. normals.push( 0, 0, 1 );
  19299. uvs.push( 0.5, 0.5 );
  19300. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19301. const segment = thetaStart + s / segments * thetaLength;
  19302. // vertex
  19303. vertex.x = radius * Math.cos( segment );
  19304. vertex.y = radius * Math.sin( segment );
  19305. vertices.push( vertex.x, vertex.y, vertex.z );
  19306. // normal
  19307. normals.push( 0, 0, 1 );
  19308. // uvs
  19309. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19310. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19311. uvs.push( uv.x, uv.y );
  19312. }
  19313. // indices
  19314. for ( let i = 1; i <= segments; i ++ ) {
  19315. indices.push( i, i + 1, 0 );
  19316. }
  19317. // build geometry
  19318. this.setIndex( indices );
  19319. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19320. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19321. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19322. }
  19323. static fromJSON( data ) {
  19324. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19325. }
  19326. }
  19327. class CylinderGeometry extends BufferGeometry {
  19328. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19329. super();
  19330. this.type = 'CylinderGeometry';
  19331. this.parameters = {
  19332. radiusTop: radiusTop,
  19333. radiusBottom: radiusBottom,
  19334. height: height,
  19335. radialSegments: radialSegments,
  19336. heightSegments: heightSegments,
  19337. openEnded: openEnded,
  19338. thetaStart: thetaStart,
  19339. thetaLength: thetaLength
  19340. };
  19341. const scope = this;
  19342. radialSegments = Math.floor( radialSegments );
  19343. heightSegments = Math.floor( heightSegments );
  19344. // buffers
  19345. const indices = [];
  19346. const vertices = [];
  19347. const normals = [];
  19348. const uvs = [];
  19349. // helper variables
  19350. let index = 0;
  19351. const indexArray = [];
  19352. const halfHeight = height / 2;
  19353. let groupStart = 0;
  19354. // generate geometry
  19355. generateTorso();
  19356. if ( openEnded === false ) {
  19357. if ( radiusTop > 0 ) generateCap( true );
  19358. if ( radiusBottom > 0 ) generateCap( false );
  19359. }
  19360. // build geometry
  19361. this.setIndex( indices );
  19362. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19363. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19364. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19365. function generateTorso() {
  19366. const normal = new Vector3();
  19367. const vertex = new Vector3();
  19368. let groupCount = 0;
  19369. // this will be used to calculate the normal
  19370. const slope = ( radiusBottom - radiusTop ) / height;
  19371. // generate vertices, normals and uvs
  19372. for ( let y = 0; y <= heightSegments; y ++ ) {
  19373. const indexRow = [];
  19374. const v = y / heightSegments;
  19375. // calculate the radius of the current row
  19376. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19377. for ( let x = 0; x <= radialSegments; x ++ ) {
  19378. const u = x / radialSegments;
  19379. const theta = u * thetaLength + thetaStart;
  19380. const sinTheta = Math.sin( theta );
  19381. const cosTheta = Math.cos( theta );
  19382. // vertex
  19383. vertex.x = radius * sinTheta;
  19384. vertex.y = - v * height + halfHeight;
  19385. vertex.z = radius * cosTheta;
  19386. vertices.push( vertex.x, vertex.y, vertex.z );
  19387. // normal
  19388. normal.set( sinTheta, slope, cosTheta ).normalize();
  19389. normals.push( normal.x, normal.y, normal.z );
  19390. // uv
  19391. uvs.push( u, 1 - v );
  19392. // save index of vertex in respective row
  19393. indexRow.push( index ++ );
  19394. }
  19395. // now save vertices of the row in our index array
  19396. indexArray.push( indexRow );
  19397. }
  19398. // generate indices
  19399. for ( let x = 0; x < radialSegments; x ++ ) {
  19400. for ( let y = 0; y < heightSegments; y ++ ) {
  19401. // we use the index array to access the correct indices
  19402. const a = indexArray[ y ][ x ];
  19403. const b = indexArray[ y + 1 ][ x ];
  19404. const c = indexArray[ y + 1 ][ x + 1 ];
  19405. const d = indexArray[ y ][ x + 1 ];
  19406. // faces
  19407. indices.push( a, b, d );
  19408. indices.push( b, c, d );
  19409. // update group counter
  19410. groupCount += 6;
  19411. }
  19412. }
  19413. // add a group to the geometry. this will ensure multi material support
  19414. scope.addGroup( groupStart, groupCount, 0 );
  19415. // calculate new start value for groups
  19416. groupStart += groupCount;
  19417. }
  19418. function generateCap( top ) {
  19419. // save the index of the first center vertex
  19420. const centerIndexStart = index;
  19421. const uv = new Vector2();
  19422. const vertex = new Vector3();
  19423. let groupCount = 0;
  19424. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19425. const sign = ( top === true ) ? 1 : - 1;
  19426. // first we generate the center vertex data of the cap.
  19427. // because the geometry needs one set of uvs per face,
  19428. // we must generate a center vertex per face/segment
  19429. for ( let x = 1; x <= radialSegments; x ++ ) {
  19430. // vertex
  19431. vertices.push( 0, halfHeight * sign, 0 );
  19432. // normal
  19433. normals.push( 0, sign, 0 );
  19434. // uv
  19435. uvs.push( 0.5, 0.5 );
  19436. // increase index
  19437. index ++;
  19438. }
  19439. // save the index of the last center vertex
  19440. const centerIndexEnd = index;
  19441. // now we generate the surrounding vertices, normals and uvs
  19442. for ( let x = 0; x <= radialSegments; x ++ ) {
  19443. const u = x / radialSegments;
  19444. const theta = u * thetaLength + thetaStart;
  19445. const cosTheta = Math.cos( theta );
  19446. const sinTheta = Math.sin( theta );
  19447. // vertex
  19448. vertex.x = radius * sinTheta;
  19449. vertex.y = halfHeight * sign;
  19450. vertex.z = radius * cosTheta;
  19451. vertices.push( vertex.x, vertex.y, vertex.z );
  19452. // normal
  19453. normals.push( 0, sign, 0 );
  19454. // uv
  19455. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19456. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19457. uvs.push( uv.x, uv.y );
  19458. // increase index
  19459. index ++;
  19460. }
  19461. // generate indices
  19462. for ( let x = 0; x < radialSegments; x ++ ) {
  19463. const c = centerIndexStart + x;
  19464. const i = centerIndexEnd + x;
  19465. if ( top === true ) {
  19466. // face top
  19467. indices.push( i, i + 1, c );
  19468. } else {
  19469. // face bottom
  19470. indices.push( i + 1, i, c );
  19471. }
  19472. groupCount += 3;
  19473. }
  19474. // add a group to the geometry. this will ensure multi material support
  19475. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19476. // calculate new start value for groups
  19477. groupStart += groupCount;
  19478. }
  19479. }
  19480. static fromJSON( data ) {
  19481. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19482. }
  19483. }
  19484. class ConeGeometry extends CylinderGeometry {
  19485. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19486. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19487. this.type = 'ConeGeometry';
  19488. this.parameters = {
  19489. radius: radius,
  19490. height: height,
  19491. radialSegments: radialSegments,
  19492. heightSegments: heightSegments,
  19493. openEnded: openEnded,
  19494. thetaStart: thetaStart,
  19495. thetaLength: thetaLength
  19496. };
  19497. }
  19498. static fromJSON( data ) {
  19499. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19500. }
  19501. }
  19502. class PolyhedronGeometry extends BufferGeometry {
  19503. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  19504. super();
  19505. this.type = 'PolyhedronGeometry';
  19506. this.parameters = {
  19507. vertices: vertices,
  19508. indices: indices,
  19509. radius: radius,
  19510. detail: detail
  19511. };
  19512. // default buffer data
  19513. const vertexBuffer = [];
  19514. const uvBuffer = [];
  19515. // the subdivision creates the vertex buffer data
  19516. subdivide( detail );
  19517. // all vertices should lie on a conceptual sphere with a given radius
  19518. applyRadius( radius );
  19519. // finally, create the uv data
  19520. generateUVs();
  19521. // build non-indexed geometry
  19522. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19523. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19524. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19525. if ( detail === 0 ) {
  19526. this.computeVertexNormals(); // flat normals
  19527. } else {
  19528. this.normalizeNormals(); // smooth normals
  19529. }
  19530. // helper functions
  19531. function subdivide( detail ) {
  19532. const a = new Vector3();
  19533. const b = new Vector3();
  19534. const c = new Vector3();
  19535. // iterate over all faces and apply a subdivison with the given detail value
  19536. for ( let i = 0; i < indices.length; i += 3 ) {
  19537. // get the vertices of the face
  19538. getVertexByIndex( indices[ i + 0 ], a );
  19539. getVertexByIndex( indices[ i + 1 ], b );
  19540. getVertexByIndex( indices[ i + 2 ], c );
  19541. // perform subdivision
  19542. subdivideFace( a, b, c, detail );
  19543. }
  19544. }
  19545. function subdivideFace( a, b, c, detail ) {
  19546. const cols = detail + 1;
  19547. // we use this multidimensional array as a data structure for creating the subdivision
  19548. const v = [];
  19549. // construct all of the vertices for this subdivision
  19550. for ( let i = 0; i <= cols; i ++ ) {
  19551. v[ i ] = [];
  19552. const aj = a.clone().lerp( c, i / cols );
  19553. const bj = b.clone().lerp( c, i / cols );
  19554. const rows = cols - i;
  19555. for ( let j = 0; j <= rows; j ++ ) {
  19556. if ( j === 0 && i === cols ) {
  19557. v[ i ][ j ] = aj;
  19558. } else {
  19559. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19560. }
  19561. }
  19562. }
  19563. // construct all of the faces
  19564. for ( let i = 0; i < cols; i ++ ) {
  19565. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19566. const k = Math.floor( j / 2 );
  19567. if ( j % 2 === 0 ) {
  19568. pushVertex( v[ i ][ k + 1 ] );
  19569. pushVertex( v[ i + 1 ][ k ] );
  19570. pushVertex( v[ i ][ k ] );
  19571. } else {
  19572. pushVertex( v[ i ][ k + 1 ] );
  19573. pushVertex( v[ i + 1 ][ k + 1 ] );
  19574. pushVertex( v[ i + 1 ][ k ] );
  19575. }
  19576. }
  19577. }
  19578. }
  19579. function applyRadius( radius ) {
  19580. const vertex = new Vector3();
  19581. // iterate over the entire buffer and apply the radius to each vertex
  19582. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19583. vertex.x = vertexBuffer[ i + 0 ];
  19584. vertex.y = vertexBuffer[ i + 1 ];
  19585. vertex.z = vertexBuffer[ i + 2 ];
  19586. vertex.normalize().multiplyScalar( radius );
  19587. vertexBuffer[ i + 0 ] = vertex.x;
  19588. vertexBuffer[ i + 1 ] = vertex.y;
  19589. vertexBuffer[ i + 2 ] = vertex.z;
  19590. }
  19591. }
  19592. function generateUVs() {
  19593. const vertex = new Vector3();
  19594. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19595. vertex.x = vertexBuffer[ i + 0 ];
  19596. vertex.y = vertexBuffer[ i + 1 ];
  19597. vertex.z = vertexBuffer[ i + 2 ];
  19598. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19599. const v = inclination( vertex ) / Math.PI + 0.5;
  19600. uvBuffer.push( u, 1 - v );
  19601. }
  19602. correctUVs();
  19603. correctSeam();
  19604. }
  19605. function correctSeam() {
  19606. // handle case when face straddles the seam, see #3269
  19607. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  19608. // uv data of a single face
  19609. const x0 = uvBuffer[ i + 0 ];
  19610. const x1 = uvBuffer[ i + 2 ];
  19611. const x2 = uvBuffer[ i + 4 ];
  19612. const max = Math.max( x0, x1, x2 );
  19613. const min = Math.min( x0, x1, x2 );
  19614. // 0.9 is somewhat arbitrary
  19615. if ( max > 0.9 && min < 0.1 ) {
  19616. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19617. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19618. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19619. }
  19620. }
  19621. }
  19622. function pushVertex( vertex ) {
  19623. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19624. }
  19625. function getVertexByIndex( index, vertex ) {
  19626. const stride = index * 3;
  19627. vertex.x = vertices[ stride + 0 ];
  19628. vertex.y = vertices[ stride + 1 ];
  19629. vertex.z = vertices[ stride + 2 ];
  19630. }
  19631. function correctUVs() {
  19632. const a = new Vector3();
  19633. const b = new Vector3();
  19634. const c = new Vector3();
  19635. const centroid = new Vector3();
  19636. const uvA = new Vector2();
  19637. const uvB = new Vector2();
  19638. const uvC = new Vector2();
  19639. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19640. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19641. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19642. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19643. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19644. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19645. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19646. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19647. const azi = azimuth( centroid );
  19648. correctUV( uvA, j + 0, a, azi );
  19649. correctUV( uvB, j + 2, b, azi );
  19650. correctUV( uvC, j + 4, c, azi );
  19651. }
  19652. }
  19653. function correctUV( uv, stride, vector, azimuth ) {
  19654. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19655. uvBuffer[ stride ] = uv.x - 1;
  19656. }
  19657. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19658. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19659. }
  19660. }
  19661. // Angle around the Y axis, counter-clockwise when looking from above.
  19662. function azimuth( vector ) {
  19663. return Math.atan2( vector.z, - vector.x );
  19664. }
  19665. // Angle above the XZ plane.
  19666. function inclination( vector ) {
  19667. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19668. }
  19669. }
  19670. static fromJSON( data ) {
  19671. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  19672. }
  19673. }
  19674. class DodecahedronGeometry extends PolyhedronGeometry {
  19675. constructor( radius = 1, detail = 0 ) {
  19676. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19677. const r = 1 / t;
  19678. const vertices = [
  19679. // (±1, ±1, ±1)
  19680. - 1, - 1, - 1, - 1, - 1, 1,
  19681. - 1, 1, - 1, - 1, 1, 1,
  19682. 1, - 1, - 1, 1, - 1, 1,
  19683. 1, 1, - 1, 1, 1, 1,
  19684. // (0, ±1/φ, ±φ)
  19685. 0, - r, - t, 0, - r, t,
  19686. 0, r, - t, 0, r, t,
  19687. // (±1/φ, ±φ, 0)
  19688. - r, - t, 0, - r, t, 0,
  19689. r, - t, 0, r, t, 0,
  19690. // (±φ, 0, ±1/φ)
  19691. - t, 0, - r, t, 0, - r,
  19692. - t, 0, r, t, 0, r
  19693. ];
  19694. const indices = [
  19695. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19696. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19697. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19698. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19699. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19700. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19701. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19702. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19703. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19704. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19705. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19706. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19707. ];
  19708. super( vertices, indices, radius, detail );
  19709. this.type = 'DodecahedronGeometry';
  19710. this.parameters = {
  19711. radius: radius,
  19712. detail: detail
  19713. };
  19714. }
  19715. static fromJSON( data ) {
  19716. return new DodecahedronGeometry( data.radius, data.detail );
  19717. }
  19718. }
  19719. const _v0 = new Vector3();
  19720. const _v1$1 = new Vector3();
  19721. const _normal = new Vector3();
  19722. const _triangle = new Triangle();
  19723. class EdgesGeometry extends BufferGeometry {
  19724. constructor( geometry = null, thresholdAngle = 1 ) {
  19725. super();
  19726. this.type = 'EdgesGeometry';
  19727. this.parameters = {
  19728. geometry: geometry,
  19729. thresholdAngle: thresholdAngle
  19730. };
  19731. if ( geometry !== null ) {
  19732. const precisionPoints = 4;
  19733. const precision = Math.pow( 10, precisionPoints );
  19734. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  19735. const indexAttr = geometry.getIndex();
  19736. const positionAttr = geometry.getAttribute( 'position' );
  19737. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19738. const indexArr = [ 0, 0, 0 ];
  19739. const vertKeys = [ 'a', 'b', 'c' ];
  19740. const hashes = new Array( 3 );
  19741. const edgeData = {};
  19742. const vertices = [];
  19743. for ( let i = 0; i < indexCount; i += 3 ) {
  19744. if ( indexAttr ) {
  19745. indexArr[ 0 ] = indexAttr.getX( i );
  19746. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  19747. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  19748. } else {
  19749. indexArr[ 0 ] = i;
  19750. indexArr[ 1 ] = i + 1;
  19751. indexArr[ 2 ] = i + 2;
  19752. }
  19753. const { a, b, c } = _triangle;
  19754. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  19755. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  19756. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  19757. _triangle.getNormal( _normal );
  19758. // create hashes for the edge from the vertices
  19759. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  19760. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  19761. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  19762. // skip degenerate triangles
  19763. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  19764. continue;
  19765. }
  19766. // iterate over every edge
  19767. for ( let j = 0; j < 3; j ++ ) {
  19768. // get the first and next vertex making up the edge
  19769. const jNext = ( j + 1 ) % 3;
  19770. const vecHash0 = hashes[ j ];
  19771. const vecHash1 = hashes[ jNext ];
  19772. const v0 = _triangle[ vertKeys[ j ] ];
  19773. const v1 = _triangle[ vertKeys[ jNext ] ];
  19774. const hash = `${ vecHash0 }_${ vecHash1 }`;
  19775. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  19776. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  19777. // if we found a sibling edge add it into the vertex array if
  19778. // it meets the angle threshold and delete the edge from the map.
  19779. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  19780. vertices.push( v0.x, v0.y, v0.z );
  19781. vertices.push( v1.x, v1.y, v1.z );
  19782. }
  19783. edgeData[ reverseHash ] = null;
  19784. } else if ( ! ( hash in edgeData ) ) {
  19785. // if we've already got an edge here then skip adding a new one
  19786. edgeData[ hash ] = {
  19787. index0: indexArr[ j ],
  19788. index1: indexArr[ jNext ],
  19789. normal: _normal.clone(),
  19790. };
  19791. }
  19792. }
  19793. }
  19794. // iterate over all remaining, unmatched edges and add them to the vertex array
  19795. for ( const key in edgeData ) {
  19796. if ( edgeData[ key ] ) {
  19797. const { index0, index1 } = edgeData[ key ];
  19798. _v0.fromBufferAttribute( positionAttr, index0 );
  19799. _v1$1.fromBufferAttribute( positionAttr, index1 );
  19800. vertices.push( _v0.x, _v0.y, _v0.z );
  19801. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  19802. }
  19803. }
  19804. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19805. }
  19806. }
  19807. }
  19808. class Shape extends Path {
  19809. constructor( points ) {
  19810. super( points );
  19811. this.uuid = generateUUID();
  19812. this.type = 'Shape';
  19813. this.holes = [];
  19814. }
  19815. getPointsHoles( divisions ) {
  19816. const holesPts = [];
  19817. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19818. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  19819. }
  19820. return holesPts;
  19821. }
  19822. // get points of shape and holes (keypoints based on segments parameter)
  19823. extractPoints( divisions ) {
  19824. return {
  19825. shape: this.getPoints( divisions ),
  19826. holes: this.getPointsHoles( divisions )
  19827. };
  19828. }
  19829. copy( source ) {
  19830. super.copy( source );
  19831. this.holes = [];
  19832. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  19833. const hole = source.holes[ i ];
  19834. this.holes.push( hole.clone() );
  19835. }
  19836. return this;
  19837. }
  19838. toJSON() {
  19839. const data = super.toJSON();
  19840. data.uuid = this.uuid;
  19841. data.holes = [];
  19842. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19843. const hole = this.holes[ i ];
  19844. data.holes.push( hole.toJSON() );
  19845. }
  19846. return data;
  19847. }
  19848. fromJSON( json ) {
  19849. super.fromJSON( json );
  19850. this.uuid = json.uuid;
  19851. this.holes = [];
  19852. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  19853. const hole = json.holes[ i ];
  19854. this.holes.push( new Path().fromJSON( hole ) );
  19855. }
  19856. return this;
  19857. }
  19858. }
  19859. /**
  19860. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19861. */
  19862. const Earcut = {
  19863. triangulate: function ( data, holeIndices, dim = 2 ) {
  19864. const hasHoles = holeIndices && holeIndices.length;
  19865. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  19866. let outerNode = linkedList( data, 0, outerLen, dim, true );
  19867. const triangles = [];
  19868. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  19869. let minX, minY, maxX, maxY, x, y, invSize;
  19870. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  19871. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19872. if ( data.length > 80 * dim ) {
  19873. minX = maxX = data[ 0 ];
  19874. minY = maxY = data[ 1 ];
  19875. for ( let i = dim; i < outerLen; i += dim ) {
  19876. x = data[ i ];
  19877. y = data[ i + 1 ];
  19878. if ( x < minX ) minX = x;
  19879. if ( y < minY ) minY = y;
  19880. if ( x > maxX ) maxX = x;
  19881. if ( y > maxY ) maxY = y;
  19882. }
  19883. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19884. invSize = Math.max( maxX - minX, maxY - minY );
  19885. invSize = invSize !== 0 ? 1 / invSize : 0;
  19886. }
  19887. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  19888. return triangles;
  19889. }
  19890. };
  19891. // create a circular doubly linked list from polygon points in the specified winding order
  19892. function linkedList( data, start, end, dim, clockwise ) {
  19893. let i, last;
  19894. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  19895. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19896. } else {
  19897. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19898. }
  19899. if ( last && equals( last, last.next ) ) {
  19900. removeNode( last );
  19901. last = last.next;
  19902. }
  19903. return last;
  19904. }
  19905. // eliminate colinear or duplicate points
  19906. function filterPoints( start, end ) {
  19907. if ( ! start ) return start;
  19908. if ( ! end ) end = start;
  19909. let p = start,
  19910. again;
  19911. do {
  19912. again = false;
  19913. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  19914. removeNode( p );
  19915. p = end = p.prev;
  19916. if ( p === p.next ) break;
  19917. again = true;
  19918. } else {
  19919. p = p.next;
  19920. }
  19921. } while ( again || p !== end );
  19922. return end;
  19923. }
  19924. // main ear slicing loop which triangulates a polygon (given as a linked list)
  19925. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  19926. if ( ! ear ) return;
  19927. // interlink polygon nodes in z-order
  19928. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  19929. let stop = ear,
  19930. prev, next;
  19931. // iterate through ears, slicing them one by one
  19932. while ( ear.prev !== ear.next ) {
  19933. prev = ear.prev;
  19934. next = ear.next;
  19935. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  19936. // cut off the triangle
  19937. triangles.push( prev.i / dim );
  19938. triangles.push( ear.i / dim );
  19939. triangles.push( next.i / dim );
  19940. removeNode( ear );
  19941. // skipping the next vertex leads to less sliver triangles
  19942. ear = next.next;
  19943. stop = next.next;
  19944. continue;
  19945. }
  19946. ear = next;
  19947. // if we looped through the whole remaining polygon and can't find any more ears
  19948. if ( ear === stop ) {
  19949. // try filtering points and slicing again
  19950. if ( ! pass ) {
  19951. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  19952. // if this didn't work, try curing all small self-intersections locally
  19953. } else if ( pass === 1 ) {
  19954. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  19955. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  19956. // as a last resort, try splitting the remaining polygon into two
  19957. } else if ( pass === 2 ) {
  19958. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  19959. }
  19960. break;
  19961. }
  19962. }
  19963. }
  19964. // check whether a polygon node forms a valid ear with adjacent nodes
  19965. function isEar( ear ) {
  19966. const a = ear.prev,
  19967. b = ear,
  19968. c = ear.next;
  19969. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19970. // now make sure we don't have other points inside the potential ear
  19971. let p = ear.next.next;
  19972. while ( p !== ear.prev ) {
  19973. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19974. area( p.prev, p, p.next ) >= 0 ) return false;
  19975. p = p.next;
  19976. }
  19977. return true;
  19978. }
  19979. function isEarHashed( ear, minX, minY, invSize ) {
  19980. const a = ear.prev,
  19981. b = ear,
  19982. c = ear.next;
  19983. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19984. // triangle bbox; min & max are calculated like this for speed
  19985. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  19986. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  19987. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  19988. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  19989. // z-order range for the current triangle bbox;
  19990. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  19991. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  19992. let p = ear.prevZ,
  19993. n = ear.nextZ;
  19994. // look for points inside the triangle in both directions
  19995. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19996. if ( p !== ear.prev && p !== ear.next &&
  19997. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19998. area( p.prev, p, p.next ) >= 0 ) return false;
  19999. p = p.prevZ;
  20000. if ( n !== ear.prev && n !== ear.next &&
  20001. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20002. area( n.prev, n, n.next ) >= 0 ) return false;
  20003. n = n.nextZ;
  20004. }
  20005. // look for remaining points in decreasing z-order
  20006. while ( p && p.z >= minZ ) {
  20007. if ( p !== ear.prev && p !== ear.next &&
  20008. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20009. area( p.prev, p, p.next ) >= 0 ) return false;
  20010. p = p.prevZ;
  20011. }
  20012. // look for remaining points in increasing z-order
  20013. while ( n && n.z <= maxZ ) {
  20014. if ( n !== ear.prev && n !== ear.next &&
  20015. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20016. area( n.prev, n, n.next ) >= 0 ) return false;
  20017. n = n.nextZ;
  20018. }
  20019. return true;
  20020. }
  20021. // go through all polygon nodes and cure small local self-intersections
  20022. function cureLocalIntersections( start, triangles, dim ) {
  20023. let p = start;
  20024. do {
  20025. const a = p.prev,
  20026. b = p.next.next;
  20027. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20028. triangles.push( a.i / dim );
  20029. triangles.push( p.i / dim );
  20030. triangles.push( b.i / dim );
  20031. // remove two nodes involved
  20032. removeNode( p );
  20033. removeNode( p.next );
  20034. p = start = b;
  20035. }
  20036. p = p.next;
  20037. } while ( p !== start );
  20038. return filterPoints( p );
  20039. }
  20040. // try splitting polygon into two and triangulate them independently
  20041. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20042. // look for a valid diagonal that divides the polygon into two
  20043. let a = start;
  20044. do {
  20045. let b = a.next.next;
  20046. while ( b !== a.prev ) {
  20047. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20048. // split the polygon in two by the diagonal
  20049. let c = splitPolygon( a, b );
  20050. // filter colinear points around the cuts
  20051. a = filterPoints( a, a.next );
  20052. c = filterPoints( c, c.next );
  20053. // run earcut on each half
  20054. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20055. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20056. return;
  20057. }
  20058. b = b.next;
  20059. }
  20060. a = a.next;
  20061. } while ( a !== start );
  20062. }
  20063. // link every hole into the outer loop, producing a single-ring polygon without holes
  20064. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20065. const queue = [];
  20066. let i, len, start, end, list;
  20067. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20068. start = holeIndices[ i ] * dim;
  20069. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20070. list = linkedList( data, start, end, dim, false );
  20071. if ( list === list.next ) list.steiner = true;
  20072. queue.push( getLeftmost( list ) );
  20073. }
  20074. queue.sort( compareX );
  20075. // process holes from left to right
  20076. for ( i = 0; i < queue.length; i ++ ) {
  20077. eliminateHole( queue[ i ], outerNode );
  20078. outerNode = filterPoints( outerNode, outerNode.next );
  20079. }
  20080. return outerNode;
  20081. }
  20082. function compareX( a, b ) {
  20083. return a.x - b.x;
  20084. }
  20085. // find a bridge between vertices that connects hole with an outer ring and link it
  20086. function eliminateHole( hole, outerNode ) {
  20087. outerNode = findHoleBridge( hole, outerNode );
  20088. if ( outerNode ) {
  20089. const b = splitPolygon( outerNode, hole );
  20090. // filter collinear points around the cuts
  20091. filterPoints( outerNode, outerNode.next );
  20092. filterPoints( b, b.next );
  20093. }
  20094. }
  20095. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20096. function findHoleBridge( hole, outerNode ) {
  20097. let p = outerNode;
  20098. const hx = hole.x;
  20099. const hy = hole.y;
  20100. let qx = - Infinity, m;
  20101. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20102. // segment's endpoint with lesser x will be potential connection point
  20103. do {
  20104. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20105. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20106. if ( x <= hx && x > qx ) {
  20107. qx = x;
  20108. if ( x === hx ) {
  20109. if ( hy === p.y ) return p;
  20110. if ( hy === p.next.y ) return p.next;
  20111. }
  20112. m = p.x < p.next.x ? p : p.next;
  20113. }
  20114. }
  20115. p = p.next;
  20116. } while ( p !== outerNode );
  20117. if ( ! m ) return null;
  20118. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  20119. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20120. // if there are no points found, we have a valid connection;
  20121. // otherwise choose the point of the minimum angle with the ray as connection point
  20122. const stop = m,
  20123. mx = m.x,
  20124. my = m.y;
  20125. let tanMin = Infinity, tan;
  20126. p = m;
  20127. do {
  20128. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20129. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20130. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20131. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20132. m = p;
  20133. tanMin = tan;
  20134. }
  20135. }
  20136. p = p.next;
  20137. } while ( p !== stop );
  20138. return m;
  20139. }
  20140. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20141. function sectorContainsSector( m, p ) {
  20142. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20143. }
  20144. // interlink polygon nodes in z-order
  20145. function indexCurve( start, minX, minY, invSize ) {
  20146. let p = start;
  20147. do {
  20148. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20149. p.prevZ = p.prev;
  20150. p.nextZ = p.next;
  20151. p = p.next;
  20152. } while ( p !== start );
  20153. p.prevZ.nextZ = null;
  20154. p.prevZ = null;
  20155. sortLinked( p );
  20156. }
  20157. // Simon Tatham's linked list merge sort algorithm
  20158. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20159. function sortLinked( list ) {
  20160. let i, p, q, e, tail, numMerges, pSize, qSize,
  20161. inSize = 1;
  20162. do {
  20163. p = list;
  20164. list = null;
  20165. tail = null;
  20166. numMerges = 0;
  20167. while ( p ) {
  20168. numMerges ++;
  20169. q = p;
  20170. pSize = 0;
  20171. for ( i = 0; i < inSize; i ++ ) {
  20172. pSize ++;
  20173. q = q.nextZ;
  20174. if ( ! q ) break;
  20175. }
  20176. qSize = inSize;
  20177. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20178. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20179. e = p;
  20180. p = p.nextZ;
  20181. pSize --;
  20182. } else {
  20183. e = q;
  20184. q = q.nextZ;
  20185. qSize --;
  20186. }
  20187. if ( tail ) tail.nextZ = e;
  20188. else list = e;
  20189. e.prevZ = tail;
  20190. tail = e;
  20191. }
  20192. p = q;
  20193. }
  20194. tail.nextZ = null;
  20195. inSize *= 2;
  20196. } while ( numMerges > 1 );
  20197. return list;
  20198. }
  20199. // z-order of a point given coords and inverse of the longer side of data bbox
  20200. function zOrder( x, y, minX, minY, invSize ) {
  20201. // coords are transformed into non-negative 15-bit integer range
  20202. x = 32767 * ( x - minX ) * invSize;
  20203. y = 32767 * ( y - minY ) * invSize;
  20204. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20205. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20206. x = ( x | ( x << 2 ) ) & 0x33333333;
  20207. x = ( x | ( x << 1 ) ) & 0x55555555;
  20208. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20209. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20210. y = ( y | ( y << 2 ) ) & 0x33333333;
  20211. y = ( y | ( y << 1 ) ) & 0x55555555;
  20212. return x | ( y << 1 );
  20213. }
  20214. // find the leftmost node of a polygon ring
  20215. function getLeftmost( start ) {
  20216. let p = start,
  20217. leftmost = start;
  20218. do {
  20219. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20220. p = p.next;
  20221. } while ( p !== start );
  20222. return leftmost;
  20223. }
  20224. // check if a point lies within a convex triangle
  20225. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20226. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20227. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20228. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20229. }
  20230. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20231. function isValidDiagonal( a, b ) {
  20232. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  20233. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20234. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20235. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20236. }
  20237. // signed area of a triangle
  20238. function area( p, q, r ) {
  20239. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20240. }
  20241. // check if two points are equal
  20242. function equals( p1, p2 ) {
  20243. return p1.x === p2.x && p1.y === p2.y;
  20244. }
  20245. // check if two segments intersect
  20246. function intersects( p1, q1, p2, q2 ) {
  20247. const o1 = sign( area( p1, q1, p2 ) );
  20248. const o2 = sign( area( p1, q1, q2 ) );
  20249. const o3 = sign( area( p2, q2, p1 ) );
  20250. const o4 = sign( area( p2, q2, q1 ) );
  20251. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20252. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20253. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20254. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20255. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20256. return false;
  20257. }
  20258. // for collinear points p, q, r, check if point q lies on segment pr
  20259. function onSegment( p, q, r ) {
  20260. 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 );
  20261. }
  20262. function sign( num ) {
  20263. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20264. }
  20265. // check if a polygon diagonal intersects any polygon segments
  20266. function intersectsPolygon( a, b ) {
  20267. let p = a;
  20268. do {
  20269. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20270. intersects( p, p.next, a, b ) ) return true;
  20271. p = p.next;
  20272. } while ( p !== a );
  20273. return false;
  20274. }
  20275. // check if a polygon diagonal is locally inside the polygon
  20276. function locallyInside( a, b ) {
  20277. return area( a.prev, a, a.next ) < 0 ?
  20278. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20279. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20280. }
  20281. // check if the middle point of a polygon diagonal is inside the polygon
  20282. function middleInside( a, b ) {
  20283. let p = a,
  20284. inside = false;
  20285. const px = ( a.x + b.x ) / 2,
  20286. py = ( a.y + b.y ) / 2;
  20287. do {
  20288. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20289. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20290. inside = ! inside;
  20291. p = p.next;
  20292. } while ( p !== a );
  20293. return inside;
  20294. }
  20295. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20296. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20297. function splitPolygon( a, b ) {
  20298. const a2 = new Node( a.i, a.x, a.y ),
  20299. b2 = new Node( b.i, b.x, b.y ),
  20300. an = a.next,
  20301. bp = b.prev;
  20302. a.next = b;
  20303. b.prev = a;
  20304. a2.next = an;
  20305. an.prev = a2;
  20306. b2.next = a2;
  20307. a2.prev = b2;
  20308. bp.next = b2;
  20309. b2.prev = bp;
  20310. return b2;
  20311. }
  20312. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20313. function insertNode( i, x, y, last ) {
  20314. const p = new Node( i, x, y );
  20315. if ( ! last ) {
  20316. p.prev = p;
  20317. p.next = p;
  20318. } else {
  20319. p.next = last.next;
  20320. p.prev = last;
  20321. last.next.prev = p;
  20322. last.next = p;
  20323. }
  20324. return p;
  20325. }
  20326. function removeNode( p ) {
  20327. p.next.prev = p.prev;
  20328. p.prev.next = p.next;
  20329. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20330. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20331. }
  20332. function Node( i, x, y ) {
  20333. // vertex index in coordinates array
  20334. this.i = i;
  20335. // vertex coordinates
  20336. this.x = x;
  20337. this.y = y;
  20338. // previous and next vertex nodes in a polygon ring
  20339. this.prev = null;
  20340. this.next = null;
  20341. // z-order curve value
  20342. this.z = null;
  20343. // previous and next nodes in z-order
  20344. this.prevZ = null;
  20345. this.nextZ = null;
  20346. // indicates whether this is a steiner point
  20347. this.steiner = false;
  20348. }
  20349. function signedArea( data, start, end, dim ) {
  20350. let sum = 0;
  20351. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20352. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20353. j = i;
  20354. }
  20355. return sum;
  20356. }
  20357. class ShapeUtils {
  20358. // calculate area of the contour polygon
  20359. static area( contour ) {
  20360. const n = contour.length;
  20361. let a = 0.0;
  20362. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20363. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20364. }
  20365. return a * 0.5;
  20366. }
  20367. static isClockWise( pts ) {
  20368. return ShapeUtils.area( pts ) < 0;
  20369. }
  20370. static triangulateShape( contour, holes ) {
  20371. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20372. const holeIndices = []; // array of hole indices
  20373. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20374. removeDupEndPts( contour );
  20375. addContour( vertices, contour );
  20376. //
  20377. let holeIndex = contour.length;
  20378. holes.forEach( removeDupEndPts );
  20379. for ( let i = 0; i < holes.length; i ++ ) {
  20380. holeIndices.push( holeIndex );
  20381. holeIndex += holes[ i ].length;
  20382. addContour( vertices, holes[ i ] );
  20383. }
  20384. //
  20385. const triangles = Earcut.triangulate( vertices, holeIndices );
  20386. //
  20387. for ( let i = 0; i < triangles.length; i += 3 ) {
  20388. faces.push( triangles.slice( i, i + 3 ) );
  20389. }
  20390. return faces;
  20391. }
  20392. }
  20393. function removeDupEndPts( points ) {
  20394. const l = points.length;
  20395. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20396. points.pop();
  20397. }
  20398. }
  20399. function addContour( vertices, contour ) {
  20400. for ( let i = 0; i < contour.length; i ++ ) {
  20401. vertices.push( contour[ i ].x );
  20402. vertices.push( contour[ i ].y );
  20403. }
  20404. }
  20405. /**
  20406. * Creates extruded geometry from a path shape.
  20407. *
  20408. * parameters = {
  20409. *
  20410. * curveSegments: <int>, // number of points on the curves
  20411. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20412. * depth: <float>, // Depth to extrude the shape
  20413. *
  20414. * bevelEnabled: <bool>, // turn on bevel
  20415. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20416. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20417. * bevelOffset: <float>, // how far from shape outline does bevel start
  20418. * bevelSegments: <int>, // number of bevel layers
  20419. *
  20420. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20421. *
  20422. * UVGenerator: <Object> // object that provides UV generator functions
  20423. *
  20424. * }
  20425. */
  20426. class ExtrudeGeometry extends BufferGeometry {
  20427. 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 = {} ) {
  20428. super();
  20429. this.type = 'ExtrudeGeometry';
  20430. this.parameters = {
  20431. shapes: shapes,
  20432. options: options
  20433. };
  20434. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20435. const scope = this;
  20436. const verticesArray = [];
  20437. const uvArray = [];
  20438. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20439. const shape = shapes[ i ];
  20440. addShape( shape );
  20441. }
  20442. // build geometry
  20443. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20444. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20445. this.computeVertexNormals();
  20446. // functions
  20447. function addShape( shape ) {
  20448. const placeholder = [];
  20449. // options
  20450. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20451. const steps = options.steps !== undefined ? options.steps : 1;
  20452. let depth = options.depth !== undefined ? options.depth : 1;
  20453. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20454. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20455. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20456. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20457. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20458. const extrudePath = options.extrudePath;
  20459. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20460. // deprecated options
  20461. if ( options.amount !== undefined ) {
  20462. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  20463. depth = options.amount;
  20464. }
  20465. //
  20466. let extrudePts, extrudeByPath = false;
  20467. let splineTube, binormal, normal, position2;
  20468. if ( extrudePath ) {
  20469. extrudePts = extrudePath.getSpacedPoints( steps );
  20470. extrudeByPath = true;
  20471. bevelEnabled = false; // bevels not supported for path extrusion
  20472. // SETUP TNB variables
  20473. // TODO1 - have a .isClosed in spline?
  20474. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20475. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20476. binormal = new Vector3();
  20477. normal = new Vector3();
  20478. position2 = new Vector3();
  20479. }
  20480. // Safeguards if bevels are not enabled
  20481. if ( ! bevelEnabled ) {
  20482. bevelSegments = 0;
  20483. bevelThickness = 0;
  20484. bevelSize = 0;
  20485. bevelOffset = 0;
  20486. }
  20487. // Variables initialization
  20488. const shapePoints = shape.extractPoints( curveSegments );
  20489. let vertices = shapePoints.shape;
  20490. const holes = shapePoints.holes;
  20491. const reverse = ! ShapeUtils.isClockWise( vertices );
  20492. if ( reverse ) {
  20493. vertices = vertices.reverse();
  20494. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20495. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20496. const ahole = holes[ h ];
  20497. if ( ShapeUtils.isClockWise( ahole ) ) {
  20498. holes[ h ] = ahole.reverse();
  20499. }
  20500. }
  20501. }
  20502. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20503. /* Vertices */
  20504. const contour = vertices; // vertices has all points but contour has only points of circumference
  20505. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20506. const ahole = holes[ h ];
  20507. vertices = vertices.concat( ahole );
  20508. }
  20509. function scalePt2( pt, vec, size ) {
  20510. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20511. return vec.clone().multiplyScalar( size ).add( pt );
  20512. }
  20513. const vlen = vertices.length, flen = faces.length;
  20514. // Find directions for point movement
  20515. function getBevelVec( inPt, inPrev, inNext ) {
  20516. // computes for inPt the corresponding point inPt' on a new contour
  20517. // shifted by 1 unit (length of normalized vector) to the left
  20518. // if we walk along contour clockwise, this new contour is outside the old one
  20519. //
  20520. // inPt' is the intersection of the two lines parallel to the two
  20521. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20522. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20523. // good reading for geometry algorithms (here: line-line intersection)
  20524. // http://geomalgorithms.com/a05-_intersect-1.html
  20525. const v_prev_x = inPt.x - inPrev.x,
  20526. v_prev_y = inPt.y - inPrev.y;
  20527. const v_next_x = inNext.x - inPt.x,
  20528. v_next_y = inNext.y - inPt.y;
  20529. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20530. // check for collinear edges
  20531. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20532. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20533. // not collinear
  20534. // length of vectors for normalizing
  20535. const v_prev_len = Math.sqrt( v_prev_lensq );
  20536. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20537. // shift adjacent points by unit vectors to the left
  20538. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20539. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20540. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20541. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20542. // scaling factor for v_prev to intersection point
  20543. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20544. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20545. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20546. // vector from inPt to intersection point
  20547. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20548. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20549. // Don't normalize!, otherwise sharp corners become ugly
  20550. // but prevent crazy spikes
  20551. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20552. if ( v_trans_lensq <= 2 ) {
  20553. return new Vector2( v_trans_x, v_trans_y );
  20554. } else {
  20555. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20556. }
  20557. } else {
  20558. // handle special case of collinear edges
  20559. let direction_eq = false; // assumes: opposite
  20560. if ( v_prev_x > Number.EPSILON ) {
  20561. if ( v_next_x > Number.EPSILON ) {
  20562. direction_eq = true;
  20563. }
  20564. } else {
  20565. if ( v_prev_x < - Number.EPSILON ) {
  20566. if ( v_next_x < - Number.EPSILON ) {
  20567. direction_eq = true;
  20568. }
  20569. } else {
  20570. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20571. direction_eq = true;
  20572. }
  20573. }
  20574. }
  20575. if ( direction_eq ) {
  20576. // console.log("Warning: lines are a straight sequence");
  20577. v_trans_x = - v_prev_y;
  20578. v_trans_y = v_prev_x;
  20579. shrink_by = Math.sqrt( v_prev_lensq );
  20580. } else {
  20581. // console.log("Warning: lines are a straight spike");
  20582. v_trans_x = v_prev_x;
  20583. v_trans_y = v_prev_y;
  20584. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20585. }
  20586. }
  20587. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20588. }
  20589. const contourMovements = [];
  20590. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20591. if ( j === il ) j = 0;
  20592. if ( k === il ) k = 0;
  20593. // (j)---(i)---(k)
  20594. // console.log('i,j,k', i, j , k)
  20595. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20596. }
  20597. const holesMovements = [];
  20598. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20599. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20600. const ahole = holes[ h ];
  20601. oneHoleMovements = [];
  20602. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20603. if ( j === il ) j = 0;
  20604. if ( k === il ) k = 0;
  20605. // (j)---(i)---(k)
  20606. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20607. }
  20608. holesMovements.push( oneHoleMovements );
  20609. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20610. }
  20611. // Loop bevelSegments, 1 for the front, 1 for the back
  20612. for ( let b = 0; b < bevelSegments; b ++ ) {
  20613. //for ( b = bevelSegments; b > 0; b -- ) {
  20614. const t = b / bevelSegments;
  20615. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20616. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20617. // contract shape
  20618. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20619. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20620. v( vert.x, vert.y, - z );
  20621. }
  20622. // expand holes
  20623. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20624. const ahole = holes[ h ];
  20625. oneHoleMovements = holesMovements[ h ];
  20626. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20627. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20628. v( vert.x, vert.y, - z );
  20629. }
  20630. }
  20631. }
  20632. const bs = bevelSize + bevelOffset;
  20633. // Back facing vertices
  20634. for ( let i = 0; i < vlen; i ++ ) {
  20635. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20636. if ( ! extrudeByPath ) {
  20637. v( vert.x, vert.y, 0 );
  20638. } else {
  20639. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20640. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20641. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20642. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20643. v( position2.x, position2.y, position2.z );
  20644. }
  20645. }
  20646. // Add stepped vertices...
  20647. // Including front facing vertices
  20648. for ( let s = 1; s <= steps; s ++ ) {
  20649. for ( let i = 0; i < vlen; i ++ ) {
  20650. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20651. if ( ! extrudeByPath ) {
  20652. v( vert.x, vert.y, depth / steps * s );
  20653. } else {
  20654. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20655. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20656. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20657. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20658. v( position2.x, position2.y, position2.z );
  20659. }
  20660. }
  20661. }
  20662. // Add bevel segments planes
  20663. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20664. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  20665. const t = b / bevelSegments;
  20666. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20667. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20668. // contract shape
  20669. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20670. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20671. v( vert.x, vert.y, depth + z );
  20672. }
  20673. // expand holes
  20674. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20675. const ahole = holes[ h ];
  20676. oneHoleMovements = holesMovements[ h ];
  20677. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20678. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20679. if ( ! extrudeByPath ) {
  20680. v( vert.x, vert.y, depth + z );
  20681. } else {
  20682. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20683. }
  20684. }
  20685. }
  20686. }
  20687. /* Faces */
  20688. // Top and bottom faces
  20689. buildLidFaces();
  20690. // Sides faces
  20691. buildSideFaces();
  20692. ///// Internal functions
  20693. function buildLidFaces() {
  20694. const start = verticesArray.length / 3;
  20695. if ( bevelEnabled ) {
  20696. let layer = 0; // steps + 1
  20697. let offset = vlen * layer;
  20698. // Bottom faces
  20699. for ( let i = 0; i < flen; i ++ ) {
  20700. const face = faces[ i ];
  20701. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20702. }
  20703. layer = steps + bevelSegments * 2;
  20704. offset = vlen * layer;
  20705. // Top faces
  20706. for ( let i = 0; i < flen; i ++ ) {
  20707. const face = faces[ i ];
  20708. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20709. }
  20710. } else {
  20711. // Bottom faces
  20712. for ( let i = 0; i < flen; i ++ ) {
  20713. const face = faces[ i ];
  20714. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20715. }
  20716. // Top faces
  20717. for ( let i = 0; i < flen; i ++ ) {
  20718. const face = faces[ i ];
  20719. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20720. }
  20721. }
  20722. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  20723. }
  20724. // Create faces for the z-sides of the shape
  20725. function buildSideFaces() {
  20726. const start = verticesArray.length / 3;
  20727. let layeroffset = 0;
  20728. sidewalls( contour, layeroffset );
  20729. layeroffset += contour.length;
  20730. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20731. const ahole = holes[ h ];
  20732. sidewalls( ahole, layeroffset );
  20733. //, true
  20734. layeroffset += ahole.length;
  20735. }
  20736. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  20737. }
  20738. function sidewalls( contour, layeroffset ) {
  20739. let i = contour.length;
  20740. while ( -- i >= 0 ) {
  20741. const j = i;
  20742. let k = i - 1;
  20743. if ( k < 0 ) k = contour.length - 1;
  20744. //console.log('b', i,j, i-1, k,vertices.length);
  20745. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  20746. const slen1 = vlen * s;
  20747. const slen2 = vlen * ( s + 1 );
  20748. const a = layeroffset + j + slen1,
  20749. b = layeroffset + k + slen1,
  20750. c = layeroffset + k + slen2,
  20751. d = layeroffset + j + slen2;
  20752. f4( a, b, c, d );
  20753. }
  20754. }
  20755. }
  20756. function v( x, y, z ) {
  20757. placeholder.push( x );
  20758. placeholder.push( y );
  20759. placeholder.push( z );
  20760. }
  20761. function f3( a, b, c ) {
  20762. addVertex( a );
  20763. addVertex( b );
  20764. addVertex( c );
  20765. const nextIndex = verticesArray.length / 3;
  20766. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20767. addUV( uvs[ 0 ] );
  20768. addUV( uvs[ 1 ] );
  20769. addUV( uvs[ 2 ] );
  20770. }
  20771. function f4( a, b, c, d ) {
  20772. addVertex( a );
  20773. addVertex( b );
  20774. addVertex( d );
  20775. addVertex( b );
  20776. addVertex( c );
  20777. addVertex( d );
  20778. const nextIndex = verticesArray.length / 3;
  20779. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20780. addUV( uvs[ 0 ] );
  20781. addUV( uvs[ 1 ] );
  20782. addUV( uvs[ 3 ] );
  20783. addUV( uvs[ 1 ] );
  20784. addUV( uvs[ 2 ] );
  20785. addUV( uvs[ 3 ] );
  20786. }
  20787. function addVertex( index ) {
  20788. verticesArray.push( placeholder[ index * 3 + 0 ] );
  20789. verticesArray.push( placeholder[ index * 3 + 1 ] );
  20790. verticesArray.push( placeholder[ index * 3 + 2 ] );
  20791. }
  20792. function addUV( vector2 ) {
  20793. uvArray.push( vector2.x );
  20794. uvArray.push( vector2.y );
  20795. }
  20796. }
  20797. }
  20798. toJSON() {
  20799. const data = super.toJSON();
  20800. const shapes = this.parameters.shapes;
  20801. const options = this.parameters.options;
  20802. return toJSON$1( shapes, options, data );
  20803. }
  20804. static fromJSON( data, shapes ) {
  20805. const geometryShapes = [];
  20806. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20807. const shape = shapes[ data.shapes[ j ] ];
  20808. geometryShapes.push( shape );
  20809. }
  20810. const extrudePath = data.options.extrudePath;
  20811. if ( extrudePath !== undefined ) {
  20812. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20813. }
  20814. return new ExtrudeGeometry( geometryShapes, data.options );
  20815. }
  20816. }
  20817. const WorldUVGenerator = {
  20818. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20819. const a_x = vertices[ indexA * 3 ];
  20820. const a_y = vertices[ indexA * 3 + 1 ];
  20821. const b_x = vertices[ indexB * 3 ];
  20822. const b_y = vertices[ indexB * 3 + 1 ];
  20823. const c_x = vertices[ indexC * 3 ];
  20824. const c_y = vertices[ indexC * 3 + 1 ];
  20825. return [
  20826. new Vector2( a_x, a_y ),
  20827. new Vector2( b_x, b_y ),
  20828. new Vector2( c_x, c_y )
  20829. ];
  20830. },
  20831. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20832. const a_x = vertices[ indexA * 3 ];
  20833. const a_y = vertices[ indexA * 3 + 1 ];
  20834. const a_z = vertices[ indexA * 3 + 2 ];
  20835. const b_x = vertices[ indexB * 3 ];
  20836. const b_y = vertices[ indexB * 3 + 1 ];
  20837. const b_z = vertices[ indexB * 3 + 2 ];
  20838. const c_x = vertices[ indexC * 3 ];
  20839. const c_y = vertices[ indexC * 3 + 1 ];
  20840. const c_z = vertices[ indexC * 3 + 2 ];
  20841. const d_x = vertices[ indexD * 3 ];
  20842. const d_y = vertices[ indexD * 3 + 1 ];
  20843. const d_z = vertices[ indexD * 3 + 2 ];
  20844. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  20845. return [
  20846. new Vector2( a_x, 1 - a_z ),
  20847. new Vector2( b_x, 1 - b_z ),
  20848. new Vector2( c_x, 1 - c_z ),
  20849. new Vector2( d_x, 1 - d_z )
  20850. ];
  20851. } else {
  20852. return [
  20853. new Vector2( a_y, 1 - a_z ),
  20854. new Vector2( b_y, 1 - b_z ),
  20855. new Vector2( c_y, 1 - c_z ),
  20856. new Vector2( d_y, 1 - d_z )
  20857. ];
  20858. }
  20859. }
  20860. };
  20861. function toJSON$1( shapes, options, data ) {
  20862. data.shapes = [];
  20863. if ( Array.isArray( shapes ) ) {
  20864. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20865. const shape = shapes[ i ];
  20866. data.shapes.push( shape.uuid );
  20867. }
  20868. } else {
  20869. data.shapes.push( shapes.uuid );
  20870. }
  20871. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  20872. return data;
  20873. }
  20874. class IcosahedronGeometry extends PolyhedronGeometry {
  20875. constructor( radius = 1, detail = 0 ) {
  20876. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20877. const vertices = [
  20878. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20879. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20880. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20881. ];
  20882. const indices = [
  20883. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20884. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20885. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20886. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20887. ];
  20888. super( vertices, indices, radius, detail );
  20889. this.type = 'IcosahedronGeometry';
  20890. this.parameters = {
  20891. radius: radius,
  20892. detail: detail
  20893. };
  20894. }
  20895. static fromJSON( data ) {
  20896. return new IcosahedronGeometry( data.radius, data.detail );
  20897. }
  20898. }
  20899. class OctahedronGeometry extends PolyhedronGeometry {
  20900. constructor( radius = 1, detail = 0 ) {
  20901. const vertices = [
  20902. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  20903. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20904. ];
  20905. const indices = [
  20906. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20907. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20908. 1, 3, 4, 1, 4, 2
  20909. ];
  20910. super( vertices, indices, radius, detail );
  20911. this.type = 'OctahedronGeometry';
  20912. this.parameters = {
  20913. radius: radius,
  20914. detail: detail
  20915. };
  20916. }
  20917. static fromJSON( data ) {
  20918. return new OctahedronGeometry( data.radius, data.detail );
  20919. }
  20920. }
  20921. class RingGeometry extends BufferGeometry {
  20922. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20923. super();
  20924. this.type = 'RingGeometry';
  20925. this.parameters = {
  20926. innerRadius: innerRadius,
  20927. outerRadius: outerRadius,
  20928. thetaSegments: thetaSegments,
  20929. phiSegments: phiSegments,
  20930. thetaStart: thetaStart,
  20931. thetaLength: thetaLength
  20932. };
  20933. thetaSegments = Math.max( 3, thetaSegments );
  20934. phiSegments = Math.max( 1, phiSegments );
  20935. // buffers
  20936. const indices = [];
  20937. const vertices = [];
  20938. const normals = [];
  20939. const uvs = [];
  20940. // some helper variables
  20941. let radius = innerRadius;
  20942. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20943. const vertex = new Vector3();
  20944. const uv = new Vector2();
  20945. // generate vertices, normals and uvs
  20946. for ( let j = 0; j <= phiSegments; j ++ ) {
  20947. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20948. // values are generate from the inside of the ring to the outside
  20949. const segment = thetaStart + i / thetaSegments * thetaLength;
  20950. // vertex
  20951. vertex.x = radius * Math.cos( segment );
  20952. vertex.y = radius * Math.sin( segment );
  20953. vertices.push( vertex.x, vertex.y, vertex.z );
  20954. // normal
  20955. normals.push( 0, 0, 1 );
  20956. // uv
  20957. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20958. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20959. uvs.push( uv.x, uv.y );
  20960. }
  20961. // increase the radius for next row of vertices
  20962. radius += radiusStep;
  20963. }
  20964. // indices
  20965. for ( let j = 0; j < phiSegments; j ++ ) {
  20966. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20967. for ( let i = 0; i < thetaSegments; i ++ ) {
  20968. const segment = i + thetaSegmentLevel;
  20969. const a = segment;
  20970. const b = segment + thetaSegments + 1;
  20971. const c = segment + thetaSegments + 2;
  20972. const d = segment + 1;
  20973. // faces
  20974. indices.push( a, b, d );
  20975. indices.push( b, c, d );
  20976. }
  20977. }
  20978. // build geometry
  20979. this.setIndex( indices );
  20980. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20981. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20982. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20983. }
  20984. static fromJSON( data ) {
  20985. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20986. }
  20987. }
  20988. class ShapeGeometry extends BufferGeometry {
  20989. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  20990. super();
  20991. this.type = 'ShapeGeometry';
  20992. this.parameters = {
  20993. shapes: shapes,
  20994. curveSegments: curveSegments
  20995. };
  20996. // buffers
  20997. const indices = [];
  20998. const vertices = [];
  20999. const normals = [];
  21000. const uvs = [];
  21001. // helper variables
  21002. let groupStart = 0;
  21003. let groupCount = 0;
  21004. // allow single and array values for "shapes" parameter
  21005. if ( Array.isArray( shapes ) === false ) {
  21006. addShape( shapes );
  21007. } else {
  21008. for ( let i = 0; i < shapes.length; i ++ ) {
  21009. addShape( shapes[ i ] );
  21010. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21011. groupStart += groupCount;
  21012. groupCount = 0;
  21013. }
  21014. }
  21015. // build geometry
  21016. this.setIndex( indices );
  21017. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21018. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21019. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21020. // helper functions
  21021. function addShape( shape ) {
  21022. const indexOffset = vertices.length / 3;
  21023. const points = shape.extractPoints( curveSegments );
  21024. let shapeVertices = points.shape;
  21025. const shapeHoles = points.holes;
  21026. // check direction of vertices
  21027. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21028. shapeVertices = shapeVertices.reverse();
  21029. }
  21030. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21031. const shapeHole = shapeHoles[ i ];
  21032. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21033. shapeHoles[ i ] = shapeHole.reverse();
  21034. }
  21035. }
  21036. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21037. // join vertices of inner and outer paths to a single array
  21038. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21039. const shapeHole = shapeHoles[ i ];
  21040. shapeVertices = shapeVertices.concat( shapeHole );
  21041. }
  21042. // vertices, normals, uvs
  21043. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21044. const vertex = shapeVertices[ i ];
  21045. vertices.push( vertex.x, vertex.y, 0 );
  21046. normals.push( 0, 0, 1 );
  21047. uvs.push( vertex.x, vertex.y ); // world uvs
  21048. }
  21049. // incides
  21050. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21051. const face = faces[ i ];
  21052. const a = face[ 0 ] + indexOffset;
  21053. const b = face[ 1 ] + indexOffset;
  21054. const c = face[ 2 ] + indexOffset;
  21055. indices.push( a, b, c );
  21056. groupCount += 3;
  21057. }
  21058. }
  21059. }
  21060. toJSON() {
  21061. const data = super.toJSON();
  21062. const shapes = this.parameters.shapes;
  21063. return toJSON( shapes, data );
  21064. }
  21065. static fromJSON( data, shapes ) {
  21066. const geometryShapes = [];
  21067. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21068. const shape = shapes[ data.shapes[ j ] ];
  21069. geometryShapes.push( shape );
  21070. }
  21071. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21072. }
  21073. }
  21074. function toJSON( shapes, data ) {
  21075. data.shapes = [];
  21076. if ( Array.isArray( shapes ) ) {
  21077. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21078. const shape = shapes[ i ];
  21079. data.shapes.push( shape.uuid );
  21080. }
  21081. } else {
  21082. data.shapes.push( shapes.uuid );
  21083. }
  21084. return data;
  21085. }
  21086. class SphereGeometry extends BufferGeometry {
  21087. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21088. super();
  21089. this.type = 'SphereGeometry';
  21090. this.parameters = {
  21091. radius: radius,
  21092. widthSegments: widthSegments,
  21093. heightSegments: heightSegments,
  21094. phiStart: phiStart,
  21095. phiLength: phiLength,
  21096. thetaStart: thetaStart,
  21097. thetaLength: thetaLength
  21098. };
  21099. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21100. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21101. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21102. let index = 0;
  21103. const grid = [];
  21104. const vertex = new Vector3();
  21105. const normal = new Vector3();
  21106. // buffers
  21107. const indices = [];
  21108. const vertices = [];
  21109. const normals = [];
  21110. const uvs = [];
  21111. // generate vertices, normals and uvs
  21112. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21113. const verticesRow = [];
  21114. const v = iy / heightSegments;
  21115. // special case for the poles
  21116. let uOffset = 0;
  21117. if ( iy == 0 && thetaStart == 0 ) {
  21118. uOffset = 0.5 / widthSegments;
  21119. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21120. uOffset = - 0.5 / widthSegments;
  21121. }
  21122. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21123. const u = ix / widthSegments;
  21124. // vertex
  21125. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21126. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21127. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21128. vertices.push( vertex.x, vertex.y, vertex.z );
  21129. // normal
  21130. normal.copy( vertex ).normalize();
  21131. normals.push( normal.x, normal.y, normal.z );
  21132. // uv
  21133. uvs.push( u + uOffset, 1 - v );
  21134. verticesRow.push( index ++ );
  21135. }
  21136. grid.push( verticesRow );
  21137. }
  21138. // indices
  21139. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21140. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21141. const a = grid[ iy ][ ix + 1 ];
  21142. const b = grid[ iy ][ ix ];
  21143. const c = grid[ iy + 1 ][ ix ];
  21144. const d = grid[ iy + 1 ][ ix + 1 ];
  21145. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21146. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21147. }
  21148. }
  21149. // build geometry
  21150. this.setIndex( indices );
  21151. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21152. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21153. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21154. }
  21155. static fromJSON( data ) {
  21156. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21157. }
  21158. }
  21159. class TetrahedronGeometry extends PolyhedronGeometry {
  21160. constructor( radius = 1, detail = 0 ) {
  21161. const vertices = [
  21162. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21163. ];
  21164. const indices = [
  21165. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21166. ];
  21167. super( vertices, indices, radius, detail );
  21168. this.type = 'TetrahedronGeometry';
  21169. this.parameters = {
  21170. radius: radius,
  21171. detail: detail
  21172. };
  21173. }
  21174. static fromJSON( data ) {
  21175. return new TetrahedronGeometry( data.radius, data.detail );
  21176. }
  21177. }
  21178. class TorusGeometry extends BufferGeometry {
  21179. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21180. super();
  21181. this.type = 'TorusGeometry';
  21182. this.parameters = {
  21183. radius: radius,
  21184. tube: tube,
  21185. radialSegments: radialSegments,
  21186. tubularSegments: tubularSegments,
  21187. arc: arc
  21188. };
  21189. radialSegments = Math.floor( radialSegments );
  21190. tubularSegments = Math.floor( tubularSegments );
  21191. // buffers
  21192. const indices = [];
  21193. const vertices = [];
  21194. const normals = [];
  21195. const uvs = [];
  21196. // helper variables
  21197. const center = new Vector3();
  21198. const vertex = new Vector3();
  21199. const normal = new Vector3();
  21200. // generate vertices, normals and uvs
  21201. for ( let j = 0; j <= radialSegments; j ++ ) {
  21202. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21203. const u = i / tubularSegments * arc;
  21204. const v = j / radialSegments * Math.PI * 2;
  21205. // vertex
  21206. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21207. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21208. vertex.z = tube * Math.sin( v );
  21209. vertices.push( vertex.x, vertex.y, vertex.z );
  21210. // normal
  21211. center.x = radius * Math.cos( u );
  21212. center.y = radius * Math.sin( u );
  21213. normal.subVectors( vertex, center ).normalize();
  21214. normals.push( normal.x, normal.y, normal.z );
  21215. // uv
  21216. uvs.push( i / tubularSegments );
  21217. uvs.push( j / radialSegments );
  21218. }
  21219. }
  21220. // generate indices
  21221. for ( let j = 1; j <= radialSegments; j ++ ) {
  21222. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21223. // indices
  21224. const a = ( tubularSegments + 1 ) * j + i - 1;
  21225. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21226. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21227. const d = ( tubularSegments + 1 ) * j + i;
  21228. // faces
  21229. indices.push( a, b, d );
  21230. indices.push( b, c, d );
  21231. }
  21232. }
  21233. // build geometry
  21234. this.setIndex( indices );
  21235. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21236. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21237. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21238. }
  21239. static fromJSON( data ) {
  21240. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21241. }
  21242. }
  21243. class TorusKnotGeometry extends BufferGeometry {
  21244. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21245. super();
  21246. this.type = 'TorusKnotGeometry';
  21247. this.parameters = {
  21248. radius: radius,
  21249. tube: tube,
  21250. tubularSegments: tubularSegments,
  21251. radialSegments: radialSegments,
  21252. p: p,
  21253. q: q
  21254. };
  21255. tubularSegments = Math.floor( tubularSegments );
  21256. radialSegments = Math.floor( radialSegments );
  21257. // buffers
  21258. const indices = [];
  21259. const vertices = [];
  21260. const normals = [];
  21261. const uvs = [];
  21262. // helper variables
  21263. const vertex = new Vector3();
  21264. const normal = new Vector3();
  21265. const P1 = new Vector3();
  21266. const P2 = new Vector3();
  21267. const B = new Vector3();
  21268. const T = new Vector3();
  21269. const N = new Vector3();
  21270. // generate vertices, normals and uvs
  21271. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21272. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21273. const u = i / tubularSegments * p * Math.PI * 2;
  21274. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21275. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21276. calculatePositionOnCurve( u, p, q, radius, P1 );
  21277. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21278. // calculate orthonormal basis
  21279. T.subVectors( P2, P1 );
  21280. N.addVectors( P2, P1 );
  21281. B.crossVectors( T, N );
  21282. N.crossVectors( B, T );
  21283. // normalize B, N. T can be ignored, we don't use it
  21284. B.normalize();
  21285. N.normalize();
  21286. for ( let j = 0; j <= radialSegments; ++ j ) {
  21287. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21288. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21289. const v = j / radialSegments * Math.PI * 2;
  21290. const cx = - tube * Math.cos( v );
  21291. const cy = tube * Math.sin( v );
  21292. // now calculate the final vertex position.
  21293. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21294. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21295. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21296. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21297. vertices.push( vertex.x, vertex.y, vertex.z );
  21298. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21299. normal.subVectors( vertex, P1 ).normalize();
  21300. normals.push( normal.x, normal.y, normal.z );
  21301. // uv
  21302. uvs.push( i / tubularSegments );
  21303. uvs.push( j / radialSegments );
  21304. }
  21305. }
  21306. // generate indices
  21307. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21308. for ( let i = 1; i <= radialSegments; i ++ ) {
  21309. // indices
  21310. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21311. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21312. const c = ( radialSegments + 1 ) * j + i;
  21313. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21314. // faces
  21315. indices.push( a, b, d );
  21316. indices.push( b, c, d );
  21317. }
  21318. }
  21319. // build geometry
  21320. this.setIndex( indices );
  21321. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21322. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21323. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21324. // this function calculates the current position on the torus curve
  21325. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21326. const cu = Math.cos( u );
  21327. const su = Math.sin( u );
  21328. const quOverP = q / p * u;
  21329. const cs = Math.cos( quOverP );
  21330. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21331. position.y = radius * ( 2 + cs ) * su * 0.5;
  21332. position.z = radius * Math.sin( quOverP ) * 0.5;
  21333. }
  21334. }
  21335. static fromJSON( data ) {
  21336. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21337. }
  21338. }
  21339. class TubeGeometry extends BufferGeometry {
  21340. 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 ) {
  21341. super();
  21342. this.type = 'TubeGeometry';
  21343. this.parameters = {
  21344. path: path,
  21345. tubularSegments: tubularSegments,
  21346. radius: radius,
  21347. radialSegments: radialSegments,
  21348. closed: closed
  21349. };
  21350. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21351. // expose internals
  21352. this.tangents = frames.tangents;
  21353. this.normals = frames.normals;
  21354. this.binormals = frames.binormals;
  21355. // helper variables
  21356. const vertex = new Vector3();
  21357. const normal = new Vector3();
  21358. const uv = new Vector2();
  21359. let P = new Vector3();
  21360. // buffer
  21361. const vertices = [];
  21362. const normals = [];
  21363. const uvs = [];
  21364. const indices = [];
  21365. // create buffer data
  21366. generateBufferData();
  21367. // build geometry
  21368. this.setIndex( indices );
  21369. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21370. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21371. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21372. // functions
  21373. function generateBufferData() {
  21374. for ( let i = 0; i < tubularSegments; i ++ ) {
  21375. generateSegment( i );
  21376. }
  21377. // if the geometry is not closed, generate the last row of vertices and normals
  21378. // at the regular position on the given path
  21379. //
  21380. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21381. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21382. // uvs are generated in a separate function.
  21383. // this makes it easy compute correct values for closed geometries
  21384. generateUVs();
  21385. // finally create faces
  21386. generateIndices();
  21387. }
  21388. function generateSegment( i ) {
  21389. // we use getPointAt to sample evenly distributed points from the given path
  21390. P = path.getPointAt( i / tubularSegments, P );
  21391. // retrieve corresponding normal and binormal
  21392. const N = frames.normals[ i ];
  21393. const B = frames.binormals[ i ];
  21394. // generate normals and vertices for the current segment
  21395. for ( let j = 0; j <= radialSegments; j ++ ) {
  21396. const v = j / radialSegments * Math.PI * 2;
  21397. const sin = Math.sin( v );
  21398. const cos = - Math.cos( v );
  21399. // normal
  21400. normal.x = ( cos * N.x + sin * B.x );
  21401. normal.y = ( cos * N.y + sin * B.y );
  21402. normal.z = ( cos * N.z + sin * B.z );
  21403. normal.normalize();
  21404. normals.push( normal.x, normal.y, normal.z );
  21405. // vertex
  21406. vertex.x = P.x + radius * normal.x;
  21407. vertex.y = P.y + radius * normal.y;
  21408. vertex.z = P.z + radius * normal.z;
  21409. vertices.push( vertex.x, vertex.y, vertex.z );
  21410. }
  21411. }
  21412. function generateIndices() {
  21413. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21414. for ( let i = 1; i <= radialSegments; i ++ ) {
  21415. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21416. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21417. const c = ( radialSegments + 1 ) * j + i;
  21418. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21419. // faces
  21420. indices.push( a, b, d );
  21421. indices.push( b, c, d );
  21422. }
  21423. }
  21424. }
  21425. function generateUVs() {
  21426. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21427. for ( let j = 0; j <= radialSegments; j ++ ) {
  21428. uv.x = i / tubularSegments;
  21429. uv.y = j / radialSegments;
  21430. uvs.push( uv.x, uv.y );
  21431. }
  21432. }
  21433. }
  21434. }
  21435. toJSON() {
  21436. const data = super.toJSON();
  21437. data.path = this.parameters.path.toJSON();
  21438. return data;
  21439. }
  21440. static fromJSON( data ) {
  21441. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21442. // User defined curves or instances of CurvePath will not be deserialized.
  21443. return new TubeGeometry(
  21444. new Curves[ data.path.type ]().fromJSON( data.path ),
  21445. data.tubularSegments,
  21446. data.radius,
  21447. data.radialSegments,
  21448. data.closed
  21449. );
  21450. }
  21451. }
  21452. class WireframeGeometry extends BufferGeometry {
  21453. constructor( geometry = null ) {
  21454. super();
  21455. this.type = 'WireframeGeometry';
  21456. this.parameters = {
  21457. geometry: geometry
  21458. };
  21459. if ( geometry !== null ) {
  21460. // buffer
  21461. const vertices = [];
  21462. const edges = new Set();
  21463. // helper variables
  21464. const start = new Vector3();
  21465. const end = new Vector3();
  21466. if ( geometry.index !== null ) {
  21467. // indexed BufferGeometry
  21468. const position = geometry.attributes.position;
  21469. const indices = geometry.index;
  21470. let groups = geometry.groups;
  21471. if ( groups.length === 0 ) {
  21472. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  21473. }
  21474. // create a data structure that contains all edges without duplicates
  21475. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21476. const group = groups[ o ];
  21477. const groupStart = group.start;
  21478. const groupCount = group.count;
  21479. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21480. for ( let j = 0; j < 3; j ++ ) {
  21481. const index1 = indices.getX( i + j );
  21482. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21483. start.fromBufferAttribute( position, index1 );
  21484. end.fromBufferAttribute( position, index2 );
  21485. if ( isUniqueEdge( start, end, edges ) === true ) {
  21486. vertices.push( start.x, start.y, start.z );
  21487. vertices.push( end.x, end.y, end.z );
  21488. }
  21489. }
  21490. }
  21491. }
  21492. } else {
  21493. // non-indexed BufferGeometry
  21494. const position = geometry.attributes.position;
  21495. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21496. for ( let j = 0; j < 3; j ++ ) {
  21497. // three edges per triangle, an edge is represented as (index1, index2)
  21498. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21499. const index1 = 3 * i + j;
  21500. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21501. start.fromBufferAttribute( position, index1 );
  21502. end.fromBufferAttribute( position, index2 );
  21503. if ( isUniqueEdge( start, end, edges ) === true ) {
  21504. vertices.push( start.x, start.y, start.z );
  21505. vertices.push( end.x, end.y, end.z );
  21506. }
  21507. }
  21508. }
  21509. }
  21510. // build geometry
  21511. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21512. }
  21513. }
  21514. }
  21515. function isUniqueEdge( start, end, edges ) {
  21516. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21517. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21518. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21519. return false;
  21520. } else {
  21521. edges.add( hash1 );
  21522. edges.add( hash2 );
  21523. return true;
  21524. }
  21525. }
  21526. var Geometries = /*#__PURE__*/Object.freeze({
  21527. __proto__: null,
  21528. BoxGeometry: BoxGeometry,
  21529. BoxBufferGeometry: BoxGeometry,
  21530. CapsuleGeometry: CapsuleGeometry,
  21531. CapsuleBufferGeometry: CapsuleGeometry,
  21532. CircleGeometry: CircleGeometry,
  21533. CircleBufferGeometry: CircleGeometry,
  21534. ConeGeometry: ConeGeometry,
  21535. ConeBufferGeometry: ConeGeometry,
  21536. CylinderGeometry: CylinderGeometry,
  21537. CylinderBufferGeometry: CylinderGeometry,
  21538. DodecahedronGeometry: DodecahedronGeometry,
  21539. DodecahedronBufferGeometry: DodecahedronGeometry,
  21540. EdgesGeometry: EdgesGeometry,
  21541. ExtrudeGeometry: ExtrudeGeometry,
  21542. ExtrudeBufferGeometry: ExtrudeGeometry,
  21543. IcosahedronGeometry: IcosahedronGeometry,
  21544. IcosahedronBufferGeometry: IcosahedronGeometry,
  21545. LatheGeometry: LatheGeometry,
  21546. LatheBufferGeometry: LatheGeometry,
  21547. OctahedronGeometry: OctahedronGeometry,
  21548. OctahedronBufferGeometry: OctahedronGeometry,
  21549. PlaneGeometry: PlaneGeometry,
  21550. PlaneBufferGeometry: PlaneGeometry,
  21551. PolyhedronGeometry: PolyhedronGeometry,
  21552. PolyhedronBufferGeometry: PolyhedronGeometry,
  21553. RingGeometry: RingGeometry,
  21554. RingBufferGeometry: RingGeometry,
  21555. ShapeGeometry: ShapeGeometry,
  21556. ShapeBufferGeometry: ShapeGeometry,
  21557. SphereGeometry: SphereGeometry,
  21558. SphereBufferGeometry: SphereGeometry,
  21559. TetrahedronGeometry: TetrahedronGeometry,
  21560. TetrahedronBufferGeometry: TetrahedronGeometry,
  21561. TorusGeometry: TorusGeometry,
  21562. TorusBufferGeometry: TorusGeometry,
  21563. TorusKnotGeometry: TorusKnotGeometry,
  21564. TorusKnotBufferGeometry: TorusKnotGeometry,
  21565. TubeGeometry: TubeGeometry,
  21566. TubeBufferGeometry: TubeGeometry,
  21567. WireframeGeometry: WireframeGeometry
  21568. });
  21569. class ShadowMaterial extends Material {
  21570. constructor( parameters ) {
  21571. super();
  21572. this.type = 'ShadowMaterial';
  21573. this.color = new Color( 0x000000 );
  21574. this.transparent = true;
  21575. this.fog = true;
  21576. this.setValues( parameters );
  21577. }
  21578. copy( source ) {
  21579. super.copy( source );
  21580. this.color.copy( source.color );
  21581. this.fog = source.fog;
  21582. return this;
  21583. }
  21584. }
  21585. ShadowMaterial.prototype.isShadowMaterial = true;
  21586. class RawShaderMaterial extends ShaderMaterial {
  21587. constructor( parameters ) {
  21588. super( parameters );
  21589. this.type = 'RawShaderMaterial';
  21590. }
  21591. }
  21592. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  21593. class MeshStandardMaterial extends Material {
  21594. constructor( parameters ) {
  21595. super();
  21596. this.defines = { 'STANDARD': '' };
  21597. this.type = 'MeshStandardMaterial';
  21598. this.color = new Color( 0xffffff ); // diffuse
  21599. this.roughness = 1.0;
  21600. this.metalness = 0.0;
  21601. this.map = null;
  21602. this.lightMap = null;
  21603. this.lightMapIntensity = 1.0;
  21604. this.aoMap = null;
  21605. this.aoMapIntensity = 1.0;
  21606. this.emissive = new Color( 0x000000 );
  21607. this.emissiveIntensity = 1.0;
  21608. this.emissiveMap = null;
  21609. this.bumpMap = null;
  21610. this.bumpScale = 1;
  21611. this.normalMap = null;
  21612. this.normalMapType = TangentSpaceNormalMap;
  21613. this.normalScale = new Vector2( 1, 1 );
  21614. this.displacementMap = null;
  21615. this.displacementScale = 1;
  21616. this.displacementBias = 0;
  21617. this.roughnessMap = null;
  21618. this.metalnessMap = null;
  21619. this.alphaMap = null;
  21620. this.envMap = null;
  21621. this.envMapIntensity = 1.0;
  21622. this.wireframe = false;
  21623. this.wireframeLinewidth = 1;
  21624. this.wireframeLinecap = 'round';
  21625. this.wireframeLinejoin = 'round';
  21626. this.flatShading = false;
  21627. this.fog = true;
  21628. this.setValues( parameters );
  21629. }
  21630. copy( source ) {
  21631. super.copy( source );
  21632. this.defines = { 'STANDARD': '' };
  21633. this.color.copy( source.color );
  21634. this.roughness = source.roughness;
  21635. this.metalness = source.metalness;
  21636. this.map = source.map;
  21637. this.lightMap = source.lightMap;
  21638. this.lightMapIntensity = source.lightMapIntensity;
  21639. this.aoMap = source.aoMap;
  21640. this.aoMapIntensity = source.aoMapIntensity;
  21641. this.emissive.copy( source.emissive );
  21642. this.emissiveMap = source.emissiveMap;
  21643. this.emissiveIntensity = source.emissiveIntensity;
  21644. this.bumpMap = source.bumpMap;
  21645. this.bumpScale = source.bumpScale;
  21646. this.normalMap = source.normalMap;
  21647. this.normalMapType = source.normalMapType;
  21648. this.normalScale.copy( source.normalScale );
  21649. this.displacementMap = source.displacementMap;
  21650. this.displacementScale = source.displacementScale;
  21651. this.displacementBias = source.displacementBias;
  21652. this.roughnessMap = source.roughnessMap;
  21653. this.metalnessMap = source.metalnessMap;
  21654. this.alphaMap = source.alphaMap;
  21655. this.envMap = source.envMap;
  21656. this.envMapIntensity = source.envMapIntensity;
  21657. this.wireframe = source.wireframe;
  21658. this.wireframeLinewidth = source.wireframeLinewidth;
  21659. this.wireframeLinecap = source.wireframeLinecap;
  21660. this.wireframeLinejoin = source.wireframeLinejoin;
  21661. this.flatShading = source.flatShading;
  21662. this.fog = source.fog;
  21663. return this;
  21664. }
  21665. }
  21666. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21667. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21668. constructor( parameters ) {
  21669. super();
  21670. this.defines = {
  21671. 'STANDARD': '',
  21672. 'PHYSICAL': ''
  21673. };
  21674. this.type = 'MeshPhysicalMaterial';
  21675. this.clearcoatMap = null;
  21676. this.clearcoatRoughness = 0.0;
  21677. this.clearcoatRoughnessMap = null;
  21678. this.clearcoatNormalScale = new Vector2( 1, 1 );
  21679. this.clearcoatNormalMap = null;
  21680. this.ior = 1.5;
  21681. Object.defineProperty( this, 'reflectivity', {
  21682. get: function () {
  21683. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  21684. },
  21685. set: function ( reflectivity ) {
  21686. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  21687. }
  21688. } );
  21689. this.sheenColor = new Color( 0x000000 );
  21690. this.sheenColorMap = null;
  21691. this.sheenRoughness = 1.0;
  21692. this.sheenRoughnessMap = null;
  21693. this.transmissionMap = null;
  21694. this.thickness = 0;
  21695. this.thicknessMap = null;
  21696. this.attenuationDistance = 0.0;
  21697. this.attenuationColor = new Color( 1, 1, 1 );
  21698. this.specularIntensity = 1.0;
  21699. this.specularIntensityMap = null;
  21700. this.specularColor = new Color( 1, 1, 1 );
  21701. this.specularColorMap = null;
  21702. this._sheen = 0.0;
  21703. this._clearcoat = 0;
  21704. this._transmission = 0;
  21705. this.setValues( parameters );
  21706. }
  21707. get sheen() {
  21708. return this._sheen;
  21709. }
  21710. set sheen( value ) {
  21711. if ( this._sheen > 0 !== value > 0 ) {
  21712. this.version ++;
  21713. }
  21714. this._sheen = value;
  21715. }
  21716. get clearcoat() {
  21717. return this._clearcoat;
  21718. }
  21719. set clearcoat( value ) {
  21720. if ( this._clearcoat > 0 !== value > 0 ) {
  21721. this.version ++;
  21722. }
  21723. this._clearcoat = value;
  21724. }
  21725. get transmission() {
  21726. return this._transmission;
  21727. }
  21728. set transmission( value ) {
  21729. if ( this._transmission > 0 !== value > 0 ) {
  21730. this.version ++;
  21731. }
  21732. this._transmission = value;
  21733. }
  21734. copy( source ) {
  21735. super.copy( source );
  21736. this.defines = {
  21737. 'STANDARD': '',
  21738. 'PHYSICAL': ''
  21739. };
  21740. this.clearcoat = source.clearcoat;
  21741. this.clearcoatMap = source.clearcoatMap;
  21742. this.clearcoatRoughness = source.clearcoatRoughness;
  21743. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21744. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21745. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21746. this.ior = source.ior;
  21747. this.sheen = source.sheen;
  21748. this.sheenColor.copy( source.sheenColor );
  21749. this.sheenColorMap = source.sheenColorMap;
  21750. this.sheenRoughness = source.sheenRoughness;
  21751. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21752. this.transmission = source.transmission;
  21753. this.transmissionMap = source.transmissionMap;
  21754. this.thickness = source.thickness;
  21755. this.thicknessMap = source.thicknessMap;
  21756. this.attenuationDistance = source.attenuationDistance;
  21757. this.attenuationColor.copy( source.attenuationColor );
  21758. this.specularIntensity = source.specularIntensity;
  21759. this.specularIntensityMap = source.specularIntensityMap;
  21760. this.specularColor.copy( source.specularColor );
  21761. this.specularColorMap = source.specularColorMap;
  21762. return this;
  21763. }
  21764. }
  21765. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21766. class MeshPhongMaterial extends Material {
  21767. constructor( parameters ) {
  21768. super();
  21769. this.type = 'MeshPhongMaterial';
  21770. this.color = new Color( 0xffffff ); // diffuse
  21771. this.specular = new Color( 0x111111 );
  21772. this.shininess = 30;
  21773. this.map = null;
  21774. this.lightMap = null;
  21775. this.lightMapIntensity = 1.0;
  21776. this.aoMap = null;
  21777. this.aoMapIntensity = 1.0;
  21778. this.emissive = new Color( 0x000000 );
  21779. this.emissiveIntensity = 1.0;
  21780. this.emissiveMap = null;
  21781. this.bumpMap = null;
  21782. this.bumpScale = 1;
  21783. this.normalMap = null;
  21784. this.normalMapType = TangentSpaceNormalMap;
  21785. this.normalScale = new Vector2( 1, 1 );
  21786. this.displacementMap = null;
  21787. this.displacementScale = 1;
  21788. this.displacementBias = 0;
  21789. this.specularMap = null;
  21790. this.alphaMap = null;
  21791. this.envMap = null;
  21792. this.combine = MultiplyOperation;
  21793. this.reflectivity = 1;
  21794. this.refractionRatio = 0.98;
  21795. this.wireframe = false;
  21796. this.wireframeLinewidth = 1;
  21797. this.wireframeLinecap = 'round';
  21798. this.wireframeLinejoin = 'round';
  21799. this.flatShading = false;
  21800. this.fog = true;
  21801. this.setValues( parameters );
  21802. }
  21803. copy( source ) {
  21804. super.copy( source );
  21805. this.color.copy( source.color );
  21806. this.specular.copy( source.specular );
  21807. this.shininess = source.shininess;
  21808. this.map = source.map;
  21809. this.lightMap = source.lightMap;
  21810. this.lightMapIntensity = source.lightMapIntensity;
  21811. this.aoMap = source.aoMap;
  21812. this.aoMapIntensity = source.aoMapIntensity;
  21813. this.emissive.copy( source.emissive );
  21814. this.emissiveMap = source.emissiveMap;
  21815. this.emissiveIntensity = source.emissiveIntensity;
  21816. this.bumpMap = source.bumpMap;
  21817. this.bumpScale = source.bumpScale;
  21818. this.normalMap = source.normalMap;
  21819. this.normalMapType = source.normalMapType;
  21820. this.normalScale.copy( source.normalScale );
  21821. this.displacementMap = source.displacementMap;
  21822. this.displacementScale = source.displacementScale;
  21823. this.displacementBias = source.displacementBias;
  21824. this.specularMap = source.specularMap;
  21825. this.alphaMap = source.alphaMap;
  21826. this.envMap = source.envMap;
  21827. this.combine = source.combine;
  21828. this.reflectivity = source.reflectivity;
  21829. this.refractionRatio = source.refractionRatio;
  21830. this.wireframe = source.wireframe;
  21831. this.wireframeLinewidth = source.wireframeLinewidth;
  21832. this.wireframeLinecap = source.wireframeLinecap;
  21833. this.wireframeLinejoin = source.wireframeLinejoin;
  21834. this.flatShading = source.flatShading;
  21835. this.fog = source.fog;
  21836. return this;
  21837. }
  21838. }
  21839. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21840. class MeshToonMaterial extends Material {
  21841. constructor( parameters ) {
  21842. super();
  21843. this.defines = { 'TOON': '' };
  21844. this.type = 'MeshToonMaterial';
  21845. this.color = new Color( 0xffffff );
  21846. this.map = null;
  21847. this.gradientMap = null;
  21848. this.lightMap = null;
  21849. this.lightMapIntensity = 1.0;
  21850. this.aoMap = null;
  21851. this.aoMapIntensity = 1.0;
  21852. this.emissive = new Color( 0x000000 );
  21853. this.emissiveIntensity = 1.0;
  21854. this.emissiveMap = null;
  21855. this.bumpMap = null;
  21856. this.bumpScale = 1;
  21857. this.normalMap = null;
  21858. this.normalMapType = TangentSpaceNormalMap;
  21859. this.normalScale = new Vector2( 1, 1 );
  21860. this.displacementMap = null;
  21861. this.displacementScale = 1;
  21862. this.displacementBias = 0;
  21863. this.alphaMap = null;
  21864. this.wireframe = false;
  21865. this.wireframeLinewidth = 1;
  21866. this.wireframeLinecap = 'round';
  21867. this.wireframeLinejoin = 'round';
  21868. this.fog = true;
  21869. this.setValues( parameters );
  21870. }
  21871. copy( source ) {
  21872. super.copy( source );
  21873. this.color.copy( source.color );
  21874. this.map = source.map;
  21875. this.gradientMap = source.gradientMap;
  21876. this.lightMap = source.lightMap;
  21877. this.lightMapIntensity = source.lightMapIntensity;
  21878. this.aoMap = source.aoMap;
  21879. this.aoMapIntensity = source.aoMapIntensity;
  21880. this.emissive.copy( source.emissive );
  21881. this.emissiveMap = source.emissiveMap;
  21882. this.emissiveIntensity = source.emissiveIntensity;
  21883. this.bumpMap = source.bumpMap;
  21884. this.bumpScale = source.bumpScale;
  21885. this.normalMap = source.normalMap;
  21886. this.normalMapType = source.normalMapType;
  21887. this.normalScale.copy( source.normalScale );
  21888. this.displacementMap = source.displacementMap;
  21889. this.displacementScale = source.displacementScale;
  21890. this.displacementBias = source.displacementBias;
  21891. this.alphaMap = source.alphaMap;
  21892. this.wireframe = source.wireframe;
  21893. this.wireframeLinewidth = source.wireframeLinewidth;
  21894. this.wireframeLinecap = source.wireframeLinecap;
  21895. this.wireframeLinejoin = source.wireframeLinejoin;
  21896. this.fog = source.fog;
  21897. return this;
  21898. }
  21899. }
  21900. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21901. class MeshNormalMaterial extends Material {
  21902. constructor( parameters ) {
  21903. super();
  21904. this.type = 'MeshNormalMaterial';
  21905. this.bumpMap = null;
  21906. this.bumpScale = 1;
  21907. this.normalMap = null;
  21908. this.normalMapType = TangentSpaceNormalMap;
  21909. this.normalScale = new Vector2( 1, 1 );
  21910. this.displacementMap = null;
  21911. this.displacementScale = 1;
  21912. this.displacementBias = 0;
  21913. this.wireframe = false;
  21914. this.wireframeLinewidth = 1;
  21915. this.flatShading = false;
  21916. this.setValues( parameters );
  21917. }
  21918. copy( source ) {
  21919. super.copy( source );
  21920. this.bumpMap = source.bumpMap;
  21921. this.bumpScale = source.bumpScale;
  21922. this.normalMap = source.normalMap;
  21923. this.normalMapType = source.normalMapType;
  21924. this.normalScale.copy( source.normalScale );
  21925. this.displacementMap = source.displacementMap;
  21926. this.displacementScale = source.displacementScale;
  21927. this.displacementBias = source.displacementBias;
  21928. this.wireframe = source.wireframe;
  21929. this.wireframeLinewidth = source.wireframeLinewidth;
  21930. this.flatShading = source.flatShading;
  21931. return this;
  21932. }
  21933. }
  21934. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21935. class MeshLambertMaterial extends Material {
  21936. constructor( parameters ) {
  21937. super();
  21938. this.type = 'MeshLambertMaterial';
  21939. this.color = new Color( 0xffffff ); // diffuse
  21940. this.map = null;
  21941. this.lightMap = null;
  21942. this.lightMapIntensity = 1.0;
  21943. this.aoMap = null;
  21944. this.aoMapIntensity = 1.0;
  21945. this.emissive = new Color( 0x000000 );
  21946. this.emissiveIntensity = 1.0;
  21947. this.emissiveMap = null;
  21948. this.specularMap = null;
  21949. this.alphaMap = null;
  21950. this.envMap = null;
  21951. this.combine = MultiplyOperation;
  21952. this.reflectivity = 1;
  21953. this.refractionRatio = 0.98;
  21954. this.wireframe = false;
  21955. this.wireframeLinewidth = 1;
  21956. this.wireframeLinecap = 'round';
  21957. this.wireframeLinejoin = 'round';
  21958. this.fog = true;
  21959. this.setValues( parameters );
  21960. }
  21961. copy( source ) {
  21962. super.copy( source );
  21963. this.color.copy( source.color );
  21964. this.map = source.map;
  21965. this.lightMap = source.lightMap;
  21966. this.lightMapIntensity = source.lightMapIntensity;
  21967. this.aoMap = source.aoMap;
  21968. this.aoMapIntensity = source.aoMapIntensity;
  21969. this.emissive.copy( source.emissive );
  21970. this.emissiveMap = source.emissiveMap;
  21971. this.emissiveIntensity = source.emissiveIntensity;
  21972. this.specularMap = source.specularMap;
  21973. this.alphaMap = source.alphaMap;
  21974. this.envMap = source.envMap;
  21975. this.combine = source.combine;
  21976. this.reflectivity = source.reflectivity;
  21977. this.refractionRatio = source.refractionRatio;
  21978. this.wireframe = source.wireframe;
  21979. this.wireframeLinewidth = source.wireframeLinewidth;
  21980. this.wireframeLinecap = source.wireframeLinecap;
  21981. this.wireframeLinejoin = source.wireframeLinejoin;
  21982. this.fog = source.fog;
  21983. return this;
  21984. }
  21985. }
  21986. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21987. class MeshMatcapMaterial extends Material {
  21988. constructor( parameters ) {
  21989. super();
  21990. this.defines = { 'MATCAP': '' };
  21991. this.type = 'MeshMatcapMaterial';
  21992. this.color = new Color( 0xffffff ); // diffuse
  21993. this.matcap = null;
  21994. this.map = null;
  21995. this.bumpMap = null;
  21996. this.bumpScale = 1;
  21997. this.normalMap = null;
  21998. this.normalMapType = TangentSpaceNormalMap;
  21999. this.normalScale = new Vector2( 1, 1 );
  22000. this.displacementMap = null;
  22001. this.displacementScale = 1;
  22002. this.displacementBias = 0;
  22003. this.alphaMap = null;
  22004. this.flatShading = false;
  22005. this.fog = true;
  22006. this.setValues( parameters );
  22007. }
  22008. copy( source ) {
  22009. super.copy( source );
  22010. this.defines = { 'MATCAP': '' };
  22011. this.color.copy( source.color );
  22012. this.matcap = source.matcap;
  22013. this.map = source.map;
  22014. this.bumpMap = source.bumpMap;
  22015. this.bumpScale = source.bumpScale;
  22016. this.normalMap = source.normalMap;
  22017. this.normalMapType = source.normalMapType;
  22018. this.normalScale.copy( source.normalScale );
  22019. this.displacementMap = source.displacementMap;
  22020. this.displacementScale = source.displacementScale;
  22021. this.displacementBias = source.displacementBias;
  22022. this.alphaMap = source.alphaMap;
  22023. this.flatShading = source.flatShading;
  22024. this.fog = source.fog;
  22025. return this;
  22026. }
  22027. }
  22028. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  22029. class LineDashedMaterial extends LineBasicMaterial {
  22030. constructor( parameters ) {
  22031. super();
  22032. this.type = 'LineDashedMaterial';
  22033. this.scale = 1;
  22034. this.dashSize = 3;
  22035. this.gapSize = 1;
  22036. this.setValues( parameters );
  22037. }
  22038. copy( source ) {
  22039. super.copy( source );
  22040. this.scale = source.scale;
  22041. this.dashSize = source.dashSize;
  22042. this.gapSize = source.gapSize;
  22043. return this;
  22044. }
  22045. }
  22046. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22047. const materialLib = {
  22048. ShadowMaterial,
  22049. SpriteMaterial,
  22050. RawShaderMaterial,
  22051. ShaderMaterial,
  22052. PointsMaterial,
  22053. MeshPhysicalMaterial,
  22054. MeshStandardMaterial,
  22055. MeshPhongMaterial,
  22056. MeshToonMaterial,
  22057. MeshNormalMaterial,
  22058. MeshLambertMaterial,
  22059. MeshDepthMaterial,
  22060. MeshDistanceMaterial,
  22061. MeshBasicMaterial,
  22062. MeshMatcapMaterial,
  22063. LineDashedMaterial,
  22064. LineBasicMaterial,
  22065. Material
  22066. };
  22067. Material.fromType = function ( type ) {
  22068. return new materialLib[ type ]();
  22069. };
  22070. const AnimationUtils = {
  22071. // same as Array.prototype.slice, but also works on typed arrays
  22072. arraySlice: function ( array, from, to ) {
  22073. if ( AnimationUtils.isTypedArray( array ) ) {
  22074. // in ios9 array.subarray(from, undefined) will return empty array
  22075. // but array.subarray(from) or array.subarray(from, len) is correct
  22076. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22077. }
  22078. return array.slice( from, to );
  22079. },
  22080. // converts an array to a specific type
  22081. convertArray: function ( array, type, forceClone ) {
  22082. if ( ! array || // let 'undefined' and 'null' pass
  22083. ! forceClone && array.constructor === type ) return array;
  22084. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22085. return new type( array ); // create typed array
  22086. }
  22087. return Array.prototype.slice.call( array ); // create Array
  22088. },
  22089. isTypedArray: function ( object ) {
  22090. return ArrayBuffer.isView( object ) &&
  22091. ! ( object instanceof DataView );
  22092. },
  22093. // returns an array by which times and values can be sorted
  22094. getKeyframeOrder: function ( times ) {
  22095. function compareTime( i, j ) {
  22096. return times[ i ] - times[ j ];
  22097. }
  22098. const n = times.length;
  22099. const result = new Array( n );
  22100. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22101. result.sort( compareTime );
  22102. return result;
  22103. },
  22104. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22105. sortedArray: function ( values, stride, order ) {
  22106. const nValues = values.length;
  22107. const result = new values.constructor( nValues );
  22108. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22109. const srcOffset = order[ i ] * stride;
  22110. for ( let j = 0; j !== stride; ++ j ) {
  22111. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22112. }
  22113. }
  22114. return result;
  22115. },
  22116. // function for parsing AOS keyframe formats
  22117. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  22118. let i = 1, key = jsonKeys[ 0 ];
  22119. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22120. key = jsonKeys[ i ++ ];
  22121. }
  22122. if ( key === undefined ) return; // no data
  22123. let value = key[ valuePropertyName ];
  22124. if ( value === undefined ) return; // no data
  22125. if ( Array.isArray( value ) ) {
  22126. do {
  22127. value = key[ valuePropertyName ];
  22128. if ( value !== undefined ) {
  22129. times.push( key.time );
  22130. values.push.apply( values, value ); // push all elements
  22131. }
  22132. key = jsonKeys[ i ++ ];
  22133. } while ( key !== undefined );
  22134. } else if ( value.toArray !== undefined ) {
  22135. // ...assume THREE.Math-ish
  22136. do {
  22137. value = key[ valuePropertyName ];
  22138. if ( value !== undefined ) {
  22139. times.push( key.time );
  22140. value.toArray( values, values.length );
  22141. }
  22142. key = jsonKeys[ i ++ ];
  22143. } while ( key !== undefined );
  22144. } else {
  22145. // otherwise push as-is
  22146. do {
  22147. value = key[ valuePropertyName ];
  22148. if ( value !== undefined ) {
  22149. times.push( key.time );
  22150. values.push( value );
  22151. }
  22152. key = jsonKeys[ i ++ ];
  22153. } while ( key !== undefined );
  22154. }
  22155. },
  22156. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22157. const clip = sourceClip.clone();
  22158. clip.name = name;
  22159. const tracks = [];
  22160. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22161. const track = clip.tracks[ i ];
  22162. const valueSize = track.getValueSize();
  22163. const times = [];
  22164. const values = [];
  22165. for ( let j = 0; j < track.times.length; ++ j ) {
  22166. const frame = track.times[ j ] * fps;
  22167. if ( frame < startFrame || frame >= endFrame ) continue;
  22168. times.push( track.times[ j ] );
  22169. for ( let k = 0; k < valueSize; ++ k ) {
  22170. values.push( track.values[ j * valueSize + k ] );
  22171. }
  22172. }
  22173. if ( times.length === 0 ) continue;
  22174. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  22175. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  22176. tracks.push( track );
  22177. }
  22178. clip.tracks = tracks;
  22179. // find minimum .times value across all tracks in the trimmed clip
  22180. let minStartTime = Infinity;
  22181. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22182. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22183. minStartTime = clip.tracks[ i ].times[ 0 ];
  22184. }
  22185. }
  22186. // shift all tracks such that clip begins at t=0
  22187. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22188. clip.tracks[ i ].shift( - 1 * minStartTime );
  22189. }
  22190. clip.resetDuration();
  22191. return clip;
  22192. },
  22193. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22194. if ( fps <= 0 ) fps = 30;
  22195. const numTracks = referenceClip.tracks.length;
  22196. const referenceTime = referenceFrame / fps;
  22197. // Make each track's values relative to the values at the reference frame
  22198. for ( let i = 0; i < numTracks; ++ i ) {
  22199. const referenceTrack = referenceClip.tracks[ i ];
  22200. const referenceTrackType = referenceTrack.ValueTypeName;
  22201. // Skip this track if it's non-numeric
  22202. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22203. // Find the track in the target clip whose name and type matches the reference track
  22204. const targetTrack = targetClip.tracks.find( function ( track ) {
  22205. return track.name === referenceTrack.name
  22206. && track.ValueTypeName === referenceTrackType;
  22207. } );
  22208. if ( targetTrack === undefined ) continue;
  22209. let referenceOffset = 0;
  22210. const referenceValueSize = referenceTrack.getValueSize();
  22211. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22212. referenceOffset = referenceValueSize / 3;
  22213. }
  22214. let targetOffset = 0;
  22215. const targetValueSize = targetTrack.getValueSize();
  22216. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22217. targetOffset = targetValueSize / 3;
  22218. }
  22219. const lastIndex = referenceTrack.times.length - 1;
  22220. let referenceValue;
  22221. // Find the value to subtract out of the track
  22222. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22223. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22224. const startIndex = referenceOffset;
  22225. const endIndex = referenceValueSize - referenceOffset;
  22226. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22227. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22228. // Reference frame is after the last keyframe, so just use the last keyframe
  22229. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22230. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22231. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22232. } else {
  22233. // Interpolate to the reference value
  22234. const interpolant = referenceTrack.createInterpolant();
  22235. const startIndex = referenceOffset;
  22236. const endIndex = referenceValueSize - referenceOffset;
  22237. interpolant.evaluate( referenceTime );
  22238. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22239. }
  22240. // Conjugate the quaternion
  22241. if ( referenceTrackType === 'quaternion' ) {
  22242. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22243. referenceQuat.toArray( referenceValue );
  22244. }
  22245. // Subtract the reference value from all of the track values
  22246. const numTimes = targetTrack.times.length;
  22247. for ( let j = 0; j < numTimes; ++ j ) {
  22248. const valueStart = j * targetValueSize + targetOffset;
  22249. if ( referenceTrackType === 'quaternion' ) {
  22250. // Multiply the conjugate for quaternion track types
  22251. Quaternion.multiplyQuaternionsFlat(
  22252. targetTrack.values,
  22253. valueStart,
  22254. referenceValue,
  22255. 0,
  22256. targetTrack.values,
  22257. valueStart
  22258. );
  22259. } else {
  22260. const valueEnd = targetValueSize - targetOffset * 2;
  22261. // Subtract each value for all other numeric track types
  22262. for ( let k = 0; k < valueEnd; ++ k ) {
  22263. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22264. }
  22265. }
  22266. }
  22267. }
  22268. targetClip.blendMode = AdditiveAnimationBlendMode;
  22269. return targetClip;
  22270. }
  22271. };
  22272. /**
  22273. * Abstract base class of interpolants over parametric samples.
  22274. *
  22275. * The parameter domain is one dimensional, typically the time or a path
  22276. * along a curve defined by the data.
  22277. *
  22278. * The sample values can have any dimensionality and derived classes may
  22279. * apply special interpretations to the data.
  22280. *
  22281. * This class provides the interval seek in a Template Method, deferring
  22282. * the actual interpolation to derived classes.
  22283. *
  22284. * Time complexity is O(1) for linear access crossing at most two points
  22285. * and O(log N) for random access, where N is the number of positions.
  22286. *
  22287. * References:
  22288. *
  22289. * http://www.oodesign.com/template-method-pattern.html
  22290. *
  22291. */
  22292. class Interpolant {
  22293. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22294. this.parameterPositions = parameterPositions;
  22295. this._cachedIndex = 0;
  22296. this.resultBuffer = resultBuffer !== undefined ?
  22297. resultBuffer : new sampleValues.constructor( sampleSize );
  22298. this.sampleValues = sampleValues;
  22299. this.valueSize = sampleSize;
  22300. this.settings = null;
  22301. this.DefaultSettings_ = {};
  22302. }
  22303. evaluate( t ) {
  22304. const pp = this.parameterPositions;
  22305. let i1 = this._cachedIndex,
  22306. t1 = pp[ i1 ],
  22307. t0 = pp[ i1 - 1 ];
  22308. validate_interval: {
  22309. seek: {
  22310. let right;
  22311. linear_scan: {
  22312. //- See http://jsperf.com/comparison-to-undefined/3
  22313. //- slower code:
  22314. //-
  22315. //- if ( t >= t1 || t1 === undefined ) {
  22316. forward_scan: if ( ! ( t < t1 ) ) {
  22317. for ( let giveUpAt = i1 + 2; ; ) {
  22318. if ( t1 === undefined ) {
  22319. if ( t < t0 ) break forward_scan;
  22320. // after end
  22321. i1 = pp.length;
  22322. this._cachedIndex = i1;
  22323. return this.afterEnd_( i1 - 1, t, t0 );
  22324. }
  22325. if ( i1 === giveUpAt ) break; // this loop
  22326. t0 = t1;
  22327. t1 = pp[ ++ i1 ];
  22328. if ( t < t1 ) {
  22329. // we have arrived at the sought interval
  22330. break seek;
  22331. }
  22332. }
  22333. // prepare binary search on the right side of the index
  22334. right = pp.length;
  22335. break linear_scan;
  22336. }
  22337. //- slower code:
  22338. //- if ( t < t0 || t0 === undefined ) {
  22339. if ( ! ( t >= t0 ) ) {
  22340. // looping?
  22341. const t1global = pp[ 1 ];
  22342. if ( t < t1global ) {
  22343. i1 = 2; // + 1, using the scan for the details
  22344. t0 = t1global;
  22345. }
  22346. // linear reverse scan
  22347. for ( let giveUpAt = i1 - 2; ; ) {
  22348. if ( t0 === undefined ) {
  22349. // before start
  22350. this._cachedIndex = 0;
  22351. return this.beforeStart_( 0, t, t1 );
  22352. }
  22353. if ( i1 === giveUpAt ) break; // this loop
  22354. t1 = t0;
  22355. t0 = pp[ -- i1 - 1 ];
  22356. if ( t >= t0 ) {
  22357. // we have arrived at the sought interval
  22358. break seek;
  22359. }
  22360. }
  22361. // prepare binary search on the left side of the index
  22362. right = i1;
  22363. i1 = 0;
  22364. break linear_scan;
  22365. }
  22366. // the interval is valid
  22367. break validate_interval;
  22368. } // linear scan
  22369. // binary search
  22370. while ( i1 < right ) {
  22371. const mid = ( i1 + right ) >>> 1;
  22372. if ( t < pp[ mid ] ) {
  22373. right = mid;
  22374. } else {
  22375. i1 = mid + 1;
  22376. }
  22377. }
  22378. t1 = pp[ i1 ];
  22379. t0 = pp[ i1 - 1 ];
  22380. // check boundary cases, again
  22381. if ( t0 === undefined ) {
  22382. this._cachedIndex = 0;
  22383. return this.beforeStart_( 0, t, t1 );
  22384. }
  22385. if ( t1 === undefined ) {
  22386. i1 = pp.length;
  22387. this._cachedIndex = i1;
  22388. return this.afterEnd_( i1 - 1, t0, t );
  22389. }
  22390. } // seek
  22391. this._cachedIndex = i1;
  22392. this.intervalChanged_( i1, t0, t1 );
  22393. } // validate_interval
  22394. return this.interpolate_( i1, t0, t, t1 );
  22395. }
  22396. getSettings_() {
  22397. return this.settings || this.DefaultSettings_;
  22398. }
  22399. copySampleValue_( index ) {
  22400. // copies a sample value to the result buffer
  22401. const result = this.resultBuffer,
  22402. values = this.sampleValues,
  22403. stride = this.valueSize,
  22404. offset = index * stride;
  22405. for ( let i = 0; i !== stride; ++ i ) {
  22406. result[ i ] = values[ offset + i ];
  22407. }
  22408. return result;
  22409. }
  22410. // Template methods for derived classes:
  22411. interpolate_( /* i1, t0, t, t1 */ ) {
  22412. throw new Error( 'call to abstract method' );
  22413. // implementations shall return this.resultBuffer
  22414. }
  22415. intervalChanged_( /* i1, t0, t1 */ ) {
  22416. // empty
  22417. }
  22418. }
  22419. // ALIAS DEFINITIONS
  22420. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22421. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22422. /**
  22423. * Fast and simple cubic spline interpolant.
  22424. *
  22425. * It was derived from a Hermitian construction setting the first derivative
  22426. * at each sample position to the linear slope between neighboring positions
  22427. * over their parameter interval.
  22428. */
  22429. class CubicInterpolant extends Interpolant {
  22430. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22431. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22432. this._weightPrev = - 0;
  22433. this._offsetPrev = - 0;
  22434. this._weightNext = - 0;
  22435. this._offsetNext = - 0;
  22436. this.DefaultSettings_ = {
  22437. endingStart: ZeroCurvatureEnding,
  22438. endingEnd: ZeroCurvatureEnding
  22439. };
  22440. }
  22441. intervalChanged_( i1, t0, t1 ) {
  22442. const pp = this.parameterPositions;
  22443. let iPrev = i1 - 2,
  22444. iNext = i1 + 1,
  22445. tPrev = pp[ iPrev ],
  22446. tNext = pp[ iNext ];
  22447. if ( tPrev === undefined ) {
  22448. switch ( this.getSettings_().endingStart ) {
  22449. case ZeroSlopeEnding:
  22450. // f'(t0) = 0
  22451. iPrev = i1;
  22452. tPrev = 2 * t0 - t1;
  22453. break;
  22454. case WrapAroundEnding:
  22455. // use the other end of the curve
  22456. iPrev = pp.length - 2;
  22457. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22458. break;
  22459. default: // ZeroCurvatureEnding
  22460. // f''(t0) = 0 a.k.a. Natural Spline
  22461. iPrev = i1;
  22462. tPrev = t1;
  22463. }
  22464. }
  22465. if ( tNext === undefined ) {
  22466. switch ( this.getSettings_().endingEnd ) {
  22467. case ZeroSlopeEnding:
  22468. // f'(tN) = 0
  22469. iNext = i1;
  22470. tNext = 2 * t1 - t0;
  22471. break;
  22472. case WrapAroundEnding:
  22473. // use the other end of the curve
  22474. iNext = 1;
  22475. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22476. break;
  22477. default: // ZeroCurvatureEnding
  22478. // f''(tN) = 0, a.k.a. Natural Spline
  22479. iNext = i1 - 1;
  22480. tNext = t0;
  22481. }
  22482. }
  22483. const halfDt = ( t1 - t0 ) * 0.5,
  22484. stride = this.valueSize;
  22485. this._weightPrev = halfDt / ( t0 - tPrev );
  22486. this._weightNext = halfDt / ( tNext - t1 );
  22487. this._offsetPrev = iPrev * stride;
  22488. this._offsetNext = iNext * stride;
  22489. }
  22490. interpolate_( i1, t0, t, t1 ) {
  22491. const result = this.resultBuffer,
  22492. values = this.sampleValues,
  22493. stride = this.valueSize,
  22494. o1 = i1 * stride, o0 = o1 - stride,
  22495. oP = this._offsetPrev, oN = this._offsetNext,
  22496. wP = this._weightPrev, wN = this._weightNext,
  22497. p = ( t - t0 ) / ( t1 - t0 ),
  22498. pp = p * p,
  22499. ppp = pp * p;
  22500. // evaluate polynomials
  22501. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  22502. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  22503. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22504. const sN = wN * ppp - wN * pp;
  22505. // combine data linearly
  22506. for ( let i = 0; i !== stride; ++ i ) {
  22507. result[ i ] =
  22508. sP * values[ oP + i ] +
  22509. s0 * values[ o0 + i ] +
  22510. s1 * values[ o1 + i ] +
  22511. sN * values[ oN + i ];
  22512. }
  22513. return result;
  22514. }
  22515. }
  22516. class LinearInterpolant extends Interpolant {
  22517. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22518. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22519. }
  22520. interpolate_( i1, t0, t, t1 ) {
  22521. const result = this.resultBuffer,
  22522. values = this.sampleValues,
  22523. stride = this.valueSize,
  22524. offset1 = i1 * stride,
  22525. offset0 = offset1 - stride,
  22526. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22527. weight0 = 1 - weight1;
  22528. for ( let i = 0; i !== stride; ++ i ) {
  22529. result[ i ] =
  22530. values[ offset0 + i ] * weight0 +
  22531. values[ offset1 + i ] * weight1;
  22532. }
  22533. return result;
  22534. }
  22535. }
  22536. /**
  22537. *
  22538. * Interpolant that evaluates to the sample value at the position preceding
  22539. * the parameter.
  22540. */
  22541. class DiscreteInterpolant extends Interpolant {
  22542. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22543. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22544. }
  22545. interpolate_( i1 /*, t0, t, t1 */ ) {
  22546. return this.copySampleValue_( i1 - 1 );
  22547. }
  22548. }
  22549. class KeyframeTrack {
  22550. constructor( name, times, values, interpolation ) {
  22551. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22552. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22553. this.name = name;
  22554. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  22555. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  22556. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22557. }
  22558. // Serialization (in static context, because of constructor invocation
  22559. // and automatic invocation of .toJSON):
  22560. static toJSON( track ) {
  22561. const trackType = track.constructor;
  22562. let json;
  22563. // derived classes can define a static toJSON method
  22564. if ( trackType.toJSON !== this.toJSON ) {
  22565. json = trackType.toJSON( track );
  22566. } else {
  22567. // by default, we assume the data can be serialized as-is
  22568. json = {
  22569. 'name': track.name,
  22570. 'times': AnimationUtils.convertArray( track.times, Array ),
  22571. 'values': AnimationUtils.convertArray( track.values, Array )
  22572. };
  22573. const interpolation = track.getInterpolation();
  22574. if ( interpolation !== track.DefaultInterpolation ) {
  22575. json.interpolation = interpolation;
  22576. }
  22577. }
  22578. json.type = track.ValueTypeName; // mandatory
  22579. return json;
  22580. }
  22581. InterpolantFactoryMethodDiscrete( result ) {
  22582. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22583. }
  22584. InterpolantFactoryMethodLinear( result ) {
  22585. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22586. }
  22587. InterpolantFactoryMethodSmooth( result ) {
  22588. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22589. }
  22590. setInterpolation( interpolation ) {
  22591. let factoryMethod;
  22592. switch ( interpolation ) {
  22593. case InterpolateDiscrete:
  22594. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22595. break;
  22596. case InterpolateLinear:
  22597. factoryMethod = this.InterpolantFactoryMethodLinear;
  22598. break;
  22599. case InterpolateSmooth:
  22600. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22601. break;
  22602. }
  22603. if ( factoryMethod === undefined ) {
  22604. const message = 'unsupported interpolation for ' +
  22605. this.ValueTypeName + ' keyframe track named ' + this.name;
  22606. if ( this.createInterpolant === undefined ) {
  22607. // fall back to default, unless the default itself is messed up
  22608. if ( interpolation !== this.DefaultInterpolation ) {
  22609. this.setInterpolation( this.DefaultInterpolation );
  22610. } else {
  22611. throw new Error( message ); // fatal, in this case
  22612. }
  22613. }
  22614. console.warn( 'THREE.KeyframeTrack:', message );
  22615. return this;
  22616. }
  22617. this.createInterpolant = factoryMethod;
  22618. return this;
  22619. }
  22620. getInterpolation() {
  22621. switch ( this.createInterpolant ) {
  22622. case this.InterpolantFactoryMethodDiscrete:
  22623. return InterpolateDiscrete;
  22624. case this.InterpolantFactoryMethodLinear:
  22625. return InterpolateLinear;
  22626. case this.InterpolantFactoryMethodSmooth:
  22627. return InterpolateSmooth;
  22628. }
  22629. }
  22630. getValueSize() {
  22631. return this.values.length / this.times.length;
  22632. }
  22633. // move all keyframes either forwards or backwards in time
  22634. shift( timeOffset ) {
  22635. if ( timeOffset !== 0.0 ) {
  22636. const times = this.times;
  22637. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22638. times[ i ] += timeOffset;
  22639. }
  22640. }
  22641. return this;
  22642. }
  22643. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22644. scale( timeScale ) {
  22645. if ( timeScale !== 1.0 ) {
  22646. const times = this.times;
  22647. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22648. times[ i ] *= timeScale;
  22649. }
  22650. }
  22651. return this;
  22652. }
  22653. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22654. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22655. trim( startTime, endTime ) {
  22656. const times = this.times,
  22657. nKeys = times.length;
  22658. let from = 0,
  22659. to = nKeys - 1;
  22660. while ( from !== nKeys && times[ from ] < startTime ) {
  22661. ++ from;
  22662. }
  22663. while ( to !== - 1 && times[ to ] > endTime ) {
  22664. -- to;
  22665. }
  22666. ++ to; // inclusive -> exclusive bound
  22667. if ( from !== 0 || to !== nKeys ) {
  22668. // empty tracks are forbidden, so keep at least one keyframe
  22669. if ( from >= to ) {
  22670. to = Math.max( to, 1 );
  22671. from = to - 1;
  22672. }
  22673. const stride = this.getValueSize();
  22674. this.times = AnimationUtils.arraySlice( times, from, to );
  22675. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  22676. }
  22677. return this;
  22678. }
  22679. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22680. validate() {
  22681. let valid = true;
  22682. const valueSize = this.getValueSize();
  22683. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22684. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22685. valid = false;
  22686. }
  22687. const times = this.times,
  22688. values = this.values,
  22689. nKeys = times.length;
  22690. if ( nKeys === 0 ) {
  22691. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22692. valid = false;
  22693. }
  22694. let prevTime = null;
  22695. for ( let i = 0; i !== nKeys; i ++ ) {
  22696. const currTime = times[ i ];
  22697. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22698. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22699. valid = false;
  22700. break;
  22701. }
  22702. if ( prevTime !== null && prevTime > currTime ) {
  22703. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22704. valid = false;
  22705. break;
  22706. }
  22707. prevTime = currTime;
  22708. }
  22709. if ( values !== undefined ) {
  22710. if ( AnimationUtils.isTypedArray( values ) ) {
  22711. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22712. const value = values[ i ];
  22713. if ( isNaN( value ) ) {
  22714. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22715. valid = false;
  22716. break;
  22717. }
  22718. }
  22719. }
  22720. }
  22721. return valid;
  22722. }
  22723. // removes equivalent sequential keys as common in morph target sequences
  22724. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22725. optimize() {
  22726. // times or values may be shared with other tracks, so overwriting is unsafe
  22727. const times = AnimationUtils.arraySlice( this.times ),
  22728. values = AnimationUtils.arraySlice( this.values ),
  22729. stride = this.getValueSize(),
  22730. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22731. lastIndex = times.length - 1;
  22732. let writeIndex = 1;
  22733. for ( let i = 1; i < lastIndex; ++ i ) {
  22734. let keep = false;
  22735. const time = times[ i ];
  22736. const timeNext = times[ i + 1 ];
  22737. // remove adjacent keyframes scheduled at the same time
  22738. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22739. if ( ! smoothInterpolation ) {
  22740. // remove unnecessary keyframes same as their neighbors
  22741. const offset = i * stride,
  22742. offsetP = offset - stride,
  22743. offsetN = offset + stride;
  22744. for ( let j = 0; j !== stride; ++ j ) {
  22745. const value = values[ offset + j ];
  22746. if ( value !== values[ offsetP + j ] ||
  22747. value !== values[ offsetN + j ] ) {
  22748. keep = true;
  22749. break;
  22750. }
  22751. }
  22752. } else {
  22753. keep = true;
  22754. }
  22755. }
  22756. // in-place compaction
  22757. if ( keep ) {
  22758. if ( i !== writeIndex ) {
  22759. times[ writeIndex ] = times[ i ];
  22760. const readOffset = i * stride,
  22761. writeOffset = writeIndex * stride;
  22762. for ( let j = 0; j !== stride; ++ j ) {
  22763. values[ writeOffset + j ] = values[ readOffset + j ];
  22764. }
  22765. }
  22766. ++ writeIndex;
  22767. }
  22768. }
  22769. // flush last keyframe (compaction looks ahead)
  22770. if ( lastIndex > 0 ) {
  22771. times[ writeIndex ] = times[ lastIndex ];
  22772. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22773. values[ writeOffset + j ] = values[ readOffset + j ];
  22774. }
  22775. ++ writeIndex;
  22776. }
  22777. if ( writeIndex !== times.length ) {
  22778. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22779. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22780. } else {
  22781. this.times = times;
  22782. this.values = values;
  22783. }
  22784. return this;
  22785. }
  22786. clone() {
  22787. const times = AnimationUtils.arraySlice( this.times, 0 );
  22788. const values = AnimationUtils.arraySlice( this.values, 0 );
  22789. const TypedKeyframeTrack = this.constructor;
  22790. const track = new TypedKeyframeTrack( this.name, times, values );
  22791. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22792. track.createInterpolant = this.createInterpolant;
  22793. return track;
  22794. }
  22795. }
  22796. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22797. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22798. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22799. /**
  22800. * A Track of Boolean keyframe values.
  22801. */
  22802. class BooleanKeyframeTrack extends KeyframeTrack {}
  22803. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22804. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22805. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22806. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22807. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22808. /**
  22809. * A Track of keyframe values that represent color.
  22810. */
  22811. class ColorKeyframeTrack extends KeyframeTrack {}
  22812. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22813. /**
  22814. * A Track of numeric keyframe values.
  22815. */
  22816. class NumberKeyframeTrack extends KeyframeTrack {}
  22817. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22818. /**
  22819. * Spherical linear unit quaternion interpolant.
  22820. */
  22821. class QuaternionLinearInterpolant extends Interpolant {
  22822. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22823. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22824. }
  22825. interpolate_( i1, t0, t, t1 ) {
  22826. const result = this.resultBuffer,
  22827. values = this.sampleValues,
  22828. stride = this.valueSize,
  22829. alpha = ( t - t0 ) / ( t1 - t0 );
  22830. let offset = i1 * stride;
  22831. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22832. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22833. }
  22834. return result;
  22835. }
  22836. }
  22837. /**
  22838. * A Track of quaternion keyframe values.
  22839. */
  22840. class QuaternionKeyframeTrack extends KeyframeTrack {
  22841. InterpolantFactoryMethodLinear( result ) {
  22842. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22843. }
  22844. }
  22845. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  22846. // ValueBufferType is inherited
  22847. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22848. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22849. /**
  22850. * A Track that interpolates Strings
  22851. */
  22852. class StringKeyframeTrack extends KeyframeTrack {}
  22853. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22854. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22855. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22856. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22857. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22858. /**
  22859. * A Track of vectored keyframe values.
  22860. */
  22861. class VectorKeyframeTrack extends KeyframeTrack {}
  22862. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  22863. class AnimationClip {
  22864. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22865. this.name = name;
  22866. this.tracks = tracks;
  22867. this.duration = duration;
  22868. this.blendMode = blendMode;
  22869. this.uuid = generateUUID();
  22870. // this means it should figure out its duration by scanning the tracks
  22871. if ( this.duration < 0 ) {
  22872. this.resetDuration();
  22873. }
  22874. }
  22875. static parse( json ) {
  22876. const tracks = [],
  22877. jsonTracks = json.tracks,
  22878. frameTime = 1.0 / ( json.fps || 1.0 );
  22879. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22880. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22881. }
  22882. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  22883. clip.uuid = json.uuid;
  22884. return clip;
  22885. }
  22886. static toJSON( clip ) {
  22887. const tracks = [],
  22888. clipTracks = clip.tracks;
  22889. const json = {
  22890. 'name': clip.name,
  22891. 'duration': clip.duration,
  22892. 'tracks': tracks,
  22893. 'uuid': clip.uuid,
  22894. 'blendMode': clip.blendMode
  22895. };
  22896. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22897. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22898. }
  22899. return json;
  22900. }
  22901. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  22902. const numMorphTargets = morphTargetSequence.length;
  22903. const tracks = [];
  22904. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22905. let times = [];
  22906. let values = [];
  22907. times.push(
  22908. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22909. i,
  22910. ( i + 1 ) % numMorphTargets );
  22911. values.push( 0, 1, 0 );
  22912. const order = AnimationUtils.getKeyframeOrder( times );
  22913. times = AnimationUtils.sortedArray( times, 1, order );
  22914. values = AnimationUtils.sortedArray( values, 1, order );
  22915. // if there is a key at the first frame, duplicate it as the
  22916. // last frame as well for perfect loop.
  22917. if ( ! noLoop && times[ 0 ] === 0 ) {
  22918. times.push( numMorphTargets );
  22919. values.push( values[ 0 ] );
  22920. }
  22921. tracks.push(
  22922. new NumberKeyframeTrack(
  22923. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22924. times, values
  22925. ).scale( 1.0 / fps ) );
  22926. }
  22927. return new this( name, - 1, tracks );
  22928. }
  22929. static findByName( objectOrClipArray, name ) {
  22930. let clipArray = objectOrClipArray;
  22931. if ( ! Array.isArray( objectOrClipArray ) ) {
  22932. const o = objectOrClipArray;
  22933. clipArray = o.geometry && o.geometry.animations || o.animations;
  22934. }
  22935. for ( let i = 0; i < clipArray.length; i ++ ) {
  22936. if ( clipArray[ i ].name === name ) {
  22937. return clipArray[ i ];
  22938. }
  22939. }
  22940. return null;
  22941. }
  22942. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  22943. const animationToMorphTargets = {};
  22944. // tested with https://regex101.com/ on trick sequences
  22945. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22946. const pattern = /^([\w-]*?)([\d]+)$/;
  22947. // sort morph target names into animation groups based
  22948. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22949. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22950. const morphTarget = morphTargets[ i ];
  22951. const parts = morphTarget.name.match( pattern );
  22952. if ( parts && parts.length > 1 ) {
  22953. const name = parts[ 1 ];
  22954. let animationMorphTargets = animationToMorphTargets[ name ];
  22955. if ( ! animationMorphTargets ) {
  22956. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22957. }
  22958. animationMorphTargets.push( morphTarget );
  22959. }
  22960. }
  22961. const clips = [];
  22962. for ( const name in animationToMorphTargets ) {
  22963. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22964. }
  22965. return clips;
  22966. }
  22967. // parse the animation.hierarchy format
  22968. static parseAnimation( animation, bones ) {
  22969. if ( ! animation ) {
  22970. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22971. return null;
  22972. }
  22973. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22974. // only return track if there are actually keys.
  22975. if ( animationKeys.length !== 0 ) {
  22976. const times = [];
  22977. const values = [];
  22978. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22979. // empty keys are filtered out, so check again
  22980. if ( times.length !== 0 ) {
  22981. destTracks.push( new trackType( trackName, times, values ) );
  22982. }
  22983. }
  22984. };
  22985. const tracks = [];
  22986. const clipName = animation.name || 'default';
  22987. const fps = animation.fps || 30;
  22988. const blendMode = animation.blendMode;
  22989. // automatic length determination in AnimationClip.
  22990. let duration = animation.length || - 1;
  22991. const hierarchyTracks = animation.hierarchy || [];
  22992. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22993. const animationKeys = hierarchyTracks[ h ].keys;
  22994. // skip empty tracks
  22995. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22996. // process morph targets
  22997. if ( animationKeys[ 0 ].morphTargets ) {
  22998. // figure out all morph targets used in this track
  22999. const morphTargetNames = {};
  23000. let k;
  23001. for ( k = 0; k < animationKeys.length; k ++ ) {
  23002. if ( animationKeys[ k ].morphTargets ) {
  23003. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23004. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23005. }
  23006. }
  23007. }
  23008. // create a track for each morph target with all zero
  23009. // morphTargetInfluences except for the keys in which
  23010. // the morphTarget is named.
  23011. for ( const morphTargetName in morphTargetNames ) {
  23012. const times = [];
  23013. const values = [];
  23014. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23015. const animationKey = animationKeys[ k ];
  23016. times.push( animationKey.time );
  23017. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23018. }
  23019. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23020. }
  23021. duration = morphTargetNames.length * fps;
  23022. } else {
  23023. // ...assume skeletal animation
  23024. const boneName = '.bones[' + bones[ h ].name + ']';
  23025. addNonemptyTrack(
  23026. VectorKeyframeTrack, boneName + '.position',
  23027. animationKeys, 'pos', tracks );
  23028. addNonemptyTrack(
  23029. QuaternionKeyframeTrack, boneName + '.quaternion',
  23030. animationKeys, 'rot', tracks );
  23031. addNonemptyTrack(
  23032. VectorKeyframeTrack, boneName + '.scale',
  23033. animationKeys, 'scl', tracks );
  23034. }
  23035. }
  23036. if ( tracks.length === 0 ) {
  23037. return null;
  23038. }
  23039. const clip = new this( clipName, duration, tracks, blendMode );
  23040. return clip;
  23041. }
  23042. resetDuration() {
  23043. const tracks = this.tracks;
  23044. let duration = 0;
  23045. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23046. const track = this.tracks[ i ];
  23047. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23048. }
  23049. this.duration = duration;
  23050. return this;
  23051. }
  23052. trim() {
  23053. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23054. this.tracks[ i ].trim( 0, this.duration );
  23055. }
  23056. return this;
  23057. }
  23058. validate() {
  23059. let valid = true;
  23060. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23061. valid = valid && this.tracks[ i ].validate();
  23062. }
  23063. return valid;
  23064. }
  23065. optimize() {
  23066. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23067. this.tracks[ i ].optimize();
  23068. }
  23069. return this;
  23070. }
  23071. clone() {
  23072. const tracks = [];
  23073. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23074. tracks.push( this.tracks[ i ].clone() );
  23075. }
  23076. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23077. }
  23078. toJSON() {
  23079. return this.constructor.toJSON( this );
  23080. }
  23081. }
  23082. function getTrackTypeForValueTypeName( typeName ) {
  23083. switch ( typeName.toLowerCase() ) {
  23084. case 'scalar':
  23085. case 'double':
  23086. case 'float':
  23087. case 'number':
  23088. case 'integer':
  23089. return NumberKeyframeTrack;
  23090. case 'vector':
  23091. case 'vector2':
  23092. case 'vector3':
  23093. case 'vector4':
  23094. return VectorKeyframeTrack;
  23095. case 'color':
  23096. return ColorKeyframeTrack;
  23097. case 'quaternion':
  23098. return QuaternionKeyframeTrack;
  23099. case 'bool':
  23100. case 'boolean':
  23101. return BooleanKeyframeTrack;
  23102. case 'string':
  23103. return StringKeyframeTrack;
  23104. }
  23105. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23106. }
  23107. function parseKeyframeTrack( json ) {
  23108. if ( json.type === undefined ) {
  23109. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23110. }
  23111. const trackType = getTrackTypeForValueTypeName( json.type );
  23112. if ( json.times === undefined ) {
  23113. const times = [], values = [];
  23114. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23115. json.times = times;
  23116. json.values = values;
  23117. }
  23118. // derived classes can define a static parse method
  23119. if ( trackType.parse !== undefined ) {
  23120. return trackType.parse( json );
  23121. } else {
  23122. // by default, we assume a constructor compatible with the base
  23123. return new trackType( json.name, json.times, json.values, json.interpolation );
  23124. }
  23125. }
  23126. const Cache = {
  23127. enabled: false,
  23128. files: {},
  23129. add: function ( key, file ) {
  23130. if ( this.enabled === false ) return;
  23131. // console.log( 'THREE.Cache', 'Adding key:', key );
  23132. this.files[ key ] = file;
  23133. },
  23134. get: function ( key ) {
  23135. if ( this.enabled === false ) return;
  23136. // console.log( 'THREE.Cache', 'Checking key:', key );
  23137. return this.files[ key ];
  23138. },
  23139. remove: function ( key ) {
  23140. delete this.files[ key ];
  23141. },
  23142. clear: function () {
  23143. this.files = {};
  23144. }
  23145. };
  23146. class LoadingManager {
  23147. constructor( onLoad, onProgress, onError ) {
  23148. const scope = this;
  23149. let isLoading = false;
  23150. let itemsLoaded = 0;
  23151. let itemsTotal = 0;
  23152. let urlModifier = undefined;
  23153. const handlers = [];
  23154. // Refer to #5689 for the reason why we don't set .onStart
  23155. // in the constructor
  23156. this.onStart = undefined;
  23157. this.onLoad = onLoad;
  23158. this.onProgress = onProgress;
  23159. this.onError = onError;
  23160. this.itemStart = function ( url ) {
  23161. itemsTotal ++;
  23162. if ( isLoading === false ) {
  23163. if ( scope.onStart !== undefined ) {
  23164. scope.onStart( url, itemsLoaded, itemsTotal );
  23165. }
  23166. }
  23167. isLoading = true;
  23168. };
  23169. this.itemEnd = function ( url ) {
  23170. itemsLoaded ++;
  23171. if ( scope.onProgress !== undefined ) {
  23172. scope.onProgress( url, itemsLoaded, itemsTotal );
  23173. }
  23174. if ( itemsLoaded === itemsTotal ) {
  23175. isLoading = false;
  23176. if ( scope.onLoad !== undefined ) {
  23177. scope.onLoad();
  23178. }
  23179. }
  23180. };
  23181. this.itemError = function ( url ) {
  23182. if ( scope.onError !== undefined ) {
  23183. scope.onError( url );
  23184. }
  23185. };
  23186. this.resolveURL = function ( url ) {
  23187. if ( urlModifier ) {
  23188. return urlModifier( url );
  23189. }
  23190. return url;
  23191. };
  23192. this.setURLModifier = function ( transform ) {
  23193. urlModifier = transform;
  23194. return this;
  23195. };
  23196. this.addHandler = function ( regex, loader ) {
  23197. handlers.push( regex, loader );
  23198. return this;
  23199. };
  23200. this.removeHandler = function ( regex ) {
  23201. const index = handlers.indexOf( regex );
  23202. if ( index !== - 1 ) {
  23203. handlers.splice( index, 2 );
  23204. }
  23205. return this;
  23206. };
  23207. this.getHandler = function ( file ) {
  23208. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23209. const regex = handlers[ i ];
  23210. const loader = handlers[ i + 1 ];
  23211. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23212. if ( regex.test( file ) ) {
  23213. return loader;
  23214. }
  23215. }
  23216. return null;
  23217. };
  23218. }
  23219. }
  23220. const DefaultLoadingManager = new LoadingManager();
  23221. class Loader {
  23222. constructor( manager ) {
  23223. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23224. this.crossOrigin = 'anonymous';
  23225. this.withCredentials = false;
  23226. this.path = '';
  23227. this.resourcePath = '';
  23228. this.requestHeader = {};
  23229. }
  23230. load( /* url, onLoad, onProgress, onError */ ) {}
  23231. loadAsync( url, onProgress ) {
  23232. const scope = this;
  23233. return new Promise( function ( resolve, reject ) {
  23234. scope.load( url, resolve, onProgress, reject );
  23235. } );
  23236. }
  23237. parse( /* data */ ) {}
  23238. setCrossOrigin( crossOrigin ) {
  23239. this.crossOrigin = crossOrigin;
  23240. return this;
  23241. }
  23242. setWithCredentials( value ) {
  23243. this.withCredentials = value;
  23244. return this;
  23245. }
  23246. setPath( path ) {
  23247. this.path = path;
  23248. return this;
  23249. }
  23250. setResourcePath( resourcePath ) {
  23251. this.resourcePath = resourcePath;
  23252. return this;
  23253. }
  23254. setRequestHeader( requestHeader ) {
  23255. this.requestHeader = requestHeader;
  23256. return this;
  23257. }
  23258. }
  23259. const loading = {};
  23260. class FileLoader extends Loader {
  23261. constructor( manager ) {
  23262. super( manager );
  23263. }
  23264. load( url, onLoad, onProgress, onError ) {
  23265. if ( url === undefined ) url = '';
  23266. if ( this.path !== undefined ) url = this.path + url;
  23267. url = this.manager.resolveURL( url );
  23268. const cached = Cache.get( url );
  23269. if ( cached !== undefined ) {
  23270. this.manager.itemStart( url );
  23271. setTimeout( () => {
  23272. if ( onLoad ) onLoad( cached );
  23273. this.manager.itemEnd( url );
  23274. }, 0 );
  23275. return cached;
  23276. }
  23277. // Check if request is duplicate
  23278. if ( loading[ url ] !== undefined ) {
  23279. loading[ url ].push( {
  23280. onLoad: onLoad,
  23281. onProgress: onProgress,
  23282. onError: onError
  23283. } );
  23284. return;
  23285. }
  23286. // Initialise array for duplicate requests
  23287. loading[ url ] = [];
  23288. loading[ url ].push( {
  23289. onLoad: onLoad,
  23290. onProgress: onProgress,
  23291. onError: onError,
  23292. } );
  23293. // create request
  23294. const req = new Request( url, {
  23295. headers: new Headers( this.requestHeader ),
  23296. credentials: this.withCredentials ? 'include' : 'same-origin',
  23297. // An abort controller could be added within a future PR
  23298. } );
  23299. // record states ( avoid data race )
  23300. const mimeType = this.mimeType;
  23301. const responseType = this.responseType;
  23302. // start the fetch
  23303. fetch( req )
  23304. .then( response => {
  23305. if ( response.status === 200 || response.status === 0 ) {
  23306. // Some browsers return HTTP Status 0 when using non-http protocol
  23307. // e.g. 'file://' or 'data://'. Handle as success.
  23308. if ( response.status === 0 ) {
  23309. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23310. }
  23311. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23312. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23313. return response;
  23314. }
  23315. const callbacks = loading[ url ];
  23316. const reader = response.body.getReader();
  23317. const contentLength = response.headers.get( 'Content-Length' );
  23318. const total = contentLength ? parseInt( contentLength ) : 0;
  23319. const lengthComputable = total !== 0;
  23320. let loaded = 0;
  23321. // periodically read data into the new stream tracking while download progress
  23322. const stream = new ReadableStream( {
  23323. start( controller ) {
  23324. readData();
  23325. function readData() {
  23326. reader.read().then( ( { done, value } ) => {
  23327. if ( done ) {
  23328. controller.close();
  23329. } else {
  23330. loaded += value.byteLength;
  23331. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23332. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23333. const callback = callbacks[ i ];
  23334. if ( callback.onProgress ) callback.onProgress( event );
  23335. }
  23336. controller.enqueue( value );
  23337. readData();
  23338. }
  23339. } );
  23340. }
  23341. }
  23342. } );
  23343. return new Response( stream );
  23344. } else {
  23345. throw Error( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}` );
  23346. }
  23347. } )
  23348. .then( response => {
  23349. switch ( responseType ) {
  23350. case 'arraybuffer':
  23351. return response.arrayBuffer();
  23352. case 'blob':
  23353. return response.blob();
  23354. case 'document':
  23355. return response.text()
  23356. .then( text => {
  23357. const parser = new DOMParser();
  23358. return parser.parseFromString( text, mimeType );
  23359. } );
  23360. case 'json':
  23361. return response.json();
  23362. default:
  23363. if ( mimeType === undefined ) {
  23364. return response.text();
  23365. } else {
  23366. // sniff encoding
  23367. const re = /charset="?([^;"\s]*)"?/i;
  23368. const exec = re.exec( mimeType );
  23369. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23370. const decoder = new TextDecoder( label );
  23371. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23372. }
  23373. }
  23374. } )
  23375. .then( data => {
  23376. // Add to cache only on HTTP success, so that we do not cache
  23377. // error response bodies as proper responses to requests.
  23378. Cache.add( url, data );
  23379. const callbacks = loading[ url ];
  23380. delete loading[ url ];
  23381. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23382. const callback = callbacks[ i ];
  23383. if ( callback.onLoad ) callback.onLoad( data );
  23384. }
  23385. } )
  23386. .catch( err => {
  23387. // Abort errors and other errors are handled the same
  23388. const callbacks = loading[ url ];
  23389. if ( callbacks === undefined ) {
  23390. // When onLoad was called and url was deleted in `loading`
  23391. this.manager.itemError( url );
  23392. throw err;
  23393. }
  23394. delete loading[ url ];
  23395. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23396. const callback = callbacks[ i ];
  23397. if ( callback.onError ) callback.onError( err );
  23398. }
  23399. this.manager.itemError( url );
  23400. } )
  23401. .finally( () => {
  23402. this.manager.itemEnd( url );
  23403. } );
  23404. this.manager.itemStart( url );
  23405. }
  23406. setResponseType( value ) {
  23407. this.responseType = value;
  23408. return this;
  23409. }
  23410. setMimeType( value ) {
  23411. this.mimeType = value;
  23412. return this;
  23413. }
  23414. }
  23415. class AnimationLoader extends Loader {
  23416. constructor( manager ) {
  23417. super( manager );
  23418. }
  23419. load( url, onLoad, onProgress, onError ) {
  23420. const scope = this;
  23421. const loader = new FileLoader( this.manager );
  23422. loader.setPath( this.path );
  23423. loader.setRequestHeader( this.requestHeader );
  23424. loader.setWithCredentials( this.withCredentials );
  23425. loader.load( url, function ( text ) {
  23426. try {
  23427. onLoad( scope.parse( JSON.parse( text ) ) );
  23428. } catch ( e ) {
  23429. if ( onError ) {
  23430. onError( e );
  23431. } else {
  23432. console.error( e );
  23433. }
  23434. scope.manager.itemError( url );
  23435. }
  23436. }, onProgress, onError );
  23437. }
  23438. parse( json ) {
  23439. const animations = [];
  23440. for ( let i = 0; i < json.length; i ++ ) {
  23441. const clip = AnimationClip.parse( json[ i ] );
  23442. animations.push( clip );
  23443. }
  23444. return animations;
  23445. }
  23446. }
  23447. /**
  23448. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23449. *
  23450. * Sub classes have to implement the parse() method which will be used in load().
  23451. */
  23452. class CompressedTextureLoader extends Loader {
  23453. constructor( manager ) {
  23454. super( manager );
  23455. }
  23456. load( url, onLoad, onProgress, onError ) {
  23457. const scope = this;
  23458. const images = [];
  23459. const texture = new CompressedTexture();
  23460. const loader = new FileLoader( this.manager );
  23461. loader.setPath( this.path );
  23462. loader.setResponseType( 'arraybuffer' );
  23463. loader.setRequestHeader( this.requestHeader );
  23464. loader.setWithCredentials( scope.withCredentials );
  23465. let loaded = 0;
  23466. function loadTexture( i ) {
  23467. loader.load( url[ i ], function ( buffer ) {
  23468. const texDatas = scope.parse( buffer, true );
  23469. images[ i ] = {
  23470. width: texDatas.width,
  23471. height: texDatas.height,
  23472. format: texDatas.format,
  23473. mipmaps: texDatas.mipmaps
  23474. };
  23475. loaded += 1;
  23476. if ( loaded === 6 ) {
  23477. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23478. texture.image = images;
  23479. texture.format = texDatas.format;
  23480. texture.needsUpdate = true;
  23481. if ( onLoad ) onLoad( texture );
  23482. }
  23483. }, onProgress, onError );
  23484. }
  23485. if ( Array.isArray( url ) ) {
  23486. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23487. loadTexture( i );
  23488. }
  23489. } else {
  23490. // compressed cubemap texture stored in a single DDS file
  23491. loader.load( url, function ( buffer ) {
  23492. const texDatas = scope.parse( buffer, true );
  23493. if ( texDatas.isCubemap ) {
  23494. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23495. for ( let f = 0; f < faces; f ++ ) {
  23496. images[ f ] = { mipmaps: [] };
  23497. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23498. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23499. images[ f ].format = texDatas.format;
  23500. images[ f ].width = texDatas.width;
  23501. images[ f ].height = texDatas.height;
  23502. }
  23503. }
  23504. texture.image = images;
  23505. } else {
  23506. texture.image.width = texDatas.width;
  23507. texture.image.height = texDatas.height;
  23508. texture.mipmaps = texDatas.mipmaps;
  23509. }
  23510. if ( texDatas.mipmapCount === 1 ) {
  23511. texture.minFilter = LinearFilter;
  23512. }
  23513. texture.format = texDatas.format;
  23514. texture.needsUpdate = true;
  23515. if ( onLoad ) onLoad( texture );
  23516. }, onProgress, onError );
  23517. }
  23518. return texture;
  23519. }
  23520. }
  23521. class ImageLoader extends Loader {
  23522. constructor( manager ) {
  23523. super( manager );
  23524. }
  23525. load( url, onLoad, onProgress, onError ) {
  23526. if ( this.path !== undefined ) url = this.path + url;
  23527. url = this.manager.resolveURL( url );
  23528. const scope = this;
  23529. const cached = Cache.get( url );
  23530. if ( cached !== undefined ) {
  23531. scope.manager.itemStart( url );
  23532. setTimeout( function () {
  23533. if ( onLoad ) onLoad( cached );
  23534. scope.manager.itemEnd( url );
  23535. }, 0 );
  23536. return cached;
  23537. }
  23538. const image = createElementNS( 'img' );
  23539. function onImageLoad() {
  23540. removeEventListeners();
  23541. Cache.add( url, this );
  23542. if ( onLoad ) onLoad( this );
  23543. scope.manager.itemEnd( url );
  23544. }
  23545. function onImageError( event ) {
  23546. removeEventListeners();
  23547. if ( onError ) onError( event );
  23548. scope.manager.itemError( url );
  23549. scope.manager.itemEnd( url );
  23550. }
  23551. function removeEventListeners() {
  23552. image.removeEventListener( 'load', onImageLoad, false );
  23553. image.removeEventListener( 'error', onImageError, false );
  23554. }
  23555. image.addEventListener( 'load', onImageLoad, false );
  23556. image.addEventListener( 'error', onImageError, false );
  23557. if ( url.slice( 0, 5 ) !== 'data:' ) {
  23558. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23559. }
  23560. scope.manager.itemStart( url );
  23561. image.src = url;
  23562. return image;
  23563. }
  23564. }
  23565. class CubeTextureLoader extends Loader {
  23566. constructor( manager ) {
  23567. super( manager );
  23568. }
  23569. load( urls, onLoad, onProgress, onError ) {
  23570. const texture = new CubeTexture();
  23571. const loader = new ImageLoader( this.manager );
  23572. loader.setCrossOrigin( this.crossOrigin );
  23573. loader.setPath( this.path );
  23574. let loaded = 0;
  23575. function loadTexture( i ) {
  23576. loader.load( urls[ i ], function ( image ) {
  23577. texture.images[ i ] = image;
  23578. loaded ++;
  23579. if ( loaded === 6 ) {
  23580. texture.needsUpdate = true;
  23581. if ( onLoad ) onLoad( texture );
  23582. }
  23583. }, undefined, onError );
  23584. }
  23585. for ( let i = 0; i < urls.length; ++ i ) {
  23586. loadTexture( i );
  23587. }
  23588. return texture;
  23589. }
  23590. }
  23591. /**
  23592. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23593. *
  23594. * Sub classes have to implement the parse() method which will be used in load().
  23595. */
  23596. class DataTextureLoader extends Loader {
  23597. constructor( manager ) {
  23598. super( manager );
  23599. }
  23600. load( url, onLoad, onProgress, onError ) {
  23601. const scope = this;
  23602. const texture = new DataTexture();
  23603. const loader = new FileLoader( this.manager );
  23604. loader.setResponseType( 'arraybuffer' );
  23605. loader.setRequestHeader( this.requestHeader );
  23606. loader.setPath( this.path );
  23607. loader.setWithCredentials( scope.withCredentials );
  23608. loader.load( url, function ( buffer ) {
  23609. const texData = scope.parse( buffer );
  23610. if ( ! texData ) return;
  23611. if ( texData.image !== undefined ) {
  23612. texture.image = texData.image;
  23613. } else if ( texData.data !== undefined ) {
  23614. texture.image.width = texData.width;
  23615. texture.image.height = texData.height;
  23616. texture.image.data = texData.data;
  23617. }
  23618. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23619. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23620. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23621. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23622. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23623. if ( texData.encoding !== undefined ) {
  23624. texture.encoding = texData.encoding;
  23625. }
  23626. if ( texData.flipY !== undefined ) {
  23627. texture.flipY = texData.flipY;
  23628. }
  23629. if ( texData.format !== undefined ) {
  23630. texture.format = texData.format;
  23631. }
  23632. if ( texData.type !== undefined ) {
  23633. texture.type = texData.type;
  23634. }
  23635. if ( texData.mipmaps !== undefined ) {
  23636. texture.mipmaps = texData.mipmaps;
  23637. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23638. }
  23639. if ( texData.mipmapCount === 1 ) {
  23640. texture.minFilter = LinearFilter;
  23641. }
  23642. if ( texData.generateMipmaps !== undefined ) {
  23643. texture.generateMipmaps = texData.generateMipmaps;
  23644. }
  23645. texture.needsUpdate = true;
  23646. if ( onLoad ) onLoad( texture, texData );
  23647. }, onProgress, onError );
  23648. return texture;
  23649. }
  23650. }
  23651. class TextureLoader extends Loader {
  23652. constructor( manager ) {
  23653. super( manager );
  23654. }
  23655. load( url, onLoad, onProgress, onError ) {
  23656. const texture = new Texture();
  23657. const loader = new ImageLoader( this.manager );
  23658. loader.setCrossOrigin( this.crossOrigin );
  23659. loader.setPath( this.path );
  23660. loader.load( url, function ( image ) {
  23661. texture.image = image;
  23662. texture.needsUpdate = true;
  23663. if ( onLoad !== undefined ) {
  23664. onLoad( texture );
  23665. }
  23666. }, onProgress, onError );
  23667. return texture;
  23668. }
  23669. }
  23670. class Light extends Object3D {
  23671. constructor( color, intensity = 1 ) {
  23672. super();
  23673. this.type = 'Light';
  23674. this.color = new Color( color );
  23675. this.intensity = intensity;
  23676. }
  23677. dispose() {
  23678. // Empty here in base class; some subclasses override.
  23679. }
  23680. copy( source ) {
  23681. super.copy( source );
  23682. this.color.copy( source.color );
  23683. this.intensity = source.intensity;
  23684. return this;
  23685. }
  23686. toJSON( meta ) {
  23687. const data = super.toJSON( meta );
  23688. data.object.color = this.color.getHex();
  23689. data.object.intensity = this.intensity;
  23690. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23691. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23692. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23693. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23694. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23695. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23696. return data;
  23697. }
  23698. }
  23699. Light.prototype.isLight = true;
  23700. class HemisphereLight extends Light {
  23701. constructor( skyColor, groundColor, intensity ) {
  23702. super( skyColor, intensity );
  23703. this.type = 'HemisphereLight';
  23704. this.position.copy( Object3D.DefaultUp );
  23705. this.updateMatrix();
  23706. this.groundColor = new Color( groundColor );
  23707. }
  23708. copy( source ) {
  23709. Light.prototype.copy.call( this, source );
  23710. this.groundColor.copy( source.groundColor );
  23711. return this;
  23712. }
  23713. }
  23714. HemisphereLight.prototype.isHemisphereLight = true;
  23715. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23716. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23717. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23718. class LightShadow {
  23719. constructor( camera ) {
  23720. this.camera = camera;
  23721. this.bias = 0;
  23722. this.normalBias = 0;
  23723. this.radius = 1;
  23724. this.blurSamples = 8;
  23725. this.mapSize = new Vector2( 512, 512 );
  23726. this.map = null;
  23727. this.mapPass = null;
  23728. this.matrix = new Matrix4();
  23729. this.autoUpdate = true;
  23730. this.needsUpdate = false;
  23731. this._frustum = new Frustum();
  23732. this._frameExtents = new Vector2( 1, 1 );
  23733. this._viewportCount = 1;
  23734. this._viewports = [
  23735. new Vector4( 0, 0, 1, 1 )
  23736. ];
  23737. }
  23738. getViewportCount() {
  23739. return this._viewportCount;
  23740. }
  23741. getFrustum() {
  23742. return this._frustum;
  23743. }
  23744. updateMatrices( light ) {
  23745. const shadowCamera = this.camera;
  23746. const shadowMatrix = this.matrix;
  23747. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23748. shadowCamera.position.copy( _lightPositionWorld$1 );
  23749. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23750. shadowCamera.lookAt( _lookTarget$1 );
  23751. shadowCamera.updateMatrixWorld();
  23752. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23753. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23754. shadowMatrix.set(
  23755. 0.5, 0.0, 0.0, 0.5,
  23756. 0.0, 0.5, 0.0, 0.5,
  23757. 0.0, 0.0, 0.5, 0.5,
  23758. 0.0, 0.0, 0.0, 1.0
  23759. );
  23760. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23761. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23762. }
  23763. getViewport( viewportIndex ) {
  23764. return this._viewports[ viewportIndex ];
  23765. }
  23766. getFrameExtents() {
  23767. return this._frameExtents;
  23768. }
  23769. dispose() {
  23770. if ( this.map ) {
  23771. this.map.dispose();
  23772. }
  23773. if ( this.mapPass ) {
  23774. this.mapPass.dispose();
  23775. }
  23776. }
  23777. copy( source ) {
  23778. this.camera = source.camera.clone();
  23779. this.bias = source.bias;
  23780. this.radius = source.radius;
  23781. this.mapSize.copy( source.mapSize );
  23782. return this;
  23783. }
  23784. clone() {
  23785. return new this.constructor().copy( this );
  23786. }
  23787. toJSON() {
  23788. const object = {};
  23789. if ( this.bias !== 0 ) object.bias = this.bias;
  23790. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23791. if ( this.radius !== 1 ) object.radius = this.radius;
  23792. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23793. object.camera = this.camera.toJSON( false ).object;
  23794. delete object.camera.matrix;
  23795. return object;
  23796. }
  23797. }
  23798. class SpotLightShadow extends LightShadow {
  23799. constructor() {
  23800. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23801. this.focus = 1;
  23802. }
  23803. updateMatrices( light ) {
  23804. const camera = this.camera;
  23805. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23806. const aspect = this.mapSize.width / this.mapSize.height;
  23807. const far = light.distance || camera.far;
  23808. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23809. camera.fov = fov;
  23810. camera.aspect = aspect;
  23811. camera.far = far;
  23812. camera.updateProjectionMatrix();
  23813. }
  23814. super.updateMatrices( light );
  23815. }
  23816. copy( source ) {
  23817. super.copy( source );
  23818. this.focus = source.focus;
  23819. return this;
  23820. }
  23821. }
  23822. SpotLightShadow.prototype.isSpotLightShadow = true;
  23823. class SpotLight extends Light {
  23824. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  23825. super( color, intensity );
  23826. this.type = 'SpotLight';
  23827. this.position.copy( Object3D.DefaultUp );
  23828. this.updateMatrix();
  23829. this.target = new Object3D();
  23830. this.distance = distance;
  23831. this.angle = angle;
  23832. this.penumbra = penumbra;
  23833. this.decay = decay; // for physically correct lights, should be 2.
  23834. this.shadow = new SpotLightShadow();
  23835. }
  23836. get power() {
  23837. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23838. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23839. return this.intensity * Math.PI;
  23840. }
  23841. set power( power ) {
  23842. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23843. this.intensity = power / Math.PI;
  23844. }
  23845. dispose() {
  23846. this.shadow.dispose();
  23847. }
  23848. copy( source ) {
  23849. super.copy( source );
  23850. this.distance = source.distance;
  23851. this.angle = source.angle;
  23852. this.penumbra = source.penumbra;
  23853. this.decay = source.decay;
  23854. this.target = source.target.clone();
  23855. this.shadow = source.shadow.clone();
  23856. return this;
  23857. }
  23858. }
  23859. SpotLight.prototype.isSpotLight = true;
  23860. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  23861. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  23862. const _lookTarget = /*@__PURE__*/ new Vector3();
  23863. class PointLightShadow extends LightShadow {
  23864. constructor() {
  23865. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23866. this._frameExtents = new Vector2( 4, 2 );
  23867. this._viewportCount = 6;
  23868. this._viewports = [
  23869. // These viewports map a cube-map onto a 2D texture with the
  23870. // following orientation:
  23871. //
  23872. // xzXZ
  23873. // y Y
  23874. //
  23875. // X - Positive x direction
  23876. // x - Negative x direction
  23877. // Y - Positive y direction
  23878. // y - Negative y direction
  23879. // Z - Positive z direction
  23880. // z - Negative z direction
  23881. // positive X
  23882. new Vector4( 2, 1, 1, 1 ),
  23883. // negative X
  23884. new Vector4( 0, 1, 1, 1 ),
  23885. // positive Z
  23886. new Vector4( 3, 1, 1, 1 ),
  23887. // negative Z
  23888. new Vector4( 1, 1, 1, 1 ),
  23889. // positive Y
  23890. new Vector4( 3, 0, 1, 1 ),
  23891. // negative Y
  23892. new Vector4( 1, 0, 1, 1 )
  23893. ];
  23894. this._cubeDirections = [
  23895. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23896. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  23897. ];
  23898. this._cubeUps = [
  23899. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23900. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  23901. ];
  23902. }
  23903. updateMatrices( light, viewportIndex = 0 ) {
  23904. const camera = this.camera;
  23905. const shadowMatrix = this.matrix;
  23906. const far = light.distance || camera.far;
  23907. if ( far !== camera.far ) {
  23908. camera.far = far;
  23909. camera.updateProjectionMatrix();
  23910. }
  23911. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23912. camera.position.copy( _lightPositionWorld );
  23913. _lookTarget.copy( camera.position );
  23914. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23915. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23916. camera.lookAt( _lookTarget );
  23917. camera.updateMatrixWorld();
  23918. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  23919. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23920. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  23921. }
  23922. }
  23923. PointLightShadow.prototype.isPointLightShadow = true;
  23924. class PointLight extends Light {
  23925. constructor( color, intensity, distance = 0, decay = 1 ) {
  23926. super( color, intensity );
  23927. this.type = 'PointLight';
  23928. this.distance = distance;
  23929. this.decay = decay; // for physically correct lights, should be 2.
  23930. this.shadow = new PointLightShadow();
  23931. }
  23932. get power() {
  23933. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23934. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23935. return this.intensity * 4 * Math.PI;
  23936. }
  23937. set power( power ) {
  23938. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23939. this.intensity = power / ( 4 * Math.PI );
  23940. }
  23941. dispose() {
  23942. this.shadow.dispose();
  23943. }
  23944. copy( source ) {
  23945. super.copy( source );
  23946. this.distance = source.distance;
  23947. this.decay = source.decay;
  23948. this.shadow = source.shadow.clone();
  23949. return this;
  23950. }
  23951. }
  23952. PointLight.prototype.isPointLight = true;
  23953. class DirectionalLightShadow extends LightShadow {
  23954. constructor() {
  23955. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23956. }
  23957. }
  23958. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23959. class DirectionalLight extends Light {
  23960. constructor( color, intensity ) {
  23961. super( color, intensity );
  23962. this.type = 'DirectionalLight';
  23963. this.position.copy( Object3D.DefaultUp );
  23964. this.updateMatrix();
  23965. this.target = new Object3D();
  23966. this.shadow = new DirectionalLightShadow();
  23967. }
  23968. dispose() {
  23969. this.shadow.dispose();
  23970. }
  23971. copy( source ) {
  23972. super.copy( source );
  23973. this.target = source.target.clone();
  23974. this.shadow = source.shadow.clone();
  23975. return this;
  23976. }
  23977. }
  23978. DirectionalLight.prototype.isDirectionalLight = true;
  23979. class AmbientLight extends Light {
  23980. constructor( color, intensity ) {
  23981. super( color, intensity );
  23982. this.type = 'AmbientLight';
  23983. }
  23984. }
  23985. AmbientLight.prototype.isAmbientLight = true;
  23986. class RectAreaLight extends Light {
  23987. constructor( color, intensity, width = 10, height = 10 ) {
  23988. super( color, intensity );
  23989. this.type = 'RectAreaLight';
  23990. this.width = width;
  23991. this.height = height;
  23992. }
  23993. get power() {
  23994. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23995. return this.intensity * this.width * this.height * Math.PI;
  23996. }
  23997. set power( power ) {
  23998. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23999. this.intensity = power / ( this.width * this.height * Math.PI );
  24000. }
  24001. copy( source ) {
  24002. super.copy( source );
  24003. this.width = source.width;
  24004. this.height = source.height;
  24005. return this;
  24006. }
  24007. toJSON( meta ) {
  24008. const data = super.toJSON( meta );
  24009. data.object.width = this.width;
  24010. data.object.height = this.height;
  24011. return data;
  24012. }
  24013. }
  24014. RectAreaLight.prototype.isRectAreaLight = true;
  24015. /**
  24016. * Primary reference:
  24017. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24018. *
  24019. * Secondary reference:
  24020. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24021. */
  24022. // 3-band SH defined by 9 coefficients
  24023. class SphericalHarmonics3 {
  24024. constructor() {
  24025. this.coefficients = [];
  24026. for ( let i = 0; i < 9; i ++ ) {
  24027. this.coefficients.push( new Vector3() );
  24028. }
  24029. }
  24030. set( coefficients ) {
  24031. for ( let i = 0; i < 9; i ++ ) {
  24032. this.coefficients[ i ].copy( coefficients[ i ] );
  24033. }
  24034. return this;
  24035. }
  24036. zero() {
  24037. for ( let i = 0; i < 9; i ++ ) {
  24038. this.coefficients[ i ].set( 0, 0, 0 );
  24039. }
  24040. return this;
  24041. }
  24042. // get the radiance in the direction of the normal
  24043. // target is a Vector3
  24044. getAt( normal, target ) {
  24045. // normal is assumed to be unit length
  24046. const x = normal.x, y = normal.y, z = normal.z;
  24047. const coeff = this.coefficients;
  24048. // band 0
  24049. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24050. // band 1
  24051. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24052. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24053. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24054. // band 2
  24055. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24056. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24057. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24058. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24059. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24060. return target;
  24061. }
  24062. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24063. // target is a Vector3
  24064. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24065. getIrradianceAt( normal, target ) {
  24066. // normal is assumed to be unit length
  24067. const x = normal.x, y = normal.y, z = normal.z;
  24068. const coeff = this.coefficients;
  24069. // band 0
  24070. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24071. // band 1
  24072. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24073. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24074. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24075. // band 2
  24076. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24077. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24078. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24079. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24080. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24081. return target;
  24082. }
  24083. add( sh ) {
  24084. for ( let i = 0; i < 9; i ++ ) {
  24085. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24086. }
  24087. return this;
  24088. }
  24089. addScaledSH( sh, s ) {
  24090. for ( let i = 0; i < 9; i ++ ) {
  24091. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24092. }
  24093. return this;
  24094. }
  24095. scale( s ) {
  24096. for ( let i = 0; i < 9; i ++ ) {
  24097. this.coefficients[ i ].multiplyScalar( s );
  24098. }
  24099. return this;
  24100. }
  24101. lerp( sh, alpha ) {
  24102. for ( let i = 0; i < 9; i ++ ) {
  24103. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24104. }
  24105. return this;
  24106. }
  24107. equals( sh ) {
  24108. for ( let i = 0; i < 9; i ++ ) {
  24109. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24110. return false;
  24111. }
  24112. }
  24113. return true;
  24114. }
  24115. copy( sh ) {
  24116. return this.set( sh.coefficients );
  24117. }
  24118. clone() {
  24119. return new this.constructor().copy( this );
  24120. }
  24121. fromArray( array, offset = 0 ) {
  24122. const coefficients = this.coefficients;
  24123. for ( let i = 0; i < 9; i ++ ) {
  24124. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24125. }
  24126. return this;
  24127. }
  24128. toArray( array = [], offset = 0 ) {
  24129. const coefficients = this.coefficients;
  24130. for ( let i = 0; i < 9; i ++ ) {
  24131. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24132. }
  24133. return array;
  24134. }
  24135. // evaluate the basis functions
  24136. // shBasis is an Array[ 9 ]
  24137. static getBasisAt( normal, shBasis ) {
  24138. // normal is assumed to be unit length
  24139. const x = normal.x, y = normal.y, z = normal.z;
  24140. // band 0
  24141. shBasis[ 0 ] = 0.282095;
  24142. // band 1
  24143. shBasis[ 1 ] = 0.488603 * y;
  24144. shBasis[ 2 ] = 0.488603 * z;
  24145. shBasis[ 3 ] = 0.488603 * x;
  24146. // band 2
  24147. shBasis[ 4 ] = 1.092548 * x * y;
  24148. shBasis[ 5 ] = 1.092548 * y * z;
  24149. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24150. shBasis[ 7 ] = 1.092548 * x * z;
  24151. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24152. }
  24153. }
  24154. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  24155. class LightProbe extends Light {
  24156. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24157. super( undefined, intensity );
  24158. this.sh = sh;
  24159. }
  24160. copy( source ) {
  24161. super.copy( source );
  24162. this.sh.copy( source.sh );
  24163. return this;
  24164. }
  24165. fromJSON( json ) {
  24166. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24167. this.sh.fromArray( json.sh );
  24168. return this;
  24169. }
  24170. toJSON( meta ) {
  24171. const data = super.toJSON( meta );
  24172. data.object.sh = this.sh.toArray();
  24173. return data;
  24174. }
  24175. }
  24176. LightProbe.prototype.isLightProbe = true;
  24177. class MaterialLoader extends Loader {
  24178. constructor( manager ) {
  24179. super( manager );
  24180. this.textures = {};
  24181. }
  24182. load( url, onLoad, onProgress, onError ) {
  24183. const scope = this;
  24184. const loader = new FileLoader( scope.manager );
  24185. loader.setPath( scope.path );
  24186. loader.setRequestHeader( scope.requestHeader );
  24187. loader.setWithCredentials( scope.withCredentials );
  24188. loader.load( url, function ( text ) {
  24189. try {
  24190. onLoad( scope.parse( JSON.parse( text ) ) );
  24191. } catch ( e ) {
  24192. if ( onError ) {
  24193. onError( e );
  24194. } else {
  24195. console.error( e );
  24196. }
  24197. scope.manager.itemError( url );
  24198. }
  24199. }, onProgress, onError );
  24200. }
  24201. parse( json ) {
  24202. const textures = this.textures;
  24203. function getTexture( name ) {
  24204. if ( textures[ name ] === undefined ) {
  24205. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24206. }
  24207. return textures[ name ];
  24208. }
  24209. const material = Material.fromType( json.type );
  24210. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24211. if ( json.name !== undefined ) material.name = json.name;
  24212. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24213. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24214. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24215. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24216. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24217. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24218. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24219. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24220. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24221. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24222. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24223. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24224. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24225. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24226. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24227. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24228. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24229. if ( json.fog !== undefined ) material.fog = json.fog;
  24230. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24231. if ( json.blending !== undefined ) material.blending = json.blending;
  24232. if ( json.combine !== undefined ) material.combine = json.combine;
  24233. if ( json.side !== undefined ) material.side = json.side;
  24234. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24235. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24236. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24237. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24238. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24239. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24240. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24241. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24242. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24243. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24244. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24245. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24246. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24247. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24248. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24249. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24250. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24251. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24252. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24253. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24254. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24255. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24256. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24257. if ( json.scale !== undefined ) material.scale = json.scale;
  24258. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24259. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24260. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24261. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24262. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24263. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24264. if ( json.visible !== undefined ) material.visible = json.visible;
  24265. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24266. if ( json.userData !== undefined ) material.userData = json.userData;
  24267. if ( json.vertexColors !== undefined ) {
  24268. if ( typeof json.vertexColors === 'number' ) {
  24269. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24270. } else {
  24271. material.vertexColors = json.vertexColors;
  24272. }
  24273. }
  24274. // Shader Material
  24275. if ( json.uniforms !== undefined ) {
  24276. for ( const name in json.uniforms ) {
  24277. const uniform = json.uniforms[ name ];
  24278. material.uniforms[ name ] = {};
  24279. switch ( uniform.type ) {
  24280. case 't':
  24281. material.uniforms[ name ].value = getTexture( uniform.value );
  24282. break;
  24283. case 'c':
  24284. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24285. break;
  24286. case 'v2':
  24287. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24288. break;
  24289. case 'v3':
  24290. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24291. break;
  24292. case 'v4':
  24293. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24294. break;
  24295. case 'm3':
  24296. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24297. break;
  24298. case 'm4':
  24299. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24300. break;
  24301. default:
  24302. material.uniforms[ name ].value = uniform.value;
  24303. }
  24304. }
  24305. }
  24306. if ( json.defines !== undefined ) material.defines = json.defines;
  24307. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24308. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24309. if ( json.extensions !== undefined ) {
  24310. for ( const key in json.extensions ) {
  24311. material.extensions[ key ] = json.extensions[ key ];
  24312. }
  24313. }
  24314. // Deprecated
  24315. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24316. // for PointsMaterial
  24317. if ( json.size !== undefined ) material.size = json.size;
  24318. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24319. // maps
  24320. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24321. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24322. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24323. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24324. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24325. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24326. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24327. if ( json.normalScale !== undefined ) {
  24328. let normalScale = json.normalScale;
  24329. if ( Array.isArray( normalScale ) === false ) {
  24330. // Blender exporter used to export a scalar. See #7459
  24331. normalScale = [ normalScale, normalScale ];
  24332. }
  24333. material.normalScale = new Vector2().fromArray( normalScale );
  24334. }
  24335. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24336. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24337. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24338. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24339. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24340. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24341. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24342. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24343. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24344. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24345. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24346. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24347. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24348. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24349. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24350. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24351. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24352. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24353. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24354. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24355. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24356. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24357. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24358. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24359. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24360. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24361. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24362. return material;
  24363. }
  24364. setTextures( value ) {
  24365. this.textures = value;
  24366. return this;
  24367. }
  24368. }
  24369. class LoaderUtils {
  24370. static decodeText( array ) {
  24371. if ( typeof TextDecoder !== 'undefined' ) {
  24372. return new TextDecoder().decode( array );
  24373. }
  24374. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24375. // throws a "maximum call stack size exceeded" error for large arrays.
  24376. let s = '';
  24377. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24378. // Implicitly assumes little-endian.
  24379. s += String.fromCharCode( array[ i ] );
  24380. }
  24381. try {
  24382. // merges multi-byte utf-8 characters.
  24383. return decodeURIComponent( escape( s ) );
  24384. } catch ( e ) { // see #16358
  24385. return s;
  24386. }
  24387. }
  24388. static extractUrlBase( url ) {
  24389. const index = url.lastIndexOf( '/' );
  24390. if ( index === - 1 ) return './';
  24391. return url.slice( 0, index + 1 );
  24392. }
  24393. static resolveURL( url, path ) {
  24394. // Invalid URL
  24395. if ( typeof url !== 'string' || url === '' ) return '';
  24396. // Host Relative URL
  24397. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24398. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24399. }
  24400. // Absolute URL http://,https://,//
  24401. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24402. // Data URI
  24403. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24404. // Blob URL
  24405. if ( /^blob:.*$/i.test( url ) ) return url;
  24406. // Relative URL
  24407. return path + url;
  24408. }
  24409. }
  24410. class InstancedBufferGeometry extends BufferGeometry {
  24411. constructor() {
  24412. super();
  24413. this.type = 'InstancedBufferGeometry';
  24414. this.instanceCount = Infinity;
  24415. }
  24416. copy( source ) {
  24417. super.copy( source );
  24418. this.instanceCount = source.instanceCount;
  24419. return this;
  24420. }
  24421. clone() {
  24422. return new this.constructor().copy( this );
  24423. }
  24424. toJSON() {
  24425. const data = super.toJSON( this );
  24426. data.instanceCount = this.instanceCount;
  24427. data.isInstancedBufferGeometry = true;
  24428. return data;
  24429. }
  24430. }
  24431. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24432. class BufferGeometryLoader extends Loader {
  24433. constructor( manager ) {
  24434. super( manager );
  24435. }
  24436. load( url, onLoad, onProgress, onError ) {
  24437. const scope = this;
  24438. const loader = new FileLoader( scope.manager );
  24439. loader.setPath( scope.path );
  24440. loader.setRequestHeader( scope.requestHeader );
  24441. loader.setWithCredentials( scope.withCredentials );
  24442. loader.load( url, function ( text ) {
  24443. try {
  24444. onLoad( scope.parse( JSON.parse( text ) ) );
  24445. } catch ( e ) {
  24446. if ( onError ) {
  24447. onError( e );
  24448. } else {
  24449. console.error( e );
  24450. }
  24451. scope.manager.itemError( url );
  24452. }
  24453. }, onProgress, onError );
  24454. }
  24455. parse( json ) {
  24456. const interleavedBufferMap = {};
  24457. const arrayBufferMap = {};
  24458. function getInterleavedBuffer( json, uuid ) {
  24459. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24460. const interleavedBuffers = json.interleavedBuffers;
  24461. const interleavedBuffer = interleavedBuffers[ uuid ];
  24462. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24463. const array = getTypedArray( interleavedBuffer.type, buffer );
  24464. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24465. ib.uuid = interleavedBuffer.uuid;
  24466. interleavedBufferMap[ uuid ] = ib;
  24467. return ib;
  24468. }
  24469. function getArrayBuffer( json, uuid ) {
  24470. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24471. const arrayBuffers = json.arrayBuffers;
  24472. const arrayBuffer = arrayBuffers[ uuid ];
  24473. const ab = new Uint32Array( arrayBuffer ).buffer;
  24474. arrayBufferMap[ uuid ] = ab;
  24475. return ab;
  24476. }
  24477. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24478. const index = json.data.index;
  24479. if ( index !== undefined ) {
  24480. const typedArray = getTypedArray( index.type, index.array );
  24481. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24482. }
  24483. const attributes = json.data.attributes;
  24484. for ( const key in attributes ) {
  24485. const attribute = attributes[ key ];
  24486. let bufferAttribute;
  24487. if ( attribute.isInterleavedBufferAttribute ) {
  24488. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24489. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24490. } else {
  24491. const typedArray = getTypedArray( attribute.type, attribute.array );
  24492. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24493. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24494. }
  24495. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24496. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24497. if ( attribute.updateRange !== undefined ) {
  24498. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24499. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24500. }
  24501. geometry.setAttribute( key, bufferAttribute );
  24502. }
  24503. const morphAttributes = json.data.morphAttributes;
  24504. if ( morphAttributes ) {
  24505. for ( const key in morphAttributes ) {
  24506. const attributeArray = morphAttributes[ key ];
  24507. const array = [];
  24508. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24509. const attribute = attributeArray[ i ];
  24510. let bufferAttribute;
  24511. if ( attribute.isInterleavedBufferAttribute ) {
  24512. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24513. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24514. } else {
  24515. const typedArray = getTypedArray( attribute.type, attribute.array );
  24516. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24517. }
  24518. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24519. array.push( bufferAttribute );
  24520. }
  24521. geometry.morphAttributes[ key ] = array;
  24522. }
  24523. }
  24524. const morphTargetsRelative = json.data.morphTargetsRelative;
  24525. if ( morphTargetsRelative ) {
  24526. geometry.morphTargetsRelative = true;
  24527. }
  24528. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24529. if ( groups !== undefined ) {
  24530. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24531. const group = groups[ i ];
  24532. geometry.addGroup( group.start, group.count, group.materialIndex );
  24533. }
  24534. }
  24535. const boundingSphere = json.data.boundingSphere;
  24536. if ( boundingSphere !== undefined ) {
  24537. const center = new Vector3();
  24538. if ( boundingSphere.center !== undefined ) {
  24539. center.fromArray( boundingSphere.center );
  24540. }
  24541. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24542. }
  24543. if ( json.name ) geometry.name = json.name;
  24544. if ( json.userData ) geometry.userData = json.userData;
  24545. return geometry;
  24546. }
  24547. }
  24548. class ObjectLoader extends Loader {
  24549. constructor( manager ) {
  24550. super( manager );
  24551. }
  24552. load( url, onLoad, onProgress, onError ) {
  24553. const scope = this;
  24554. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24555. this.resourcePath = this.resourcePath || path;
  24556. const loader = new FileLoader( this.manager );
  24557. loader.setPath( this.path );
  24558. loader.setRequestHeader( this.requestHeader );
  24559. loader.setWithCredentials( this.withCredentials );
  24560. loader.load( url, function ( text ) {
  24561. let json = null;
  24562. try {
  24563. json = JSON.parse( text );
  24564. } catch ( error ) {
  24565. if ( onError !== undefined ) onError( error );
  24566. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24567. return;
  24568. }
  24569. const metadata = json.metadata;
  24570. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24571. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24572. return;
  24573. }
  24574. scope.parse( json, onLoad );
  24575. }, onProgress, onError );
  24576. }
  24577. async loadAsync( url, onProgress ) {
  24578. const scope = this;
  24579. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24580. this.resourcePath = this.resourcePath || path;
  24581. const loader = new FileLoader( this.manager );
  24582. loader.setPath( this.path );
  24583. loader.setRequestHeader( this.requestHeader );
  24584. loader.setWithCredentials( this.withCredentials );
  24585. const text = await loader.loadAsync( url, onProgress );
  24586. const json = JSON.parse( text );
  24587. const metadata = json.metadata;
  24588. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24589. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24590. }
  24591. return await scope.parseAsync( json );
  24592. }
  24593. parse( json, onLoad ) {
  24594. const animations = this.parseAnimations( json.animations );
  24595. const shapes = this.parseShapes( json.shapes );
  24596. const geometries = this.parseGeometries( json.geometries, shapes );
  24597. const images = this.parseImages( json.images, function () {
  24598. if ( onLoad !== undefined ) onLoad( object );
  24599. } );
  24600. const textures = this.parseTextures( json.textures, images );
  24601. const materials = this.parseMaterials( json.materials, textures );
  24602. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24603. const skeletons = this.parseSkeletons( json.skeletons, object );
  24604. this.bindSkeletons( object, skeletons );
  24605. //
  24606. if ( onLoad !== undefined ) {
  24607. let hasImages = false;
  24608. for ( const uuid in images ) {
  24609. if ( images[ uuid ] instanceof HTMLImageElement ) {
  24610. hasImages = true;
  24611. break;
  24612. }
  24613. }
  24614. if ( hasImages === false ) onLoad( object );
  24615. }
  24616. return object;
  24617. }
  24618. async parseAsync( json ) {
  24619. const animations = this.parseAnimations( json.animations );
  24620. const shapes = this.parseShapes( json.shapes );
  24621. const geometries = this.parseGeometries( json.geometries, shapes );
  24622. const images = await this.parseImagesAsync( json.images );
  24623. const textures = this.parseTextures( json.textures, images );
  24624. const materials = this.parseMaterials( json.materials, textures );
  24625. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24626. const skeletons = this.parseSkeletons( json.skeletons, object );
  24627. this.bindSkeletons( object, skeletons );
  24628. return object;
  24629. }
  24630. parseShapes( json ) {
  24631. const shapes = {};
  24632. if ( json !== undefined ) {
  24633. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24634. const shape = new Shape().fromJSON( json[ i ] );
  24635. shapes[ shape.uuid ] = shape;
  24636. }
  24637. }
  24638. return shapes;
  24639. }
  24640. parseSkeletons( json, object ) {
  24641. const skeletons = {};
  24642. const bones = {};
  24643. // generate bone lookup table
  24644. object.traverse( function ( child ) {
  24645. if ( child.isBone ) bones[ child.uuid ] = child;
  24646. } );
  24647. // create skeletons
  24648. if ( json !== undefined ) {
  24649. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24650. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24651. skeletons[ skeleton.uuid ] = skeleton;
  24652. }
  24653. }
  24654. return skeletons;
  24655. }
  24656. parseGeometries( json, shapes ) {
  24657. const geometries = {};
  24658. if ( json !== undefined ) {
  24659. const bufferGeometryLoader = new BufferGeometryLoader();
  24660. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24661. let geometry;
  24662. const data = json[ i ];
  24663. switch ( data.type ) {
  24664. case 'BufferGeometry':
  24665. case 'InstancedBufferGeometry':
  24666. geometry = bufferGeometryLoader.parse( data );
  24667. break;
  24668. case 'Geometry':
  24669. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  24670. break;
  24671. default:
  24672. if ( data.type in Geometries ) {
  24673. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24674. } else {
  24675. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24676. }
  24677. }
  24678. geometry.uuid = data.uuid;
  24679. if ( data.name !== undefined ) geometry.name = data.name;
  24680. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24681. geometries[ data.uuid ] = geometry;
  24682. }
  24683. }
  24684. return geometries;
  24685. }
  24686. parseMaterials( json, textures ) {
  24687. const cache = {}; // MultiMaterial
  24688. const materials = {};
  24689. if ( json !== undefined ) {
  24690. const loader = new MaterialLoader();
  24691. loader.setTextures( textures );
  24692. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24693. const data = json[ i ];
  24694. if ( data.type === 'MultiMaterial' ) {
  24695. // Deprecated
  24696. const array = [];
  24697. for ( let j = 0; j < data.materials.length; j ++ ) {
  24698. const material = data.materials[ j ];
  24699. if ( cache[ material.uuid ] === undefined ) {
  24700. cache[ material.uuid ] = loader.parse( material );
  24701. }
  24702. array.push( cache[ material.uuid ] );
  24703. }
  24704. materials[ data.uuid ] = array;
  24705. } else {
  24706. if ( cache[ data.uuid ] === undefined ) {
  24707. cache[ data.uuid ] = loader.parse( data );
  24708. }
  24709. materials[ data.uuid ] = cache[ data.uuid ];
  24710. }
  24711. }
  24712. }
  24713. return materials;
  24714. }
  24715. parseAnimations( json ) {
  24716. const animations = {};
  24717. if ( json !== undefined ) {
  24718. for ( let i = 0; i < json.length; i ++ ) {
  24719. const data = json[ i ];
  24720. const clip = AnimationClip.parse( data );
  24721. animations[ clip.uuid ] = clip;
  24722. }
  24723. }
  24724. return animations;
  24725. }
  24726. parseImages( json, onLoad ) {
  24727. const scope = this;
  24728. const images = {};
  24729. let loader;
  24730. function loadImage( url ) {
  24731. scope.manager.itemStart( url );
  24732. return loader.load( url, function () {
  24733. scope.manager.itemEnd( url );
  24734. }, undefined, function () {
  24735. scope.manager.itemError( url );
  24736. scope.manager.itemEnd( url );
  24737. } );
  24738. }
  24739. function deserializeImage( image ) {
  24740. if ( typeof image === 'string' ) {
  24741. const url = image;
  24742. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24743. return loadImage( path );
  24744. } else {
  24745. if ( image.data ) {
  24746. return {
  24747. data: getTypedArray( image.type, image.data ),
  24748. width: image.width,
  24749. height: image.height
  24750. };
  24751. } else {
  24752. return null;
  24753. }
  24754. }
  24755. }
  24756. if ( json !== undefined && json.length > 0 ) {
  24757. const manager = new LoadingManager( onLoad );
  24758. loader = new ImageLoader( manager );
  24759. loader.setCrossOrigin( this.crossOrigin );
  24760. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24761. const image = json[ i ];
  24762. const url = image.url;
  24763. if ( Array.isArray( url ) ) {
  24764. // load array of images e.g CubeTexture
  24765. const imageArray = [];
  24766. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24767. const currentUrl = url[ j ];
  24768. const deserializedImage = deserializeImage( currentUrl );
  24769. if ( deserializedImage !== null ) {
  24770. if ( deserializedImage instanceof HTMLImageElement ) {
  24771. imageArray.push( deserializedImage );
  24772. } else {
  24773. // special case: handle array of data textures for cube textures
  24774. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24775. }
  24776. }
  24777. }
  24778. images[ image.uuid ] = new Source( imageArray );
  24779. } else {
  24780. // load single image
  24781. const deserializedImage = deserializeImage( image.url );
  24782. images[ image.uuid ] = new Source( deserializedImage );
  24783. }
  24784. }
  24785. }
  24786. return images;
  24787. }
  24788. async parseImagesAsync( json ) {
  24789. const scope = this;
  24790. const images = {};
  24791. let loader;
  24792. async function deserializeImage( image ) {
  24793. if ( typeof image === 'string' ) {
  24794. const url = image;
  24795. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24796. return await loader.loadAsync( path );
  24797. } else {
  24798. if ( image.data ) {
  24799. return {
  24800. data: getTypedArray( image.type, image.data ),
  24801. width: image.width,
  24802. height: image.height
  24803. };
  24804. } else {
  24805. return null;
  24806. }
  24807. }
  24808. }
  24809. if ( json !== undefined && json.length > 0 ) {
  24810. loader = new ImageLoader( this.manager );
  24811. loader.setCrossOrigin( this.crossOrigin );
  24812. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24813. const image = json[ i ];
  24814. const url = image.url;
  24815. if ( Array.isArray( url ) ) {
  24816. // load array of images e.g CubeTexture
  24817. const imageArray = [];
  24818. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24819. const currentUrl = url[ j ];
  24820. const deserializedImage = await deserializeImage( currentUrl );
  24821. if ( deserializedImage !== null ) {
  24822. if ( deserializedImage instanceof HTMLImageElement ) {
  24823. imageArray.push( deserializedImage );
  24824. } else {
  24825. // special case: handle array of data textures for cube textures
  24826. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24827. }
  24828. }
  24829. }
  24830. images[ image.uuid ] = new Source( imageArray );
  24831. } else {
  24832. // load single image
  24833. const deserializedImage = await deserializeImage( image.url );
  24834. images[ image.uuid ] = new Source( deserializedImage );
  24835. }
  24836. }
  24837. }
  24838. return images;
  24839. }
  24840. parseTextures( json, images ) {
  24841. function parseConstant( value, type ) {
  24842. if ( typeof value === 'number' ) return value;
  24843. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24844. return type[ value ];
  24845. }
  24846. const textures = {};
  24847. if ( json !== undefined ) {
  24848. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24849. const data = json[ i ];
  24850. if ( data.image === undefined ) {
  24851. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24852. }
  24853. if ( images[ data.image ] === undefined ) {
  24854. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24855. }
  24856. const source = images[ data.image ];
  24857. const image = source.data;
  24858. let texture;
  24859. if ( Array.isArray( image ) ) {
  24860. texture = new CubeTexture();
  24861. if ( image.length === 6 ) texture.needsUpdate = true;
  24862. } else {
  24863. if ( image && image.data ) {
  24864. texture = new DataTexture();
  24865. } else {
  24866. texture = new Texture();
  24867. }
  24868. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24869. }
  24870. texture.source = source;
  24871. texture.uuid = data.uuid;
  24872. if ( data.name !== undefined ) texture.name = data.name;
  24873. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24874. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24875. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24876. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24877. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24878. if ( data.wrap !== undefined ) {
  24879. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24880. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24881. }
  24882. if ( data.format !== undefined ) texture.format = data.format;
  24883. if ( data.type !== undefined ) texture.type = data.type;
  24884. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  24885. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24886. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24887. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24888. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24889. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24890. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24891. if ( data.userData !== undefined ) texture.userData = data.userData;
  24892. textures[ data.uuid ] = texture;
  24893. }
  24894. }
  24895. return textures;
  24896. }
  24897. parseObject( data, geometries, materials, textures, animations ) {
  24898. let object;
  24899. function getGeometry( name ) {
  24900. if ( geometries[ name ] === undefined ) {
  24901. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24902. }
  24903. return geometries[ name ];
  24904. }
  24905. function getMaterial( name ) {
  24906. if ( name === undefined ) return undefined;
  24907. if ( Array.isArray( name ) ) {
  24908. const array = [];
  24909. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24910. const uuid = name[ i ];
  24911. if ( materials[ uuid ] === undefined ) {
  24912. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24913. }
  24914. array.push( materials[ uuid ] );
  24915. }
  24916. return array;
  24917. }
  24918. if ( materials[ name ] === undefined ) {
  24919. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24920. }
  24921. return materials[ name ];
  24922. }
  24923. function getTexture( uuid ) {
  24924. if ( textures[ uuid ] === undefined ) {
  24925. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  24926. }
  24927. return textures[ uuid ];
  24928. }
  24929. let geometry, material;
  24930. switch ( data.type ) {
  24931. case 'Scene':
  24932. object = new Scene();
  24933. if ( data.background !== undefined ) {
  24934. if ( Number.isInteger( data.background ) ) {
  24935. object.background = new Color( data.background );
  24936. } else {
  24937. object.background = getTexture( data.background );
  24938. }
  24939. }
  24940. if ( data.environment !== undefined ) {
  24941. object.environment = getTexture( data.environment );
  24942. }
  24943. if ( data.fog !== undefined ) {
  24944. if ( data.fog.type === 'Fog' ) {
  24945. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24946. } else if ( data.fog.type === 'FogExp2' ) {
  24947. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24948. }
  24949. }
  24950. break;
  24951. case 'PerspectiveCamera':
  24952. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24953. if ( data.focus !== undefined ) object.focus = data.focus;
  24954. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24955. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24956. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24957. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24958. break;
  24959. case 'OrthographicCamera':
  24960. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24961. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24962. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24963. break;
  24964. case 'AmbientLight':
  24965. object = new AmbientLight( data.color, data.intensity );
  24966. break;
  24967. case 'DirectionalLight':
  24968. object = new DirectionalLight( data.color, data.intensity );
  24969. break;
  24970. case 'PointLight':
  24971. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24972. break;
  24973. case 'RectAreaLight':
  24974. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24975. break;
  24976. case 'SpotLight':
  24977. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24978. break;
  24979. case 'HemisphereLight':
  24980. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24981. break;
  24982. case 'LightProbe':
  24983. object = new LightProbe().fromJSON( data );
  24984. break;
  24985. case 'SkinnedMesh':
  24986. geometry = getGeometry( data.geometry );
  24987. material = getMaterial( data.material );
  24988. object = new SkinnedMesh( geometry, material );
  24989. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24990. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24991. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24992. break;
  24993. case 'Mesh':
  24994. geometry = getGeometry( data.geometry );
  24995. material = getMaterial( data.material );
  24996. object = new Mesh( geometry, material );
  24997. break;
  24998. case 'InstancedMesh':
  24999. geometry = getGeometry( data.geometry );
  25000. material = getMaterial( data.material );
  25001. const count = data.count;
  25002. const instanceMatrix = data.instanceMatrix;
  25003. const instanceColor = data.instanceColor;
  25004. object = new InstancedMesh( geometry, material, count );
  25005. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25006. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25007. break;
  25008. case 'LOD':
  25009. object = new LOD();
  25010. break;
  25011. case 'Line':
  25012. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25013. break;
  25014. case 'LineLoop':
  25015. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25016. break;
  25017. case 'LineSegments':
  25018. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25019. break;
  25020. case 'PointCloud':
  25021. case 'Points':
  25022. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25023. break;
  25024. case 'Sprite':
  25025. object = new Sprite( getMaterial( data.material ) );
  25026. break;
  25027. case 'Group':
  25028. object = new Group();
  25029. break;
  25030. case 'Bone':
  25031. object = new Bone();
  25032. break;
  25033. default:
  25034. object = new Object3D();
  25035. }
  25036. object.uuid = data.uuid;
  25037. if ( data.name !== undefined ) object.name = data.name;
  25038. if ( data.matrix !== undefined ) {
  25039. object.matrix.fromArray( data.matrix );
  25040. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25041. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25042. } else {
  25043. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25044. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25045. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25046. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25047. }
  25048. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25049. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25050. if ( data.shadow ) {
  25051. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25052. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25053. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25054. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25055. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25056. }
  25057. if ( data.visible !== undefined ) object.visible = data.visible;
  25058. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25059. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25060. if ( data.userData !== undefined ) object.userData = data.userData;
  25061. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25062. if ( data.children !== undefined ) {
  25063. const children = data.children;
  25064. for ( let i = 0; i < children.length; i ++ ) {
  25065. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25066. }
  25067. }
  25068. if ( data.animations !== undefined ) {
  25069. const objectAnimations = data.animations;
  25070. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25071. const uuid = objectAnimations[ i ];
  25072. object.animations.push( animations[ uuid ] );
  25073. }
  25074. }
  25075. if ( data.type === 'LOD' ) {
  25076. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25077. const levels = data.levels;
  25078. for ( let l = 0; l < levels.length; l ++ ) {
  25079. const level = levels[ l ];
  25080. const child = object.getObjectByProperty( 'uuid', level.object );
  25081. if ( child !== undefined ) {
  25082. object.addLevel( child, level.distance );
  25083. }
  25084. }
  25085. }
  25086. return object;
  25087. }
  25088. bindSkeletons( object, skeletons ) {
  25089. if ( Object.keys( skeletons ).length === 0 ) return;
  25090. object.traverse( function ( child ) {
  25091. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25092. const skeleton = skeletons[ child.skeleton ];
  25093. if ( skeleton === undefined ) {
  25094. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25095. } else {
  25096. child.bind( skeleton, child.bindMatrix );
  25097. }
  25098. }
  25099. } );
  25100. }
  25101. /* DEPRECATED */
  25102. setTexturePath( value ) {
  25103. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  25104. return this.setResourcePath( value );
  25105. }
  25106. }
  25107. const TEXTURE_MAPPING = {
  25108. UVMapping: UVMapping,
  25109. CubeReflectionMapping: CubeReflectionMapping,
  25110. CubeRefractionMapping: CubeRefractionMapping,
  25111. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25112. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25113. CubeUVReflectionMapping: CubeUVReflectionMapping
  25114. };
  25115. const TEXTURE_WRAPPING = {
  25116. RepeatWrapping: RepeatWrapping,
  25117. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25118. MirroredRepeatWrapping: MirroredRepeatWrapping
  25119. };
  25120. const TEXTURE_FILTER = {
  25121. NearestFilter: NearestFilter,
  25122. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25123. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25124. LinearFilter: LinearFilter,
  25125. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25126. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25127. };
  25128. class ImageBitmapLoader extends Loader {
  25129. constructor( manager ) {
  25130. super( manager );
  25131. if ( typeof createImageBitmap === 'undefined' ) {
  25132. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25133. }
  25134. if ( typeof fetch === 'undefined' ) {
  25135. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25136. }
  25137. this.options = { premultiplyAlpha: 'none' };
  25138. }
  25139. setOptions( options ) {
  25140. this.options = options;
  25141. return this;
  25142. }
  25143. load( url, onLoad, onProgress, onError ) {
  25144. if ( url === undefined ) url = '';
  25145. if ( this.path !== undefined ) url = this.path + url;
  25146. url = this.manager.resolveURL( url );
  25147. const scope = this;
  25148. const cached = Cache.get( url );
  25149. if ( cached !== undefined ) {
  25150. scope.manager.itemStart( url );
  25151. setTimeout( function () {
  25152. if ( onLoad ) onLoad( cached );
  25153. scope.manager.itemEnd( url );
  25154. }, 0 );
  25155. return cached;
  25156. }
  25157. const fetchOptions = {};
  25158. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25159. fetchOptions.headers = this.requestHeader;
  25160. fetch( url, fetchOptions ).then( function ( res ) {
  25161. return res.blob();
  25162. } ).then( function ( blob ) {
  25163. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25164. } ).then( function ( imageBitmap ) {
  25165. Cache.add( url, imageBitmap );
  25166. if ( onLoad ) onLoad( imageBitmap );
  25167. scope.manager.itemEnd( url );
  25168. } ).catch( function ( e ) {
  25169. if ( onError ) onError( e );
  25170. scope.manager.itemError( url );
  25171. scope.manager.itemEnd( url );
  25172. } );
  25173. scope.manager.itemStart( url );
  25174. }
  25175. }
  25176. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  25177. let _context;
  25178. const AudioContext = {
  25179. getContext: function () {
  25180. if ( _context === undefined ) {
  25181. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25182. }
  25183. return _context;
  25184. },
  25185. setContext: function ( value ) {
  25186. _context = value;
  25187. }
  25188. };
  25189. class AudioLoader extends Loader {
  25190. constructor( manager ) {
  25191. super( manager );
  25192. }
  25193. load( url, onLoad, onProgress, onError ) {
  25194. const scope = this;
  25195. const loader = new FileLoader( this.manager );
  25196. loader.setResponseType( 'arraybuffer' );
  25197. loader.setPath( this.path );
  25198. loader.setRequestHeader( this.requestHeader );
  25199. loader.setWithCredentials( this.withCredentials );
  25200. loader.load( url, function ( buffer ) {
  25201. try {
  25202. // Create a copy of the buffer. The `decodeAudioData` method
  25203. // detaches the buffer when complete, preventing reuse.
  25204. const bufferCopy = buffer.slice( 0 );
  25205. const context = AudioContext.getContext();
  25206. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25207. onLoad( audioBuffer );
  25208. } );
  25209. } catch ( e ) {
  25210. if ( onError ) {
  25211. onError( e );
  25212. } else {
  25213. console.error( e );
  25214. }
  25215. scope.manager.itemError( url );
  25216. }
  25217. }, onProgress, onError );
  25218. }
  25219. }
  25220. class HemisphereLightProbe extends LightProbe {
  25221. constructor( skyColor, groundColor, intensity = 1 ) {
  25222. super( undefined, intensity );
  25223. const color1 = new Color().set( skyColor );
  25224. const color2 = new Color().set( groundColor );
  25225. const sky = new Vector3( color1.r, color1.g, color1.b );
  25226. const ground = new Vector3( color2.r, color2.g, color2.b );
  25227. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25228. const c0 = Math.sqrt( Math.PI );
  25229. const c1 = c0 * Math.sqrt( 0.75 );
  25230. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25231. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25232. }
  25233. }
  25234. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  25235. class AmbientLightProbe extends LightProbe {
  25236. constructor( color, intensity = 1 ) {
  25237. super( undefined, intensity );
  25238. const color1 = new Color().set( color );
  25239. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25240. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25241. }
  25242. }
  25243. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  25244. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25245. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25246. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25247. class StereoCamera {
  25248. constructor() {
  25249. this.type = 'StereoCamera';
  25250. this.aspect = 1;
  25251. this.eyeSep = 0.064;
  25252. this.cameraL = new PerspectiveCamera();
  25253. this.cameraL.layers.enable( 1 );
  25254. this.cameraL.matrixAutoUpdate = false;
  25255. this.cameraR = new PerspectiveCamera();
  25256. this.cameraR.layers.enable( 2 );
  25257. this.cameraR.matrixAutoUpdate = false;
  25258. this._cache = {
  25259. focus: null,
  25260. fov: null,
  25261. aspect: null,
  25262. near: null,
  25263. far: null,
  25264. zoom: null,
  25265. eyeSep: null
  25266. };
  25267. }
  25268. update( camera ) {
  25269. const cache = this._cache;
  25270. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25271. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25272. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25273. if ( needsUpdate ) {
  25274. cache.focus = camera.focus;
  25275. cache.fov = camera.fov;
  25276. cache.aspect = camera.aspect * this.aspect;
  25277. cache.near = camera.near;
  25278. cache.far = camera.far;
  25279. cache.zoom = camera.zoom;
  25280. cache.eyeSep = this.eyeSep;
  25281. // Off-axis stereoscopic effect based on
  25282. // http://paulbourke.net/stereographics/stereorender/
  25283. _projectionMatrix.copy( camera.projectionMatrix );
  25284. const eyeSepHalf = cache.eyeSep / 2;
  25285. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25286. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25287. let xmin, xmax;
  25288. // translate xOffset
  25289. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25290. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25291. // for left eye
  25292. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25293. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25294. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25295. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25296. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25297. // for right eye
  25298. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25299. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25300. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25301. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25302. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25303. }
  25304. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25305. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25306. }
  25307. }
  25308. class Clock {
  25309. constructor( autoStart = true ) {
  25310. this.autoStart = autoStart;
  25311. this.startTime = 0;
  25312. this.oldTime = 0;
  25313. this.elapsedTime = 0;
  25314. this.running = false;
  25315. }
  25316. start() {
  25317. this.startTime = now();
  25318. this.oldTime = this.startTime;
  25319. this.elapsedTime = 0;
  25320. this.running = true;
  25321. }
  25322. stop() {
  25323. this.getElapsedTime();
  25324. this.running = false;
  25325. this.autoStart = false;
  25326. }
  25327. getElapsedTime() {
  25328. this.getDelta();
  25329. return this.elapsedTime;
  25330. }
  25331. getDelta() {
  25332. let diff = 0;
  25333. if ( this.autoStart && ! this.running ) {
  25334. this.start();
  25335. return 0;
  25336. }
  25337. if ( this.running ) {
  25338. const newTime = now();
  25339. diff = ( newTime - this.oldTime ) / 1000;
  25340. this.oldTime = newTime;
  25341. this.elapsedTime += diff;
  25342. }
  25343. return diff;
  25344. }
  25345. }
  25346. function now() {
  25347. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25348. }
  25349. const _position$1 = /*@__PURE__*/ new Vector3();
  25350. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25351. const _scale$1 = /*@__PURE__*/ new Vector3();
  25352. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25353. class AudioListener extends Object3D {
  25354. constructor() {
  25355. super();
  25356. this.type = 'AudioListener';
  25357. this.context = AudioContext.getContext();
  25358. this.gain = this.context.createGain();
  25359. this.gain.connect( this.context.destination );
  25360. this.filter = null;
  25361. this.timeDelta = 0;
  25362. // private
  25363. this._clock = new Clock();
  25364. }
  25365. getInput() {
  25366. return this.gain;
  25367. }
  25368. removeFilter() {
  25369. if ( this.filter !== null ) {
  25370. this.gain.disconnect( this.filter );
  25371. this.filter.disconnect( this.context.destination );
  25372. this.gain.connect( this.context.destination );
  25373. this.filter = null;
  25374. }
  25375. return this;
  25376. }
  25377. getFilter() {
  25378. return this.filter;
  25379. }
  25380. setFilter( value ) {
  25381. if ( this.filter !== null ) {
  25382. this.gain.disconnect( this.filter );
  25383. this.filter.disconnect( this.context.destination );
  25384. } else {
  25385. this.gain.disconnect( this.context.destination );
  25386. }
  25387. this.filter = value;
  25388. this.gain.connect( this.filter );
  25389. this.filter.connect( this.context.destination );
  25390. return this;
  25391. }
  25392. getMasterVolume() {
  25393. return this.gain.gain.value;
  25394. }
  25395. setMasterVolume( value ) {
  25396. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25397. return this;
  25398. }
  25399. updateMatrixWorld( force ) {
  25400. super.updateMatrixWorld( force );
  25401. const listener = this.context.listener;
  25402. const up = this.up;
  25403. this.timeDelta = this._clock.getDelta();
  25404. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25405. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25406. if ( listener.positionX ) {
  25407. // code path for Chrome (see #14393)
  25408. const endTime = this.context.currentTime + this.timeDelta;
  25409. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25410. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25411. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25412. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25413. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25414. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25415. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25416. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25417. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25418. } else {
  25419. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25420. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25421. }
  25422. }
  25423. }
  25424. class Audio extends Object3D {
  25425. constructor( listener ) {
  25426. super();
  25427. this.type = 'Audio';
  25428. this.listener = listener;
  25429. this.context = listener.context;
  25430. this.gain = this.context.createGain();
  25431. this.gain.connect( listener.getInput() );
  25432. this.autoplay = false;
  25433. this.buffer = null;
  25434. this.detune = 0;
  25435. this.loop = false;
  25436. this.loopStart = 0;
  25437. this.loopEnd = 0;
  25438. this.offset = 0;
  25439. this.duration = undefined;
  25440. this.playbackRate = 1;
  25441. this.isPlaying = false;
  25442. this.hasPlaybackControl = true;
  25443. this.source = null;
  25444. this.sourceType = 'empty';
  25445. this._startedAt = 0;
  25446. this._progress = 0;
  25447. this._connected = false;
  25448. this.filters = [];
  25449. }
  25450. getOutput() {
  25451. return this.gain;
  25452. }
  25453. setNodeSource( audioNode ) {
  25454. this.hasPlaybackControl = false;
  25455. this.sourceType = 'audioNode';
  25456. this.source = audioNode;
  25457. this.connect();
  25458. return this;
  25459. }
  25460. setMediaElementSource( mediaElement ) {
  25461. this.hasPlaybackControl = false;
  25462. this.sourceType = 'mediaNode';
  25463. this.source = this.context.createMediaElementSource( mediaElement );
  25464. this.connect();
  25465. return this;
  25466. }
  25467. setMediaStreamSource( mediaStream ) {
  25468. this.hasPlaybackControl = false;
  25469. this.sourceType = 'mediaStreamNode';
  25470. this.source = this.context.createMediaStreamSource( mediaStream );
  25471. this.connect();
  25472. return this;
  25473. }
  25474. setBuffer( audioBuffer ) {
  25475. this.buffer = audioBuffer;
  25476. this.sourceType = 'buffer';
  25477. if ( this.autoplay ) this.play();
  25478. return this;
  25479. }
  25480. play( delay = 0 ) {
  25481. if ( this.isPlaying === true ) {
  25482. console.warn( 'THREE.Audio: Audio is already playing.' );
  25483. return;
  25484. }
  25485. if ( this.hasPlaybackControl === false ) {
  25486. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25487. return;
  25488. }
  25489. this._startedAt = this.context.currentTime + delay;
  25490. const source = this.context.createBufferSource();
  25491. source.buffer = this.buffer;
  25492. source.loop = this.loop;
  25493. source.loopStart = this.loopStart;
  25494. source.loopEnd = this.loopEnd;
  25495. source.onended = this.onEnded.bind( this );
  25496. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25497. this.isPlaying = true;
  25498. this.source = source;
  25499. this.setDetune( this.detune );
  25500. this.setPlaybackRate( this.playbackRate );
  25501. return this.connect();
  25502. }
  25503. pause() {
  25504. if ( this.hasPlaybackControl === false ) {
  25505. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25506. return;
  25507. }
  25508. if ( this.isPlaying === true ) {
  25509. // update current progress
  25510. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25511. if ( this.loop === true ) {
  25512. // ensure _progress does not exceed duration with looped audios
  25513. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25514. }
  25515. this.source.stop();
  25516. this.source.onended = null;
  25517. this.isPlaying = false;
  25518. }
  25519. return this;
  25520. }
  25521. stop() {
  25522. if ( this.hasPlaybackControl === false ) {
  25523. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25524. return;
  25525. }
  25526. this._progress = 0;
  25527. this.source.stop();
  25528. this.source.onended = null;
  25529. this.isPlaying = false;
  25530. return this;
  25531. }
  25532. connect() {
  25533. if ( this.filters.length > 0 ) {
  25534. this.source.connect( this.filters[ 0 ] );
  25535. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25536. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25537. }
  25538. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25539. } else {
  25540. this.source.connect( this.getOutput() );
  25541. }
  25542. this._connected = true;
  25543. return this;
  25544. }
  25545. disconnect() {
  25546. if ( this.filters.length > 0 ) {
  25547. this.source.disconnect( this.filters[ 0 ] );
  25548. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25549. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25550. }
  25551. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25552. } else {
  25553. this.source.disconnect( this.getOutput() );
  25554. }
  25555. this._connected = false;
  25556. return this;
  25557. }
  25558. getFilters() {
  25559. return this.filters;
  25560. }
  25561. setFilters( value ) {
  25562. if ( ! value ) value = [];
  25563. if ( this._connected === true ) {
  25564. this.disconnect();
  25565. this.filters = value.slice();
  25566. this.connect();
  25567. } else {
  25568. this.filters = value.slice();
  25569. }
  25570. return this;
  25571. }
  25572. setDetune( value ) {
  25573. this.detune = value;
  25574. if ( this.source.detune === undefined ) return; // only set detune when available
  25575. if ( this.isPlaying === true ) {
  25576. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25577. }
  25578. return this;
  25579. }
  25580. getDetune() {
  25581. return this.detune;
  25582. }
  25583. getFilter() {
  25584. return this.getFilters()[ 0 ];
  25585. }
  25586. setFilter( filter ) {
  25587. return this.setFilters( filter ? [ filter ] : [] );
  25588. }
  25589. setPlaybackRate( value ) {
  25590. if ( this.hasPlaybackControl === false ) {
  25591. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25592. return;
  25593. }
  25594. this.playbackRate = value;
  25595. if ( this.isPlaying === true ) {
  25596. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25597. }
  25598. return this;
  25599. }
  25600. getPlaybackRate() {
  25601. return this.playbackRate;
  25602. }
  25603. onEnded() {
  25604. this.isPlaying = false;
  25605. }
  25606. getLoop() {
  25607. if ( this.hasPlaybackControl === false ) {
  25608. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25609. return false;
  25610. }
  25611. return this.loop;
  25612. }
  25613. setLoop( value ) {
  25614. if ( this.hasPlaybackControl === false ) {
  25615. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25616. return;
  25617. }
  25618. this.loop = value;
  25619. if ( this.isPlaying === true ) {
  25620. this.source.loop = this.loop;
  25621. }
  25622. return this;
  25623. }
  25624. setLoopStart( value ) {
  25625. this.loopStart = value;
  25626. return this;
  25627. }
  25628. setLoopEnd( value ) {
  25629. this.loopEnd = value;
  25630. return this;
  25631. }
  25632. getVolume() {
  25633. return this.gain.gain.value;
  25634. }
  25635. setVolume( value ) {
  25636. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25637. return this;
  25638. }
  25639. }
  25640. const _position = /*@__PURE__*/ new Vector3();
  25641. const _quaternion = /*@__PURE__*/ new Quaternion();
  25642. const _scale = /*@__PURE__*/ new Vector3();
  25643. const _orientation = /*@__PURE__*/ new Vector3();
  25644. class PositionalAudio extends Audio {
  25645. constructor( listener ) {
  25646. super( listener );
  25647. this.panner = this.context.createPanner();
  25648. this.panner.panningModel = 'HRTF';
  25649. this.panner.connect( this.gain );
  25650. }
  25651. disconnect() {
  25652. super.disconnect();
  25653. this.panner.disconnect( this.gain );
  25654. }
  25655. getOutput() {
  25656. return this.panner;
  25657. }
  25658. getRefDistance() {
  25659. return this.panner.refDistance;
  25660. }
  25661. setRefDistance( value ) {
  25662. this.panner.refDistance = value;
  25663. return this;
  25664. }
  25665. getRolloffFactor() {
  25666. return this.panner.rolloffFactor;
  25667. }
  25668. setRolloffFactor( value ) {
  25669. this.panner.rolloffFactor = value;
  25670. return this;
  25671. }
  25672. getDistanceModel() {
  25673. return this.panner.distanceModel;
  25674. }
  25675. setDistanceModel( value ) {
  25676. this.panner.distanceModel = value;
  25677. return this;
  25678. }
  25679. getMaxDistance() {
  25680. return this.panner.maxDistance;
  25681. }
  25682. setMaxDistance( value ) {
  25683. this.panner.maxDistance = value;
  25684. return this;
  25685. }
  25686. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25687. this.panner.coneInnerAngle = coneInnerAngle;
  25688. this.panner.coneOuterAngle = coneOuterAngle;
  25689. this.panner.coneOuterGain = coneOuterGain;
  25690. return this;
  25691. }
  25692. updateMatrixWorld( force ) {
  25693. super.updateMatrixWorld( force );
  25694. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25695. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25696. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25697. const panner = this.panner;
  25698. if ( panner.positionX ) {
  25699. // code path for Chrome and Firefox (see #14393)
  25700. const endTime = this.context.currentTime + this.listener.timeDelta;
  25701. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25702. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25703. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25704. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25705. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25706. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25707. } else {
  25708. panner.setPosition( _position.x, _position.y, _position.z );
  25709. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25710. }
  25711. }
  25712. }
  25713. class AudioAnalyser {
  25714. constructor( audio, fftSize = 2048 ) {
  25715. this.analyser = audio.context.createAnalyser();
  25716. this.analyser.fftSize = fftSize;
  25717. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25718. audio.getOutput().connect( this.analyser );
  25719. }
  25720. getFrequencyData() {
  25721. this.analyser.getByteFrequencyData( this.data );
  25722. return this.data;
  25723. }
  25724. getAverageFrequency() {
  25725. let value = 0;
  25726. const data = this.getFrequencyData();
  25727. for ( let i = 0; i < data.length; i ++ ) {
  25728. value += data[ i ];
  25729. }
  25730. return value / data.length;
  25731. }
  25732. }
  25733. class PropertyMixer {
  25734. constructor( binding, typeName, valueSize ) {
  25735. this.binding = binding;
  25736. this.valueSize = valueSize;
  25737. let mixFunction,
  25738. mixFunctionAdditive,
  25739. setIdentity;
  25740. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25741. //
  25742. // interpolators can use .buffer as their .result
  25743. // the data then goes to 'incoming'
  25744. //
  25745. // 'accu0' and 'accu1' are used frame-interleaved for
  25746. // the cumulative result and are compared to detect
  25747. // changes
  25748. //
  25749. // 'orig' stores the original state of the property
  25750. //
  25751. // 'add' is used for additive cumulative results
  25752. //
  25753. // 'work' is optional and is only present for quaternion types. It is used
  25754. // to store intermediate quaternion multiplication results
  25755. switch ( typeName ) {
  25756. case 'quaternion':
  25757. mixFunction = this._slerp;
  25758. mixFunctionAdditive = this._slerpAdditive;
  25759. setIdentity = this._setAdditiveIdentityQuaternion;
  25760. this.buffer = new Float64Array( valueSize * 6 );
  25761. this._workIndex = 5;
  25762. break;
  25763. case 'string':
  25764. case 'bool':
  25765. mixFunction = this._select;
  25766. // Use the regular mix function and for additive on these types,
  25767. // additive is not relevant for non-numeric types
  25768. mixFunctionAdditive = this._select;
  25769. setIdentity = this._setAdditiveIdentityOther;
  25770. this.buffer = new Array( valueSize * 5 );
  25771. break;
  25772. default:
  25773. mixFunction = this._lerp;
  25774. mixFunctionAdditive = this._lerpAdditive;
  25775. setIdentity = this._setAdditiveIdentityNumeric;
  25776. this.buffer = new Float64Array( valueSize * 5 );
  25777. }
  25778. this._mixBufferRegion = mixFunction;
  25779. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25780. this._setIdentity = setIdentity;
  25781. this._origIndex = 3;
  25782. this._addIndex = 4;
  25783. this.cumulativeWeight = 0;
  25784. this.cumulativeWeightAdditive = 0;
  25785. this.useCount = 0;
  25786. this.referenceCount = 0;
  25787. }
  25788. // accumulate data in the 'incoming' region into 'accu<i>'
  25789. accumulate( accuIndex, weight ) {
  25790. // note: happily accumulating nothing when weight = 0, the caller knows
  25791. // the weight and shouldn't have made the call in the first place
  25792. const buffer = this.buffer,
  25793. stride = this.valueSize,
  25794. offset = accuIndex * stride + stride;
  25795. let currentWeight = this.cumulativeWeight;
  25796. if ( currentWeight === 0 ) {
  25797. // accuN := incoming * weight
  25798. for ( let i = 0; i !== stride; ++ i ) {
  25799. buffer[ offset + i ] = buffer[ i ];
  25800. }
  25801. currentWeight = weight;
  25802. } else {
  25803. // accuN := accuN + incoming * weight
  25804. currentWeight += weight;
  25805. const mix = weight / currentWeight;
  25806. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25807. }
  25808. this.cumulativeWeight = currentWeight;
  25809. }
  25810. // accumulate data in the 'incoming' region into 'add'
  25811. accumulateAdditive( weight ) {
  25812. const buffer = this.buffer,
  25813. stride = this.valueSize,
  25814. offset = stride * this._addIndex;
  25815. if ( this.cumulativeWeightAdditive === 0 ) {
  25816. // add = identity
  25817. this._setIdentity();
  25818. }
  25819. // add := add + incoming * weight
  25820. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25821. this.cumulativeWeightAdditive += weight;
  25822. }
  25823. // apply the state of 'accu<i>' to the binding when accus differ
  25824. apply( accuIndex ) {
  25825. const stride = this.valueSize,
  25826. buffer = this.buffer,
  25827. offset = accuIndex * stride + stride,
  25828. weight = this.cumulativeWeight,
  25829. weightAdditive = this.cumulativeWeightAdditive,
  25830. binding = this.binding;
  25831. this.cumulativeWeight = 0;
  25832. this.cumulativeWeightAdditive = 0;
  25833. if ( weight < 1 ) {
  25834. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25835. const originalValueOffset = stride * this._origIndex;
  25836. this._mixBufferRegion(
  25837. buffer, offset, originalValueOffset, 1 - weight, stride );
  25838. }
  25839. if ( weightAdditive > 0 ) {
  25840. // accuN := accuN + additive accuN
  25841. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25842. }
  25843. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25844. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25845. // value has changed -> update scene graph
  25846. binding.setValue( buffer, offset );
  25847. break;
  25848. }
  25849. }
  25850. }
  25851. // remember the state of the bound property and copy it to both accus
  25852. saveOriginalState() {
  25853. const binding = this.binding;
  25854. const buffer = this.buffer,
  25855. stride = this.valueSize,
  25856. originalValueOffset = stride * this._origIndex;
  25857. binding.getValue( buffer, originalValueOffset );
  25858. // accu[0..1] := orig -- initially detect changes against the original
  25859. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25860. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25861. }
  25862. // Add to identity for additive
  25863. this._setIdentity();
  25864. this.cumulativeWeight = 0;
  25865. this.cumulativeWeightAdditive = 0;
  25866. }
  25867. // apply the state previously taken via 'saveOriginalState' to the binding
  25868. restoreOriginalState() {
  25869. const originalValueOffset = this.valueSize * 3;
  25870. this.binding.setValue( this.buffer, originalValueOffset );
  25871. }
  25872. _setAdditiveIdentityNumeric() {
  25873. const startIndex = this._addIndex * this.valueSize;
  25874. const endIndex = startIndex + this.valueSize;
  25875. for ( let i = startIndex; i < endIndex; i ++ ) {
  25876. this.buffer[ i ] = 0;
  25877. }
  25878. }
  25879. _setAdditiveIdentityQuaternion() {
  25880. this._setAdditiveIdentityNumeric();
  25881. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  25882. }
  25883. _setAdditiveIdentityOther() {
  25884. const startIndex = this._origIndex * this.valueSize;
  25885. const targetIndex = this._addIndex * this.valueSize;
  25886. for ( let i = 0; i < this.valueSize; i ++ ) {
  25887. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  25888. }
  25889. }
  25890. // mix functions
  25891. _select( buffer, dstOffset, srcOffset, t, stride ) {
  25892. if ( t >= 0.5 ) {
  25893. for ( let i = 0; i !== stride; ++ i ) {
  25894. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  25895. }
  25896. }
  25897. }
  25898. _slerp( buffer, dstOffset, srcOffset, t ) {
  25899. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  25900. }
  25901. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25902. const workOffset = this._workIndex * stride;
  25903. // Store result in intermediate buffer offset
  25904. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  25905. // Slerp to the intermediate result
  25906. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  25907. }
  25908. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  25909. const s = 1 - t;
  25910. for ( let i = 0; i !== stride; ++ i ) {
  25911. const j = dstOffset + i;
  25912. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  25913. }
  25914. }
  25915. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25916. for ( let i = 0; i !== stride; ++ i ) {
  25917. const j = dstOffset + i;
  25918. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  25919. }
  25920. }
  25921. }
  25922. // Characters [].:/ are reserved for track binding syntax.
  25923. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25924. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  25925. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25926. // only latin characters, and the unicode \p{L} is not yet supported. So
  25927. // instead, we exclude reserved characters and match everything else.
  25928. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25929. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  25930. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25931. // be matched to parse the rest of the track name.
  25932. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  25933. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25934. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  25935. // Object on target node, and accessor. May not contain reserved
  25936. // characters. Accessor may contain any character except closing bracket.
  25937. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  25938. // Property and accessor. May not contain reserved characters. Accessor may
  25939. // contain any non-bracket characters.
  25940. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  25941. const _trackRe = new RegExp( ''
  25942. + '^'
  25943. + _directoryRe
  25944. + _nodeRe
  25945. + _objectRe
  25946. + _propertyRe
  25947. + '$'
  25948. );
  25949. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  25950. class Composite {
  25951. constructor( targetGroup, path, optionalParsedPath ) {
  25952. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  25953. this._targetGroup = targetGroup;
  25954. this._bindings = targetGroup.subscribe_( path, parsedPath );
  25955. }
  25956. getValue( array, offset ) {
  25957. this.bind(); // bind all binding
  25958. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25959. binding = this._bindings[ firstValidIndex ];
  25960. // and only call .getValue on the first
  25961. if ( binding !== undefined ) binding.getValue( array, offset );
  25962. }
  25963. setValue( array, offset ) {
  25964. const bindings = this._bindings;
  25965. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25966. bindings[ i ].setValue( array, offset );
  25967. }
  25968. }
  25969. bind() {
  25970. const bindings = this._bindings;
  25971. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25972. bindings[ i ].bind();
  25973. }
  25974. }
  25975. unbind() {
  25976. const bindings = this._bindings;
  25977. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25978. bindings[ i ].unbind();
  25979. }
  25980. }
  25981. }
  25982. // Note: This class uses a State pattern on a per-method basis:
  25983. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25984. // prototype version of these methods with one that represents
  25985. // the bound state. When the property is not found, the methods
  25986. // become no-ops.
  25987. class PropertyBinding {
  25988. constructor( rootNode, path, parsedPath ) {
  25989. this.path = path;
  25990. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  25991. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  25992. this.rootNode = rootNode;
  25993. // initial state of these methods that calls 'bind'
  25994. this.getValue = this._getValue_unbound;
  25995. this.setValue = this._setValue_unbound;
  25996. }
  25997. static create( root, path, parsedPath ) {
  25998. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  25999. return new PropertyBinding( root, path, parsedPath );
  26000. } else {
  26001. return new PropertyBinding.Composite( root, path, parsedPath );
  26002. }
  26003. }
  26004. /**
  26005. * Replaces spaces with underscores and removes unsupported characters from
  26006. * node names, to ensure compatibility with parseTrackName().
  26007. *
  26008. * @param {string} name Node name to be sanitized.
  26009. * @return {string}
  26010. */
  26011. static sanitizeNodeName( name ) {
  26012. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26013. }
  26014. static parseTrackName( trackName ) {
  26015. const matches = _trackRe.exec( trackName );
  26016. if ( matches === null ) {
  26017. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26018. }
  26019. const results = {
  26020. // directoryName: matches[ 1 ], // (tschw) currently unused
  26021. nodeName: matches[ 2 ],
  26022. objectName: matches[ 3 ],
  26023. objectIndex: matches[ 4 ],
  26024. propertyName: matches[ 5 ], // required
  26025. propertyIndex: matches[ 6 ]
  26026. };
  26027. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26028. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26029. const objectName = results.nodeName.substring( lastDot + 1 );
  26030. // Object names must be checked against an allowlist. Otherwise, there
  26031. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26032. // 'bar' could be the objectName, or part of a nodeName (which can
  26033. // include '.' characters).
  26034. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26035. results.nodeName = results.nodeName.substring( 0, lastDot );
  26036. results.objectName = objectName;
  26037. }
  26038. }
  26039. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26040. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26041. }
  26042. return results;
  26043. }
  26044. static findNode( root, nodeName ) {
  26045. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26046. return root;
  26047. }
  26048. // search into skeleton bones.
  26049. if ( root.skeleton ) {
  26050. const bone = root.skeleton.getBoneByName( nodeName );
  26051. if ( bone !== undefined ) {
  26052. return bone;
  26053. }
  26054. }
  26055. // search into node subtree.
  26056. if ( root.children ) {
  26057. const searchNodeSubtree = function ( children ) {
  26058. for ( let i = 0; i < children.length; i ++ ) {
  26059. const childNode = children[ i ];
  26060. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26061. return childNode;
  26062. }
  26063. const result = searchNodeSubtree( childNode.children );
  26064. if ( result ) return result;
  26065. }
  26066. return null;
  26067. };
  26068. const subTreeNode = searchNodeSubtree( root.children );
  26069. if ( subTreeNode ) {
  26070. return subTreeNode;
  26071. }
  26072. }
  26073. return null;
  26074. }
  26075. // these are used to "bind" a nonexistent property
  26076. _getValue_unavailable() {}
  26077. _setValue_unavailable() {}
  26078. // Getters
  26079. _getValue_direct( buffer, offset ) {
  26080. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26081. }
  26082. _getValue_array( buffer, offset ) {
  26083. const source = this.resolvedProperty;
  26084. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26085. buffer[ offset ++ ] = source[ i ];
  26086. }
  26087. }
  26088. _getValue_arrayElement( buffer, offset ) {
  26089. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26090. }
  26091. _getValue_toArray( buffer, offset ) {
  26092. this.resolvedProperty.toArray( buffer, offset );
  26093. }
  26094. // Direct
  26095. _setValue_direct( buffer, offset ) {
  26096. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26097. }
  26098. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26099. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26100. this.targetObject.needsUpdate = true;
  26101. }
  26102. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26103. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26104. this.targetObject.matrixWorldNeedsUpdate = true;
  26105. }
  26106. // EntireArray
  26107. _setValue_array( buffer, offset ) {
  26108. const dest = this.resolvedProperty;
  26109. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26110. dest[ i ] = buffer[ offset ++ ];
  26111. }
  26112. }
  26113. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26114. const dest = this.resolvedProperty;
  26115. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26116. dest[ i ] = buffer[ offset ++ ];
  26117. }
  26118. this.targetObject.needsUpdate = true;
  26119. }
  26120. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26121. const dest = this.resolvedProperty;
  26122. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26123. dest[ i ] = buffer[ offset ++ ];
  26124. }
  26125. this.targetObject.matrixWorldNeedsUpdate = true;
  26126. }
  26127. // ArrayElement
  26128. _setValue_arrayElement( buffer, offset ) {
  26129. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26130. }
  26131. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26132. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26133. this.targetObject.needsUpdate = true;
  26134. }
  26135. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26136. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26137. this.targetObject.matrixWorldNeedsUpdate = true;
  26138. }
  26139. // HasToFromArray
  26140. _setValue_fromArray( buffer, offset ) {
  26141. this.resolvedProperty.fromArray( buffer, offset );
  26142. }
  26143. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26144. this.resolvedProperty.fromArray( buffer, offset );
  26145. this.targetObject.needsUpdate = true;
  26146. }
  26147. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26148. this.resolvedProperty.fromArray( buffer, offset );
  26149. this.targetObject.matrixWorldNeedsUpdate = true;
  26150. }
  26151. _getValue_unbound( targetArray, offset ) {
  26152. this.bind();
  26153. this.getValue( targetArray, offset );
  26154. }
  26155. _setValue_unbound( sourceArray, offset ) {
  26156. this.bind();
  26157. this.setValue( sourceArray, offset );
  26158. }
  26159. // create getter / setter pair for a property in the scene graph
  26160. bind() {
  26161. let targetObject = this.node;
  26162. const parsedPath = this.parsedPath;
  26163. const objectName = parsedPath.objectName;
  26164. const propertyName = parsedPath.propertyName;
  26165. let propertyIndex = parsedPath.propertyIndex;
  26166. if ( ! targetObject ) {
  26167. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26168. this.node = targetObject;
  26169. }
  26170. // set fail state so we can just 'return' on error
  26171. this.getValue = this._getValue_unavailable;
  26172. this.setValue = this._setValue_unavailable;
  26173. // ensure there is a value node
  26174. if ( ! targetObject ) {
  26175. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26176. return;
  26177. }
  26178. if ( objectName ) {
  26179. let objectIndex = parsedPath.objectIndex;
  26180. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26181. switch ( objectName ) {
  26182. case 'materials':
  26183. if ( ! targetObject.material ) {
  26184. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26185. return;
  26186. }
  26187. if ( ! targetObject.material.materials ) {
  26188. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26189. return;
  26190. }
  26191. targetObject = targetObject.material.materials;
  26192. break;
  26193. case 'bones':
  26194. if ( ! targetObject.skeleton ) {
  26195. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26196. return;
  26197. }
  26198. // potential future optimization: skip this if propertyIndex is already an integer
  26199. // and convert the integer string to a true integer.
  26200. targetObject = targetObject.skeleton.bones;
  26201. // support resolving morphTarget names into indices.
  26202. for ( let i = 0; i < targetObject.length; i ++ ) {
  26203. if ( targetObject[ i ].name === objectIndex ) {
  26204. objectIndex = i;
  26205. break;
  26206. }
  26207. }
  26208. break;
  26209. default:
  26210. if ( targetObject[ objectName ] === undefined ) {
  26211. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26212. return;
  26213. }
  26214. targetObject = targetObject[ objectName ];
  26215. }
  26216. if ( objectIndex !== undefined ) {
  26217. if ( targetObject[ objectIndex ] === undefined ) {
  26218. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26219. return;
  26220. }
  26221. targetObject = targetObject[ objectIndex ];
  26222. }
  26223. }
  26224. // resolve property
  26225. const nodeProperty = targetObject[ propertyName ];
  26226. if ( nodeProperty === undefined ) {
  26227. const nodeName = parsedPath.nodeName;
  26228. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26229. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26230. return;
  26231. }
  26232. // determine versioning scheme
  26233. let versioning = this.Versioning.None;
  26234. this.targetObject = targetObject;
  26235. if ( targetObject.needsUpdate !== undefined ) { // material
  26236. versioning = this.Versioning.NeedsUpdate;
  26237. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26238. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26239. }
  26240. // determine how the property gets bound
  26241. let bindingType = this.BindingType.Direct;
  26242. if ( propertyIndex !== undefined ) {
  26243. // access a sub element of the property array (only primitives are supported right now)
  26244. if ( propertyName === 'morphTargetInfluences' ) {
  26245. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26246. // support resolving morphTarget names into indices.
  26247. if ( ! targetObject.geometry ) {
  26248. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26249. return;
  26250. }
  26251. if ( targetObject.geometry.isBufferGeometry ) {
  26252. if ( ! targetObject.geometry.morphAttributes ) {
  26253. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26254. return;
  26255. }
  26256. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26257. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26258. }
  26259. } else {
  26260. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  26261. return;
  26262. }
  26263. }
  26264. bindingType = this.BindingType.ArrayElement;
  26265. this.resolvedProperty = nodeProperty;
  26266. this.propertyIndex = propertyIndex;
  26267. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26268. // must use copy for Object3D.Euler/Quaternion
  26269. bindingType = this.BindingType.HasFromToArray;
  26270. this.resolvedProperty = nodeProperty;
  26271. } else if ( Array.isArray( nodeProperty ) ) {
  26272. bindingType = this.BindingType.EntireArray;
  26273. this.resolvedProperty = nodeProperty;
  26274. } else {
  26275. this.propertyName = propertyName;
  26276. }
  26277. // select getter / setter
  26278. this.getValue = this.GetterByBindingType[ bindingType ];
  26279. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26280. }
  26281. unbind() {
  26282. this.node = null;
  26283. // back to the prototype version of getValue / setValue
  26284. // note: avoiding to mutate the shape of 'this' via 'delete'
  26285. this.getValue = this._getValue_unbound;
  26286. this.setValue = this._setValue_unbound;
  26287. }
  26288. }
  26289. PropertyBinding.Composite = Composite;
  26290. PropertyBinding.prototype.BindingType = {
  26291. Direct: 0,
  26292. EntireArray: 1,
  26293. ArrayElement: 2,
  26294. HasFromToArray: 3
  26295. };
  26296. PropertyBinding.prototype.Versioning = {
  26297. None: 0,
  26298. NeedsUpdate: 1,
  26299. MatrixWorldNeedsUpdate: 2
  26300. };
  26301. PropertyBinding.prototype.GetterByBindingType = [
  26302. PropertyBinding.prototype._getValue_direct,
  26303. PropertyBinding.prototype._getValue_array,
  26304. PropertyBinding.prototype._getValue_arrayElement,
  26305. PropertyBinding.prototype._getValue_toArray,
  26306. ];
  26307. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26308. [
  26309. // Direct
  26310. PropertyBinding.prototype._setValue_direct,
  26311. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26312. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26313. ], [
  26314. // EntireArray
  26315. PropertyBinding.prototype._setValue_array,
  26316. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26317. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26318. ], [
  26319. // ArrayElement
  26320. PropertyBinding.prototype._setValue_arrayElement,
  26321. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26322. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26323. ], [
  26324. // HasToFromArray
  26325. PropertyBinding.prototype._setValue_fromArray,
  26326. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26327. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26328. ]
  26329. ];
  26330. /**
  26331. *
  26332. * A group of objects that receives a shared animation state.
  26333. *
  26334. * Usage:
  26335. *
  26336. * - Add objects you would otherwise pass as 'root' to the
  26337. * constructor or the .clipAction method of AnimationMixer.
  26338. *
  26339. * - Instead pass this object as 'root'.
  26340. *
  26341. * - You can also add and remove objects later when the mixer
  26342. * is running.
  26343. *
  26344. * Note:
  26345. *
  26346. * Objects of this class appear as one object to the mixer,
  26347. * so cache control of the individual objects must be done
  26348. * on the group.
  26349. *
  26350. * Limitation:
  26351. *
  26352. * - The animated properties must be compatible among the
  26353. * all objects in the group.
  26354. *
  26355. * - A single property can either be controlled through a
  26356. * target group or directly, but not both.
  26357. */
  26358. class AnimationObjectGroup {
  26359. constructor() {
  26360. this.uuid = generateUUID();
  26361. // cached objects followed by the active ones
  26362. this._objects = Array.prototype.slice.call( arguments );
  26363. this.nCachedObjects_ = 0; // threshold
  26364. // note: read by PropertyBinding.Composite
  26365. const indices = {};
  26366. this._indicesByUUID = indices; // for bookkeeping
  26367. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26368. indices[ arguments[ i ].uuid ] = i;
  26369. }
  26370. this._paths = []; // inside: string
  26371. this._parsedPaths = []; // inside: { we don't care, here }
  26372. this._bindings = []; // inside: Array< PropertyBinding >
  26373. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26374. const scope = this;
  26375. this.stats = {
  26376. objects: {
  26377. get total() {
  26378. return scope._objects.length;
  26379. },
  26380. get inUse() {
  26381. return this.total - scope.nCachedObjects_;
  26382. }
  26383. },
  26384. get bindingsPerObject() {
  26385. return scope._bindings.length;
  26386. }
  26387. };
  26388. }
  26389. add() {
  26390. const objects = this._objects,
  26391. indicesByUUID = this._indicesByUUID,
  26392. paths = this._paths,
  26393. parsedPaths = this._parsedPaths,
  26394. bindings = this._bindings,
  26395. nBindings = bindings.length;
  26396. let knownObject = undefined,
  26397. nObjects = objects.length,
  26398. nCachedObjects = this.nCachedObjects_;
  26399. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26400. const object = arguments[ i ],
  26401. uuid = object.uuid;
  26402. let index = indicesByUUID[ uuid ];
  26403. if ( index === undefined ) {
  26404. // unknown object -> add it to the ACTIVE region
  26405. index = nObjects ++;
  26406. indicesByUUID[ uuid ] = index;
  26407. objects.push( object );
  26408. // accounting is done, now do the same for all bindings
  26409. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26410. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26411. }
  26412. } else if ( index < nCachedObjects ) {
  26413. knownObject = objects[ index ];
  26414. // move existing object to the ACTIVE region
  26415. const firstActiveIndex = -- nCachedObjects,
  26416. lastCachedObject = objects[ firstActiveIndex ];
  26417. indicesByUUID[ lastCachedObject.uuid ] = index;
  26418. objects[ index ] = lastCachedObject;
  26419. indicesByUUID[ uuid ] = firstActiveIndex;
  26420. objects[ firstActiveIndex ] = object;
  26421. // accounting is done, now do the same for all bindings
  26422. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26423. const bindingsForPath = bindings[ j ],
  26424. lastCached = bindingsForPath[ firstActiveIndex ];
  26425. let binding = bindingsForPath[ index ];
  26426. bindingsForPath[ index ] = lastCached;
  26427. if ( binding === undefined ) {
  26428. // since we do not bother to create new bindings
  26429. // for objects that are cached, the binding may
  26430. // or may not exist
  26431. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26432. }
  26433. bindingsForPath[ firstActiveIndex ] = binding;
  26434. }
  26435. } else if ( objects[ index ] !== knownObject ) {
  26436. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26437. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26438. } // else the object is already where we want it to be
  26439. } // for arguments
  26440. this.nCachedObjects_ = nCachedObjects;
  26441. }
  26442. remove() {
  26443. const objects = this._objects,
  26444. indicesByUUID = this._indicesByUUID,
  26445. bindings = this._bindings,
  26446. nBindings = bindings.length;
  26447. let nCachedObjects = this.nCachedObjects_;
  26448. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26449. const object = arguments[ i ],
  26450. uuid = object.uuid,
  26451. index = indicesByUUID[ uuid ];
  26452. if ( index !== undefined && index >= nCachedObjects ) {
  26453. // move existing object into the CACHED region
  26454. const lastCachedIndex = nCachedObjects ++,
  26455. firstActiveObject = objects[ lastCachedIndex ];
  26456. indicesByUUID[ firstActiveObject.uuid ] = index;
  26457. objects[ index ] = firstActiveObject;
  26458. indicesByUUID[ uuid ] = lastCachedIndex;
  26459. objects[ lastCachedIndex ] = object;
  26460. // accounting is done, now do the same for all bindings
  26461. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26462. const bindingsForPath = bindings[ j ],
  26463. firstActive = bindingsForPath[ lastCachedIndex ],
  26464. binding = bindingsForPath[ index ];
  26465. bindingsForPath[ index ] = firstActive;
  26466. bindingsForPath[ lastCachedIndex ] = binding;
  26467. }
  26468. }
  26469. } // for arguments
  26470. this.nCachedObjects_ = nCachedObjects;
  26471. }
  26472. // remove & forget
  26473. uncache() {
  26474. const objects = this._objects,
  26475. indicesByUUID = this._indicesByUUID,
  26476. bindings = this._bindings,
  26477. nBindings = bindings.length;
  26478. let nCachedObjects = this.nCachedObjects_,
  26479. nObjects = objects.length;
  26480. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26481. const object = arguments[ i ],
  26482. uuid = object.uuid,
  26483. index = indicesByUUID[ uuid ];
  26484. if ( index !== undefined ) {
  26485. delete indicesByUUID[ uuid ];
  26486. if ( index < nCachedObjects ) {
  26487. // object is cached, shrink the CACHED region
  26488. const firstActiveIndex = -- nCachedObjects,
  26489. lastCachedObject = objects[ firstActiveIndex ],
  26490. lastIndex = -- nObjects,
  26491. lastObject = objects[ lastIndex ];
  26492. // last cached object takes this object's place
  26493. indicesByUUID[ lastCachedObject.uuid ] = index;
  26494. objects[ index ] = lastCachedObject;
  26495. // last object goes to the activated slot and pop
  26496. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26497. objects[ firstActiveIndex ] = lastObject;
  26498. objects.pop();
  26499. // accounting is done, now do the same for all bindings
  26500. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26501. const bindingsForPath = bindings[ j ],
  26502. lastCached = bindingsForPath[ firstActiveIndex ],
  26503. last = bindingsForPath[ lastIndex ];
  26504. bindingsForPath[ index ] = lastCached;
  26505. bindingsForPath[ firstActiveIndex ] = last;
  26506. bindingsForPath.pop();
  26507. }
  26508. } else {
  26509. // object is active, just swap with the last and pop
  26510. const lastIndex = -- nObjects,
  26511. lastObject = objects[ lastIndex ];
  26512. if ( lastIndex > 0 ) {
  26513. indicesByUUID[ lastObject.uuid ] = index;
  26514. }
  26515. objects[ index ] = lastObject;
  26516. objects.pop();
  26517. // accounting is done, now do the same for all bindings
  26518. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26519. const bindingsForPath = bindings[ j ];
  26520. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26521. bindingsForPath.pop();
  26522. }
  26523. } // cached or active
  26524. } // if object is known
  26525. } // for arguments
  26526. this.nCachedObjects_ = nCachedObjects;
  26527. }
  26528. // Internal interface used by befriended PropertyBinding.Composite:
  26529. subscribe_( path, parsedPath ) {
  26530. // returns an array of bindings for the given path that is changed
  26531. // according to the contained objects in the group
  26532. const indicesByPath = this._bindingsIndicesByPath;
  26533. let index = indicesByPath[ path ];
  26534. const bindings = this._bindings;
  26535. if ( index !== undefined ) return bindings[ index ];
  26536. const paths = this._paths,
  26537. parsedPaths = this._parsedPaths,
  26538. objects = this._objects,
  26539. nObjects = objects.length,
  26540. nCachedObjects = this.nCachedObjects_,
  26541. bindingsForPath = new Array( nObjects );
  26542. index = bindings.length;
  26543. indicesByPath[ path ] = index;
  26544. paths.push( path );
  26545. parsedPaths.push( parsedPath );
  26546. bindings.push( bindingsForPath );
  26547. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26548. const object = objects[ i ];
  26549. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26550. }
  26551. return bindingsForPath;
  26552. }
  26553. unsubscribe_( path ) {
  26554. // tells the group to forget about a property path and no longer
  26555. // update the array previously obtained with 'subscribe_'
  26556. const indicesByPath = this._bindingsIndicesByPath,
  26557. index = indicesByPath[ path ];
  26558. if ( index !== undefined ) {
  26559. const paths = this._paths,
  26560. parsedPaths = this._parsedPaths,
  26561. bindings = this._bindings,
  26562. lastBindingsIndex = bindings.length - 1,
  26563. lastBindings = bindings[ lastBindingsIndex ],
  26564. lastBindingsPath = path[ lastBindingsIndex ];
  26565. indicesByPath[ lastBindingsPath ] = index;
  26566. bindings[ index ] = lastBindings;
  26567. bindings.pop();
  26568. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26569. parsedPaths.pop();
  26570. paths[ index ] = paths[ lastBindingsIndex ];
  26571. paths.pop();
  26572. }
  26573. }
  26574. }
  26575. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26576. class AnimationAction {
  26577. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26578. this._mixer = mixer;
  26579. this._clip = clip;
  26580. this._localRoot = localRoot;
  26581. this.blendMode = blendMode;
  26582. const tracks = clip.tracks,
  26583. nTracks = tracks.length,
  26584. interpolants = new Array( nTracks );
  26585. const interpolantSettings = {
  26586. endingStart: ZeroCurvatureEnding,
  26587. endingEnd: ZeroCurvatureEnding
  26588. };
  26589. for ( let i = 0; i !== nTracks; ++ i ) {
  26590. const interpolant = tracks[ i ].createInterpolant( null );
  26591. interpolants[ i ] = interpolant;
  26592. interpolant.settings = interpolantSettings;
  26593. }
  26594. this._interpolantSettings = interpolantSettings;
  26595. this._interpolants = interpolants; // bound by the mixer
  26596. // inside: PropertyMixer (managed by the mixer)
  26597. this._propertyBindings = new Array( nTracks );
  26598. this._cacheIndex = null; // for the memory manager
  26599. this._byClipCacheIndex = null; // for the memory manager
  26600. this._timeScaleInterpolant = null;
  26601. this._weightInterpolant = null;
  26602. this.loop = LoopRepeat;
  26603. this._loopCount = - 1;
  26604. // global mixer time when the action is to be started
  26605. // it's set back to 'null' upon start of the action
  26606. this._startTime = null;
  26607. // scaled local time of the action
  26608. // gets clamped or wrapped to 0..clip.duration according to loop
  26609. this.time = 0;
  26610. this.timeScale = 1;
  26611. this._effectiveTimeScale = 1;
  26612. this.weight = 1;
  26613. this._effectiveWeight = 1;
  26614. this.repetitions = Infinity; // no. of repetitions when looping
  26615. this.paused = false; // true -> zero effective time scale
  26616. this.enabled = true; // false -> zero effective weight
  26617. this.clampWhenFinished = false;// keep feeding the last frame?
  26618. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26619. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26620. }
  26621. // State & Scheduling
  26622. play() {
  26623. this._mixer._activateAction( this );
  26624. return this;
  26625. }
  26626. stop() {
  26627. this._mixer._deactivateAction( this );
  26628. return this.reset();
  26629. }
  26630. reset() {
  26631. this.paused = false;
  26632. this.enabled = true;
  26633. this.time = 0; // restart clip
  26634. this._loopCount = - 1;// forget previous loops
  26635. this._startTime = null;// forget scheduling
  26636. return this.stopFading().stopWarping();
  26637. }
  26638. isRunning() {
  26639. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26640. this._startTime === null && this._mixer._isActiveAction( this );
  26641. }
  26642. // return true when play has been called
  26643. isScheduled() {
  26644. return this._mixer._isActiveAction( this );
  26645. }
  26646. startAt( time ) {
  26647. this._startTime = time;
  26648. return this;
  26649. }
  26650. setLoop( mode, repetitions ) {
  26651. this.loop = mode;
  26652. this.repetitions = repetitions;
  26653. return this;
  26654. }
  26655. // Weight
  26656. // set the weight stopping any scheduled fading
  26657. // although .enabled = false yields an effective weight of zero, this
  26658. // method does *not* change .enabled, because it would be confusing
  26659. setEffectiveWeight( weight ) {
  26660. this.weight = weight;
  26661. // note: same logic as when updated at runtime
  26662. this._effectiveWeight = this.enabled ? weight : 0;
  26663. return this.stopFading();
  26664. }
  26665. // return the weight considering fading and .enabled
  26666. getEffectiveWeight() {
  26667. return this._effectiveWeight;
  26668. }
  26669. fadeIn( duration ) {
  26670. return this._scheduleFading( duration, 0, 1 );
  26671. }
  26672. fadeOut( duration ) {
  26673. return this._scheduleFading( duration, 1, 0 );
  26674. }
  26675. crossFadeFrom( fadeOutAction, duration, warp ) {
  26676. fadeOutAction.fadeOut( duration );
  26677. this.fadeIn( duration );
  26678. if ( warp ) {
  26679. const fadeInDuration = this._clip.duration,
  26680. fadeOutDuration = fadeOutAction._clip.duration,
  26681. startEndRatio = fadeOutDuration / fadeInDuration,
  26682. endStartRatio = fadeInDuration / fadeOutDuration;
  26683. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26684. this.warp( endStartRatio, 1.0, duration );
  26685. }
  26686. return this;
  26687. }
  26688. crossFadeTo( fadeInAction, duration, warp ) {
  26689. return fadeInAction.crossFadeFrom( this, duration, warp );
  26690. }
  26691. stopFading() {
  26692. const weightInterpolant = this._weightInterpolant;
  26693. if ( weightInterpolant !== null ) {
  26694. this._weightInterpolant = null;
  26695. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26696. }
  26697. return this;
  26698. }
  26699. // Time Scale Control
  26700. // set the time scale stopping any scheduled warping
  26701. // although .paused = true yields an effective time scale of zero, this
  26702. // method does *not* change .paused, because it would be confusing
  26703. setEffectiveTimeScale( timeScale ) {
  26704. this.timeScale = timeScale;
  26705. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26706. return this.stopWarping();
  26707. }
  26708. // return the time scale considering warping and .paused
  26709. getEffectiveTimeScale() {
  26710. return this._effectiveTimeScale;
  26711. }
  26712. setDuration( duration ) {
  26713. this.timeScale = this._clip.duration / duration;
  26714. return this.stopWarping();
  26715. }
  26716. syncWith( action ) {
  26717. this.time = action.time;
  26718. this.timeScale = action.timeScale;
  26719. return this.stopWarping();
  26720. }
  26721. halt( duration ) {
  26722. return this.warp( this._effectiveTimeScale, 0, duration );
  26723. }
  26724. warp( startTimeScale, endTimeScale, duration ) {
  26725. const mixer = this._mixer,
  26726. now = mixer.time,
  26727. timeScale = this.timeScale;
  26728. let interpolant = this._timeScaleInterpolant;
  26729. if ( interpolant === null ) {
  26730. interpolant = mixer._lendControlInterpolant();
  26731. this._timeScaleInterpolant = interpolant;
  26732. }
  26733. const times = interpolant.parameterPositions,
  26734. values = interpolant.sampleValues;
  26735. times[ 0 ] = now;
  26736. times[ 1 ] = now + duration;
  26737. values[ 0 ] = startTimeScale / timeScale;
  26738. values[ 1 ] = endTimeScale / timeScale;
  26739. return this;
  26740. }
  26741. stopWarping() {
  26742. const timeScaleInterpolant = this._timeScaleInterpolant;
  26743. if ( timeScaleInterpolant !== null ) {
  26744. this._timeScaleInterpolant = null;
  26745. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26746. }
  26747. return this;
  26748. }
  26749. // Object Accessors
  26750. getMixer() {
  26751. return this._mixer;
  26752. }
  26753. getClip() {
  26754. return this._clip;
  26755. }
  26756. getRoot() {
  26757. return this._localRoot || this._mixer._root;
  26758. }
  26759. // Interna
  26760. _update( time, deltaTime, timeDirection, accuIndex ) {
  26761. // called by the mixer
  26762. if ( ! this.enabled ) {
  26763. // call ._updateWeight() to update ._effectiveWeight
  26764. this._updateWeight( time );
  26765. return;
  26766. }
  26767. const startTime = this._startTime;
  26768. if ( startTime !== null ) {
  26769. // check for scheduled start of action
  26770. const timeRunning = ( time - startTime ) * timeDirection;
  26771. if ( timeRunning < 0 || timeDirection === 0 ) {
  26772. return; // yet to come / don't decide when delta = 0
  26773. }
  26774. // start
  26775. this._startTime = null; // unschedule
  26776. deltaTime = timeDirection * timeRunning;
  26777. }
  26778. // apply time scale and advance time
  26779. deltaTime *= this._updateTimeScale( time );
  26780. const clipTime = this._updateTime( deltaTime );
  26781. // note: _updateTime may disable the action resulting in
  26782. // an effective weight of 0
  26783. const weight = this._updateWeight( time );
  26784. if ( weight > 0 ) {
  26785. const interpolants = this._interpolants;
  26786. const propertyMixers = this._propertyBindings;
  26787. switch ( this.blendMode ) {
  26788. case AdditiveAnimationBlendMode:
  26789. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26790. interpolants[ j ].evaluate( clipTime );
  26791. propertyMixers[ j ].accumulateAdditive( weight );
  26792. }
  26793. break;
  26794. case NormalAnimationBlendMode:
  26795. default:
  26796. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26797. interpolants[ j ].evaluate( clipTime );
  26798. propertyMixers[ j ].accumulate( accuIndex, weight );
  26799. }
  26800. }
  26801. }
  26802. }
  26803. _updateWeight( time ) {
  26804. let weight = 0;
  26805. if ( this.enabled ) {
  26806. weight = this.weight;
  26807. const interpolant = this._weightInterpolant;
  26808. if ( interpolant !== null ) {
  26809. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26810. weight *= interpolantValue;
  26811. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26812. this.stopFading();
  26813. if ( interpolantValue === 0 ) {
  26814. // faded out, disable
  26815. this.enabled = false;
  26816. }
  26817. }
  26818. }
  26819. }
  26820. this._effectiveWeight = weight;
  26821. return weight;
  26822. }
  26823. _updateTimeScale( time ) {
  26824. let timeScale = 0;
  26825. if ( ! this.paused ) {
  26826. timeScale = this.timeScale;
  26827. const interpolant = this._timeScaleInterpolant;
  26828. if ( interpolant !== null ) {
  26829. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26830. timeScale *= interpolantValue;
  26831. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26832. this.stopWarping();
  26833. if ( timeScale === 0 ) {
  26834. // motion has halted, pause
  26835. this.paused = true;
  26836. } else {
  26837. // warp done - apply final time scale
  26838. this.timeScale = timeScale;
  26839. }
  26840. }
  26841. }
  26842. }
  26843. this._effectiveTimeScale = timeScale;
  26844. return timeScale;
  26845. }
  26846. _updateTime( deltaTime ) {
  26847. const duration = this._clip.duration;
  26848. const loop = this.loop;
  26849. let time = this.time + deltaTime;
  26850. let loopCount = this._loopCount;
  26851. const pingPong = ( loop === LoopPingPong );
  26852. if ( deltaTime === 0 ) {
  26853. if ( loopCount === - 1 ) return time;
  26854. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26855. }
  26856. if ( loop === LoopOnce ) {
  26857. if ( loopCount === - 1 ) {
  26858. // just started
  26859. this._loopCount = 0;
  26860. this._setEndings( true, true, false );
  26861. }
  26862. handle_stop: {
  26863. if ( time >= duration ) {
  26864. time = duration;
  26865. } else if ( time < 0 ) {
  26866. time = 0;
  26867. } else {
  26868. this.time = time;
  26869. break handle_stop;
  26870. }
  26871. if ( this.clampWhenFinished ) this.paused = true;
  26872. else this.enabled = false;
  26873. this.time = time;
  26874. this._mixer.dispatchEvent( {
  26875. type: 'finished', action: this,
  26876. direction: deltaTime < 0 ? - 1 : 1
  26877. } );
  26878. }
  26879. } else { // repetitive Repeat or PingPong
  26880. if ( loopCount === - 1 ) {
  26881. // just started
  26882. if ( deltaTime >= 0 ) {
  26883. loopCount = 0;
  26884. this._setEndings( true, this.repetitions === 0, pingPong );
  26885. } else {
  26886. // when looping in reverse direction, the initial
  26887. // transition through zero counts as a repetition,
  26888. // so leave loopCount at -1
  26889. this._setEndings( this.repetitions === 0, true, pingPong );
  26890. }
  26891. }
  26892. if ( time >= duration || time < 0 ) {
  26893. // wrap around
  26894. const loopDelta = Math.floor( time / duration ); // signed
  26895. time -= duration * loopDelta;
  26896. loopCount += Math.abs( loopDelta );
  26897. const pending = this.repetitions - loopCount;
  26898. if ( pending <= 0 ) {
  26899. // have to stop (switch state, clamp time, fire event)
  26900. if ( this.clampWhenFinished ) this.paused = true;
  26901. else this.enabled = false;
  26902. time = deltaTime > 0 ? duration : 0;
  26903. this.time = time;
  26904. this._mixer.dispatchEvent( {
  26905. type: 'finished', action: this,
  26906. direction: deltaTime > 0 ? 1 : - 1
  26907. } );
  26908. } else {
  26909. // keep running
  26910. if ( pending === 1 ) {
  26911. // entering the last round
  26912. const atStart = deltaTime < 0;
  26913. this._setEndings( atStart, ! atStart, pingPong );
  26914. } else {
  26915. this._setEndings( false, false, pingPong );
  26916. }
  26917. this._loopCount = loopCount;
  26918. this.time = time;
  26919. this._mixer.dispatchEvent( {
  26920. type: 'loop', action: this, loopDelta: loopDelta
  26921. } );
  26922. }
  26923. } else {
  26924. this.time = time;
  26925. }
  26926. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  26927. // invert time for the "pong round"
  26928. return duration - time;
  26929. }
  26930. }
  26931. return time;
  26932. }
  26933. _setEndings( atStart, atEnd, pingPong ) {
  26934. const settings = this._interpolantSettings;
  26935. if ( pingPong ) {
  26936. settings.endingStart = ZeroSlopeEnding;
  26937. settings.endingEnd = ZeroSlopeEnding;
  26938. } else {
  26939. // assuming for LoopOnce atStart == atEnd == true
  26940. if ( atStart ) {
  26941. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26942. } else {
  26943. settings.endingStart = WrapAroundEnding;
  26944. }
  26945. if ( atEnd ) {
  26946. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26947. } else {
  26948. settings.endingEnd = WrapAroundEnding;
  26949. }
  26950. }
  26951. }
  26952. _scheduleFading( duration, weightNow, weightThen ) {
  26953. const mixer = this._mixer, now = mixer.time;
  26954. let interpolant = this._weightInterpolant;
  26955. if ( interpolant === null ) {
  26956. interpolant = mixer._lendControlInterpolant();
  26957. this._weightInterpolant = interpolant;
  26958. }
  26959. const times = interpolant.parameterPositions,
  26960. values = interpolant.sampleValues;
  26961. times[ 0 ] = now;
  26962. values[ 0 ] = weightNow;
  26963. times[ 1 ] = now + duration;
  26964. values[ 1 ] = weightThen;
  26965. return this;
  26966. }
  26967. }
  26968. class AnimationMixer extends EventDispatcher {
  26969. constructor( root ) {
  26970. super();
  26971. this._root = root;
  26972. this._initMemoryManager();
  26973. this._accuIndex = 0;
  26974. this.time = 0;
  26975. this.timeScale = 1.0;
  26976. }
  26977. _bindAction( action, prototypeAction ) {
  26978. const root = action._localRoot || this._root,
  26979. tracks = action._clip.tracks,
  26980. nTracks = tracks.length,
  26981. bindings = action._propertyBindings,
  26982. interpolants = action._interpolants,
  26983. rootUuid = root.uuid,
  26984. bindingsByRoot = this._bindingsByRootAndName;
  26985. let bindingsByName = bindingsByRoot[ rootUuid ];
  26986. if ( bindingsByName === undefined ) {
  26987. bindingsByName = {};
  26988. bindingsByRoot[ rootUuid ] = bindingsByName;
  26989. }
  26990. for ( let i = 0; i !== nTracks; ++ i ) {
  26991. const track = tracks[ i ],
  26992. trackName = track.name;
  26993. let binding = bindingsByName[ trackName ];
  26994. if ( binding !== undefined ) {
  26995. ++ binding.referenceCount;
  26996. bindings[ i ] = binding;
  26997. } else {
  26998. binding = bindings[ i ];
  26999. if ( binding !== undefined ) {
  27000. // existing binding, make sure the cache knows
  27001. if ( binding._cacheIndex === null ) {
  27002. ++ binding.referenceCount;
  27003. this._addInactiveBinding( binding, rootUuid, trackName );
  27004. }
  27005. continue;
  27006. }
  27007. const path = prototypeAction && prototypeAction.
  27008. _propertyBindings[ i ].binding.parsedPath;
  27009. binding = new PropertyMixer(
  27010. PropertyBinding.create( root, trackName, path ),
  27011. track.ValueTypeName, track.getValueSize() );
  27012. ++ binding.referenceCount;
  27013. this._addInactiveBinding( binding, rootUuid, trackName );
  27014. bindings[ i ] = binding;
  27015. }
  27016. interpolants[ i ].resultBuffer = binding.buffer;
  27017. }
  27018. }
  27019. _activateAction( action ) {
  27020. if ( ! this._isActiveAction( action ) ) {
  27021. if ( action._cacheIndex === null ) {
  27022. // this action has been forgotten by the cache, but the user
  27023. // appears to be still using it -> rebind
  27024. const rootUuid = ( action._localRoot || this._root ).uuid,
  27025. clipUuid = action._clip.uuid,
  27026. actionsForClip = this._actionsByClip[ clipUuid ];
  27027. this._bindAction( action,
  27028. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27029. this._addInactiveAction( action, clipUuid, rootUuid );
  27030. }
  27031. const bindings = action._propertyBindings;
  27032. // increment reference counts / sort out state
  27033. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27034. const binding = bindings[ i ];
  27035. if ( binding.useCount ++ === 0 ) {
  27036. this._lendBinding( binding );
  27037. binding.saveOriginalState();
  27038. }
  27039. }
  27040. this._lendAction( action );
  27041. }
  27042. }
  27043. _deactivateAction( action ) {
  27044. if ( this._isActiveAction( action ) ) {
  27045. const bindings = action._propertyBindings;
  27046. // decrement reference counts / sort out state
  27047. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27048. const binding = bindings[ i ];
  27049. if ( -- binding.useCount === 0 ) {
  27050. binding.restoreOriginalState();
  27051. this._takeBackBinding( binding );
  27052. }
  27053. }
  27054. this._takeBackAction( action );
  27055. }
  27056. }
  27057. // Memory manager
  27058. _initMemoryManager() {
  27059. this._actions = []; // 'nActiveActions' followed by inactive ones
  27060. this._nActiveActions = 0;
  27061. this._actionsByClip = {};
  27062. // inside:
  27063. // {
  27064. // knownActions: Array< AnimationAction > - used as prototypes
  27065. // actionByRoot: AnimationAction - lookup
  27066. // }
  27067. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27068. this._nActiveBindings = 0;
  27069. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27070. this._controlInterpolants = []; // same game as above
  27071. this._nActiveControlInterpolants = 0;
  27072. const scope = this;
  27073. this.stats = {
  27074. actions: {
  27075. get total() {
  27076. return scope._actions.length;
  27077. },
  27078. get inUse() {
  27079. return scope._nActiveActions;
  27080. }
  27081. },
  27082. bindings: {
  27083. get total() {
  27084. return scope._bindings.length;
  27085. },
  27086. get inUse() {
  27087. return scope._nActiveBindings;
  27088. }
  27089. },
  27090. controlInterpolants: {
  27091. get total() {
  27092. return scope._controlInterpolants.length;
  27093. },
  27094. get inUse() {
  27095. return scope._nActiveControlInterpolants;
  27096. }
  27097. }
  27098. };
  27099. }
  27100. // Memory management for AnimationAction objects
  27101. _isActiveAction( action ) {
  27102. const index = action._cacheIndex;
  27103. return index !== null && index < this._nActiveActions;
  27104. }
  27105. _addInactiveAction( action, clipUuid, rootUuid ) {
  27106. const actions = this._actions,
  27107. actionsByClip = this._actionsByClip;
  27108. let actionsForClip = actionsByClip[ clipUuid ];
  27109. if ( actionsForClip === undefined ) {
  27110. actionsForClip = {
  27111. knownActions: [ action ],
  27112. actionByRoot: {}
  27113. };
  27114. action._byClipCacheIndex = 0;
  27115. actionsByClip[ clipUuid ] = actionsForClip;
  27116. } else {
  27117. const knownActions = actionsForClip.knownActions;
  27118. action._byClipCacheIndex = knownActions.length;
  27119. knownActions.push( action );
  27120. }
  27121. action._cacheIndex = actions.length;
  27122. actions.push( action );
  27123. actionsForClip.actionByRoot[ rootUuid ] = action;
  27124. }
  27125. _removeInactiveAction( action ) {
  27126. const actions = this._actions,
  27127. lastInactiveAction = actions[ actions.length - 1 ],
  27128. cacheIndex = action._cacheIndex;
  27129. lastInactiveAction._cacheIndex = cacheIndex;
  27130. actions[ cacheIndex ] = lastInactiveAction;
  27131. actions.pop();
  27132. action._cacheIndex = null;
  27133. const clipUuid = action._clip.uuid,
  27134. actionsByClip = this._actionsByClip,
  27135. actionsForClip = actionsByClip[ clipUuid ],
  27136. knownActionsForClip = actionsForClip.knownActions,
  27137. lastKnownAction =
  27138. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27139. byClipCacheIndex = action._byClipCacheIndex;
  27140. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27141. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27142. knownActionsForClip.pop();
  27143. action._byClipCacheIndex = null;
  27144. const actionByRoot = actionsForClip.actionByRoot,
  27145. rootUuid = ( action._localRoot || this._root ).uuid;
  27146. delete actionByRoot[ rootUuid ];
  27147. if ( knownActionsForClip.length === 0 ) {
  27148. delete actionsByClip[ clipUuid ];
  27149. }
  27150. this._removeInactiveBindingsForAction( action );
  27151. }
  27152. _removeInactiveBindingsForAction( action ) {
  27153. const bindings = action._propertyBindings;
  27154. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27155. const binding = bindings[ i ];
  27156. if ( -- binding.referenceCount === 0 ) {
  27157. this._removeInactiveBinding( binding );
  27158. }
  27159. }
  27160. }
  27161. _lendAction( action ) {
  27162. // [ active actions | inactive actions ]
  27163. // [ active actions >| inactive actions ]
  27164. // s a
  27165. // <-swap->
  27166. // a s
  27167. const actions = this._actions,
  27168. prevIndex = action._cacheIndex,
  27169. lastActiveIndex = this._nActiveActions ++,
  27170. firstInactiveAction = actions[ lastActiveIndex ];
  27171. action._cacheIndex = lastActiveIndex;
  27172. actions[ lastActiveIndex ] = action;
  27173. firstInactiveAction._cacheIndex = prevIndex;
  27174. actions[ prevIndex ] = firstInactiveAction;
  27175. }
  27176. _takeBackAction( action ) {
  27177. // [ active actions | inactive actions ]
  27178. // [ active actions |< inactive actions ]
  27179. // a s
  27180. // <-swap->
  27181. // s a
  27182. const actions = this._actions,
  27183. prevIndex = action._cacheIndex,
  27184. firstInactiveIndex = -- this._nActiveActions,
  27185. lastActiveAction = actions[ firstInactiveIndex ];
  27186. action._cacheIndex = firstInactiveIndex;
  27187. actions[ firstInactiveIndex ] = action;
  27188. lastActiveAction._cacheIndex = prevIndex;
  27189. actions[ prevIndex ] = lastActiveAction;
  27190. }
  27191. // Memory management for PropertyMixer objects
  27192. _addInactiveBinding( binding, rootUuid, trackName ) {
  27193. const bindingsByRoot = this._bindingsByRootAndName,
  27194. bindings = this._bindings;
  27195. let bindingByName = bindingsByRoot[ rootUuid ];
  27196. if ( bindingByName === undefined ) {
  27197. bindingByName = {};
  27198. bindingsByRoot[ rootUuid ] = bindingByName;
  27199. }
  27200. bindingByName[ trackName ] = binding;
  27201. binding._cacheIndex = bindings.length;
  27202. bindings.push( binding );
  27203. }
  27204. _removeInactiveBinding( binding ) {
  27205. const bindings = this._bindings,
  27206. propBinding = binding.binding,
  27207. rootUuid = propBinding.rootNode.uuid,
  27208. trackName = propBinding.path,
  27209. bindingsByRoot = this._bindingsByRootAndName,
  27210. bindingByName = bindingsByRoot[ rootUuid ],
  27211. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27212. cacheIndex = binding._cacheIndex;
  27213. lastInactiveBinding._cacheIndex = cacheIndex;
  27214. bindings[ cacheIndex ] = lastInactiveBinding;
  27215. bindings.pop();
  27216. delete bindingByName[ trackName ];
  27217. if ( Object.keys( bindingByName ).length === 0 ) {
  27218. delete bindingsByRoot[ rootUuid ];
  27219. }
  27220. }
  27221. _lendBinding( binding ) {
  27222. const bindings = this._bindings,
  27223. prevIndex = binding._cacheIndex,
  27224. lastActiveIndex = this._nActiveBindings ++,
  27225. firstInactiveBinding = bindings[ lastActiveIndex ];
  27226. binding._cacheIndex = lastActiveIndex;
  27227. bindings[ lastActiveIndex ] = binding;
  27228. firstInactiveBinding._cacheIndex = prevIndex;
  27229. bindings[ prevIndex ] = firstInactiveBinding;
  27230. }
  27231. _takeBackBinding( binding ) {
  27232. const bindings = this._bindings,
  27233. prevIndex = binding._cacheIndex,
  27234. firstInactiveIndex = -- this._nActiveBindings,
  27235. lastActiveBinding = bindings[ firstInactiveIndex ];
  27236. binding._cacheIndex = firstInactiveIndex;
  27237. bindings[ firstInactiveIndex ] = binding;
  27238. lastActiveBinding._cacheIndex = prevIndex;
  27239. bindings[ prevIndex ] = lastActiveBinding;
  27240. }
  27241. // Memory management of Interpolants for weight and time scale
  27242. _lendControlInterpolant() {
  27243. const interpolants = this._controlInterpolants,
  27244. lastActiveIndex = this._nActiveControlInterpolants ++;
  27245. let interpolant = interpolants[ lastActiveIndex ];
  27246. if ( interpolant === undefined ) {
  27247. interpolant = new LinearInterpolant(
  27248. new Float32Array( 2 ), new Float32Array( 2 ),
  27249. 1, this._controlInterpolantsResultBuffer );
  27250. interpolant.__cacheIndex = lastActiveIndex;
  27251. interpolants[ lastActiveIndex ] = interpolant;
  27252. }
  27253. return interpolant;
  27254. }
  27255. _takeBackControlInterpolant( interpolant ) {
  27256. const interpolants = this._controlInterpolants,
  27257. prevIndex = interpolant.__cacheIndex,
  27258. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27259. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27260. interpolant.__cacheIndex = firstInactiveIndex;
  27261. interpolants[ firstInactiveIndex ] = interpolant;
  27262. lastActiveInterpolant.__cacheIndex = prevIndex;
  27263. interpolants[ prevIndex ] = lastActiveInterpolant;
  27264. }
  27265. // return an action for a clip optionally using a custom root target
  27266. // object (this method allocates a lot of dynamic memory in case a
  27267. // previously unknown clip/root combination is specified)
  27268. clipAction( clip, optionalRoot, blendMode ) {
  27269. const root = optionalRoot || this._root,
  27270. rootUuid = root.uuid;
  27271. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27272. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27273. const actionsForClip = this._actionsByClip[ clipUuid ];
  27274. let prototypeAction = null;
  27275. if ( blendMode === undefined ) {
  27276. if ( clipObject !== null ) {
  27277. blendMode = clipObject.blendMode;
  27278. } else {
  27279. blendMode = NormalAnimationBlendMode;
  27280. }
  27281. }
  27282. if ( actionsForClip !== undefined ) {
  27283. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27284. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27285. return existingAction;
  27286. }
  27287. // we know the clip, so we don't have to parse all
  27288. // the bindings again but can just copy
  27289. prototypeAction = actionsForClip.knownActions[ 0 ];
  27290. // also, take the clip from the prototype action
  27291. if ( clipObject === null )
  27292. clipObject = prototypeAction._clip;
  27293. }
  27294. // clip must be known when specified via string
  27295. if ( clipObject === null ) return null;
  27296. // allocate all resources required to run it
  27297. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27298. this._bindAction( newAction, prototypeAction );
  27299. // and make the action known to the memory manager
  27300. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27301. return newAction;
  27302. }
  27303. // get an existing action
  27304. existingAction( clip, optionalRoot ) {
  27305. const root = optionalRoot || this._root,
  27306. rootUuid = root.uuid,
  27307. clipObject = typeof clip === 'string' ?
  27308. AnimationClip.findByName( root, clip ) : clip,
  27309. clipUuid = clipObject ? clipObject.uuid : clip,
  27310. actionsForClip = this._actionsByClip[ clipUuid ];
  27311. if ( actionsForClip !== undefined ) {
  27312. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27313. }
  27314. return null;
  27315. }
  27316. // deactivates all previously scheduled actions
  27317. stopAllAction() {
  27318. const actions = this._actions,
  27319. nActions = this._nActiveActions;
  27320. for ( let i = nActions - 1; i >= 0; -- i ) {
  27321. actions[ i ].stop();
  27322. }
  27323. return this;
  27324. }
  27325. // advance the time and update apply the animation
  27326. update( deltaTime ) {
  27327. deltaTime *= this.timeScale;
  27328. const actions = this._actions,
  27329. nActions = this._nActiveActions,
  27330. time = this.time += deltaTime,
  27331. timeDirection = Math.sign( deltaTime ),
  27332. accuIndex = this._accuIndex ^= 1;
  27333. // run active actions
  27334. for ( let i = 0; i !== nActions; ++ i ) {
  27335. const action = actions[ i ];
  27336. action._update( time, deltaTime, timeDirection, accuIndex );
  27337. }
  27338. // update scene graph
  27339. const bindings = this._bindings,
  27340. nBindings = this._nActiveBindings;
  27341. for ( let i = 0; i !== nBindings; ++ i ) {
  27342. bindings[ i ].apply( accuIndex );
  27343. }
  27344. return this;
  27345. }
  27346. // Allows you to seek to a specific time in an animation.
  27347. setTime( timeInSeconds ) {
  27348. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27349. for ( let i = 0; i < this._actions.length; i ++ ) {
  27350. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27351. }
  27352. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27353. }
  27354. // return this mixer's root target object
  27355. getRoot() {
  27356. return this._root;
  27357. }
  27358. // free all resources specific to a particular clip
  27359. uncacheClip( clip ) {
  27360. const actions = this._actions,
  27361. clipUuid = clip.uuid,
  27362. actionsByClip = this._actionsByClip,
  27363. actionsForClip = actionsByClip[ clipUuid ];
  27364. if ( actionsForClip !== undefined ) {
  27365. // note: just calling _removeInactiveAction would mess up the
  27366. // iteration state and also require updating the state we can
  27367. // just throw away
  27368. const actionsToRemove = actionsForClip.knownActions;
  27369. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27370. const action = actionsToRemove[ i ];
  27371. this._deactivateAction( action );
  27372. const cacheIndex = action._cacheIndex,
  27373. lastInactiveAction = actions[ actions.length - 1 ];
  27374. action._cacheIndex = null;
  27375. action._byClipCacheIndex = null;
  27376. lastInactiveAction._cacheIndex = cacheIndex;
  27377. actions[ cacheIndex ] = lastInactiveAction;
  27378. actions.pop();
  27379. this._removeInactiveBindingsForAction( action );
  27380. }
  27381. delete actionsByClip[ clipUuid ];
  27382. }
  27383. }
  27384. // free all resources specific to a particular root target object
  27385. uncacheRoot( root ) {
  27386. const rootUuid = root.uuid,
  27387. actionsByClip = this._actionsByClip;
  27388. for ( const clipUuid in actionsByClip ) {
  27389. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27390. action = actionByRoot[ rootUuid ];
  27391. if ( action !== undefined ) {
  27392. this._deactivateAction( action );
  27393. this._removeInactiveAction( action );
  27394. }
  27395. }
  27396. const bindingsByRoot = this._bindingsByRootAndName,
  27397. bindingByName = bindingsByRoot[ rootUuid ];
  27398. if ( bindingByName !== undefined ) {
  27399. for ( const trackName in bindingByName ) {
  27400. const binding = bindingByName[ trackName ];
  27401. binding.restoreOriginalState();
  27402. this._removeInactiveBinding( binding );
  27403. }
  27404. }
  27405. }
  27406. // remove a targeted clip from the cache
  27407. uncacheAction( clip, optionalRoot ) {
  27408. const action = this.existingAction( clip, optionalRoot );
  27409. if ( action !== null ) {
  27410. this._deactivateAction( action );
  27411. this._removeInactiveAction( action );
  27412. }
  27413. }
  27414. }
  27415. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  27416. class Uniform {
  27417. constructor( value ) {
  27418. if ( typeof value === 'string' ) {
  27419. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27420. value = arguments[ 1 ];
  27421. }
  27422. this.value = value;
  27423. }
  27424. clone() {
  27425. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27426. }
  27427. }
  27428. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27429. constructor( array, stride, meshPerAttribute = 1 ) {
  27430. super( array, stride );
  27431. this.meshPerAttribute = meshPerAttribute;
  27432. }
  27433. copy( source ) {
  27434. super.copy( source );
  27435. this.meshPerAttribute = source.meshPerAttribute;
  27436. return this;
  27437. }
  27438. clone( data ) {
  27439. const ib = super.clone( data );
  27440. ib.meshPerAttribute = this.meshPerAttribute;
  27441. return ib;
  27442. }
  27443. toJSON( data ) {
  27444. const json = super.toJSON( data );
  27445. json.isInstancedInterleavedBuffer = true;
  27446. json.meshPerAttribute = this.meshPerAttribute;
  27447. return json;
  27448. }
  27449. }
  27450. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27451. class GLBufferAttribute {
  27452. constructor( buffer, type, itemSize, elementSize, count ) {
  27453. this.buffer = buffer;
  27454. this.type = type;
  27455. this.itemSize = itemSize;
  27456. this.elementSize = elementSize;
  27457. this.count = count;
  27458. this.version = 0;
  27459. }
  27460. set needsUpdate( value ) {
  27461. if ( value === true ) this.version ++;
  27462. }
  27463. setBuffer( buffer ) {
  27464. this.buffer = buffer;
  27465. return this;
  27466. }
  27467. setType( type, elementSize ) {
  27468. this.type = type;
  27469. this.elementSize = elementSize;
  27470. return this;
  27471. }
  27472. setItemSize( itemSize ) {
  27473. this.itemSize = itemSize;
  27474. return this;
  27475. }
  27476. setCount( count ) {
  27477. this.count = count;
  27478. return this;
  27479. }
  27480. }
  27481. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27482. class Raycaster {
  27483. constructor( origin, direction, near = 0, far = Infinity ) {
  27484. this.ray = new Ray( origin, direction );
  27485. // direction is assumed to be normalized (for accurate distance calculations)
  27486. this.near = near;
  27487. this.far = far;
  27488. this.camera = null;
  27489. this.layers = new Layers();
  27490. this.params = {
  27491. Mesh: {},
  27492. Line: { threshold: 1 },
  27493. LOD: {},
  27494. Points: { threshold: 1 },
  27495. Sprite: {}
  27496. };
  27497. }
  27498. set( origin, direction ) {
  27499. // direction is assumed to be normalized (for accurate distance calculations)
  27500. this.ray.set( origin, direction );
  27501. }
  27502. setFromCamera( coords, camera ) {
  27503. if ( camera.isPerspectiveCamera ) {
  27504. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27505. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27506. this.camera = camera;
  27507. } else if ( camera.isOrthographicCamera ) {
  27508. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27509. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27510. this.camera = camera;
  27511. } else {
  27512. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27513. }
  27514. }
  27515. intersectObject( object, recursive = true, intersects = [] ) {
  27516. intersectObject( object, this, intersects, recursive );
  27517. intersects.sort( ascSort );
  27518. return intersects;
  27519. }
  27520. intersectObjects( objects, recursive = true, intersects = [] ) {
  27521. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27522. intersectObject( objects[ i ], this, intersects, recursive );
  27523. }
  27524. intersects.sort( ascSort );
  27525. return intersects;
  27526. }
  27527. }
  27528. function ascSort( a, b ) {
  27529. return a.distance - b.distance;
  27530. }
  27531. function intersectObject( object, raycaster, intersects, recursive ) {
  27532. if ( object.layers.test( raycaster.layers ) ) {
  27533. object.raycast( raycaster, intersects );
  27534. }
  27535. if ( recursive === true ) {
  27536. const children = object.children;
  27537. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27538. intersectObject( children[ i ], raycaster, intersects, true );
  27539. }
  27540. }
  27541. }
  27542. /**
  27543. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27544. *
  27545. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27546. * The azimuthal angle (theta) is measured from the positive z-axis.
  27547. */
  27548. class Spherical {
  27549. constructor( radius = 1, phi = 0, theta = 0 ) {
  27550. this.radius = radius;
  27551. this.phi = phi; // polar angle
  27552. this.theta = theta; // azimuthal angle
  27553. return this;
  27554. }
  27555. set( radius, phi, theta ) {
  27556. this.radius = radius;
  27557. this.phi = phi;
  27558. this.theta = theta;
  27559. return this;
  27560. }
  27561. copy( other ) {
  27562. this.radius = other.radius;
  27563. this.phi = other.phi;
  27564. this.theta = other.theta;
  27565. return this;
  27566. }
  27567. // restrict phi to be between EPS and PI-EPS
  27568. makeSafe() {
  27569. const EPS = 0.000001;
  27570. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27571. return this;
  27572. }
  27573. setFromVector3( v ) {
  27574. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27575. }
  27576. setFromCartesianCoords( x, y, z ) {
  27577. this.radius = Math.sqrt( x * x + y * y + z * z );
  27578. if ( this.radius === 0 ) {
  27579. this.theta = 0;
  27580. this.phi = 0;
  27581. } else {
  27582. this.theta = Math.atan2( x, z );
  27583. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27584. }
  27585. return this;
  27586. }
  27587. clone() {
  27588. return new this.constructor().copy( this );
  27589. }
  27590. }
  27591. /**
  27592. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27593. */
  27594. class Cylindrical {
  27595. constructor( radius = 1, theta = 0, y = 0 ) {
  27596. this.radius = radius; // distance from the origin to a point in the x-z plane
  27597. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27598. this.y = y; // height above the x-z plane
  27599. return this;
  27600. }
  27601. set( radius, theta, y ) {
  27602. this.radius = radius;
  27603. this.theta = theta;
  27604. this.y = y;
  27605. return this;
  27606. }
  27607. copy( other ) {
  27608. this.radius = other.radius;
  27609. this.theta = other.theta;
  27610. this.y = other.y;
  27611. return this;
  27612. }
  27613. setFromVector3( v ) {
  27614. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27615. }
  27616. setFromCartesianCoords( x, y, z ) {
  27617. this.radius = Math.sqrt( x * x + z * z );
  27618. this.theta = Math.atan2( x, z );
  27619. this.y = y;
  27620. return this;
  27621. }
  27622. clone() {
  27623. return new this.constructor().copy( this );
  27624. }
  27625. }
  27626. const _vector$4 = /*@__PURE__*/ new Vector2();
  27627. class Box2 {
  27628. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  27629. this.min = min;
  27630. this.max = max;
  27631. }
  27632. set( min, max ) {
  27633. this.min.copy( min );
  27634. this.max.copy( max );
  27635. return this;
  27636. }
  27637. setFromPoints( points ) {
  27638. this.makeEmpty();
  27639. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27640. this.expandByPoint( points[ i ] );
  27641. }
  27642. return this;
  27643. }
  27644. setFromCenterAndSize( center, size ) {
  27645. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  27646. this.min.copy( center ).sub( halfSize );
  27647. this.max.copy( center ).add( halfSize );
  27648. return this;
  27649. }
  27650. clone() {
  27651. return new this.constructor().copy( this );
  27652. }
  27653. copy( box ) {
  27654. this.min.copy( box.min );
  27655. this.max.copy( box.max );
  27656. return this;
  27657. }
  27658. makeEmpty() {
  27659. this.min.x = this.min.y = + Infinity;
  27660. this.max.x = this.max.y = - Infinity;
  27661. return this;
  27662. }
  27663. isEmpty() {
  27664. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27665. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27666. }
  27667. getCenter( target ) {
  27668. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27669. }
  27670. getSize( target ) {
  27671. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27672. }
  27673. expandByPoint( point ) {
  27674. this.min.min( point );
  27675. this.max.max( point );
  27676. return this;
  27677. }
  27678. expandByVector( vector ) {
  27679. this.min.sub( vector );
  27680. this.max.add( vector );
  27681. return this;
  27682. }
  27683. expandByScalar( scalar ) {
  27684. this.min.addScalar( - scalar );
  27685. this.max.addScalar( scalar );
  27686. return this;
  27687. }
  27688. containsPoint( point ) {
  27689. return point.x < this.min.x || point.x > this.max.x ||
  27690. point.y < this.min.y || point.y > this.max.y ? false : true;
  27691. }
  27692. containsBox( box ) {
  27693. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27694. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27695. }
  27696. getParameter( point, target ) {
  27697. // This can potentially have a divide by zero if the box
  27698. // has a size dimension of 0.
  27699. return target.set(
  27700. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27701. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27702. );
  27703. }
  27704. intersectsBox( box ) {
  27705. // using 4 splitting planes to rule out intersections
  27706. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27707. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27708. }
  27709. clampPoint( point, target ) {
  27710. return target.copy( point ).clamp( this.min, this.max );
  27711. }
  27712. distanceToPoint( point ) {
  27713. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  27714. return clampedPoint.sub( point ).length();
  27715. }
  27716. intersect( box ) {
  27717. this.min.max( box.min );
  27718. this.max.min( box.max );
  27719. return this;
  27720. }
  27721. union( box ) {
  27722. this.min.min( box.min );
  27723. this.max.max( box.max );
  27724. return this;
  27725. }
  27726. translate( offset ) {
  27727. this.min.add( offset );
  27728. this.max.add( offset );
  27729. return this;
  27730. }
  27731. equals( box ) {
  27732. return box.min.equals( this.min ) && box.max.equals( this.max );
  27733. }
  27734. }
  27735. Box2.prototype.isBox2 = true;
  27736. const _startP = /*@__PURE__*/ new Vector3();
  27737. const _startEnd = /*@__PURE__*/ new Vector3();
  27738. class Line3 {
  27739. constructor( start = new Vector3(), end = new Vector3() ) {
  27740. this.start = start;
  27741. this.end = end;
  27742. }
  27743. set( start, end ) {
  27744. this.start.copy( start );
  27745. this.end.copy( end );
  27746. return this;
  27747. }
  27748. copy( line ) {
  27749. this.start.copy( line.start );
  27750. this.end.copy( line.end );
  27751. return this;
  27752. }
  27753. getCenter( target ) {
  27754. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27755. }
  27756. delta( target ) {
  27757. return target.subVectors( this.end, this.start );
  27758. }
  27759. distanceSq() {
  27760. return this.start.distanceToSquared( this.end );
  27761. }
  27762. distance() {
  27763. return this.start.distanceTo( this.end );
  27764. }
  27765. at( t, target ) {
  27766. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27767. }
  27768. closestPointToPointParameter( point, clampToLine ) {
  27769. _startP.subVectors( point, this.start );
  27770. _startEnd.subVectors( this.end, this.start );
  27771. const startEnd2 = _startEnd.dot( _startEnd );
  27772. const startEnd_startP = _startEnd.dot( _startP );
  27773. let t = startEnd_startP / startEnd2;
  27774. if ( clampToLine ) {
  27775. t = clamp( t, 0, 1 );
  27776. }
  27777. return t;
  27778. }
  27779. closestPointToPoint( point, clampToLine, target ) {
  27780. const t = this.closestPointToPointParameter( point, clampToLine );
  27781. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27782. }
  27783. applyMatrix4( matrix ) {
  27784. this.start.applyMatrix4( matrix );
  27785. this.end.applyMatrix4( matrix );
  27786. return this;
  27787. }
  27788. equals( line ) {
  27789. return line.start.equals( this.start ) && line.end.equals( this.end );
  27790. }
  27791. clone() {
  27792. return new this.constructor().copy( this );
  27793. }
  27794. }
  27795. const _vector$3 = /*@__PURE__*/ new Vector3();
  27796. class SpotLightHelper extends Object3D {
  27797. constructor( light, color ) {
  27798. super();
  27799. this.light = light;
  27800. this.light.updateMatrixWorld();
  27801. this.matrix = light.matrixWorld;
  27802. this.matrixAutoUpdate = false;
  27803. this.color = color;
  27804. const geometry = new BufferGeometry();
  27805. const positions = [
  27806. 0, 0, 0, 0, 0, 1,
  27807. 0, 0, 0, 1, 0, 1,
  27808. 0, 0, 0, - 1, 0, 1,
  27809. 0, 0, 0, 0, 1, 1,
  27810. 0, 0, 0, 0, - 1, 1
  27811. ];
  27812. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27813. const p1 = ( i / l ) * Math.PI * 2;
  27814. const p2 = ( j / l ) * Math.PI * 2;
  27815. positions.push(
  27816. Math.cos( p1 ), Math.sin( p1 ), 1,
  27817. Math.cos( p2 ), Math.sin( p2 ), 1
  27818. );
  27819. }
  27820. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27821. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27822. this.cone = new LineSegments( geometry, material );
  27823. this.add( this.cone );
  27824. this.update();
  27825. }
  27826. dispose() {
  27827. this.cone.geometry.dispose();
  27828. this.cone.material.dispose();
  27829. }
  27830. update() {
  27831. this.light.updateMatrixWorld();
  27832. const coneLength = this.light.distance ? this.light.distance : 1000;
  27833. const coneWidth = coneLength * Math.tan( this.light.angle );
  27834. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  27835. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  27836. this.cone.lookAt( _vector$3 );
  27837. if ( this.color !== undefined ) {
  27838. this.cone.material.color.set( this.color );
  27839. } else {
  27840. this.cone.material.color.copy( this.light.color );
  27841. }
  27842. }
  27843. }
  27844. const _vector$2 = /*@__PURE__*/ new Vector3();
  27845. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  27846. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  27847. class SkeletonHelper extends LineSegments {
  27848. constructor( object ) {
  27849. const bones = getBoneList( object );
  27850. const geometry = new BufferGeometry();
  27851. const vertices = [];
  27852. const colors = [];
  27853. const color1 = new Color( 0, 0, 1 );
  27854. const color2 = new Color( 0, 1, 0 );
  27855. for ( let i = 0; i < bones.length; i ++ ) {
  27856. const bone = bones[ i ];
  27857. if ( bone.parent && bone.parent.isBone ) {
  27858. vertices.push( 0, 0, 0 );
  27859. vertices.push( 0, 0, 0 );
  27860. colors.push( color1.r, color1.g, color1.b );
  27861. colors.push( color2.r, color2.g, color2.b );
  27862. }
  27863. }
  27864. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27865. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27866. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  27867. super( geometry, material );
  27868. this.type = 'SkeletonHelper';
  27869. this.isSkeletonHelper = true;
  27870. this.root = object;
  27871. this.bones = bones;
  27872. this.matrix = object.matrixWorld;
  27873. this.matrixAutoUpdate = false;
  27874. }
  27875. updateMatrixWorld( force ) {
  27876. const bones = this.bones;
  27877. const geometry = this.geometry;
  27878. const position = geometry.getAttribute( 'position' );
  27879. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  27880. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  27881. const bone = bones[ i ];
  27882. if ( bone.parent && bone.parent.isBone ) {
  27883. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  27884. _vector$2.setFromMatrixPosition( _boneMatrix );
  27885. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  27886. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  27887. _vector$2.setFromMatrixPosition( _boneMatrix );
  27888. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  27889. j += 2;
  27890. }
  27891. }
  27892. geometry.getAttribute( 'position' ).needsUpdate = true;
  27893. super.updateMatrixWorld( force );
  27894. }
  27895. }
  27896. function getBoneList( object ) {
  27897. const boneList = [];
  27898. if ( object.isBone === true ) {
  27899. boneList.push( object );
  27900. }
  27901. for ( let i = 0; i < object.children.length; i ++ ) {
  27902. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  27903. }
  27904. return boneList;
  27905. }
  27906. class PointLightHelper extends Mesh {
  27907. constructor( light, sphereSize, color ) {
  27908. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  27909. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27910. super( geometry, material );
  27911. this.light = light;
  27912. this.light.updateMatrixWorld();
  27913. this.color = color;
  27914. this.type = 'PointLightHelper';
  27915. this.matrix = this.light.matrixWorld;
  27916. this.matrixAutoUpdate = false;
  27917. this.update();
  27918. /*
  27919. // TODO: delete this comment?
  27920. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  27921. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27922. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27923. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27924. const d = light.distance;
  27925. if ( d === 0.0 ) {
  27926. this.lightDistance.visible = false;
  27927. } else {
  27928. this.lightDistance.scale.set( d, d, d );
  27929. }
  27930. this.add( this.lightDistance );
  27931. */
  27932. }
  27933. dispose() {
  27934. this.geometry.dispose();
  27935. this.material.dispose();
  27936. }
  27937. update() {
  27938. if ( this.color !== undefined ) {
  27939. this.material.color.set( this.color );
  27940. } else {
  27941. this.material.color.copy( this.light.color );
  27942. }
  27943. /*
  27944. const d = this.light.distance;
  27945. if ( d === 0.0 ) {
  27946. this.lightDistance.visible = false;
  27947. } else {
  27948. this.lightDistance.visible = true;
  27949. this.lightDistance.scale.set( d, d, d );
  27950. }
  27951. */
  27952. }
  27953. }
  27954. const _vector$1 = /*@__PURE__*/ new Vector3();
  27955. const _color1 = /*@__PURE__*/ new Color();
  27956. const _color2 = /*@__PURE__*/ new Color();
  27957. class HemisphereLightHelper extends Object3D {
  27958. constructor( light, size, color ) {
  27959. super();
  27960. this.light = light;
  27961. this.light.updateMatrixWorld();
  27962. this.matrix = light.matrixWorld;
  27963. this.matrixAutoUpdate = false;
  27964. this.color = color;
  27965. const geometry = new OctahedronGeometry( size );
  27966. geometry.rotateY( Math.PI * 0.5 );
  27967. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27968. if ( this.color === undefined ) this.material.vertexColors = true;
  27969. const position = geometry.getAttribute( 'position' );
  27970. const colors = new Float32Array( position.count * 3 );
  27971. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  27972. this.add( new Mesh( geometry, this.material ) );
  27973. this.update();
  27974. }
  27975. dispose() {
  27976. this.children[ 0 ].geometry.dispose();
  27977. this.children[ 0 ].material.dispose();
  27978. }
  27979. update() {
  27980. const mesh = this.children[ 0 ];
  27981. if ( this.color !== undefined ) {
  27982. this.material.color.set( this.color );
  27983. } else {
  27984. const colors = mesh.geometry.getAttribute( 'color' );
  27985. _color1.copy( this.light.color );
  27986. _color2.copy( this.light.groundColor );
  27987. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  27988. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  27989. colors.setXYZ( i, color.r, color.g, color.b );
  27990. }
  27991. colors.needsUpdate = true;
  27992. }
  27993. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  27994. }
  27995. }
  27996. class GridHelper extends LineSegments {
  27997. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  27998. color1 = new Color( color1 );
  27999. color2 = new Color( color2 );
  28000. const center = divisions / 2;
  28001. const step = size / divisions;
  28002. const halfSize = size / 2;
  28003. const vertices = [], colors = [];
  28004. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28005. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28006. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28007. const color = i === center ? color1 : color2;
  28008. color.toArray( colors, j ); j += 3;
  28009. color.toArray( colors, j ); j += 3;
  28010. color.toArray( colors, j ); j += 3;
  28011. color.toArray( colors, j ); j += 3;
  28012. }
  28013. const geometry = new BufferGeometry();
  28014. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28015. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28016. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28017. super( geometry, material );
  28018. this.type = 'GridHelper';
  28019. }
  28020. }
  28021. class PolarGridHelper extends LineSegments {
  28022. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28023. color1 = new Color( color1 );
  28024. color2 = new Color( color2 );
  28025. const vertices = [];
  28026. const colors = [];
  28027. // create the radials
  28028. for ( let i = 0; i <= radials; i ++ ) {
  28029. const v = ( i / radials ) * ( Math.PI * 2 );
  28030. const x = Math.sin( v ) * radius;
  28031. const z = Math.cos( v ) * radius;
  28032. vertices.push( 0, 0, 0 );
  28033. vertices.push( x, 0, z );
  28034. const color = ( i & 1 ) ? color1 : color2;
  28035. colors.push( color.r, color.g, color.b );
  28036. colors.push( color.r, color.g, color.b );
  28037. }
  28038. // create the circles
  28039. for ( let i = 0; i <= circles; i ++ ) {
  28040. const color = ( i & 1 ) ? color1 : color2;
  28041. const r = radius - ( radius / circles * i );
  28042. for ( let j = 0; j < divisions; j ++ ) {
  28043. // first vertex
  28044. let v = ( j / divisions ) * ( Math.PI * 2 );
  28045. let x = Math.sin( v ) * r;
  28046. let z = Math.cos( v ) * r;
  28047. vertices.push( x, 0, z );
  28048. colors.push( color.r, color.g, color.b );
  28049. // second vertex
  28050. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28051. x = Math.sin( v ) * r;
  28052. z = Math.cos( v ) * r;
  28053. vertices.push( x, 0, z );
  28054. colors.push( color.r, color.g, color.b );
  28055. }
  28056. }
  28057. const geometry = new BufferGeometry();
  28058. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28059. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28060. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28061. super( geometry, material );
  28062. this.type = 'PolarGridHelper';
  28063. }
  28064. }
  28065. const _v1 = /*@__PURE__*/ new Vector3();
  28066. const _v2 = /*@__PURE__*/ new Vector3();
  28067. const _v3 = /*@__PURE__*/ new Vector3();
  28068. class DirectionalLightHelper extends Object3D {
  28069. constructor( light, size, color ) {
  28070. super();
  28071. this.light = light;
  28072. this.light.updateMatrixWorld();
  28073. this.matrix = light.matrixWorld;
  28074. this.matrixAutoUpdate = false;
  28075. this.color = color;
  28076. if ( size === undefined ) size = 1;
  28077. let geometry = new BufferGeometry();
  28078. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28079. - size, size, 0,
  28080. size, size, 0,
  28081. size, - size, 0,
  28082. - size, - size, 0,
  28083. - size, size, 0
  28084. ], 3 ) );
  28085. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28086. this.lightPlane = new Line( geometry, material );
  28087. this.add( this.lightPlane );
  28088. geometry = new BufferGeometry();
  28089. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28090. this.targetLine = new Line( geometry, material );
  28091. this.add( this.targetLine );
  28092. this.update();
  28093. }
  28094. dispose() {
  28095. this.lightPlane.geometry.dispose();
  28096. this.lightPlane.material.dispose();
  28097. this.targetLine.geometry.dispose();
  28098. this.targetLine.material.dispose();
  28099. }
  28100. update() {
  28101. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28102. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28103. _v3.subVectors( _v2, _v1 );
  28104. this.lightPlane.lookAt( _v2 );
  28105. if ( this.color !== undefined ) {
  28106. this.lightPlane.material.color.set( this.color );
  28107. this.targetLine.material.color.set( this.color );
  28108. } else {
  28109. this.lightPlane.material.color.copy( this.light.color );
  28110. this.targetLine.material.color.copy( this.light.color );
  28111. }
  28112. this.targetLine.lookAt( _v2 );
  28113. this.targetLine.scale.z = _v3.length();
  28114. }
  28115. }
  28116. const _vector = /*@__PURE__*/ new Vector3();
  28117. const _camera = /*@__PURE__*/ new Camera();
  28118. /**
  28119. * - shows frustum, line of sight and up of the camera
  28120. * - suitable for fast updates
  28121. * - based on frustum visualization in lightgl.js shadowmap example
  28122. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28123. */
  28124. class CameraHelper extends LineSegments {
  28125. constructor( camera ) {
  28126. const geometry = new BufferGeometry();
  28127. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28128. const vertices = [];
  28129. const colors = [];
  28130. const pointMap = {};
  28131. // colors
  28132. const colorFrustum = new Color( 0xffaa00 );
  28133. const colorCone = new Color( 0xff0000 );
  28134. const colorUp = new Color( 0x00aaff );
  28135. const colorTarget = new Color( 0xffffff );
  28136. const colorCross = new Color( 0x333333 );
  28137. // near
  28138. addLine( 'n1', 'n2', colorFrustum );
  28139. addLine( 'n2', 'n4', colorFrustum );
  28140. addLine( 'n4', 'n3', colorFrustum );
  28141. addLine( 'n3', 'n1', colorFrustum );
  28142. // far
  28143. addLine( 'f1', 'f2', colorFrustum );
  28144. addLine( 'f2', 'f4', colorFrustum );
  28145. addLine( 'f4', 'f3', colorFrustum );
  28146. addLine( 'f3', 'f1', colorFrustum );
  28147. // sides
  28148. addLine( 'n1', 'f1', colorFrustum );
  28149. addLine( 'n2', 'f2', colorFrustum );
  28150. addLine( 'n3', 'f3', colorFrustum );
  28151. addLine( 'n4', 'f4', colorFrustum );
  28152. // cone
  28153. addLine( 'p', 'n1', colorCone );
  28154. addLine( 'p', 'n2', colorCone );
  28155. addLine( 'p', 'n3', colorCone );
  28156. addLine( 'p', 'n4', colorCone );
  28157. // up
  28158. addLine( 'u1', 'u2', colorUp );
  28159. addLine( 'u2', 'u3', colorUp );
  28160. addLine( 'u3', 'u1', colorUp );
  28161. // target
  28162. addLine( 'c', 't', colorTarget );
  28163. addLine( 'p', 'c', colorCross );
  28164. // cross
  28165. addLine( 'cn1', 'cn2', colorCross );
  28166. addLine( 'cn3', 'cn4', colorCross );
  28167. addLine( 'cf1', 'cf2', colorCross );
  28168. addLine( 'cf3', 'cf4', colorCross );
  28169. function addLine( a, b, color ) {
  28170. addPoint( a, color );
  28171. addPoint( b, color );
  28172. }
  28173. function addPoint( id, color ) {
  28174. vertices.push( 0, 0, 0 );
  28175. colors.push( color.r, color.g, color.b );
  28176. if ( pointMap[ id ] === undefined ) {
  28177. pointMap[ id ] = [];
  28178. }
  28179. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28180. }
  28181. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28182. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28183. super( geometry, material );
  28184. this.type = 'CameraHelper';
  28185. this.camera = camera;
  28186. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28187. this.matrix = camera.matrixWorld;
  28188. this.matrixAutoUpdate = false;
  28189. this.pointMap = pointMap;
  28190. this.update();
  28191. }
  28192. update() {
  28193. const geometry = this.geometry;
  28194. const pointMap = this.pointMap;
  28195. const w = 1, h = 1;
  28196. // we need just camera projection matrix inverse
  28197. // world matrix must be identity
  28198. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28199. // center / target
  28200. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28201. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28202. // near
  28203. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28204. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28205. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28206. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28207. // far
  28208. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28209. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28210. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28211. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28212. // up
  28213. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28214. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28215. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28216. // cross
  28217. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28218. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28219. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28220. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28221. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28222. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28223. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28224. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28225. geometry.getAttribute( 'position' ).needsUpdate = true;
  28226. }
  28227. dispose() {
  28228. this.geometry.dispose();
  28229. this.material.dispose();
  28230. }
  28231. }
  28232. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28233. _vector.set( x, y, z ).unproject( camera );
  28234. const points = pointMap[ point ];
  28235. if ( points !== undefined ) {
  28236. const position = geometry.getAttribute( 'position' );
  28237. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28238. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28239. }
  28240. }
  28241. }
  28242. const _box = /*@__PURE__*/ new Box3();
  28243. class BoxHelper extends LineSegments {
  28244. constructor( object, color = 0xffff00 ) {
  28245. 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 ] );
  28246. const positions = new Float32Array( 8 * 3 );
  28247. const geometry = new BufferGeometry();
  28248. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28249. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28250. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28251. this.object = object;
  28252. this.type = 'BoxHelper';
  28253. this.matrixAutoUpdate = false;
  28254. this.update();
  28255. }
  28256. update( object ) {
  28257. if ( object !== undefined ) {
  28258. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28259. }
  28260. if ( this.object !== undefined ) {
  28261. _box.setFromObject( this.object );
  28262. }
  28263. if ( _box.isEmpty() ) return;
  28264. const min = _box.min;
  28265. const max = _box.max;
  28266. /*
  28267. 5____4
  28268. 1/___0/|
  28269. | 6__|_7
  28270. 2/___3/
  28271. 0: max.x, max.y, max.z
  28272. 1: min.x, max.y, max.z
  28273. 2: min.x, min.y, max.z
  28274. 3: max.x, min.y, max.z
  28275. 4: max.x, max.y, min.z
  28276. 5: min.x, max.y, min.z
  28277. 6: min.x, min.y, min.z
  28278. 7: max.x, min.y, min.z
  28279. */
  28280. const position = this.geometry.attributes.position;
  28281. const array = position.array;
  28282. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28283. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28284. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28285. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28286. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28287. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28288. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28289. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28290. position.needsUpdate = true;
  28291. this.geometry.computeBoundingSphere();
  28292. }
  28293. setFromObject( object ) {
  28294. this.object = object;
  28295. this.update();
  28296. return this;
  28297. }
  28298. copy( source ) {
  28299. LineSegments.prototype.copy.call( this, source );
  28300. this.object = source.object;
  28301. return this;
  28302. }
  28303. }
  28304. class Box3Helper extends LineSegments {
  28305. constructor( box, color = 0xffff00 ) {
  28306. 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 ] );
  28307. 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 ];
  28308. const geometry = new BufferGeometry();
  28309. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28310. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28311. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28312. this.box = box;
  28313. this.type = 'Box3Helper';
  28314. this.geometry.computeBoundingSphere();
  28315. }
  28316. updateMatrixWorld( force ) {
  28317. const box = this.box;
  28318. if ( box.isEmpty() ) return;
  28319. box.getCenter( this.position );
  28320. box.getSize( this.scale );
  28321. this.scale.multiplyScalar( 0.5 );
  28322. super.updateMatrixWorld( force );
  28323. }
  28324. }
  28325. class PlaneHelper extends Line {
  28326. constructor( plane, size = 1, hex = 0xffff00 ) {
  28327. const color = hex;
  28328. 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, 0, 0, 1, 0, 0, 0 ];
  28329. const geometry = new BufferGeometry();
  28330. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28331. geometry.computeBoundingSphere();
  28332. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28333. this.type = 'PlaneHelper';
  28334. this.plane = plane;
  28335. this.size = size;
  28336. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28337. const geometry2 = new BufferGeometry();
  28338. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28339. geometry2.computeBoundingSphere();
  28340. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28341. }
  28342. updateMatrixWorld( force ) {
  28343. let scale = - this.plane.constant;
  28344. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28345. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28346. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28347. this.lookAt( this.plane.normal );
  28348. super.updateMatrixWorld( force );
  28349. }
  28350. }
  28351. const _axis = /*@__PURE__*/ new Vector3();
  28352. let _lineGeometry, _coneGeometry;
  28353. class ArrowHelper extends Object3D {
  28354. // dir is assumed to be normalized
  28355. 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 ) {
  28356. super();
  28357. this.type = 'ArrowHelper';
  28358. if ( _lineGeometry === undefined ) {
  28359. _lineGeometry = new BufferGeometry();
  28360. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28361. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28362. _coneGeometry.translate( 0, - 0.5, 0 );
  28363. }
  28364. this.position.copy( origin );
  28365. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28366. this.line.matrixAutoUpdate = false;
  28367. this.add( this.line );
  28368. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28369. this.cone.matrixAutoUpdate = false;
  28370. this.add( this.cone );
  28371. this.setDirection( dir );
  28372. this.setLength( length, headLength, headWidth );
  28373. }
  28374. setDirection( dir ) {
  28375. // dir is assumed to be normalized
  28376. if ( dir.y > 0.99999 ) {
  28377. this.quaternion.set( 0, 0, 0, 1 );
  28378. } else if ( dir.y < - 0.99999 ) {
  28379. this.quaternion.set( 1, 0, 0, 0 );
  28380. } else {
  28381. _axis.set( dir.z, 0, - dir.x ).normalize();
  28382. const radians = Math.acos( dir.y );
  28383. this.quaternion.setFromAxisAngle( _axis, radians );
  28384. }
  28385. }
  28386. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28387. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28388. this.line.updateMatrix();
  28389. this.cone.scale.set( headWidth, headLength, headWidth );
  28390. this.cone.position.y = length;
  28391. this.cone.updateMatrix();
  28392. }
  28393. setColor( color ) {
  28394. this.line.material.color.set( color );
  28395. this.cone.material.color.set( color );
  28396. }
  28397. copy( source ) {
  28398. super.copy( source, false );
  28399. this.line.copy( source.line );
  28400. this.cone.copy( source.cone );
  28401. return this;
  28402. }
  28403. }
  28404. class AxesHelper extends LineSegments {
  28405. constructor( size = 1 ) {
  28406. const vertices = [
  28407. 0, 0, 0, size, 0, 0,
  28408. 0, 0, 0, 0, size, 0,
  28409. 0, 0, 0, 0, 0, size
  28410. ];
  28411. const colors = [
  28412. 1, 0, 0, 1, 0.6, 0,
  28413. 0, 1, 0, 0.6, 1, 0,
  28414. 0, 0, 1, 0, 0.6, 1
  28415. ];
  28416. const geometry = new BufferGeometry();
  28417. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28418. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28419. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28420. super( geometry, material );
  28421. this.type = 'AxesHelper';
  28422. }
  28423. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28424. const color = new Color();
  28425. const array = this.geometry.attributes.color.array;
  28426. color.set( xAxisColor );
  28427. color.toArray( array, 0 );
  28428. color.toArray( array, 3 );
  28429. color.set( yAxisColor );
  28430. color.toArray( array, 6 );
  28431. color.toArray( array, 9 );
  28432. color.set( zAxisColor );
  28433. color.toArray( array, 12 );
  28434. color.toArray( array, 15 );
  28435. this.geometry.attributes.color.needsUpdate = true;
  28436. return this;
  28437. }
  28438. dispose() {
  28439. this.geometry.dispose();
  28440. this.material.dispose();
  28441. }
  28442. }
  28443. class ShapePath {
  28444. constructor() {
  28445. this.type = 'ShapePath';
  28446. this.color = new Color();
  28447. this.subPaths = [];
  28448. this.currentPath = null;
  28449. }
  28450. moveTo( x, y ) {
  28451. this.currentPath = new Path();
  28452. this.subPaths.push( this.currentPath );
  28453. this.currentPath.moveTo( x, y );
  28454. return this;
  28455. }
  28456. lineTo( x, y ) {
  28457. this.currentPath.lineTo( x, y );
  28458. return this;
  28459. }
  28460. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  28461. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28462. return this;
  28463. }
  28464. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28465. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28466. return this;
  28467. }
  28468. splineThru( pts ) {
  28469. this.currentPath.splineThru( pts );
  28470. return this;
  28471. }
  28472. toShapes( isCCW, noHoles ) {
  28473. function toShapesNoHoles( inSubpaths ) {
  28474. const shapes = [];
  28475. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28476. const tmpPath = inSubpaths[ i ];
  28477. const tmpShape = new Shape();
  28478. tmpShape.curves = tmpPath.curves;
  28479. shapes.push( tmpShape );
  28480. }
  28481. return shapes;
  28482. }
  28483. function isPointInsidePolygon( inPt, inPolygon ) {
  28484. const polyLen = inPolygon.length;
  28485. // inPt on polygon contour => immediate success or
  28486. // toggling of inside/outside at every single! intersection point of an edge
  28487. // with the horizontal line through inPt, left of inPt
  28488. // not counting lowerY endpoints of edges and whole edges on that line
  28489. let inside = false;
  28490. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28491. let edgeLowPt = inPolygon[ p ];
  28492. let edgeHighPt = inPolygon[ q ];
  28493. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28494. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28495. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28496. // not parallel
  28497. if ( edgeDy < 0 ) {
  28498. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28499. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28500. }
  28501. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28502. if ( inPt.y === edgeLowPt.y ) {
  28503. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28504. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28505. } else {
  28506. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28507. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28508. if ( perpEdge < 0 ) continue;
  28509. inside = ! inside; // true intersection left of inPt
  28510. }
  28511. } else {
  28512. // parallel or collinear
  28513. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28514. // edge lies on the same horizontal line as inPt
  28515. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28516. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28517. // continue;
  28518. }
  28519. }
  28520. return inside;
  28521. }
  28522. const isClockWise = ShapeUtils.isClockWise;
  28523. const subPaths = this.subPaths;
  28524. if ( subPaths.length === 0 ) return [];
  28525. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28526. let solid, tmpPath, tmpShape;
  28527. const shapes = [];
  28528. if ( subPaths.length === 1 ) {
  28529. tmpPath = subPaths[ 0 ];
  28530. tmpShape = new Shape();
  28531. tmpShape.curves = tmpPath.curves;
  28532. shapes.push( tmpShape );
  28533. return shapes;
  28534. }
  28535. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28536. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28537. // console.log("Holes first", holesFirst);
  28538. const betterShapeHoles = [];
  28539. const newShapes = [];
  28540. let newShapeHoles = [];
  28541. let mainIdx = 0;
  28542. let tmpPoints;
  28543. newShapes[ mainIdx ] = undefined;
  28544. newShapeHoles[ mainIdx ] = [];
  28545. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  28546. tmpPath = subPaths[ i ];
  28547. tmpPoints = tmpPath.getPoints();
  28548. solid = isClockWise( tmpPoints );
  28549. solid = isCCW ? ! solid : solid;
  28550. if ( solid ) {
  28551. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28552. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28553. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28554. if ( holesFirst ) mainIdx ++;
  28555. newShapeHoles[ mainIdx ] = [];
  28556. //console.log('cw', i);
  28557. } else {
  28558. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28559. //console.log('ccw', i);
  28560. }
  28561. }
  28562. // only Holes? -> probably all Shapes with wrong orientation
  28563. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28564. if ( newShapes.length > 1 ) {
  28565. let ambiguous = false;
  28566. let toChange = 0;
  28567. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28568. betterShapeHoles[ sIdx ] = [];
  28569. }
  28570. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28571. const sho = newShapeHoles[ sIdx ];
  28572. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28573. const ho = sho[ hIdx ];
  28574. let hole_unassigned = true;
  28575. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28576. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28577. if ( sIdx !== s2Idx ) toChange ++;
  28578. if ( hole_unassigned ) {
  28579. hole_unassigned = false;
  28580. betterShapeHoles[ s2Idx ].push( ho );
  28581. } else {
  28582. ambiguous = true;
  28583. }
  28584. }
  28585. }
  28586. if ( hole_unassigned ) {
  28587. betterShapeHoles[ sIdx ].push( ho );
  28588. }
  28589. }
  28590. }
  28591. if ( toChange > 0 && ambiguous === false ) {
  28592. newShapeHoles = betterShapeHoles;
  28593. }
  28594. }
  28595. let tmpHoles;
  28596. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  28597. tmpShape = newShapes[ i ].s;
  28598. shapes.push( tmpShape );
  28599. tmpHoles = newShapeHoles[ i ];
  28600. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28601. tmpShape.holes.push( tmpHoles[ j ].h );
  28602. }
  28603. }
  28604. //console.log("shape", shapes);
  28605. return shapes;
  28606. }
  28607. }
  28608. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  28609. class DataUtils {
  28610. // float32 to float16
  28611. static toHalfFloat( val ) {
  28612. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  28613. val = clamp( val, - 65504, 65504 );
  28614. _floatView[ 0 ] = val;
  28615. const f = _uint32View[ 0 ];
  28616. const e = ( f >> 23 ) & 0x1ff;
  28617. return _baseTable[ e ] + ( ( f & 0x007fffff ) >> _shiftTable[ e ] );
  28618. }
  28619. // float16 to float32
  28620. static fromHalfFloat( val ) {
  28621. const m = val >> 10;
  28622. _uint32View[ 0 ] = _mantissaTable[ _offsetTable[ m ] + ( val & 0x3ff ) ] + _exponentTable[ m ];
  28623. return _floatView[ 0 ];
  28624. }
  28625. }
  28626. // float32 to float16 helpers
  28627. const _buffer = new ArrayBuffer( 4 );
  28628. const _floatView = new Float32Array( _buffer );
  28629. const _uint32View = new Uint32Array( _buffer );
  28630. const _baseTable = new Uint32Array( 512 );
  28631. const _shiftTable = new Uint32Array( 512 );
  28632. for ( let i = 0; i < 256; ++ i ) {
  28633. const e = i - 127;
  28634. // very small number (0, -0)
  28635. if ( e < - 27 ) {
  28636. _baseTable[ i ] = 0x0000;
  28637. _baseTable[ i | 0x100 ] = 0x8000;
  28638. _shiftTable[ i ] = 24;
  28639. _shiftTable[ i | 0x100 ] = 24;
  28640. // small number (denorm)
  28641. } else if ( e < - 14 ) {
  28642. _baseTable[ i ] = 0x0400 >> ( - e - 14 );
  28643. _baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  28644. _shiftTable[ i ] = - e - 1;
  28645. _shiftTable[ i | 0x100 ] = - e - 1;
  28646. // normal number
  28647. } else if ( e <= 15 ) {
  28648. _baseTable[ i ] = ( e + 15 ) << 10;
  28649. _baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  28650. _shiftTable[ i ] = 13;
  28651. _shiftTable[ i | 0x100 ] = 13;
  28652. // large number (Infinity, -Infinity)
  28653. } else if ( e < 128 ) {
  28654. _baseTable[ i ] = 0x7c00;
  28655. _baseTable[ i | 0x100 ] = 0xfc00;
  28656. _shiftTable[ i ] = 24;
  28657. _shiftTable[ i | 0x100 ] = 24;
  28658. // stay (NaN, Infinity, -Infinity)
  28659. } else {
  28660. _baseTable[ i ] = 0x7c00;
  28661. _baseTable[ i | 0x100 ] = 0xfc00;
  28662. _shiftTable[ i ] = 13;
  28663. _shiftTable[ i | 0x100 ] = 13;
  28664. }
  28665. }
  28666. // float16 to float32 helpers
  28667. const _mantissaTable = new Uint32Array( 2048 );
  28668. const _exponentTable = new Uint32Array( 64 );
  28669. const _offsetTable = new Uint32Array( 64 );
  28670. for ( let i = 1; i < 1024; ++ i ) {
  28671. let m = i << 13; // zero pad mantissa bits
  28672. let e = 0; // zero exponent
  28673. // normalized
  28674. while ( ( m & 0x00800000 ) === 0 ) {
  28675. m <<= 1;
  28676. e -= 0x00800000; // decrement exponent
  28677. }
  28678. m &= ~ 0x00800000; // clear leading 1 bit
  28679. e += 0x38800000; // adjust bias
  28680. _mantissaTable[ i ] = m | e;
  28681. }
  28682. for ( let i = 1024; i < 2048; ++ i ) {
  28683. _mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  28684. }
  28685. for ( let i = 1; i < 31; ++ i ) {
  28686. _exponentTable[ i ] = i << 23;
  28687. }
  28688. _exponentTable[ 31 ] = 0x47800000;
  28689. _exponentTable[ 32 ] = 0x80000000;
  28690. for ( let i = 33; i < 63; ++ i ) {
  28691. _exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  28692. }
  28693. _exponentTable[ 63 ] = 0xc7800000;
  28694. for ( let i = 1; i < 64; ++ i ) {
  28695. if ( i !== 32 ) {
  28696. _offsetTable[ i ] = 1024;
  28697. }
  28698. }
  28699. const LineStrip = 0;
  28700. const LinePieces = 1;
  28701. const NoColors = 0;
  28702. const FaceColors = 1;
  28703. const VertexColors = 2;
  28704. function MeshFaceMaterial( materials ) {
  28705. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  28706. return materials;
  28707. }
  28708. function MultiMaterial( materials = [] ) {
  28709. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  28710. materials.isMultiMaterial = true;
  28711. materials.materials = materials;
  28712. materials.clone = function () {
  28713. return materials.slice();
  28714. };
  28715. return materials;
  28716. }
  28717. class PointCloud extends Points {
  28718. constructor( geometry, material ) {
  28719. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28720. super( geometry, material );
  28721. }
  28722. }
  28723. class Particle extends Sprite {
  28724. constructor( material ) {
  28725. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28726. super( material );
  28727. }
  28728. }
  28729. class ParticleSystem extends Points {
  28730. constructor( geometry, material ) {
  28731. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28732. super( geometry, material );
  28733. }
  28734. }
  28735. class PointCloudMaterial extends PointsMaterial {
  28736. constructor( parameters ) {
  28737. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28738. super( parameters );
  28739. }
  28740. }
  28741. class ParticleBasicMaterial extends PointsMaterial {
  28742. constructor( parameters ) {
  28743. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28744. super( parameters );
  28745. }
  28746. }
  28747. class ParticleSystemMaterial extends PointsMaterial {
  28748. constructor( parameters ) {
  28749. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28750. super( parameters );
  28751. }
  28752. }
  28753. class Vertex extends Vector3 {
  28754. constructor( x, y, z ) {
  28755. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28756. super( x, y, z );
  28757. }
  28758. }
  28759. //
  28760. class DynamicBufferAttribute extends BufferAttribute {
  28761. constructor( array, itemSize ) {
  28762. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  28763. super( array, itemSize );
  28764. this.setUsage( DynamicDrawUsage );
  28765. }
  28766. }
  28767. class Int8Attribute extends Int8BufferAttribute {
  28768. constructor( array, itemSize ) {
  28769. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28770. super( array, itemSize );
  28771. }
  28772. }
  28773. class Uint8Attribute extends Uint8BufferAttribute {
  28774. constructor( array, itemSize ) {
  28775. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28776. super( array, itemSize );
  28777. }
  28778. }
  28779. class Uint8ClampedAttribute extends Uint8ClampedBufferAttribute {
  28780. constructor( array, itemSize ) {
  28781. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28782. super( array, itemSize );
  28783. }
  28784. }
  28785. class Int16Attribute extends Int16BufferAttribute {
  28786. constructor( array, itemSize ) {
  28787. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28788. super( array, itemSize );
  28789. }
  28790. }
  28791. class Uint16Attribute extends Uint16BufferAttribute {
  28792. constructor( array, itemSize ) {
  28793. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28794. super( array, itemSize );
  28795. }
  28796. }
  28797. class Int32Attribute extends Int32BufferAttribute {
  28798. constructor( array, itemSize ) {
  28799. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28800. super( array, itemSize );
  28801. }
  28802. }
  28803. class Uint32Attribute extends Uint32BufferAttribute {
  28804. constructor( array, itemSize ) {
  28805. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28806. super( array, itemSize );
  28807. }
  28808. }
  28809. class Float32Attribute extends Float32BufferAttribute {
  28810. constructor( array, itemSize ) {
  28811. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28812. super( array, itemSize );
  28813. }
  28814. }
  28815. class Float64Attribute extends Float64BufferAttribute {
  28816. constructor( array, itemSize ) {
  28817. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  28818. super( array, itemSize );
  28819. }
  28820. }
  28821. //
  28822. Curve.create = function ( construct, getPoint ) {
  28823. console.log( 'THREE.Curve.create() has been deprecated' );
  28824. construct.prototype = Object.create( Curve.prototype );
  28825. construct.prototype.constructor = construct;
  28826. construct.prototype.getPoint = getPoint;
  28827. return construct;
  28828. };
  28829. //
  28830. Path.prototype.fromPoints = function ( points ) {
  28831. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28832. return this.setFromPoints( points );
  28833. };
  28834. //
  28835. class AxisHelper extends AxesHelper {
  28836. constructor( size ) {
  28837. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28838. super( size );
  28839. }
  28840. }
  28841. class BoundingBoxHelper extends BoxHelper {
  28842. constructor( object, color ) {
  28843. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28844. super( object, color );
  28845. }
  28846. }
  28847. class EdgesHelper extends LineSegments {
  28848. constructor( object, hex ) {
  28849. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28850. super( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28851. }
  28852. }
  28853. GridHelper.prototype.setColors = function () {
  28854. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28855. };
  28856. SkeletonHelper.prototype.update = function () {
  28857. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28858. };
  28859. class WireframeHelper extends LineSegments {
  28860. constructor( object, hex ) {
  28861. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28862. super( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28863. }
  28864. }
  28865. //
  28866. Loader.prototype.extractUrlBase = function ( url ) {
  28867. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28868. return LoaderUtils.extractUrlBase( url );
  28869. };
  28870. Loader.Handlers = {
  28871. add: function ( /* regex, loader */ ) {
  28872. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28873. },
  28874. get: function ( /* file */ ) {
  28875. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28876. }
  28877. };
  28878. class XHRLoader extends FileLoader {
  28879. constructor( manager ) {
  28880. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28881. super( manager );
  28882. }
  28883. }
  28884. class BinaryTextureLoader extends DataTextureLoader {
  28885. constructor( manager ) {
  28886. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28887. super( manager );
  28888. }
  28889. }
  28890. //
  28891. Box2.prototype.center = function ( optionalTarget ) {
  28892. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28893. return this.getCenter( optionalTarget );
  28894. };
  28895. Box2.prototype.empty = function () {
  28896. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28897. return this.isEmpty();
  28898. };
  28899. Box2.prototype.isIntersectionBox = function ( box ) {
  28900. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28901. return this.intersectsBox( box );
  28902. };
  28903. Box2.prototype.size = function ( optionalTarget ) {
  28904. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28905. return this.getSize( optionalTarget );
  28906. };
  28907. //
  28908. Box3.prototype.center = function ( optionalTarget ) {
  28909. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28910. return this.getCenter( optionalTarget );
  28911. };
  28912. Box3.prototype.empty = function () {
  28913. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28914. return this.isEmpty();
  28915. };
  28916. Box3.prototype.isIntersectionBox = function ( box ) {
  28917. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28918. return this.intersectsBox( box );
  28919. };
  28920. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28921. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28922. return this.intersectsSphere( sphere );
  28923. };
  28924. Box3.prototype.size = function ( optionalTarget ) {
  28925. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  28926. return this.getSize( optionalTarget );
  28927. };
  28928. //
  28929. Euler.prototype.toVector3 = function () {
  28930. console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' );
  28931. };
  28932. //
  28933. Sphere.prototype.empty = function () {
  28934. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  28935. return this.isEmpty();
  28936. };
  28937. //
  28938. Frustum.prototype.setFromMatrix = function ( m ) {
  28939. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  28940. return this.setFromProjectionMatrix( m );
  28941. };
  28942. //
  28943. Line3.prototype.center = function ( optionalTarget ) {
  28944. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  28945. return this.getCenter( optionalTarget );
  28946. };
  28947. //
  28948. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  28949. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28950. return this.toArray( array, offset );
  28951. };
  28952. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  28953. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  28954. return vector.applyMatrix3( this );
  28955. };
  28956. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  28957. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  28958. };
  28959. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  28960. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  28961. return attribute.applyMatrix3( this );
  28962. };
  28963. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28964. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  28965. };
  28966. Matrix3.prototype.getInverse = function ( matrix ) {
  28967. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28968. return this.copy( matrix ).invert();
  28969. };
  28970. //
  28971. Matrix4.prototype.extractPosition = function ( m ) {
  28972. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  28973. return this.copyPosition( m );
  28974. };
  28975. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  28976. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28977. return this.toArray( array, offset );
  28978. };
  28979. Matrix4.prototype.getPosition = function () {
  28980. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  28981. return new Vector3().setFromMatrixColumn( this, 3 );
  28982. };
  28983. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  28984. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  28985. return this.makeRotationFromQuaternion( q );
  28986. };
  28987. Matrix4.prototype.multiplyToArray = function () {
  28988. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  28989. };
  28990. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  28991. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28992. return vector.applyMatrix4( this );
  28993. };
  28994. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  28995. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28996. return vector.applyMatrix4( this );
  28997. };
  28998. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  28999. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  29000. };
  29001. Matrix4.prototype.rotateAxis = function ( v ) {
  29002. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29003. v.transformDirection( this );
  29004. };
  29005. Matrix4.prototype.crossVector = function ( vector ) {
  29006. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29007. return vector.applyMatrix4( this );
  29008. };
  29009. Matrix4.prototype.translate = function () {
  29010. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29011. };
  29012. Matrix4.prototype.rotateX = function () {
  29013. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29014. };
  29015. Matrix4.prototype.rotateY = function () {
  29016. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29017. };
  29018. Matrix4.prototype.rotateZ = function () {
  29019. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29020. };
  29021. Matrix4.prototype.rotateByAxis = function () {
  29022. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29023. };
  29024. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  29025. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  29026. return attribute.applyMatrix4( this );
  29027. };
  29028. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  29029. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29030. };
  29031. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  29032. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29033. return this.makePerspective( left, right, top, bottom, near, far );
  29034. };
  29035. Matrix4.prototype.getInverse = function ( matrix ) {
  29036. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29037. return this.copy( matrix ).invert();
  29038. };
  29039. //
  29040. Plane.prototype.isIntersectionLine = function ( line ) {
  29041. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29042. return this.intersectsLine( line );
  29043. };
  29044. //
  29045. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29046. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29047. return vector.applyQuaternion( this );
  29048. };
  29049. Quaternion.prototype.inverse = function ( ) {
  29050. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  29051. return this.invert();
  29052. };
  29053. //
  29054. Ray.prototype.isIntersectionBox = function ( box ) {
  29055. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29056. return this.intersectsBox( box );
  29057. };
  29058. Ray.prototype.isIntersectionPlane = function ( plane ) {
  29059. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29060. return this.intersectsPlane( plane );
  29061. };
  29062. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  29063. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29064. return this.intersectsSphere( sphere );
  29065. };
  29066. //
  29067. Triangle.prototype.area = function () {
  29068. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  29069. return this.getArea();
  29070. };
  29071. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  29072. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29073. return this.getBarycoord( point, target );
  29074. };
  29075. Triangle.prototype.midpoint = function ( target ) {
  29076. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  29077. return this.getMidpoint( target );
  29078. };
  29079. Triangle.prototypenormal = function ( target ) {
  29080. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29081. return this.getNormal( target );
  29082. };
  29083. Triangle.prototype.plane = function ( target ) {
  29084. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  29085. return this.getPlane( target );
  29086. };
  29087. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  29088. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29089. return Triangle.getBarycoord( point, a, b, c, target );
  29090. };
  29091. Triangle.normal = function ( a, b, c, target ) {
  29092. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29093. return Triangle.getNormal( a, b, c, target );
  29094. };
  29095. //
  29096. Shape.prototype.extractAllPoints = function ( divisions ) {
  29097. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  29098. return this.extractPoints( divisions );
  29099. };
  29100. Shape.prototype.extrude = function ( options ) {
  29101. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29102. return new ExtrudeGeometry( this, options );
  29103. };
  29104. Shape.prototype.makeGeometry = function ( options ) {
  29105. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29106. return new ShapeGeometry( this, options );
  29107. };
  29108. //
  29109. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  29110. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29111. return this.fromBufferAttribute( attribute, index, offset );
  29112. };
  29113. Vector2.prototype.distanceToManhattan = function ( v ) {
  29114. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29115. return this.manhattanDistanceTo( v );
  29116. };
  29117. Vector2.prototype.lengthManhattan = function () {
  29118. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  29119. return this.manhattanLength();
  29120. };
  29121. //
  29122. Vector3.prototype.setEulerFromRotationMatrix = function () {
  29123. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29124. };
  29125. Vector3.prototype.setEulerFromQuaternion = function () {
  29126. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29127. };
  29128. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  29129. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29130. return this.setFromMatrixPosition( m );
  29131. };
  29132. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  29133. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29134. return this.setFromMatrixScale( m );
  29135. };
  29136. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  29137. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29138. return this.setFromMatrixColumn( matrix, index );
  29139. };
  29140. Vector3.prototype.applyProjection = function ( m ) {
  29141. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  29142. return this.applyMatrix4( m );
  29143. };
  29144. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  29145. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29146. return this.fromBufferAttribute( attribute, index, offset );
  29147. };
  29148. Vector3.prototype.distanceToManhattan = function ( v ) {
  29149. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29150. return this.manhattanDistanceTo( v );
  29151. };
  29152. Vector3.prototype.lengthManhattan = function () {
  29153. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  29154. return this.manhattanLength();
  29155. };
  29156. //
  29157. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  29158. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29159. return this.fromBufferAttribute( attribute, index, offset );
  29160. };
  29161. Vector4.prototype.lengthManhattan = function () {
  29162. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  29163. return this.manhattanLength();
  29164. };
  29165. //
  29166. Object3D.prototype.getChildByName = function ( name ) {
  29167. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29168. return this.getObjectByName( name );
  29169. };
  29170. Object3D.prototype.renderDepth = function () {
  29171. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29172. };
  29173. Object3D.prototype.translate = function ( distance, axis ) {
  29174. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29175. return this.translateOnAxis( axis, distance );
  29176. };
  29177. Object3D.prototype.getWorldRotation = function () {
  29178. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  29179. };
  29180. Object3D.prototype.applyMatrix = function ( matrix ) {
  29181. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  29182. return this.applyMatrix4( matrix );
  29183. };
  29184. Object.defineProperties( Object3D.prototype, {
  29185. eulerOrder: {
  29186. get: function () {
  29187. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29188. return this.rotation.order;
  29189. },
  29190. set: function ( value ) {
  29191. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29192. this.rotation.order = value;
  29193. }
  29194. },
  29195. useQuaternion: {
  29196. get: function () {
  29197. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29198. },
  29199. set: function () {
  29200. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29201. }
  29202. }
  29203. } );
  29204. Mesh.prototype.setDrawMode = function () {
  29205. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29206. };
  29207. Object.defineProperties( Mesh.prototype, {
  29208. drawMode: {
  29209. get: function () {
  29210. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  29211. return TrianglesDrawMode;
  29212. },
  29213. set: function () {
  29214. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29215. }
  29216. }
  29217. } );
  29218. SkinnedMesh.prototype.initBones = function () {
  29219. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  29220. };
  29221. //
  29222. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29223. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  29224. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  29225. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29226. this.setFocalLength( focalLength );
  29227. };
  29228. //
  29229. Object.defineProperties( Light.prototype, {
  29230. onlyShadow: {
  29231. set: function () {
  29232. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29233. }
  29234. },
  29235. shadowCameraFov: {
  29236. set: function ( value ) {
  29237. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29238. this.shadow.camera.fov = value;
  29239. }
  29240. },
  29241. shadowCameraLeft: {
  29242. set: function ( value ) {
  29243. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29244. this.shadow.camera.left = value;
  29245. }
  29246. },
  29247. shadowCameraRight: {
  29248. set: function ( value ) {
  29249. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29250. this.shadow.camera.right = value;
  29251. }
  29252. },
  29253. shadowCameraTop: {
  29254. set: function ( value ) {
  29255. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29256. this.shadow.camera.top = value;
  29257. }
  29258. },
  29259. shadowCameraBottom: {
  29260. set: function ( value ) {
  29261. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29262. this.shadow.camera.bottom = value;
  29263. }
  29264. },
  29265. shadowCameraNear: {
  29266. set: function ( value ) {
  29267. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29268. this.shadow.camera.near = value;
  29269. }
  29270. },
  29271. shadowCameraFar: {
  29272. set: function ( value ) {
  29273. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29274. this.shadow.camera.far = value;
  29275. }
  29276. },
  29277. shadowCameraVisible: {
  29278. set: function () {
  29279. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29280. }
  29281. },
  29282. shadowBias: {
  29283. set: function ( value ) {
  29284. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29285. this.shadow.bias = value;
  29286. }
  29287. },
  29288. shadowDarkness: {
  29289. set: function () {
  29290. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29291. }
  29292. },
  29293. shadowMapWidth: {
  29294. set: function ( value ) {
  29295. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29296. this.shadow.mapSize.width = value;
  29297. }
  29298. },
  29299. shadowMapHeight: {
  29300. set: function ( value ) {
  29301. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29302. this.shadow.mapSize.height = value;
  29303. }
  29304. }
  29305. } );
  29306. //
  29307. Object.defineProperties( BufferAttribute.prototype, {
  29308. length: {
  29309. get: function () {
  29310. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29311. return this.array.length;
  29312. }
  29313. },
  29314. dynamic: {
  29315. get: function () {
  29316. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29317. return this.usage === DynamicDrawUsage;
  29318. },
  29319. set: function ( /* value */ ) {
  29320. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29321. this.setUsage( DynamicDrawUsage );
  29322. }
  29323. }
  29324. } );
  29325. BufferAttribute.prototype.setDynamic = function ( value ) {
  29326. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29327. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29328. return this;
  29329. };
  29330. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  29331. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  29332. },
  29333. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  29334. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29335. };
  29336. //
  29337. BufferGeometry.prototype.addIndex = function ( index ) {
  29338. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29339. this.setIndex( index );
  29340. };
  29341. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  29342. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  29343. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  29344. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  29345. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  29346. }
  29347. if ( name === 'index' ) {
  29348. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  29349. this.setIndex( attribute );
  29350. return this;
  29351. }
  29352. return this.setAttribute( name, attribute );
  29353. };
  29354. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  29355. if ( indexOffset !== undefined ) {
  29356. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29357. }
  29358. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29359. this.addGroup( start, count );
  29360. };
  29361. BufferGeometry.prototype.clearDrawCalls = function () {
  29362. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29363. this.clearGroups();
  29364. };
  29365. BufferGeometry.prototype.computeOffsets = function () {
  29366. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29367. };
  29368. BufferGeometry.prototype.removeAttribute = function ( name ) {
  29369. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  29370. return this.deleteAttribute( name );
  29371. };
  29372. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  29373. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29374. return this.applyMatrix4( matrix );
  29375. };
  29376. Object.defineProperties( BufferGeometry.prototype, {
  29377. drawcalls: {
  29378. get: function () {
  29379. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29380. return this.groups;
  29381. }
  29382. },
  29383. offsets: {
  29384. get: function () {
  29385. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29386. return this.groups;
  29387. }
  29388. }
  29389. } );
  29390. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  29391. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29392. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29393. return this;
  29394. };
  29395. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  29396. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29397. };
  29398. //
  29399. ExtrudeGeometry.prototype.getArrays = function () {
  29400. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  29401. };
  29402. ExtrudeGeometry.prototype.addShapeList = function () {
  29403. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  29404. };
  29405. ExtrudeGeometry.prototype.addShape = function () {
  29406. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  29407. };
  29408. //
  29409. Scene.prototype.dispose = function () {
  29410. console.error( 'THREE.Scene: .dispose() has been removed.' );
  29411. };
  29412. //
  29413. Uniform.prototype.onUpdate = function () {
  29414. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29415. return this;
  29416. };
  29417. //
  29418. Object.defineProperties( Material.prototype, {
  29419. wrapAround: {
  29420. get: function () {
  29421. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29422. },
  29423. set: function () {
  29424. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29425. }
  29426. },
  29427. overdraw: {
  29428. get: function () {
  29429. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29430. },
  29431. set: function () {
  29432. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29433. }
  29434. },
  29435. wrapRGB: {
  29436. get: function () {
  29437. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  29438. return new Color();
  29439. }
  29440. },
  29441. shading: {
  29442. get: function () {
  29443. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29444. },
  29445. set: function ( value ) {
  29446. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29447. this.flatShading = ( value === FlatShading );
  29448. }
  29449. },
  29450. stencilMask: {
  29451. get: function () {
  29452. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29453. return this.stencilFuncMask;
  29454. },
  29455. set: function ( value ) {
  29456. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29457. this.stencilFuncMask = value;
  29458. }
  29459. },
  29460. vertexTangents: {
  29461. get: function () {
  29462. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29463. },
  29464. set: function () {
  29465. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29466. }
  29467. },
  29468. } );
  29469. Object.defineProperties( ShaderMaterial.prototype, {
  29470. derivatives: {
  29471. get: function () {
  29472. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29473. return this.extensions.derivatives;
  29474. },
  29475. set: function ( value ) {
  29476. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29477. this.extensions.derivatives = value;
  29478. }
  29479. }
  29480. } );
  29481. //
  29482. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  29483. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  29484. this.setRenderTarget( renderTarget );
  29485. this.clear( color, depth, stencil );
  29486. };
  29487. WebGLRenderer.prototype.animate = function ( callback ) {
  29488. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  29489. this.setAnimationLoop( callback );
  29490. };
  29491. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  29492. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  29493. return this.getRenderTarget();
  29494. };
  29495. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  29496. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  29497. return this.capabilities.getMaxAnisotropy();
  29498. };
  29499. WebGLRenderer.prototype.getPrecision = function () {
  29500. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  29501. return this.capabilities.precision;
  29502. };
  29503. WebGLRenderer.prototype.resetGLState = function () {
  29504. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  29505. return this.state.reset();
  29506. };
  29507. WebGLRenderer.prototype.supportsFloatTextures = function () {
  29508. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29509. return this.extensions.get( 'OES_texture_float' );
  29510. };
  29511. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  29512. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29513. return this.extensions.get( 'OES_texture_half_float' );
  29514. };
  29515. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  29516. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29517. return this.extensions.get( 'OES_standard_derivatives' );
  29518. };
  29519. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  29520. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29521. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29522. };
  29523. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  29524. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29525. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29526. };
  29527. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  29528. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29529. return this.extensions.get( 'EXT_blend_minmax' );
  29530. };
  29531. WebGLRenderer.prototype.supportsVertexTextures = function () {
  29532. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29533. return this.capabilities.vertexTextures;
  29534. };
  29535. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  29536. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29537. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29538. };
  29539. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  29540. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29541. this.setScissorTest( boolean );
  29542. };
  29543. WebGLRenderer.prototype.initMaterial = function () {
  29544. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29545. };
  29546. WebGLRenderer.prototype.addPrePlugin = function () {
  29547. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29548. };
  29549. WebGLRenderer.prototype.addPostPlugin = function () {
  29550. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29551. };
  29552. WebGLRenderer.prototype.updateShadowMap = function () {
  29553. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29554. };
  29555. WebGLRenderer.prototype.setFaceCulling = function () {
  29556. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  29557. };
  29558. WebGLRenderer.prototype.allocTextureUnit = function () {
  29559. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  29560. };
  29561. WebGLRenderer.prototype.setTexture = function () {
  29562. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  29563. };
  29564. WebGLRenderer.prototype.setTexture2D = function () {
  29565. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  29566. };
  29567. WebGLRenderer.prototype.setTextureCube = function () {
  29568. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  29569. };
  29570. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29571. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  29572. return this.getActiveMipmapLevel();
  29573. };
  29574. Object.defineProperties( WebGLRenderer.prototype, {
  29575. shadowMapEnabled: {
  29576. get: function () {
  29577. return this.shadowMap.enabled;
  29578. },
  29579. set: function ( value ) {
  29580. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29581. this.shadowMap.enabled = value;
  29582. }
  29583. },
  29584. shadowMapType: {
  29585. get: function () {
  29586. return this.shadowMap.type;
  29587. },
  29588. set: function ( value ) {
  29589. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29590. this.shadowMap.type = value;
  29591. }
  29592. },
  29593. shadowMapCullFace: {
  29594. get: function () {
  29595. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29596. return undefined;
  29597. },
  29598. set: function ( /* value */ ) {
  29599. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29600. }
  29601. },
  29602. context: {
  29603. get: function () {
  29604. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  29605. return this.getContext();
  29606. }
  29607. },
  29608. vr: {
  29609. get: function () {
  29610. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  29611. return this.xr;
  29612. }
  29613. },
  29614. gammaInput: {
  29615. get: function () {
  29616. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29617. return false;
  29618. },
  29619. set: function () {
  29620. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29621. }
  29622. },
  29623. gammaOutput: {
  29624. get: function () {
  29625. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29626. return false;
  29627. },
  29628. set: function ( value ) {
  29629. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29630. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  29631. }
  29632. },
  29633. toneMappingWhitePoint: {
  29634. get: function () {
  29635. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29636. return 1.0;
  29637. },
  29638. set: function () {
  29639. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29640. }
  29641. },
  29642. gammaFactor: {
  29643. get: function () {
  29644. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  29645. return 2;
  29646. },
  29647. set: function () {
  29648. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  29649. }
  29650. }
  29651. } );
  29652. Object.defineProperties( WebGLShadowMap.prototype, {
  29653. cullFace: {
  29654. get: function () {
  29655. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29656. return undefined;
  29657. },
  29658. set: function ( /* cullFace */ ) {
  29659. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29660. }
  29661. },
  29662. renderReverseSided: {
  29663. get: function () {
  29664. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29665. return undefined;
  29666. },
  29667. set: function () {
  29668. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29669. }
  29670. },
  29671. renderSingleSided: {
  29672. get: function () {
  29673. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29674. return undefined;
  29675. },
  29676. set: function () {
  29677. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29678. }
  29679. }
  29680. } );
  29681. class WebGLRenderTargetCube extends WebGLCubeRenderTarget {
  29682. constructor( width, height, options ) {
  29683. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  29684. super( width, options );
  29685. }
  29686. }
  29687. //
  29688. Object.defineProperties( WebGLRenderTarget.prototype, {
  29689. wrapS: {
  29690. get: function () {
  29691. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29692. return this.texture.wrapS;
  29693. },
  29694. set: function ( value ) {
  29695. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29696. this.texture.wrapS = value;
  29697. }
  29698. },
  29699. wrapT: {
  29700. get: function () {
  29701. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29702. return this.texture.wrapT;
  29703. },
  29704. set: function ( value ) {
  29705. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29706. this.texture.wrapT = value;
  29707. }
  29708. },
  29709. magFilter: {
  29710. get: function () {
  29711. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29712. return this.texture.magFilter;
  29713. },
  29714. set: function ( value ) {
  29715. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29716. this.texture.magFilter = value;
  29717. }
  29718. },
  29719. minFilter: {
  29720. get: function () {
  29721. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29722. return this.texture.minFilter;
  29723. },
  29724. set: function ( value ) {
  29725. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29726. this.texture.minFilter = value;
  29727. }
  29728. },
  29729. anisotropy: {
  29730. get: function () {
  29731. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29732. return this.texture.anisotropy;
  29733. },
  29734. set: function ( value ) {
  29735. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29736. this.texture.anisotropy = value;
  29737. }
  29738. },
  29739. offset: {
  29740. get: function () {
  29741. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29742. return this.texture.offset;
  29743. },
  29744. set: function ( value ) {
  29745. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29746. this.texture.offset = value;
  29747. }
  29748. },
  29749. repeat: {
  29750. get: function () {
  29751. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29752. return this.texture.repeat;
  29753. },
  29754. set: function ( value ) {
  29755. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29756. this.texture.repeat = value;
  29757. }
  29758. },
  29759. format: {
  29760. get: function () {
  29761. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29762. return this.texture.format;
  29763. },
  29764. set: function ( value ) {
  29765. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29766. this.texture.format = value;
  29767. }
  29768. },
  29769. type: {
  29770. get: function () {
  29771. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29772. return this.texture.type;
  29773. },
  29774. set: function ( value ) {
  29775. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29776. this.texture.type = value;
  29777. }
  29778. },
  29779. generateMipmaps: {
  29780. get: function () {
  29781. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29782. return this.texture.generateMipmaps;
  29783. },
  29784. set: function ( value ) {
  29785. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29786. this.texture.generateMipmaps = value;
  29787. }
  29788. }
  29789. } );
  29790. //
  29791. Audio.prototype.load = function ( file ) {
  29792. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29793. const scope = this;
  29794. const audioLoader = new AudioLoader();
  29795. audioLoader.load( file, function ( buffer ) {
  29796. scope.setBuffer( buffer );
  29797. } );
  29798. return this;
  29799. };
  29800. AudioAnalyser.prototype.getData = function () {
  29801. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29802. return this.getFrequencyData();
  29803. };
  29804. //
  29805. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29806. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29807. return this.update( renderer, scene );
  29808. };
  29809. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29810. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29811. return this.renderTarget.clear( renderer, color, depth, stencil );
  29812. };
  29813. ImageUtils.crossOrigin = undefined;
  29814. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29815. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29816. const loader = new TextureLoader();
  29817. loader.setCrossOrigin( this.crossOrigin );
  29818. const texture = loader.load( url, onLoad, undefined, onError );
  29819. if ( mapping ) texture.mapping = mapping;
  29820. return texture;
  29821. };
  29822. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29823. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29824. const loader = new CubeTextureLoader();
  29825. loader.setCrossOrigin( this.crossOrigin );
  29826. const texture = loader.load( urls, onLoad, undefined, onError );
  29827. if ( mapping ) texture.mapping = mapping;
  29828. return texture;
  29829. };
  29830. ImageUtils.loadCompressedTexture = function () {
  29831. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29832. };
  29833. ImageUtils.loadCompressedTextureCube = function () {
  29834. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29835. };
  29836. //
  29837. function CanvasRenderer() {
  29838. console.error( 'THREE.CanvasRenderer has been removed' );
  29839. }
  29840. //
  29841. function JSONLoader() {
  29842. console.error( 'THREE.JSONLoader has been removed.' );
  29843. }
  29844. //
  29845. const SceneUtils = {
  29846. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29847. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29848. },
  29849. detach: function ( /* child, parent, scene */ ) {
  29850. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29851. },
  29852. attach: function ( /* child, scene, parent */ ) {
  29853. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29854. }
  29855. };
  29856. //
  29857. function LensFlare() {
  29858. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29859. }
  29860. //
  29861. class ParametricGeometry extends BufferGeometry {
  29862. constructor() {
  29863. console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' );
  29864. super();
  29865. }
  29866. }
  29867. class TextGeometry extends BufferGeometry {
  29868. constructor() {
  29869. console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' );
  29870. super();
  29871. }
  29872. }
  29873. function FontLoader() {
  29874. console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' );
  29875. }
  29876. function Font() {
  29877. console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' );
  29878. }
  29879. function ImmediateRenderObject() {
  29880. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29881. }
  29882. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  29883. constructor( width, height, options ) {
  29884. console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' );
  29885. super( width, height, options );
  29886. this.samples = 4;
  29887. }
  29888. }
  29889. class DataTexture2DArray extends DataArrayTexture {
  29890. constructor( data, width, height, depth ) {
  29891. console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' );
  29892. super( data, width, height, depth );
  29893. }
  29894. }
  29895. class DataTexture3D extends Data3DTexture {
  29896. constructor( data, width, height, depth ) {
  29897. console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' );
  29898. super( data, width, height, depth );
  29899. }
  29900. }
  29901. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29902. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29903. revision: REVISION,
  29904. } } ) );
  29905. }
  29906. if ( typeof window !== 'undefined' ) {
  29907. if ( window.__THREE__ ) {
  29908. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29909. } else {
  29910. window.__THREE__ = REVISION;
  29911. }
  29912. }
  29913. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxGeometry as BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CapsuleGeometry as CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry as DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry as ExtrudeBufferGeometry, ExtrudeGeometry, FaceColors, FileLoader, FlatShading, Float16BufferAttribute, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry as OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneGeometry as PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry as 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, RingGeometry as RingBufferGeometry, RingGeometry, SRGBColorSpace, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry as ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Source, Sphere, SphereGeometry as SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry as TetrahedronBufferGeometry, TetrahedronGeometry, TextGeometry, Texture, TextureLoader, TorusGeometry as TorusBufferGeometry, TorusGeometry, TorusKnotGeometry as TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry as TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };