three.module.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '135';
  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 CubeUVRefractionMapping = 307;
  68. const RepeatWrapping = 1000;
  69. const ClampToEdgeWrapping = 1001;
  70. const MirroredRepeatWrapping = 1002;
  71. const NearestFilter = 1003;
  72. const NearestMipmapNearestFilter = 1004;
  73. const NearestMipMapNearestFilter = 1004;
  74. const NearestMipmapLinearFilter = 1005;
  75. const NearestMipMapLinearFilter = 1005;
  76. const LinearFilter = 1006;
  77. const LinearMipmapNearestFilter = 1007;
  78. const LinearMipMapNearestFilter = 1007;
  79. const LinearMipmapLinearFilter = 1008;
  80. const LinearMipMapLinearFilter = 1008;
  81. const UnsignedByteType = 1009;
  82. const ByteType = 1010;
  83. const ShortType = 1011;
  84. const UnsignedShortType = 1012;
  85. const IntType = 1013;
  86. const UnsignedIntType = 1014;
  87. const FloatType = 1015;
  88. const HalfFloatType = 1016;
  89. const UnsignedShort4444Type = 1017;
  90. const UnsignedShort5551Type = 1018;
  91. const UnsignedShort565Type = 1019;
  92. const UnsignedInt248Type = 1020;
  93. const AlphaFormat = 1021;
  94. const RGBFormat = 1022;
  95. const RGBAFormat = 1023;
  96. const LuminanceFormat = 1024;
  97. const LuminanceAlphaFormat = 1025;
  98. const RGBEFormat = RGBAFormat;
  99. const DepthFormat = 1026;
  100. const DepthStencilFormat = 1027;
  101. const RedFormat = 1028;
  102. const RedIntegerFormat = 1029;
  103. const RGFormat = 1030;
  104. const RGIntegerFormat = 1031;
  105. const RGBIntegerFormat = 1032;
  106. const RGBAIntegerFormat = 1033;
  107. const RGB_S3TC_DXT1_Format = 33776;
  108. const RGBA_S3TC_DXT1_Format = 33777;
  109. const RGBA_S3TC_DXT3_Format = 33778;
  110. const RGBA_S3TC_DXT5_Format = 33779;
  111. const RGB_PVRTC_4BPPV1_Format = 35840;
  112. const RGB_PVRTC_2BPPV1_Format = 35841;
  113. const RGBA_PVRTC_4BPPV1_Format = 35842;
  114. const RGBA_PVRTC_2BPPV1_Format = 35843;
  115. const RGB_ETC1_Format = 36196;
  116. const RGB_ETC2_Format = 37492;
  117. const RGBA_ETC2_EAC_Format = 37496;
  118. const RGBA_ASTC_4x4_Format = 37808;
  119. const RGBA_ASTC_5x4_Format = 37809;
  120. const RGBA_ASTC_5x5_Format = 37810;
  121. const RGBA_ASTC_6x5_Format = 37811;
  122. const RGBA_ASTC_6x6_Format = 37812;
  123. const RGBA_ASTC_8x5_Format = 37813;
  124. const RGBA_ASTC_8x6_Format = 37814;
  125. const RGBA_ASTC_8x8_Format = 37815;
  126. const RGBA_ASTC_10x5_Format = 37816;
  127. const RGBA_ASTC_10x6_Format = 37817;
  128. const RGBA_ASTC_10x8_Format = 37818;
  129. const RGBA_ASTC_10x10_Format = 37819;
  130. const RGBA_ASTC_12x10_Format = 37820;
  131. const RGBA_ASTC_12x12_Format = 37821;
  132. const RGBA_BPTC_Format = 36492;
  133. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  134. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  135. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  136. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  137. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  138. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  139. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  140. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  141. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  142. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  143. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  144. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  145. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  146. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  147. const LoopOnce = 2200;
  148. const LoopRepeat = 2201;
  149. const LoopPingPong = 2202;
  150. const InterpolateDiscrete = 2300;
  151. const InterpolateLinear = 2301;
  152. const InterpolateSmooth = 2302;
  153. const ZeroCurvatureEnding = 2400;
  154. const ZeroSlopeEnding = 2401;
  155. const WrapAroundEnding = 2402;
  156. const NormalAnimationBlendMode = 2500;
  157. const AdditiveAnimationBlendMode = 2501;
  158. const TrianglesDrawMode = 0;
  159. const TriangleStripDrawMode = 1;
  160. const TriangleFanDrawMode = 2;
  161. const LinearEncoding = 3000;
  162. const sRGBEncoding = 3001;
  163. const GammaEncoding = 3007;
  164. const RGBEEncoding = 3002;
  165. const RGBM7Encoding = 3004;
  166. const RGBM16Encoding = 3005;
  167. const RGBDEncoding = 3006;
  168. const BasicDepthPacking = 3200;
  169. const RGBADepthPacking = 3201;
  170. const TangentSpaceNormalMap = 0;
  171. const ObjectSpaceNormalMap = 1;
  172. const ZeroStencilOp = 0;
  173. const KeepStencilOp = 7680;
  174. const ReplaceStencilOp = 7681;
  175. const IncrementStencilOp = 7682;
  176. const DecrementStencilOp = 7683;
  177. const IncrementWrapStencilOp = 34055;
  178. const DecrementWrapStencilOp = 34056;
  179. const InvertStencilOp = 5386;
  180. const NeverStencilFunc = 512;
  181. const LessStencilFunc = 513;
  182. const EqualStencilFunc = 514;
  183. const LessEqualStencilFunc = 515;
  184. const GreaterStencilFunc = 516;
  185. const NotEqualStencilFunc = 517;
  186. const GreaterEqualStencilFunc = 518;
  187. const AlwaysStencilFunc = 519;
  188. const StaticDrawUsage = 35044;
  189. const DynamicDrawUsage = 35048;
  190. const StreamDrawUsage = 35040;
  191. const StaticReadUsage = 35045;
  192. const DynamicReadUsage = 35049;
  193. const StreamReadUsage = 35041;
  194. const StaticCopyUsage = 35046;
  195. const DynamicCopyUsage = 35050;
  196. const StreamCopyUsage = 35042;
  197. const GLSL1 = '100';
  198. const GLSL3 = '300 es';
  199. /**
  200. * https://github.com/mrdoob/eventdispatcher.js/
  201. */
  202. class EventDispatcher {
  203. addEventListener( type, listener ) {
  204. if ( this._listeners === undefined ) this._listeners = {};
  205. const listeners = this._listeners;
  206. if ( listeners[ type ] === undefined ) {
  207. listeners[ type ] = [];
  208. }
  209. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  210. listeners[ type ].push( listener );
  211. }
  212. }
  213. hasEventListener( type, listener ) {
  214. if ( this._listeners === undefined ) return false;
  215. const listeners = this._listeners;
  216. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  217. }
  218. removeEventListener( type, listener ) {
  219. if ( this._listeners === undefined ) return;
  220. const listeners = this._listeners;
  221. const listenerArray = listeners[ type ];
  222. if ( listenerArray !== undefined ) {
  223. const index = listenerArray.indexOf( listener );
  224. if ( index !== - 1 ) {
  225. listenerArray.splice( index, 1 );
  226. }
  227. }
  228. }
  229. dispatchEvent( event ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ event.type ];
  233. if ( listenerArray !== undefined ) {
  234. event.target = this;
  235. // Make a copy, in case listeners are removed while iterating.
  236. const array = listenerArray.slice( 0 );
  237. for ( let i = 0, l = array.length; i < l; i ++ ) {
  238. array[ i ].call( this, event );
  239. }
  240. event.target = null;
  241. }
  242. }
  243. }
  244. const _lut = [];
  245. for ( let i = 0; i < 256; i ++ ) {
  246. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  247. }
  248. let _seed = 1234567;
  249. const DEG2RAD = Math.PI / 180;
  250. const RAD2DEG = 180 / Math.PI;
  251. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  252. function generateUUID() {
  253. const d0 = Math.random() * 0xffffffff | 0;
  254. const d1 = Math.random() * 0xffffffff | 0;
  255. const d2 = Math.random() * 0xffffffff | 0;
  256. const d3 = Math.random() * 0xffffffff | 0;
  257. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  258. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  259. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  260. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  261. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  262. return uuid.toUpperCase();
  263. }
  264. function clamp( value, min, max ) {
  265. return Math.max( min, Math.min( max, value ) );
  266. }
  267. // compute euclidian modulo of m % n
  268. // https://en.wikipedia.org/wiki/Modulo_operation
  269. function euclideanModulo( n, m ) {
  270. return ( ( n % m ) + m ) % m;
  271. }
  272. // Linear mapping from range <a1, a2> to range <b1, b2>
  273. function mapLinear( x, a1, a2, b1, b2 ) {
  274. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  275. }
  276. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  277. function inverseLerp( x, y, value ) {
  278. if ( x !== y ) {
  279. return ( value - x ) / ( y - x );
  280. } else {
  281. return 0;
  282. }
  283. }
  284. // https://en.wikipedia.org/wiki/Linear_interpolation
  285. function lerp( x, y, t ) {
  286. return ( 1 - t ) * x + t * y;
  287. }
  288. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  289. function damp( x, y, lambda, dt ) {
  290. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  291. }
  292. // https://www.desmos.com/calculator/vcsjnyz7x4
  293. function pingpong( x, length = 1 ) {
  294. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  295. }
  296. // http://en.wikipedia.org/wiki/Smoothstep
  297. function smoothstep( x, min, max ) {
  298. if ( x <= min ) return 0;
  299. if ( x >= max ) return 1;
  300. x = ( x - min ) / ( max - min );
  301. return x * x * ( 3 - 2 * x );
  302. }
  303. function smootherstep( x, min, max ) {
  304. if ( x <= min ) return 0;
  305. if ( x >= max ) return 1;
  306. x = ( x - min ) / ( max - min );
  307. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  308. }
  309. // Random integer from <low, high> interval
  310. function randInt( low, high ) {
  311. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  312. }
  313. // Random float from <low, high> interval
  314. function randFloat( low, high ) {
  315. return low + Math.random() * ( high - low );
  316. }
  317. // Random float from <-range/2, range/2> interval
  318. function randFloatSpread( range ) {
  319. return range * ( 0.5 - Math.random() );
  320. }
  321. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  322. function seededRandom( s ) {
  323. if ( s !== undefined ) _seed = s % 2147483647;
  324. // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return ( _seed - 1 ) / 2147483646;
  327. }
  328. function degToRad( degrees ) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg( radians ) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo( value ) {
  335. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo( value ) {
  338. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  339. }
  340. function floorPowerOfTwo( value ) {
  341. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  342. }
  343. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos( b / 2 );
  351. const s2 = sin( b / 2 );
  352. const c13 = cos( ( a + c ) / 2 );
  353. const s13 = sin( ( a + c ) / 2 );
  354. const c1_3 = cos( ( a - c ) / 2 );
  355. const s1_3 = sin( ( a - c ) / 2 );
  356. const c3_1 = cos( ( c - a ) / 2 );
  357. const s3_1 = sin( ( c - a ) / 2 );
  358. switch ( order ) {
  359. case 'XYX':
  360. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  361. break;
  362. case 'YZY':
  363. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  364. break;
  365. case 'ZXZ':
  366. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  367. break;
  368. case 'XZX':
  369. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  370. break;
  371. case 'YXY':
  372. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  373. break;
  374. case 'ZYZ':
  375. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  376. break;
  377. default:
  378. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor( x = 0, y = 0 ) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width( value ) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height( value ) {
  421. this.y = value;
  422. }
  423. set( x, y ) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar( scalar ) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX( x ) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY( y ) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent( index, value ) {
  442. switch ( index ) {
  443. case 0: this.x = value; break;
  444. case 1: this.y = value; break;
  445. default: throw new Error( 'index is out of range: ' + index );
  446. }
  447. return this;
  448. }
  449. getComponent( index ) {
  450. switch ( index ) {
  451. case 0: return this.x;
  452. case 1: return this.y;
  453. default: throw new Error( 'index is out of range: ' + index );
  454. }
  455. }
  456. clone() {
  457. return new this.constructor( this.x, this.y );
  458. }
  459. copy( v ) {
  460. this.x = v.x;
  461. this.y = v.y;
  462. return this;
  463. }
  464. add( v, w ) {
  465. if ( w !== undefined ) {
  466. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  467. return this.addVectors( v, w );
  468. }
  469. this.x += v.x;
  470. this.y += v.y;
  471. return this;
  472. }
  473. addScalar( s ) {
  474. this.x += s;
  475. this.y += s;
  476. return this;
  477. }
  478. addVectors( a, b ) {
  479. this.x = a.x + b.x;
  480. this.y = a.y + b.y;
  481. return this;
  482. }
  483. addScaledVector( v, s ) {
  484. this.x += v.x * s;
  485. this.y += v.y * s;
  486. return this;
  487. }
  488. sub( v, w ) {
  489. if ( w !== undefined ) {
  490. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  491. return this.subVectors( v, w );
  492. }
  493. this.x -= v.x;
  494. this.y -= v.y;
  495. return this;
  496. }
  497. subScalar( s ) {
  498. this.x -= s;
  499. this.y -= s;
  500. return this;
  501. }
  502. subVectors( a, b ) {
  503. this.x = a.x - b.x;
  504. this.y = a.y - b.y;
  505. return this;
  506. }
  507. multiply( v ) {
  508. this.x *= v.x;
  509. this.y *= v.y;
  510. return this;
  511. }
  512. multiplyScalar( scalar ) {
  513. this.x *= scalar;
  514. this.y *= scalar;
  515. return this;
  516. }
  517. divide( v ) {
  518. this.x /= v.x;
  519. this.y /= v.y;
  520. return this;
  521. }
  522. divideScalar( scalar ) {
  523. return this.multiplyScalar( 1 / scalar );
  524. }
  525. applyMatrix3( m ) {
  526. const x = this.x, y = this.y;
  527. const e = m.elements;
  528. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  529. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  530. return this;
  531. }
  532. min( v ) {
  533. this.x = Math.min( this.x, v.x );
  534. this.y = Math.min( this.y, v.y );
  535. return this;
  536. }
  537. max( v ) {
  538. this.x = Math.max( this.x, v.x );
  539. this.y = Math.max( this.y, v.y );
  540. return this;
  541. }
  542. clamp( min, max ) {
  543. // assumes min < max, componentwise
  544. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  545. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  546. return this;
  547. }
  548. clampScalar( minVal, maxVal ) {
  549. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  550. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  551. return this;
  552. }
  553. clampLength( min, max ) {
  554. const length = this.length();
  555. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  556. }
  557. floor() {
  558. this.x = Math.floor( this.x );
  559. this.y = Math.floor( this.y );
  560. return this;
  561. }
  562. ceil() {
  563. this.x = Math.ceil( this.x );
  564. this.y = Math.ceil( this.y );
  565. return this;
  566. }
  567. round() {
  568. this.x = Math.round( this.x );
  569. this.y = Math.round( this.y );
  570. return this;
  571. }
  572. roundToZero() {
  573. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  574. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  575. return this;
  576. }
  577. negate() {
  578. this.x = - this.x;
  579. this.y = - this.y;
  580. return this;
  581. }
  582. dot( v ) {
  583. return this.x * v.x + this.y * v.y;
  584. }
  585. cross( v ) {
  586. return this.x * v.y - this.y * v.x;
  587. }
  588. lengthSq() {
  589. return this.x * this.x + this.y * this.y;
  590. }
  591. length() {
  592. return Math.sqrt( this.x * this.x + this.y * this.y );
  593. }
  594. manhattanLength() {
  595. return Math.abs( this.x ) + Math.abs( this.y );
  596. }
  597. normalize() {
  598. return this.divideScalar( this.length() || 1 );
  599. }
  600. angle() {
  601. // computes the angle in radians with respect to the positive x-axis
  602. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  603. return angle;
  604. }
  605. distanceTo( v ) {
  606. return Math.sqrt( this.distanceToSquared( v ) );
  607. }
  608. distanceToSquared( v ) {
  609. const dx = this.x - v.x, dy = this.y - v.y;
  610. return dx * dx + dy * dy;
  611. }
  612. manhattanDistanceTo( v ) {
  613. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  614. }
  615. setLength( length ) {
  616. return this.normalize().multiplyScalar( length );
  617. }
  618. lerp( v, alpha ) {
  619. this.x += ( v.x - this.x ) * alpha;
  620. this.y += ( v.y - this.y ) * alpha;
  621. return this;
  622. }
  623. lerpVectors( v1, v2, alpha ) {
  624. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  625. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  626. return this;
  627. }
  628. equals( v ) {
  629. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  630. }
  631. fromArray( array, offset = 0 ) {
  632. this.x = array[ offset ];
  633. this.y = array[ offset + 1 ];
  634. return this;
  635. }
  636. toArray( array = [], offset = 0 ) {
  637. array[ offset ] = this.x;
  638. array[ offset + 1 ] = this.y;
  639. return array;
  640. }
  641. fromBufferAttribute( attribute, index, offset ) {
  642. if ( offset !== undefined ) {
  643. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  644. }
  645. this.x = attribute.getX( index );
  646. this.y = attribute.getY( index );
  647. return this;
  648. }
  649. rotateAround( center, angle ) {
  650. const c = Math.cos( angle ), s = Math.sin( angle );
  651. const x = this.x - center.x;
  652. const y = this.y - center.y;
  653. this.x = x * c - y * s + center.x;
  654. this.y = x * s + y * c + center.y;
  655. return this;
  656. }
  657. random() {
  658. this.x = Math.random();
  659. this.y = Math.random();
  660. return this;
  661. }
  662. *[ Symbol.iterator ]() {
  663. yield this.x;
  664. yield this.y;
  665. }
  666. }
  667. Vector2.prototype.isVector2 = true;
  668. class Matrix3 {
  669. constructor() {
  670. this.elements = [
  671. 1, 0, 0,
  672. 0, 1, 0,
  673. 0, 0, 1
  674. ];
  675. if ( arguments.length > 0 ) {
  676. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  677. }
  678. }
  679. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  680. const te = this.elements;
  681. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  682. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  683. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  684. return this;
  685. }
  686. identity() {
  687. this.set(
  688. 1, 0, 0,
  689. 0, 1, 0,
  690. 0, 0, 1
  691. );
  692. return this;
  693. }
  694. copy( m ) {
  695. const te = this.elements;
  696. const me = m.elements;
  697. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  698. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  699. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  700. return this;
  701. }
  702. extractBasis( xAxis, yAxis, zAxis ) {
  703. xAxis.setFromMatrix3Column( this, 0 );
  704. yAxis.setFromMatrix3Column( this, 1 );
  705. zAxis.setFromMatrix3Column( this, 2 );
  706. return this;
  707. }
  708. setFromMatrix4( m ) {
  709. const me = m.elements;
  710. this.set(
  711. me[ 0 ], me[ 4 ], me[ 8 ],
  712. me[ 1 ], me[ 5 ], me[ 9 ],
  713. me[ 2 ], me[ 6 ], me[ 10 ]
  714. );
  715. return this;
  716. }
  717. multiply( m ) {
  718. return this.multiplyMatrices( this, m );
  719. }
  720. premultiply( m ) {
  721. return this.multiplyMatrices( m, this );
  722. }
  723. multiplyMatrices( a, b ) {
  724. const ae = a.elements;
  725. const be = b.elements;
  726. const te = this.elements;
  727. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  728. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  729. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  730. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  731. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  732. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  733. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  734. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  735. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  736. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  737. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  738. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  739. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  740. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  741. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  742. return this;
  743. }
  744. multiplyScalar( s ) {
  745. const te = this.elements;
  746. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  747. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  748. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  749. return this;
  750. }
  751. determinant() {
  752. const te = this.elements;
  753. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  754. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  755. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  756. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  757. }
  758. invert() {
  759. const te = this.elements,
  760. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  761. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  762. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  763. t11 = n33 * n22 - n32 * n23,
  764. t12 = n32 * n13 - n33 * n12,
  765. t13 = n23 * n12 - n22 * n13,
  766. det = n11 * t11 + n21 * t12 + n31 * t13;
  767. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  768. const detInv = 1 / det;
  769. te[ 0 ] = t11 * detInv;
  770. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  771. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  772. te[ 3 ] = t12 * detInv;
  773. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  774. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  775. te[ 6 ] = t13 * detInv;
  776. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  777. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  778. return this;
  779. }
  780. transpose() {
  781. let tmp;
  782. const m = this.elements;
  783. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  784. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  785. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  786. return this;
  787. }
  788. getNormalMatrix( matrix4 ) {
  789. return this.setFromMatrix4( matrix4 ).invert().transpose();
  790. }
  791. transposeIntoArray( r ) {
  792. const m = this.elements;
  793. r[ 0 ] = m[ 0 ];
  794. r[ 1 ] = m[ 3 ];
  795. r[ 2 ] = m[ 6 ];
  796. r[ 3 ] = m[ 1 ];
  797. r[ 4 ] = m[ 4 ];
  798. r[ 5 ] = m[ 7 ];
  799. r[ 6 ] = m[ 2 ];
  800. r[ 7 ] = m[ 5 ];
  801. r[ 8 ] = m[ 8 ];
  802. return this;
  803. }
  804. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  805. const c = Math.cos( rotation );
  806. const s = Math.sin( rotation );
  807. this.set(
  808. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  809. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  810. 0, 0, 1
  811. );
  812. return this;
  813. }
  814. scale( sx, sy ) {
  815. const te = this.elements;
  816. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  817. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  818. return this;
  819. }
  820. rotate( theta ) {
  821. const c = Math.cos( theta );
  822. const s = Math.sin( theta );
  823. const te = this.elements;
  824. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  825. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  826. te[ 0 ] = c * a11 + s * a21;
  827. te[ 3 ] = c * a12 + s * a22;
  828. te[ 6 ] = c * a13 + s * a23;
  829. te[ 1 ] = - s * a11 + c * a21;
  830. te[ 4 ] = - s * a12 + c * a22;
  831. te[ 7 ] = - s * a13 + c * a23;
  832. return this;
  833. }
  834. translate( tx, ty ) {
  835. const te = this.elements;
  836. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  837. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  838. return this;
  839. }
  840. equals( matrix ) {
  841. const te = this.elements;
  842. const me = matrix.elements;
  843. for ( let i = 0; i < 9; i ++ ) {
  844. if ( te[ i ] !== me[ i ] ) return false;
  845. }
  846. return true;
  847. }
  848. fromArray( array, offset = 0 ) {
  849. for ( let i = 0; i < 9; i ++ ) {
  850. this.elements[ i ] = array[ i + offset ];
  851. }
  852. return this;
  853. }
  854. toArray( array = [], offset = 0 ) {
  855. const te = this.elements;
  856. array[ offset ] = te[ 0 ];
  857. array[ offset + 1 ] = te[ 1 ];
  858. array[ offset + 2 ] = te[ 2 ];
  859. array[ offset + 3 ] = te[ 3 ];
  860. array[ offset + 4 ] = te[ 4 ];
  861. array[ offset + 5 ] = te[ 5 ];
  862. array[ offset + 6 ] = te[ 6 ];
  863. array[ offset + 7 ] = te[ 7 ];
  864. array[ offset + 8 ] = te[ 8 ];
  865. return array;
  866. }
  867. clone() {
  868. return new this.constructor().fromArray( this.elements );
  869. }
  870. }
  871. Matrix3.prototype.isMatrix3 = true;
  872. function arrayMax( array ) {
  873. if ( array.length === 0 ) return - Infinity;
  874. let max = array[ 0 ];
  875. for ( let i = 1, l = array.length; i < l; ++ i ) {
  876. if ( array[ i ] > max ) max = array[ i ];
  877. }
  878. return max;
  879. }
  880. const TYPED_ARRAYS = {
  881. Int8Array: Int8Array,
  882. Uint8Array: Uint8Array,
  883. Uint8ClampedArray: Uint8ClampedArray,
  884. Int16Array: Int16Array,
  885. Uint16Array: Uint16Array,
  886. Int32Array: Int32Array,
  887. Uint32Array: Uint32Array,
  888. Float32Array: Float32Array,
  889. Float64Array: Float64Array
  890. };
  891. function getTypedArray( type, buffer ) {
  892. return new TYPED_ARRAYS[ type ]( buffer );
  893. }
  894. function createElementNS( name ) {
  895. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  896. }
  897. /**
  898. * cyrb53 hash for string from: https://stackoverflow.com/a/52171480
  899. *
  900. * Public Domain, @bryc - https://stackoverflow.com/users/815680/bryc
  901. *
  902. * It is roughly similar to the well-known MurmurHash/xxHash algorithms. It uses a combination
  903. * of multiplication and Xorshift to generate the hash, but not as thorough. As a result it's
  904. * faster than either would be in JavaScript and significantly simpler to implement. Keep in
  905. * mind this is not a secure algorithm, if privacy/security is a concern, this is not for you.
  906. *
  907. * @param {string} str
  908. * @param {number} seed, default 0
  909. * @returns number
  910. */
  911. function hashString( str, seed = 0 ) {
  912. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  913. for ( let i = 0, ch; i < str.length; i ++ ) {
  914. ch = str.charCodeAt( i );
  915. h1 = Math.imul( h1 ^ ch, 2654435761 );
  916. h2 = Math.imul( h2 ^ ch, 1597334677 );
  917. }
  918. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 ) ^ Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  919. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 ) ^ Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  920. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  921. }
  922. let _canvas;
  923. class ImageUtils {
  924. static getDataURL( image ) {
  925. if ( /^data:/i.test( image.src ) ) {
  926. return image.src;
  927. }
  928. if ( typeof HTMLCanvasElement == 'undefined' ) {
  929. return image.src;
  930. }
  931. let canvas;
  932. if ( image instanceof HTMLCanvasElement ) {
  933. canvas = image;
  934. } else {
  935. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  936. _canvas.width = image.width;
  937. _canvas.height = image.height;
  938. const context = _canvas.getContext( '2d' );
  939. if ( image instanceof ImageData ) {
  940. context.putImageData( image, 0, 0 );
  941. } else {
  942. context.drawImage( image, 0, 0, image.width, image.height );
  943. }
  944. canvas = _canvas;
  945. }
  946. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  947. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  948. return canvas.toDataURL( 'image/jpeg', 0.6 );
  949. } else {
  950. return canvas.toDataURL( 'image/png' );
  951. }
  952. }
  953. }
  954. let textureId = 0;
  955. class Texture extends EventDispatcher {
  956. 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 ) {
  957. super();
  958. Object.defineProperty( this, 'id', { value: textureId ++ } );
  959. this.uuid = generateUUID();
  960. this.name = '';
  961. this.image = image;
  962. this.mipmaps = [];
  963. this.mapping = mapping;
  964. this.wrapS = wrapS;
  965. this.wrapT = wrapT;
  966. this.magFilter = magFilter;
  967. this.minFilter = minFilter;
  968. this.anisotropy = anisotropy;
  969. this.format = format;
  970. this.internalFormat = null;
  971. this.type = type;
  972. this.offset = new Vector2( 0, 0 );
  973. this.repeat = new Vector2( 1, 1 );
  974. this.center = new Vector2( 0, 0 );
  975. this.rotation = 0;
  976. this.matrixAutoUpdate = true;
  977. this.matrix = new Matrix3();
  978. this.generateMipmaps = true;
  979. this.premultiplyAlpha = false;
  980. this.flipY = true;
  981. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  982. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  983. //
  984. // Also changing the encoding after already used by a Material will not automatically make the Material
  985. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  986. this.encoding = encoding;
  987. this.userData = {};
  988. this.version = 0;
  989. this.onUpdate = null;
  990. this.isRenderTargetTexture = false;
  991. }
  992. updateMatrix() {
  993. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  994. }
  995. clone() {
  996. return new this.constructor().copy( this );
  997. }
  998. copy( source ) {
  999. this.name = source.name;
  1000. this.image = source.image;
  1001. this.mipmaps = source.mipmaps.slice( 0 );
  1002. this.mapping = source.mapping;
  1003. this.wrapS = source.wrapS;
  1004. this.wrapT = source.wrapT;
  1005. this.magFilter = source.magFilter;
  1006. this.minFilter = source.minFilter;
  1007. this.anisotropy = source.anisotropy;
  1008. this.format = source.format;
  1009. this.internalFormat = source.internalFormat;
  1010. this.type = source.type;
  1011. this.offset.copy( source.offset );
  1012. this.repeat.copy( source.repeat );
  1013. this.center.copy( source.center );
  1014. this.rotation = source.rotation;
  1015. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1016. this.matrix.copy( source.matrix );
  1017. this.generateMipmaps = source.generateMipmaps;
  1018. this.premultiplyAlpha = source.premultiplyAlpha;
  1019. this.flipY = source.flipY;
  1020. this.unpackAlignment = source.unpackAlignment;
  1021. this.encoding = source.encoding;
  1022. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1023. return this;
  1024. }
  1025. toJSON( meta ) {
  1026. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1027. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1028. return meta.textures[ this.uuid ];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [ this.repeat.x, this.repeat.y ],
  1040. offset: [ this.offset.x, this.offset.y ],
  1041. center: [ this.center.x, this.center.y ],
  1042. rotation: this.rotation,
  1043. wrap: [ this.wrapS, this.wrapT ],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if ( this.image !== undefined ) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if ( image.uuid === undefined ) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1061. let url;
  1062. if ( Array.isArray( image ) ) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1066. // check cube texture with data textures
  1067. if ( image[ i ].isDataTexture ) {
  1068. url.push( serializeImage( image[ i ].image ) );
  1069. } else {
  1070. url.push( serializeImage( image[ i ] ) );
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage( image );
  1076. }
  1077. meta.images[ image.uuid ] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData;
  1085. if ( ! isRootObject ) {
  1086. meta.textures[ this.uuid ] = output;
  1087. }
  1088. return output;
  1089. }
  1090. dispose() {
  1091. this.dispatchEvent( { type: 'dispose' } );
  1092. }
  1093. transformUv( uv ) {
  1094. if ( this.mapping !== UVMapping ) return uv;
  1095. uv.applyMatrix3( this.matrix );
  1096. if ( uv.x < 0 || uv.x > 1 ) {
  1097. switch ( this.wrapS ) {
  1098. case RepeatWrapping:
  1099. uv.x = uv.x - Math.floor( uv.x );
  1100. break;
  1101. case ClampToEdgeWrapping:
  1102. uv.x = uv.x < 0 ? 0 : 1;
  1103. break;
  1104. case MirroredRepeatWrapping:
  1105. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1106. uv.x = Math.ceil( uv.x ) - uv.x;
  1107. } else {
  1108. uv.x = uv.x - Math.floor( uv.x );
  1109. }
  1110. break;
  1111. }
  1112. }
  1113. if ( uv.y < 0 || uv.y > 1 ) {
  1114. switch ( this.wrapT ) {
  1115. case RepeatWrapping:
  1116. uv.y = uv.y - Math.floor( uv.y );
  1117. break;
  1118. case ClampToEdgeWrapping:
  1119. uv.y = uv.y < 0 ? 0 : 1;
  1120. break;
  1121. case MirroredRepeatWrapping:
  1122. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1123. uv.y = Math.ceil( uv.y ) - uv.y;
  1124. } else {
  1125. uv.y = uv.y - Math.floor( uv.y );
  1126. }
  1127. break;
  1128. }
  1129. }
  1130. if ( this.flipY ) {
  1131. uv.y = 1 - uv.y;
  1132. }
  1133. return uv;
  1134. }
  1135. set needsUpdate( value ) {
  1136. if ( value === true ) this.version ++;
  1137. }
  1138. }
  1139. Texture.DEFAULT_IMAGE = undefined;
  1140. Texture.DEFAULT_MAPPING = UVMapping;
  1141. Texture.prototype.isTexture = true;
  1142. function serializeImage( image ) {
  1143. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1144. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1145. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1146. // default images
  1147. return ImageUtils.getDataURL( image );
  1148. } else {
  1149. if ( image.data ) {
  1150. // images of DataTexture
  1151. return {
  1152. data: Array.prototype.slice.call( image.data ),
  1153. width: image.width,
  1154. height: image.height,
  1155. type: image.data.constructor.name
  1156. };
  1157. } else {
  1158. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1159. return {};
  1160. }
  1161. }
  1162. }
  1163. class Vector4 {
  1164. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1165. this.x = x;
  1166. this.y = y;
  1167. this.z = z;
  1168. this.w = w;
  1169. }
  1170. get width() {
  1171. return this.z;
  1172. }
  1173. set width( value ) {
  1174. this.z = value;
  1175. }
  1176. get height() {
  1177. return this.w;
  1178. }
  1179. set height( value ) {
  1180. this.w = value;
  1181. }
  1182. set( x, y, z, w ) {
  1183. this.x = x;
  1184. this.y = y;
  1185. this.z = z;
  1186. this.w = w;
  1187. return this;
  1188. }
  1189. setScalar( scalar ) {
  1190. this.x = scalar;
  1191. this.y = scalar;
  1192. this.z = scalar;
  1193. this.w = scalar;
  1194. return this;
  1195. }
  1196. setX( x ) {
  1197. this.x = x;
  1198. return this;
  1199. }
  1200. setY( y ) {
  1201. this.y = y;
  1202. return this;
  1203. }
  1204. setZ( z ) {
  1205. this.z = z;
  1206. return this;
  1207. }
  1208. setW( w ) {
  1209. this.w = w;
  1210. return this;
  1211. }
  1212. setComponent( index, value ) {
  1213. switch ( index ) {
  1214. case 0: this.x = value; break;
  1215. case 1: this.y = value; break;
  1216. case 2: this.z = value; break;
  1217. case 3: this.w = value; break;
  1218. default: throw new Error( 'index is out of range: ' + index );
  1219. }
  1220. return this;
  1221. }
  1222. getComponent( index ) {
  1223. switch ( index ) {
  1224. case 0: return this.x;
  1225. case 1: return this.y;
  1226. case 2: return this.z;
  1227. case 3: return this.w;
  1228. default: throw new Error( 'index is out of range: ' + index );
  1229. }
  1230. }
  1231. clone() {
  1232. return new this.constructor( this.x, this.y, this.z, this.w );
  1233. }
  1234. copy( v ) {
  1235. this.x = v.x;
  1236. this.y = v.y;
  1237. this.z = v.z;
  1238. this.w = ( v.w !== undefined ) ? v.w : 1;
  1239. return this;
  1240. }
  1241. add( v, w ) {
  1242. if ( w !== undefined ) {
  1243. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1244. return this.addVectors( v, w );
  1245. }
  1246. this.x += v.x;
  1247. this.y += v.y;
  1248. this.z += v.z;
  1249. this.w += v.w;
  1250. return this;
  1251. }
  1252. addScalar( s ) {
  1253. this.x += s;
  1254. this.y += s;
  1255. this.z += s;
  1256. this.w += s;
  1257. return this;
  1258. }
  1259. addVectors( a, b ) {
  1260. this.x = a.x + b.x;
  1261. this.y = a.y + b.y;
  1262. this.z = a.z + b.z;
  1263. this.w = a.w + b.w;
  1264. return this;
  1265. }
  1266. addScaledVector( v, s ) {
  1267. this.x += v.x * s;
  1268. this.y += v.y * s;
  1269. this.z += v.z * s;
  1270. this.w += v.w * s;
  1271. return this;
  1272. }
  1273. sub( v, w ) {
  1274. if ( w !== undefined ) {
  1275. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1276. return this.subVectors( v, w );
  1277. }
  1278. this.x -= v.x;
  1279. this.y -= v.y;
  1280. this.z -= v.z;
  1281. this.w -= v.w;
  1282. return this;
  1283. }
  1284. subScalar( s ) {
  1285. this.x -= s;
  1286. this.y -= s;
  1287. this.z -= s;
  1288. this.w -= s;
  1289. return this;
  1290. }
  1291. subVectors( a, b ) {
  1292. this.x = a.x - b.x;
  1293. this.y = a.y - b.y;
  1294. this.z = a.z - b.z;
  1295. this.w = a.w - b.w;
  1296. return this;
  1297. }
  1298. multiply( v ) {
  1299. this.x *= v.x;
  1300. this.y *= v.y;
  1301. this.z *= v.z;
  1302. this.w *= v.w;
  1303. return this;
  1304. }
  1305. multiplyScalar( scalar ) {
  1306. this.x *= scalar;
  1307. this.y *= scalar;
  1308. this.z *= scalar;
  1309. this.w *= scalar;
  1310. return this;
  1311. }
  1312. applyMatrix4( m ) {
  1313. const x = this.x, y = this.y, z = this.z, w = this.w;
  1314. const e = m.elements;
  1315. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1316. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1317. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1318. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1319. return this;
  1320. }
  1321. divideScalar( scalar ) {
  1322. return this.multiplyScalar( 1 / scalar );
  1323. }
  1324. setAxisAngleFromQuaternion( q ) {
  1325. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1326. // q is assumed to be normalized
  1327. this.w = 2 * Math.acos( q.w );
  1328. const s = Math.sqrt( 1 - q.w * q.w );
  1329. if ( s < 0.0001 ) {
  1330. this.x = 1;
  1331. this.y = 0;
  1332. this.z = 0;
  1333. } else {
  1334. this.x = q.x / s;
  1335. this.y = q.y / s;
  1336. this.z = q.z / s;
  1337. }
  1338. return this;
  1339. }
  1340. setAxisAngleFromRotationMatrix( m ) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1342. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1343. let angle, x, y, z; // variables for result
  1344. const epsilon = 0.01, // margin to allow for rounding errors
  1345. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1346. te = m.elements,
  1347. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1348. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1349. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1350. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1351. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1352. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1353. // singularity found
  1354. // first check for identity matrix which must have +1 for all terms
  1355. // in leading diagonal and zero in other terms
  1356. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1357. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1358. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1359. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1360. // this singularity is identity matrix so angle = 0
  1361. this.set( 1, 0, 0, 0 );
  1362. return this; // zero angle, arbitrary axis
  1363. }
  1364. // otherwise this singularity is angle = 180
  1365. angle = Math.PI;
  1366. const xx = ( m11 + 1 ) / 2;
  1367. const yy = ( m22 + 1 ) / 2;
  1368. const zz = ( m33 + 1 ) / 2;
  1369. const xy = ( m12 + m21 ) / 4;
  1370. const xz = ( m13 + m31 ) / 4;
  1371. const yz = ( m23 + m32 ) / 4;
  1372. if ( ( xx > yy ) && ( xx > zz ) ) {
  1373. // m11 is the largest diagonal term
  1374. if ( xx < epsilon ) {
  1375. x = 0;
  1376. y = 0.707106781;
  1377. z = 0.707106781;
  1378. } else {
  1379. x = Math.sqrt( xx );
  1380. y = xy / x;
  1381. z = xz / x;
  1382. }
  1383. } else if ( yy > zz ) {
  1384. // m22 is the largest diagonal term
  1385. if ( yy < epsilon ) {
  1386. x = 0.707106781;
  1387. y = 0;
  1388. z = 0.707106781;
  1389. } else {
  1390. y = Math.sqrt( yy );
  1391. x = xy / y;
  1392. z = yz / y;
  1393. }
  1394. } else {
  1395. // m33 is the largest diagonal term so base result on this
  1396. if ( zz < epsilon ) {
  1397. x = 0.707106781;
  1398. y = 0.707106781;
  1399. z = 0;
  1400. } else {
  1401. z = Math.sqrt( zz );
  1402. x = xz / z;
  1403. y = yz / z;
  1404. }
  1405. }
  1406. this.set( x, y, z, angle );
  1407. return this; // return 180 deg rotation
  1408. }
  1409. // as we have reached here there are no singularities so we can handle normally
  1410. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1411. ( m13 - m31 ) * ( m13 - m31 ) +
  1412. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1413. if ( Math.abs( s ) < 0.001 ) s = 1;
  1414. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1415. // caught by singularity test above, but I've left it in just in case
  1416. this.x = ( m32 - m23 ) / s;
  1417. this.y = ( m13 - m31 ) / s;
  1418. this.z = ( m21 - m12 ) / s;
  1419. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1420. return this;
  1421. }
  1422. min( v ) {
  1423. this.x = Math.min( this.x, v.x );
  1424. this.y = Math.min( this.y, v.y );
  1425. this.z = Math.min( this.z, v.z );
  1426. this.w = Math.min( this.w, v.w );
  1427. return this;
  1428. }
  1429. max( v ) {
  1430. this.x = Math.max( this.x, v.x );
  1431. this.y = Math.max( this.y, v.y );
  1432. this.z = Math.max( this.z, v.z );
  1433. this.w = Math.max( this.w, v.w );
  1434. return this;
  1435. }
  1436. clamp( min, max ) {
  1437. // assumes min < max, componentwise
  1438. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1439. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1440. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1441. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1442. return this;
  1443. }
  1444. clampScalar( minVal, maxVal ) {
  1445. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1446. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1447. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1448. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1449. return this;
  1450. }
  1451. clampLength( min, max ) {
  1452. const length = this.length();
  1453. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1454. }
  1455. floor() {
  1456. this.x = Math.floor( this.x );
  1457. this.y = Math.floor( this.y );
  1458. this.z = Math.floor( this.z );
  1459. this.w = Math.floor( this.w );
  1460. return this;
  1461. }
  1462. ceil() {
  1463. this.x = Math.ceil( this.x );
  1464. this.y = Math.ceil( this.y );
  1465. this.z = Math.ceil( this.z );
  1466. this.w = Math.ceil( this.w );
  1467. return this;
  1468. }
  1469. round() {
  1470. this.x = Math.round( this.x );
  1471. this.y = Math.round( this.y );
  1472. this.z = Math.round( this.z );
  1473. this.w = Math.round( this.w );
  1474. return this;
  1475. }
  1476. roundToZero() {
  1477. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1478. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1479. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1480. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1481. return this;
  1482. }
  1483. negate() {
  1484. this.x = - this.x;
  1485. this.y = - this.y;
  1486. this.z = - this.z;
  1487. this.w = - this.w;
  1488. return this;
  1489. }
  1490. dot( v ) {
  1491. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1492. }
  1493. lengthSq() {
  1494. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1495. }
  1496. length() {
  1497. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1498. }
  1499. manhattanLength() {
  1500. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1501. }
  1502. normalize() {
  1503. return this.divideScalar( this.length() || 1 );
  1504. }
  1505. setLength( length ) {
  1506. return this.normalize().multiplyScalar( length );
  1507. }
  1508. lerp( v, alpha ) {
  1509. this.x += ( v.x - this.x ) * alpha;
  1510. this.y += ( v.y - this.y ) * alpha;
  1511. this.z += ( v.z - this.z ) * alpha;
  1512. this.w += ( v.w - this.w ) * alpha;
  1513. return this;
  1514. }
  1515. lerpVectors( v1, v2, alpha ) {
  1516. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1517. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1518. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1519. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1520. return this;
  1521. }
  1522. equals( v ) {
  1523. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1524. }
  1525. fromArray( array, offset = 0 ) {
  1526. this.x = array[ offset ];
  1527. this.y = array[ offset + 1 ];
  1528. this.z = array[ offset + 2 ];
  1529. this.w = array[ offset + 3 ];
  1530. return this;
  1531. }
  1532. toArray( array = [], offset = 0 ) {
  1533. array[ offset ] = this.x;
  1534. array[ offset + 1 ] = this.y;
  1535. array[ offset + 2 ] = this.z;
  1536. array[ offset + 3 ] = this.w;
  1537. return array;
  1538. }
  1539. fromBufferAttribute( attribute, index, offset ) {
  1540. if ( offset !== undefined ) {
  1541. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1542. }
  1543. this.x = attribute.getX( index );
  1544. this.y = attribute.getY( index );
  1545. this.z = attribute.getZ( index );
  1546. this.w = attribute.getW( index );
  1547. return this;
  1548. }
  1549. random() {
  1550. this.x = Math.random();
  1551. this.y = Math.random();
  1552. this.z = Math.random();
  1553. this.w = Math.random();
  1554. return this;
  1555. }
  1556. *[ Symbol.iterator ]() {
  1557. yield this.x;
  1558. yield this.y;
  1559. yield this.z;
  1560. yield this.w;
  1561. }
  1562. }
  1563. Vector4.prototype.isVector4 = true;
  1564. /*
  1565. In options, we can specify:
  1566. * Texture parameters for an auto-generated target texture
  1567. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1568. */
  1569. class WebGLRenderTarget extends EventDispatcher {
  1570. constructor( width, height, options = {} ) {
  1571. super();
  1572. this.width = width;
  1573. this.height = height;
  1574. this.depth = 1;
  1575. this.scissor = new Vector4( 0, 0, width, height );
  1576. this.scissorTest = false;
  1577. this.viewport = new Vector4( 0, 0, width, height );
  1578. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1579. this.texture.isRenderTargetTexture = true;
  1580. this.texture.image = { width: width, height: height, depth: 1 };
  1581. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1582. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1583. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1584. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1585. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1586. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1587. }
  1588. setTexture( texture ) {
  1589. texture.image = {
  1590. width: this.width,
  1591. height: this.height,
  1592. depth: this.depth
  1593. };
  1594. this.texture = texture;
  1595. }
  1596. setSize( width, height, depth = 1 ) {
  1597. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1598. this.width = width;
  1599. this.height = height;
  1600. this.depth = depth;
  1601. this.texture.image.width = width;
  1602. this.texture.image.height = height;
  1603. this.texture.image.depth = depth;
  1604. this.dispose();
  1605. }
  1606. this.viewport.set( 0, 0, width, height );
  1607. this.scissor.set( 0, 0, width, height );
  1608. }
  1609. clone() {
  1610. return new this.constructor().copy( this );
  1611. }
  1612. copy( source ) {
  1613. this.width = source.width;
  1614. this.height = source.height;
  1615. this.depth = source.depth;
  1616. this.viewport.copy( source.viewport );
  1617. this.texture = source.texture.clone();
  1618. this.texture.image = { ...this.texture.image }; // See #20328.
  1619. this.depthBuffer = source.depthBuffer;
  1620. this.stencilBuffer = source.stencilBuffer;
  1621. this.depthTexture = source.depthTexture;
  1622. return this;
  1623. }
  1624. dispose() {
  1625. this.dispatchEvent( { type: 'dispose' } );
  1626. }
  1627. }
  1628. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1629. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1630. constructor( width, height, count ) {
  1631. super( width, height );
  1632. const texture = this.texture;
  1633. this.texture = [];
  1634. for ( let i = 0; i < count; i ++ ) {
  1635. this.texture[ i ] = texture.clone();
  1636. }
  1637. }
  1638. setSize( width, height, depth = 1 ) {
  1639. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1640. this.width = width;
  1641. this.height = height;
  1642. this.depth = depth;
  1643. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1644. this.texture[ i ].image.width = width;
  1645. this.texture[ i ].image.height = height;
  1646. this.texture[ i ].image.depth = depth;
  1647. }
  1648. this.dispose();
  1649. }
  1650. this.viewport.set( 0, 0, width, height );
  1651. this.scissor.set( 0, 0, width, height );
  1652. return this;
  1653. }
  1654. copy( source ) {
  1655. this.dispose();
  1656. this.width = source.width;
  1657. this.height = source.height;
  1658. this.depth = source.depth;
  1659. this.viewport.set( 0, 0, this.width, this.height );
  1660. this.scissor.set( 0, 0, this.width, this.height );
  1661. this.depthBuffer = source.depthBuffer;
  1662. this.stencilBuffer = source.stencilBuffer;
  1663. this.depthTexture = source.depthTexture;
  1664. this.texture.length = 0;
  1665. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1666. this.texture[ i ] = source.texture[ i ].clone();
  1667. }
  1668. return this;
  1669. }
  1670. }
  1671. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1672. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1673. constructor( width, height, options = {} ) {
  1674. super( width, height, options );
  1675. this.samples = 4;
  1676. this.ignoreDepthForMultisampleCopy = options.ignoreDepth !== undefined ? options.ignoreDepth : true;
  1677. this.useRenderToTexture = ( options.useRenderToTexture !== undefined ) ? options.useRenderToTexture : false;
  1678. this.useRenderbuffer = this.useRenderToTexture === false;
  1679. }
  1680. copy( source ) {
  1681. super.copy.call( this, source );
  1682. this.samples = source.samples;
  1683. this.useRenderToTexture = source.useRenderToTexture;
  1684. this.useRenderbuffer = source.useRenderbuffer;
  1685. return this;
  1686. }
  1687. }
  1688. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1689. class Quaternion {
  1690. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1691. this._x = x;
  1692. this._y = y;
  1693. this._z = z;
  1694. this._w = w;
  1695. }
  1696. static slerp( qa, qb, qm, t ) {
  1697. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  1698. return qm.slerpQuaternions( qa, qb, t );
  1699. }
  1700. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1701. // fuzz-free, array-based Quaternion SLERP operation
  1702. let x0 = src0[ srcOffset0 + 0 ],
  1703. y0 = src0[ srcOffset0 + 1 ],
  1704. z0 = src0[ srcOffset0 + 2 ],
  1705. w0 = src0[ srcOffset0 + 3 ];
  1706. const x1 = src1[ srcOffset1 + 0 ],
  1707. y1 = src1[ srcOffset1 + 1 ],
  1708. z1 = src1[ srcOffset1 + 2 ],
  1709. w1 = src1[ srcOffset1 + 3 ];
  1710. if ( t === 0 ) {
  1711. dst[ dstOffset + 0 ] = x0;
  1712. dst[ dstOffset + 1 ] = y0;
  1713. dst[ dstOffset + 2 ] = z0;
  1714. dst[ dstOffset + 3 ] = w0;
  1715. return;
  1716. }
  1717. if ( t === 1 ) {
  1718. dst[ dstOffset + 0 ] = x1;
  1719. dst[ dstOffset + 1 ] = y1;
  1720. dst[ dstOffset + 2 ] = z1;
  1721. dst[ dstOffset + 3 ] = w1;
  1722. return;
  1723. }
  1724. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1725. let s = 1 - t;
  1726. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1727. dir = ( cos >= 0 ? 1 : - 1 ),
  1728. sqrSin = 1 - cos * cos;
  1729. // Skip the Slerp for tiny steps to avoid numeric problems:
  1730. if ( sqrSin > Number.EPSILON ) {
  1731. const sin = Math.sqrt( sqrSin ),
  1732. len = Math.atan2( sin, cos * dir );
  1733. s = Math.sin( s * len ) / sin;
  1734. t = Math.sin( t * len ) / sin;
  1735. }
  1736. const tDir = t * dir;
  1737. x0 = x0 * s + x1 * tDir;
  1738. y0 = y0 * s + y1 * tDir;
  1739. z0 = z0 * s + z1 * tDir;
  1740. w0 = w0 * s + w1 * tDir;
  1741. // Normalize in case we just did a lerp:
  1742. if ( s === 1 - t ) {
  1743. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1744. x0 *= f;
  1745. y0 *= f;
  1746. z0 *= f;
  1747. w0 *= f;
  1748. }
  1749. }
  1750. dst[ dstOffset ] = x0;
  1751. dst[ dstOffset + 1 ] = y0;
  1752. dst[ dstOffset + 2 ] = z0;
  1753. dst[ dstOffset + 3 ] = w0;
  1754. }
  1755. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1756. const x0 = src0[ srcOffset0 ];
  1757. const y0 = src0[ srcOffset0 + 1 ];
  1758. const z0 = src0[ srcOffset0 + 2 ];
  1759. const w0 = src0[ srcOffset0 + 3 ];
  1760. const x1 = src1[ srcOffset1 ];
  1761. const y1 = src1[ srcOffset1 + 1 ];
  1762. const z1 = src1[ srcOffset1 + 2 ];
  1763. const w1 = src1[ srcOffset1 + 3 ];
  1764. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1765. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1766. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1767. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1768. return dst;
  1769. }
  1770. get x() {
  1771. return this._x;
  1772. }
  1773. set x( value ) {
  1774. this._x = value;
  1775. this._onChangeCallback();
  1776. }
  1777. get y() {
  1778. return this._y;
  1779. }
  1780. set y( value ) {
  1781. this._y = value;
  1782. this._onChangeCallback();
  1783. }
  1784. get z() {
  1785. return this._z;
  1786. }
  1787. set z( value ) {
  1788. this._z = value;
  1789. this._onChangeCallback();
  1790. }
  1791. get w() {
  1792. return this._w;
  1793. }
  1794. set w( value ) {
  1795. this._w = value;
  1796. this._onChangeCallback();
  1797. }
  1798. set( x, y, z, w ) {
  1799. this._x = x;
  1800. this._y = y;
  1801. this._z = z;
  1802. this._w = w;
  1803. this._onChangeCallback();
  1804. return this;
  1805. }
  1806. clone() {
  1807. return new this.constructor( this._x, this._y, this._z, this._w );
  1808. }
  1809. copy( quaternion ) {
  1810. this._x = quaternion.x;
  1811. this._y = quaternion.y;
  1812. this._z = quaternion.z;
  1813. this._w = quaternion.w;
  1814. this._onChangeCallback();
  1815. return this;
  1816. }
  1817. setFromEuler( euler, update ) {
  1818. if ( ! ( euler && euler.isEuler ) ) {
  1819. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1820. }
  1821. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1822. // http://www.mathworks.com/matlabcentral/fileexchange/
  1823. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1824. // content/SpinCalc.m
  1825. const cos = Math.cos;
  1826. const sin = Math.sin;
  1827. const c1 = cos( x / 2 );
  1828. const c2 = cos( y / 2 );
  1829. const c3 = cos( z / 2 );
  1830. const s1 = sin( x / 2 );
  1831. const s2 = sin( y / 2 );
  1832. const s3 = sin( z / 2 );
  1833. switch ( order ) {
  1834. case 'XYZ':
  1835. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1836. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1837. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1838. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1839. break;
  1840. case 'YXZ':
  1841. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1842. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1843. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1844. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1845. break;
  1846. case 'ZXY':
  1847. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1848. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1849. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1850. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1851. break;
  1852. case 'ZYX':
  1853. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1854. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1855. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1856. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1857. break;
  1858. case 'YZX':
  1859. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1860. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1861. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1862. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1863. break;
  1864. case 'XZY':
  1865. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1866. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1867. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1868. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1869. break;
  1870. default:
  1871. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1872. }
  1873. if ( update !== false ) this._onChangeCallback();
  1874. return this;
  1875. }
  1876. setFromAxisAngle( axis, angle ) {
  1877. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1878. // assumes axis is normalized
  1879. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1880. this._x = axis.x * s;
  1881. this._y = axis.y * s;
  1882. this._z = axis.z * s;
  1883. this._w = Math.cos( halfAngle );
  1884. this._onChangeCallback();
  1885. return this;
  1886. }
  1887. setFromRotationMatrix( m ) {
  1888. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1889. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1890. const te = m.elements,
  1891. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1892. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1893. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1894. trace = m11 + m22 + m33;
  1895. if ( trace > 0 ) {
  1896. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1897. this._w = 0.25 / s;
  1898. this._x = ( m32 - m23 ) * s;
  1899. this._y = ( m13 - m31 ) * s;
  1900. this._z = ( m21 - m12 ) * s;
  1901. } else if ( m11 > m22 && m11 > m33 ) {
  1902. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1903. this._w = ( m32 - m23 ) / s;
  1904. this._x = 0.25 * s;
  1905. this._y = ( m12 + m21 ) / s;
  1906. this._z = ( m13 + m31 ) / s;
  1907. } else if ( m22 > m33 ) {
  1908. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1909. this._w = ( m13 - m31 ) / s;
  1910. this._x = ( m12 + m21 ) / s;
  1911. this._y = 0.25 * s;
  1912. this._z = ( m23 + m32 ) / s;
  1913. } else {
  1914. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1915. this._w = ( m21 - m12 ) / s;
  1916. this._x = ( m13 + m31 ) / s;
  1917. this._y = ( m23 + m32 ) / s;
  1918. this._z = 0.25 * s;
  1919. }
  1920. this._onChangeCallback();
  1921. return this;
  1922. }
  1923. setFromUnitVectors( vFrom, vTo ) {
  1924. // assumes direction vectors vFrom and vTo are normalized
  1925. let r = vFrom.dot( vTo ) + 1;
  1926. if ( r < Number.EPSILON ) {
  1927. // vFrom and vTo point in opposite directions
  1928. r = 0;
  1929. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1930. this._x = - vFrom.y;
  1931. this._y = vFrom.x;
  1932. this._z = 0;
  1933. this._w = r;
  1934. } else {
  1935. this._x = 0;
  1936. this._y = - vFrom.z;
  1937. this._z = vFrom.y;
  1938. this._w = r;
  1939. }
  1940. } else {
  1941. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1942. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1943. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1944. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1945. this._w = r;
  1946. }
  1947. return this.normalize();
  1948. }
  1949. angleTo( q ) {
  1950. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1951. }
  1952. rotateTowards( q, step ) {
  1953. const angle = this.angleTo( q );
  1954. if ( angle === 0 ) return this;
  1955. const t = Math.min( 1, step / angle );
  1956. this.slerp( q, t );
  1957. return this;
  1958. }
  1959. identity() {
  1960. return this.set( 0, 0, 0, 1 );
  1961. }
  1962. invert() {
  1963. // quaternion is assumed to have unit length
  1964. return this.conjugate();
  1965. }
  1966. conjugate() {
  1967. this._x *= - 1;
  1968. this._y *= - 1;
  1969. this._z *= - 1;
  1970. this._onChangeCallback();
  1971. return this;
  1972. }
  1973. dot( v ) {
  1974. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1975. }
  1976. lengthSq() {
  1977. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1978. }
  1979. length() {
  1980. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1981. }
  1982. normalize() {
  1983. let l = this.length();
  1984. if ( l === 0 ) {
  1985. this._x = 0;
  1986. this._y = 0;
  1987. this._z = 0;
  1988. this._w = 1;
  1989. } else {
  1990. l = 1 / l;
  1991. this._x = this._x * l;
  1992. this._y = this._y * l;
  1993. this._z = this._z * l;
  1994. this._w = this._w * l;
  1995. }
  1996. this._onChangeCallback();
  1997. return this;
  1998. }
  1999. multiply( q, p ) {
  2000. if ( p !== undefined ) {
  2001. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2002. return this.multiplyQuaternions( q, p );
  2003. }
  2004. return this.multiplyQuaternions( this, q );
  2005. }
  2006. premultiply( q ) {
  2007. return this.multiplyQuaternions( q, this );
  2008. }
  2009. multiplyQuaternions( a, b ) {
  2010. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2011. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2012. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2013. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2014. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2015. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2016. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2017. this._onChangeCallback();
  2018. return this;
  2019. }
  2020. slerp( qb, t ) {
  2021. if ( t === 0 ) return this;
  2022. if ( t === 1 ) return this.copy( qb );
  2023. const x = this._x, y = this._y, z = this._z, w = this._w;
  2024. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2025. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2026. if ( cosHalfTheta < 0 ) {
  2027. this._w = - qb._w;
  2028. this._x = - qb._x;
  2029. this._y = - qb._y;
  2030. this._z = - qb._z;
  2031. cosHalfTheta = - cosHalfTheta;
  2032. } else {
  2033. this.copy( qb );
  2034. }
  2035. if ( cosHalfTheta >= 1.0 ) {
  2036. this._w = w;
  2037. this._x = x;
  2038. this._y = y;
  2039. this._z = z;
  2040. return this;
  2041. }
  2042. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2043. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2044. const s = 1 - t;
  2045. this._w = s * w + t * this._w;
  2046. this._x = s * x + t * this._x;
  2047. this._y = s * y + t * this._y;
  2048. this._z = s * z + t * this._z;
  2049. this.normalize();
  2050. this._onChangeCallback();
  2051. return this;
  2052. }
  2053. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2054. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2055. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2056. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2057. this._w = ( w * ratioA + this._w * ratioB );
  2058. this._x = ( x * ratioA + this._x * ratioB );
  2059. this._y = ( y * ratioA + this._y * ratioB );
  2060. this._z = ( z * ratioA + this._z * ratioB );
  2061. this._onChangeCallback();
  2062. return this;
  2063. }
  2064. slerpQuaternions( qa, qb, t ) {
  2065. this.copy( qa ).slerp( qb, t );
  2066. }
  2067. random() {
  2068. // Derived from http://planning.cs.uiuc.edu/node198.html
  2069. // Note, this source uses w, x, y, z ordering,
  2070. // so we swap the order below.
  2071. const u1 = Math.random();
  2072. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2073. const sqrtu1 = Math.sqrt( u1 );
  2074. const u2 = 2 * Math.PI * Math.random();
  2075. const u3 = 2 * Math.PI * Math.random();
  2076. return this.set(
  2077. sqrt1u1 * Math.cos( u2 ),
  2078. sqrtu1 * Math.sin( u3 ),
  2079. sqrtu1 * Math.cos( u3 ),
  2080. sqrt1u1 * Math.sin( u2 ),
  2081. );
  2082. }
  2083. equals( quaternion ) {
  2084. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2085. }
  2086. fromArray( array, offset = 0 ) {
  2087. this._x = array[ offset ];
  2088. this._y = array[ offset + 1 ];
  2089. this._z = array[ offset + 2 ];
  2090. this._w = array[ offset + 3 ];
  2091. this._onChangeCallback();
  2092. return this;
  2093. }
  2094. toArray( array = [], offset = 0 ) {
  2095. array[ offset ] = this._x;
  2096. array[ offset + 1 ] = this._y;
  2097. array[ offset + 2 ] = this._z;
  2098. array[ offset + 3 ] = this._w;
  2099. return array;
  2100. }
  2101. fromBufferAttribute( attribute, index ) {
  2102. this._x = attribute.getX( index );
  2103. this._y = attribute.getY( index );
  2104. this._z = attribute.getZ( index );
  2105. this._w = attribute.getW( index );
  2106. return this;
  2107. }
  2108. _onChange( callback ) {
  2109. this._onChangeCallback = callback;
  2110. return this;
  2111. }
  2112. _onChangeCallback() {}
  2113. }
  2114. Quaternion.prototype.isQuaternion = true;
  2115. class Vector3 {
  2116. constructor( x = 0, y = 0, z = 0 ) {
  2117. this.x = x;
  2118. this.y = y;
  2119. this.z = z;
  2120. }
  2121. set( x, y, z ) {
  2122. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2123. this.x = x;
  2124. this.y = y;
  2125. this.z = z;
  2126. return this;
  2127. }
  2128. setScalar( scalar ) {
  2129. this.x = scalar;
  2130. this.y = scalar;
  2131. this.z = scalar;
  2132. return this;
  2133. }
  2134. setX( x ) {
  2135. this.x = x;
  2136. return this;
  2137. }
  2138. setY( y ) {
  2139. this.y = y;
  2140. return this;
  2141. }
  2142. setZ( z ) {
  2143. this.z = z;
  2144. return this;
  2145. }
  2146. setComponent( index, value ) {
  2147. switch ( index ) {
  2148. case 0: this.x = value; break;
  2149. case 1: this.y = value; break;
  2150. case 2: this.z = value; break;
  2151. default: throw new Error( 'index is out of range: ' + index );
  2152. }
  2153. return this;
  2154. }
  2155. getComponent( index ) {
  2156. switch ( index ) {
  2157. case 0: return this.x;
  2158. case 1: return this.y;
  2159. case 2: return this.z;
  2160. default: throw new Error( 'index is out of range: ' + index );
  2161. }
  2162. }
  2163. clone() {
  2164. return new this.constructor( this.x, this.y, this.z );
  2165. }
  2166. copy( v ) {
  2167. this.x = v.x;
  2168. this.y = v.y;
  2169. this.z = v.z;
  2170. return this;
  2171. }
  2172. add( v, w ) {
  2173. if ( w !== undefined ) {
  2174. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2175. return this.addVectors( v, w );
  2176. }
  2177. this.x += v.x;
  2178. this.y += v.y;
  2179. this.z += v.z;
  2180. return this;
  2181. }
  2182. addScalar( s ) {
  2183. this.x += s;
  2184. this.y += s;
  2185. this.z += s;
  2186. return this;
  2187. }
  2188. addVectors( a, b ) {
  2189. this.x = a.x + b.x;
  2190. this.y = a.y + b.y;
  2191. this.z = a.z + b.z;
  2192. return this;
  2193. }
  2194. addScaledVector( v, s ) {
  2195. this.x += v.x * s;
  2196. this.y += v.y * s;
  2197. this.z += v.z * s;
  2198. return this;
  2199. }
  2200. sub( v, w ) {
  2201. if ( w !== undefined ) {
  2202. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2203. return this.subVectors( v, w );
  2204. }
  2205. this.x -= v.x;
  2206. this.y -= v.y;
  2207. this.z -= v.z;
  2208. return this;
  2209. }
  2210. subScalar( s ) {
  2211. this.x -= s;
  2212. this.y -= s;
  2213. this.z -= s;
  2214. return this;
  2215. }
  2216. subVectors( a, b ) {
  2217. this.x = a.x - b.x;
  2218. this.y = a.y - b.y;
  2219. this.z = a.z - b.z;
  2220. return this;
  2221. }
  2222. multiply( v, w ) {
  2223. if ( w !== undefined ) {
  2224. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2225. return this.multiplyVectors( v, w );
  2226. }
  2227. this.x *= v.x;
  2228. this.y *= v.y;
  2229. this.z *= v.z;
  2230. return this;
  2231. }
  2232. multiplyScalar( scalar ) {
  2233. this.x *= scalar;
  2234. this.y *= scalar;
  2235. this.z *= scalar;
  2236. return this;
  2237. }
  2238. multiplyVectors( a, b ) {
  2239. this.x = a.x * b.x;
  2240. this.y = a.y * b.y;
  2241. this.z = a.z * b.z;
  2242. return this;
  2243. }
  2244. applyEuler( euler ) {
  2245. if ( ! ( euler && euler.isEuler ) ) {
  2246. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2247. }
  2248. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2249. }
  2250. applyAxisAngle( axis, angle ) {
  2251. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2252. }
  2253. applyMatrix3( m ) {
  2254. const x = this.x, y = this.y, z = this.z;
  2255. const e = m.elements;
  2256. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2257. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2258. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2259. return this;
  2260. }
  2261. applyNormalMatrix( m ) {
  2262. return this.applyMatrix3( m ).normalize();
  2263. }
  2264. applyMatrix4( m ) {
  2265. const x = this.x, y = this.y, z = this.z;
  2266. const e = m.elements;
  2267. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2268. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2269. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2270. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2271. return this;
  2272. }
  2273. applyQuaternion( q ) {
  2274. const x = this.x, y = this.y, z = this.z;
  2275. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2276. // calculate quat * vector
  2277. const ix = qw * x + qy * z - qz * y;
  2278. const iy = qw * y + qz * x - qx * z;
  2279. const iz = qw * z + qx * y - qy * x;
  2280. const iw = - qx * x - qy * y - qz * z;
  2281. // calculate result * inverse quat
  2282. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2283. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2284. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2285. return this;
  2286. }
  2287. project( camera ) {
  2288. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2289. }
  2290. unproject( camera ) {
  2291. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2292. }
  2293. transformDirection( m ) {
  2294. // input: THREE.Matrix4 affine matrix
  2295. // vector interpreted as a direction
  2296. const x = this.x, y = this.y, z = this.z;
  2297. const e = m.elements;
  2298. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2299. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2300. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2301. return this.normalize();
  2302. }
  2303. divide( v ) {
  2304. this.x /= v.x;
  2305. this.y /= v.y;
  2306. this.z /= v.z;
  2307. return this;
  2308. }
  2309. divideScalar( scalar ) {
  2310. return this.multiplyScalar( 1 / scalar );
  2311. }
  2312. min( v ) {
  2313. this.x = Math.min( this.x, v.x );
  2314. this.y = Math.min( this.y, v.y );
  2315. this.z = Math.min( this.z, v.z );
  2316. return this;
  2317. }
  2318. max( v ) {
  2319. this.x = Math.max( this.x, v.x );
  2320. this.y = Math.max( this.y, v.y );
  2321. this.z = Math.max( this.z, v.z );
  2322. return this;
  2323. }
  2324. clamp( min, max ) {
  2325. // assumes min < max, componentwise
  2326. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2327. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2328. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2329. return this;
  2330. }
  2331. clampScalar( minVal, maxVal ) {
  2332. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2333. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2334. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2335. return this;
  2336. }
  2337. clampLength( min, max ) {
  2338. const length = this.length();
  2339. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2340. }
  2341. floor() {
  2342. this.x = Math.floor( this.x );
  2343. this.y = Math.floor( this.y );
  2344. this.z = Math.floor( this.z );
  2345. return this;
  2346. }
  2347. ceil() {
  2348. this.x = Math.ceil( this.x );
  2349. this.y = Math.ceil( this.y );
  2350. this.z = Math.ceil( this.z );
  2351. return this;
  2352. }
  2353. round() {
  2354. this.x = Math.round( this.x );
  2355. this.y = Math.round( this.y );
  2356. this.z = Math.round( this.z );
  2357. return this;
  2358. }
  2359. roundToZero() {
  2360. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2361. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2362. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2363. return this;
  2364. }
  2365. negate() {
  2366. this.x = - this.x;
  2367. this.y = - this.y;
  2368. this.z = - this.z;
  2369. return this;
  2370. }
  2371. dot( v ) {
  2372. return this.x * v.x + this.y * v.y + this.z * v.z;
  2373. }
  2374. // TODO lengthSquared?
  2375. lengthSq() {
  2376. return this.x * this.x + this.y * this.y + this.z * this.z;
  2377. }
  2378. length() {
  2379. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2380. }
  2381. manhattanLength() {
  2382. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2383. }
  2384. normalize() {
  2385. return this.divideScalar( this.length() || 1 );
  2386. }
  2387. setLength( length ) {
  2388. return this.normalize().multiplyScalar( length );
  2389. }
  2390. lerp( v, alpha ) {
  2391. this.x += ( v.x - this.x ) * alpha;
  2392. this.y += ( v.y - this.y ) * alpha;
  2393. this.z += ( v.z - this.z ) * alpha;
  2394. return this;
  2395. }
  2396. lerpVectors( v1, v2, alpha ) {
  2397. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2398. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2399. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2400. return this;
  2401. }
  2402. cross( v, w ) {
  2403. if ( w !== undefined ) {
  2404. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2405. return this.crossVectors( v, w );
  2406. }
  2407. return this.crossVectors( this, v );
  2408. }
  2409. crossVectors( a, b ) {
  2410. const ax = a.x, ay = a.y, az = a.z;
  2411. const bx = b.x, by = b.y, bz = b.z;
  2412. this.x = ay * bz - az * by;
  2413. this.y = az * bx - ax * bz;
  2414. this.z = ax * by - ay * bx;
  2415. return this;
  2416. }
  2417. projectOnVector( v ) {
  2418. const denominator = v.lengthSq();
  2419. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2420. const scalar = v.dot( this ) / denominator;
  2421. return this.copy( v ).multiplyScalar( scalar );
  2422. }
  2423. projectOnPlane( planeNormal ) {
  2424. _vector$c.copy( this ).projectOnVector( planeNormal );
  2425. return this.sub( _vector$c );
  2426. }
  2427. reflect( normal ) {
  2428. // reflect incident vector off plane orthogonal to normal
  2429. // normal is assumed to have unit length
  2430. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2431. }
  2432. angleTo( v ) {
  2433. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2434. if ( denominator === 0 ) return Math.PI / 2;
  2435. const theta = this.dot( v ) / denominator;
  2436. // clamp, to handle numerical problems
  2437. return Math.acos( clamp( theta, - 1, 1 ) );
  2438. }
  2439. distanceTo( v ) {
  2440. return Math.sqrt( this.distanceToSquared( v ) );
  2441. }
  2442. distanceToSquared( v ) {
  2443. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2444. return dx * dx + dy * dy + dz * dz;
  2445. }
  2446. manhattanDistanceTo( v ) {
  2447. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2448. }
  2449. setFromSpherical( s ) {
  2450. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2451. }
  2452. setFromSphericalCoords( radius, phi, theta ) {
  2453. const sinPhiRadius = Math.sin( phi ) * radius;
  2454. this.x = sinPhiRadius * Math.sin( theta );
  2455. this.y = Math.cos( phi ) * radius;
  2456. this.z = sinPhiRadius * Math.cos( theta );
  2457. return this;
  2458. }
  2459. setFromCylindrical( c ) {
  2460. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2461. }
  2462. setFromCylindricalCoords( radius, theta, y ) {
  2463. this.x = radius * Math.sin( theta );
  2464. this.y = y;
  2465. this.z = radius * Math.cos( theta );
  2466. return this;
  2467. }
  2468. setFromMatrixPosition( m ) {
  2469. const e = m.elements;
  2470. this.x = e[ 12 ];
  2471. this.y = e[ 13 ];
  2472. this.z = e[ 14 ];
  2473. return this;
  2474. }
  2475. setFromMatrixScale( m ) {
  2476. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2477. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2478. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2479. this.x = sx;
  2480. this.y = sy;
  2481. this.z = sz;
  2482. return this;
  2483. }
  2484. setFromMatrixColumn( m, index ) {
  2485. return this.fromArray( m.elements, index * 4 );
  2486. }
  2487. setFromMatrix3Column( m, index ) {
  2488. return this.fromArray( m.elements, index * 3 );
  2489. }
  2490. equals( v ) {
  2491. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2492. }
  2493. fromArray( array, offset = 0 ) {
  2494. this.x = array[ offset ];
  2495. this.y = array[ offset + 1 ];
  2496. this.z = array[ offset + 2 ];
  2497. return this;
  2498. }
  2499. toArray( array = [], offset = 0 ) {
  2500. array[ offset ] = this.x;
  2501. array[ offset + 1 ] = this.y;
  2502. array[ offset + 2 ] = this.z;
  2503. return array;
  2504. }
  2505. fromBufferAttribute( attribute, index, offset ) {
  2506. if ( offset !== undefined ) {
  2507. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2508. }
  2509. this.x = attribute.getX( index );
  2510. this.y = attribute.getY( index );
  2511. this.z = attribute.getZ( index );
  2512. return this;
  2513. }
  2514. random() {
  2515. this.x = Math.random();
  2516. this.y = Math.random();
  2517. this.z = Math.random();
  2518. return this;
  2519. }
  2520. randomDirection() {
  2521. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2522. const u = ( Math.random() - 0.5 ) * 2;
  2523. const t = Math.random() * Math.PI * 2;
  2524. const f = Math.sqrt( 1 - u ** 2 );
  2525. this.x = f * Math.cos( t );
  2526. this.y = f * Math.sin( t );
  2527. this.z = u;
  2528. return this;
  2529. }
  2530. *[ Symbol.iterator ]() {
  2531. yield this.x;
  2532. yield this.y;
  2533. yield this.z;
  2534. }
  2535. }
  2536. Vector3.prototype.isVector3 = true;
  2537. const _vector$c = /*@__PURE__*/ new Vector3();
  2538. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2539. class Box3 {
  2540. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2541. this.min = min;
  2542. this.max = max;
  2543. }
  2544. set( min, max ) {
  2545. this.min.copy( min );
  2546. this.max.copy( max );
  2547. return this;
  2548. }
  2549. setFromArray( array ) {
  2550. let minX = + Infinity;
  2551. let minY = + Infinity;
  2552. let minZ = + Infinity;
  2553. let maxX = - Infinity;
  2554. let maxY = - Infinity;
  2555. let maxZ = - Infinity;
  2556. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2557. const x = array[ i ];
  2558. const y = array[ i + 1 ];
  2559. const z = array[ i + 2 ];
  2560. if ( x < minX ) minX = x;
  2561. if ( y < minY ) minY = y;
  2562. if ( z < minZ ) minZ = z;
  2563. if ( x > maxX ) maxX = x;
  2564. if ( y > maxY ) maxY = y;
  2565. if ( z > maxZ ) maxZ = z;
  2566. }
  2567. this.min.set( minX, minY, minZ );
  2568. this.max.set( maxX, maxY, maxZ );
  2569. return this;
  2570. }
  2571. setFromBufferAttribute( attribute ) {
  2572. let minX = + Infinity;
  2573. let minY = + Infinity;
  2574. let minZ = + Infinity;
  2575. let maxX = - Infinity;
  2576. let maxY = - Infinity;
  2577. let maxZ = - Infinity;
  2578. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2579. const x = attribute.getX( i );
  2580. const y = attribute.getY( i );
  2581. const z = attribute.getZ( i );
  2582. if ( x < minX ) minX = x;
  2583. if ( y < minY ) minY = y;
  2584. if ( z < minZ ) minZ = z;
  2585. if ( x > maxX ) maxX = x;
  2586. if ( y > maxY ) maxY = y;
  2587. if ( z > maxZ ) maxZ = z;
  2588. }
  2589. this.min.set( minX, minY, minZ );
  2590. this.max.set( maxX, maxY, maxZ );
  2591. return this;
  2592. }
  2593. setFromPoints( points ) {
  2594. this.makeEmpty();
  2595. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2596. this.expandByPoint( points[ i ] );
  2597. }
  2598. return this;
  2599. }
  2600. setFromCenterAndSize( center, size ) {
  2601. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2602. this.min.copy( center ).sub( halfSize );
  2603. this.max.copy( center ).add( halfSize );
  2604. return this;
  2605. }
  2606. setFromObject( object ) {
  2607. this.makeEmpty();
  2608. return this.expandByObject( object );
  2609. }
  2610. clone() {
  2611. return new this.constructor().copy( this );
  2612. }
  2613. copy( box ) {
  2614. this.min.copy( box.min );
  2615. this.max.copy( box.max );
  2616. return this;
  2617. }
  2618. makeEmpty() {
  2619. this.min.x = this.min.y = this.min.z = + Infinity;
  2620. this.max.x = this.max.y = this.max.z = - Infinity;
  2621. return this;
  2622. }
  2623. isEmpty() {
  2624. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2625. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2626. }
  2627. getCenter( target ) {
  2628. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2629. }
  2630. getSize( target ) {
  2631. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2632. }
  2633. expandByPoint( point ) {
  2634. this.min.min( point );
  2635. this.max.max( point );
  2636. return this;
  2637. }
  2638. expandByVector( vector ) {
  2639. this.min.sub( vector );
  2640. this.max.add( vector );
  2641. return this;
  2642. }
  2643. expandByScalar( scalar ) {
  2644. this.min.addScalar( - scalar );
  2645. this.max.addScalar( scalar );
  2646. return this;
  2647. }
  2648. expandByObject( object ) {
  2649. // Computes the world-axis-aligned bounding box of an object (including its children),
  2650. // accounting for both the object's, and children's, world transforms
  2651. object.updateWorldMatrix( false, false );
  2652. const geometry = object.geometry;
  2653. if ( geometry !== undefined ) {
  2654. if ( geometry.boundingBox === null ) {
  2655. geometry.computeBoundingBox();
  2656. }
  2657. _box$3.copy( geometry.boundingBox );
  2658. _box$3.applyMatrix4( object.matrixWorld );
  2659. this.union( _box$3 );
  2660. }
  2661. const children = object.children;
  2662. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2663. this.expandByObject( children[ i ] );
  2664. }
  2665. return this;
  2666. }
  2667. containsPoint( point ) {
  2668. return point.x < this.min.x || point.x > this.max.x ||
  2669. point.y < this.min.y || point.y > this.max.y ||
  2670. point.z < this.min.z || point.z > this.max.z ? false : true;
  2671. }
  2672. containsBox( box ) {
  2673. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2674. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2675. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2676. }
  2677. getParameter( point, target ) {
  2678. // This can potentially have a divide by zero if the box
  2679. // has a size dimension of 0.
  2680. return target.set(
  2681. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2682. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2683. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2684. );
  2685. }
  2686. intersectsBox( box ) {
  2687. // using 6 splitting planes to rule out intersections.
  2688. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2689. box.max.y < this.min.y || box.min.y > this.max.y ||
  2690. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2691. }
  2692. intersectsSphere( sphere ) {
  2693. // Find the point on the AABB closest to the sphere center.
  2694. this.clampPoint( sphere.center, _vector$b );
  2695. // If that point is inside the sphere, the AABB and sphere intersect.
  2696. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2697. }
  2698. intersectsPlane( plane ) {
  2699. // We compute the minimum and maximum dot product values. If those values
  2700. // are on the same side (back or front) of the plane, then there is no intersection.
  2701. let min, max;
  2702. if ( plane.normal.x > 0 ) {
  2703. min = plane.normal.x * this.min.x;
  2704. max = plane.normal.x * this.max.x;
  2705. } else {
  2706. min = plane.normal.x * this.max.x;
  2707. max = plane.normal.x * this.min.x;
  2708. }
  2709. if ( plane.normal.y > 0 ) {
  2710. min += plane.normal.y * this.min.y;
  2711. max += plane.normal.y * this.max.y;
  2712. } else {
  2713. min += plane.normal.y * this.max.y;
  2714. max += plane.normal.y * this.min.y;
  2715. }
  2716. if ( plane.normal.z > 0 ) {
  2717. min += plane.normal.z * this.min.z;
  2718. max += plane.normal.z * this.max.z;
  2719. } else {
  2720. min += plane.normal.z * this.max.z;
  2721. max += plane.normal.z * this.min.z;
  2722. }
  2723. return ( min <= - plane.constant && max >= - plane.constant );
  2724. }
  2725. intersectsTriangle( triangle ) {
  2726. if ( this.isEmpty() ) {
  2727. return false;
  2728. }
  2729. // compute box center and extents
  2730. this.getCenter( _center );
  2731. _extents.subVectors( this.max, _center );
  2732. // translate triangle to aabb origin
  2733. _v0$2.subVectors( triangle.a, _center );
  2734. _v1$7.subVectors( triangle.b, _center );
  2735. _v2$3.subVectors( triangle.c, _center );
  2736. // compute edge vectors for triangle
  2737. _f0.subVectors( _v1$7, _v0$2 );
  2738. _f1.subVectors( _v2$3, _v1$7 );
  2739. _f2.subVectors( _v0$2, _v2$3 );
  2740. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2741. // 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
  2742. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2743. let axes = [
  2744. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2745. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2746. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2747. ];
  2748. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2749. return false;
  2750. }
  2751. // test 3 face normals from the aabb
  2752. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2753. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2754. return false;
  2755. }
  2756. // finally testing the face normal of the triangle
  2757. // use already existing triangle edge vectors here
  2758. _triangleNormal.crossVectors( _f0, _f1 );
  2759. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2760. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  2761. }
  2762. clampPoint( point, target ) {
  2763. return target.copy( point ).clamp( this.min, this.max );
  2764. }
  2765. distanceToPoint( point ) {
  2766. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  2767. return clampedPoint.sub( point ).length();
  2768. }
  2769. getBoundingSphere( target ) {
  2770. this.getCenter( target.center );
  2771. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2772. return target;
  2773. }
  2774. intersect( box ) {
  2775. this.min.max( box.min );
  2776. this.max.min( box.max );
  2777. // 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.
  2778. if ( this.isEmpty() ) this.makeEmpty();
  2779. return this;
  2780. }
  2781. union( box ) {
  2782. this.min.min( box.min );
  2783. this.max.max( box.max );
  2784. return this;
  2785. }
  2786. applyMatrix4( matrix ) {
  2787. // transform of empty box is an empty box.
  2788. if ( this.isEmpty() ) return this;
  2789. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2790. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2791. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2792. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2793. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2794. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2795. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2796. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2797. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2798. this.setFromPoints( _points );
  2799. return this;
  2800. }
  2801. translate( offset ) {
  2802. this.min.add( offset );
  2803. this.max.add( offset );
  2804. return this;
  2805. }
  2806. equals( box ) {
  2807. return box.min.equals( this.min ) && box.max.equals( this.max );
  2808. }
  2809. }
  2810. Box3.prototype.isBox3 = true;
  2811. const _points = [
  2812. /*@__PURE__*/ new Vector3(),
  2813. /*@__PURE__*/ new Vector3(),
  2814. /*@__PURE__*/ new Vector3(),
  2815. /*@__PURE__*/ new Vector3(),
  2816. /*@__PURE__*/ new Vector3(),
  2817. /*@__PURE__*/ new Vector3(),
  2818. /*@__PURE__*/ new Vector3(),
  2819. /*@__PURE__*/ new Vector3()
  2820. ];
  2821. const _vector$b = /*@__PURE__*/ new Vector3();
  2822. const _box$3 = /*@__PURE__*/ new Box3();
  2823. // triangle centered vertices
  2824. const _v0$2 = /*@__PURE__*/ new Vector3();
  2825. const _v1$7 = /*@__PURE__*/ new Vector3();
  2826. const _v2$3 = /*@__PURE__*/ new Vector3();
  2827. // triangle edge vectors
  2828. const _f0 = /*@__PURE__*/ new Vector3();
  2829. const _f1 = /*@__PURE__*/ new Vector3();
  2830. const _f2 = /*@__PURE__*/ new Vector3();
  2831. const _center = /*@__PURE__*/ new Vector3();
  2832. const _extents = /*@__PURE__*/ new Vector3();
  2833. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2834. const _testAxis = /*@__PURE__*/ new Vector3();
  2835. function satForAxes( axes, v0, v1, v2, extents ) {
  2836. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2837. _testAxis.fromArray( axes, i );
  2838. // project the aabb onto the seperating axis
  2839. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2840. // project all 3 vertices of the triangle onto the seperating axis
  2841. const p0 = v0.dot( _testAxis );
  2842. const p1 = v1.dot( _testAxis );
  2843. const p2 = v2.dot( _testAxis );
  2844. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2845. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2846. // points of the projected triangle are outside the projected half-length of the aabb
  2847. // the axis is seperating and we can exit
  2848. return false;
  2849. }
  2850. }
  2851. return true;
  2852. }
  2853. const _box$2 = /*@__PURE__*/ new Box3();
  2854. const _v1$6 = /*@__PURE__*/ new Vector3();
  2855. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  2856. const _toPoint = /*@__PURE__*/ new Vector3();
  2857. class Sphere {
  2858. constructor( center = new Vector3(), radius = - 1 ) {
  2859. this.center = center;
  2860. this.radius = radius;
  2861. }
  2862. set( center, radius ) {
  2863. this.center.copy( center );
  2864. this.radius = radius;
  2865. return this;
  2866. }
  2867. setFromPoints( points, optionalCenter ) {
  2868. const center = this.center;
  2869. if ( optionalCenter !== undefined ) {
  2870. center.copy( optionalCenter );
  2871. } else {
  2872. _box$2.setFromPoints( points ).getCenter( center );
  2873. }
  2874. let maxRadiusSq = 0;
  2875. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2876. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2877. }
  2878. this.radius = Math.sqrt( maxRadiusSq );
  2879. return this;
  2880. }
  2881. copy( sphere ) {
  2882. this.center.copy( sphere.center );
  2883. this.radius = sphere.radius;
  2884. return this;
  2885. }
  2886. isEmpty() {
  2887. return ( this.radius < 0 );
  2888. }
  2889. makeEmpty() {
  2890. this.center.set( 0, 0, 0 );
  2891. this.radius = - 1;
  2892. return this;
  2893. }
  2894. containsPoint( point ) {
  2895. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2896. }
  2897. distanceToPoint( point ) {
  2898. return ( point.distanceTo( this.center ) - this.radius );
  2899. }
  2900. intersectsSphere( sphere ) {
  2901. const radiusSum = this.radius + sphere.radius;
  2902. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2903. }
  2904. intersectsBox( box ) {
  2905. return box.intersectsSphere( this );
  2906. }
  2907. intersectsPlane( plane ) {
  2908. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2909. }
  2910. clampPoint( point, target ) {
  2911. const deltaLengthSq = this.center.distanceToSquared( point );
  2912. target.copy( point );
  2913. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2914. target.sub( this.center ).normalize();
  2915. target.multiplyScalar( this.radius ).add( this.center );
  2916. }
  2917. return target;
  2918. }
  2919. getBoundingBox( target ) {
  2920. if ( this.isEmpty() ) {
  2921. // Empty sphere produces empty bounding box
  2922. target.makeEmpty();
  2923. return target;
  2924. }
  2925. target.set( this.center, this.center );
  2926. target.expandByScalar( this.radius );
  2927. return target;
  2928. }
  2929. applyMatrix4( matrix ) {
  2930. this.center.applyMatrix4( matrix );
  2931. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2932. return this;
  2933. }
  2934. translate( offset ) {
  2935. this.center.add( offset );
  2936. return this;
  2937. }
  2938. expandByPoint( point ) {
  2939. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2940. _toPoint.subVectors( point, this.center );
  2941. const lengthSq = _toPoint.lengthSq();
  2942. if ( lengthSq > ( this.radius * this.radius ) ) {
  2943. const length = Math.sqrt( lengthSq );
  2944. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  2945. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2946. // and the other half to position. This gives a tighter enclosure, instead of if
  2947. // the whole missing distance were just added to radius.
  2948. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  2949. this.radius += missingRadiusHalf;
  2950. }
  2951. return this;
  2952. }
  2953. union( sphere ) {
  2954. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2955. // To enclose another sphere into this sphere, we only need to enclose two points:
  2956. // 1) Enclose the farthest point on the other sphere into this sphere.
  2957. // 2) Enclose the opposite point of the farthest point into this sphere.
  2958. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  2959. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  2960. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  2961. return this;
  2962. }
  2963. equals( sphere ) {
  2964. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2965. }
  2966. clone() {
  2967. return new this.constructor().copy( this );
  2968. }
  2969. }
  2970. const _vector$a = /*@__PURE__*/ new Vector3();
  2971. const _segCenter = /*@__PURE__*/ new Vector3();
  2972. const _segDir = /*@__PURE__*/ new Vector3();
  2973. const _diff = /*@__PURE__*/ new Vector3();
  2974. const _edge1 = /*@__PURE__*/ new Vector3();
  2975. const _edge2 = /*@__PURE__*/ new Vector3();
  2976. const _normal$1 = /*@__PURE__*/ new Vector3();
  2977. class Ray {
  2978. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  2979. this.origin = origin;
  2980. this.direction = direction;
  2981. }
  2982. set( origin, direction ) {
  2983. this.origin.copy( origin );
  2984. this.direction.copy( direction );
  2985. return this;
  2986. }
  2987. copy( ray ) {
  2988. this.origin.copy( ray.origin );
  2989. this.direction.copy( ray.direction );
  2990. return this;
  2991. }
  2992. at( t, target ) {
  2993. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2994. }
  2995. lookAt( v ) {
  2996. this.direction.copy( v ).sub( this.origin ).normalize();
  2997. return this;
  2998. }
  2999. recast( t ) {
  3000. this.origin.copy( this.at( t, _vector$a ) );
  3001. return this;
  3002. }
  3003. closestPointToPoint( point, target ) {
  3004. target.subVectors( point, this.origin );
  3005. const directionDistance = target.dot( this.direction );
  3006. if ( directionDistance < 0 ) {
  3007. return target.copy( this.origin );
  3008. }
  3009. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3010. }
  3011. distanceToPoint( point ) {
  3012. return Math.sqrt( this.distanceSqToPoint( point ) );
  3013. }
  3014. distanceSqToPoint( point ) {
  3015. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3016. // point behind the ray
  3017. if ( directionDistance < 0 ) {
  3018. return this.origin.distanceToSquared( point );
  3019. }
  3020. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3021. return _vector$a.distanceToSquared( point );
  3022. }
  3023. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3024. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3025. // It returns the min distance between the ray and the segment
  3026. // defined by v0 and v1
  3027. // It can also set two optional targets :
  3028. // - The closest point on the ray
  3029. // - The closest point on the segment
  3030. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3031. _segDir.copy( v1 ).sub( v0 ).normalize();
  3032. _diff.copy( this.origin ).sub( _segCenter );
  3033. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3034. const a01 = - this.direction.dot( _segDir );
  3035. const b0 = _diff.dot( this.direction );
  3036. const b1 = - _diff.dot( _segDir );
  3037. const c = _diff.lengthSq();
  3038. const det = Math.abs( 1 - a01 * a01 );
  3039. let s0, s1, sqrDist, extDet;
  3040. if ( det > 0 ) {
  3041. // The ray and segment are not parallel.
  3042. s0 = a01 * b1 - b0;
  3043. s1 = a01 * b0 - b1;
  3044. extDet = segExtent * det;
  3045. if ( s0 >= 0 ) {
  3046. if ( s1 >= - extDet ) {
  3047. if ( s1 <= extDet ) {
  3048. // region 0
  3049. // Minimum at interior points of ray and segment.
  3050. const invDet = 1 / det;
  3051. s0 *= invDet;
  3052. s1 *= invDet;
  3053. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3054. } else {
  3055. // region 1
  3056. s1 = segExtent;
  3057. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3058. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3059. }
  3060. } else {
  3061. // region 5
  3062. s1 = - segExtent;
  3063. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3064. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3065. }
  3066. } else {
  3067. if ( s1 <= - extDet ) {
  3068. // region 4
  3069. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3070. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3071. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3072. } else if ( s1 <= extDet ) {
  3073. // region 3
  3074. s0 = 0;
  3075. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3076. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3077. } else {
  3078. // region 2
  3079. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3080. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3081. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3082. }
  3083. }
  3084. } else {
  3085. // Ray and segment are parallel.
  3086. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3087. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3088. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3089. }
  3090. if ( optionalPointOnRay ) {
  3091. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3092. }
  3093. if ( optionalPointOnSegment ) {
  3094. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3095. }
  3096. return sqrDist;
  3097. }
  3098. intersectSphere( sphere, target ) {
  3099. _vector$a.subVectors( sphere.center, this.origin );
  3100. const tca = _vector$a.dot( this.direction );
  3101. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3102. const radius2 = sphere.radius * sphere.radius;
  3103. if ( d2 > radius2 ) return null;
  3104. const thc = Math.sqrt( radius2 - d2 );
  3105. // t0 = first intersect point - entrance on front of sphere
  3106. const t0 = tca - thc;
  3107. // t1 = second intersect point - exit point on back of sphere
  3108. const t1 = tca + thc;
  3109. // test to see if both t0 and t1 are behind the ray - if so, return null
  3110. if ( t0 < 0 && t1 < 0 ) return null;
  3111. // test to see if t0 is behind the ray:
  3112. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3113. // in order to always return an intersect point that is in front of the ray.
  3114. if ( t0 < 0 ) return this.at( t1, target );
  3115. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3116. return this.at( t0, target );
  3117. }
  3118. intersectsSphere( sphere ) {
  3119. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3120. }
  3121. distanceToPlane( plane ) {
  3122. const denominator = plane.normal.dot( this.direction );
  3123. if ( denominator === 0 ) {
  3124. // line is coplanar, return origin
  3125. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3126. return 0;
  3127. }
  3128. // Null is preferable to undefined since undefined means.... it is undefined
  3129. return null;
  3130. }
  3131. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3132. // Return if the ray never intersects the plane
  3133. return t >= 0 ? t : null;
  3134. }
  3135. intersectPlane( plane, target ) {
  3136. const t = this.distanceToPlane( plane );
  3137. if ( t === null ) {
  3138. return null;
  3139. }
  3140. return this.at( t, target );
  3141. }
  3142. intersectsPlane( plane ) {
  3143. // check if the ray lies on the plane first
  3144. const distToPoint = plane.distanceToPoint( this.origin );
  3145. if ( distToPoint === 0 ) {
  3146. return true;
  3147. }
  3148. const denominator = plane.normal.dot( this.direction );
  3149. if ( denominator * distToPoint < 0 ) {
  3150. return true;
  3151. }
  3152. // ray origin is behind the plane (and is pointing behind it)
  3153. return false;
  3154. }
  3155. intersectBox( box, target ) {
  3156. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3157. const invdirx = 1 / this.direction.x,
  3158. invdiry = 1 / this.direction.y,
  3159. invdirz = 1 / this.direction.z;
  3160. const origin = this.origin;
  3161. if ( invdirx >= 0 ) {
  3162. tmin = ( box.min.x - origin.x ) * invdirx;
  3163. tmax = ( box.max.x - origin.x ) * invdirx;
  3164. } else {
  3165. tmin = ( box.max.x - origin.x ) * invdirx;
  3166. tmax = ( box.min.x - origin.x ) * invdirx;
  3167. }
  3168. if ( invdiry >= 0 ) {
  3169. tymin = ( box.min.y - origin.y ) * invdiry;
  3170. tymax = ( box.max.y - origin.y ) * invdiry;
  3171. } else {
  3172. tymin = ( box.max.y - origin.y ) * invdiry;
  3173. tymax = ( box.min.y - origin.y ) * invdiry;
  3174. }
  3175. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3176. // These lines also handle the case where tmin or tmax is NaN
  3177. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3178. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3179. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3180. if ( invdirz >= 0 ) {
  3181. tzmin = ( box.min.z - origin.z ) * invdirz;
  3182. tzmax = ( box.max.z - origin.z ) * invdirz;
  3183. } else {
  3184. tzmin = ( box.max.z - origin.z ) * invdirz;
  3185. tzmax = ( box.min.z - origin.z ) * invdirz;
  3186. }
  3187. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3188. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3189. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3190. //return point closest to the ray (positive side)
  3191. if ( tmax < 0 ) return null;
  3192. return this.at( tmin >= 0 ? tmin : tmax, target );
  3193. }
  3194. intersectsBox( box ) {
  3195. return this.intersectBox( box, _vector$a ) !== null;
  3196. }
  3197. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3198. // Compute the offset origin, edges, and normal.
  3199. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3200. _edge1.subVectors( b, a );
  3201. _edge2.subVectors( c, a );
  3202. _normal$1.crossVectors( _edge1, _edge2 );
  3203. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3204. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3205. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3206. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3207. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3208. let DdN = this.direction.dot( _normal$1 );
  3209. let sign;
  3210. if ( DdN > 0 ) {
  3211. if ( backfaceCulling ) return null;
  3212. sign = 1;
  3213. } else if ( DdN < 0 ) {
  3214. sign = - 1;
  3215. DdN = - DdN;
  3216. } else {
  3217. return null;
  3218. }
  3219. _diff.subVectors( this.origin, a );
  3220. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3221. // b1 < 0, no intersection
  3222. if ( DdQxE2 < 0 ) {
  3223. return null;
  3224. }
  3225. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3226. // b2 < 0, no intersection
  3227. if ( DdE1xQ < 0 ) {
  3228. return null;
  3229. }
  3230. // b1+b2 > 1, no intersection
  3231. if ( DdQxE2 + DdE1xQ > DdN ) {
  3232. return null;
  3233. }
  3234. // Line intersects triangle, check if ray does.
  3235. const QdN = - sign * _diff.dot( _normal$1 );
  3236. // t < 0, no intersection
  3237. if ( QdN < 0 ) {
  3238. return null;
  3239. }
  3240. // Ray intersects triangle.
  3241. return this.at( QdN / DdN, target );
  3242. }
  3243. applyMatrix4( matrix4 ) {
  3244. this.origin.applyMatrix4( matrix4 );
  3245. this.direction.transformDirection( matrix4 );
  3246. return this;
  3247. }
  3248. equals( ray ) {
  3249. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3250. }
  3251. clone() {
  3252. return new this.constructor().copy( this );
  3253. }
  3254. }
  3255. class Matrix4 {
  3256. constructor() {
  3257. this.elements = [
  3258. 1, 0, 0, 0,
  3259. 0, 1, 0, 0,
  3260. 0, 0, 1, 0,
  3261. 0, 0, 0, 1
  3262. ];
  3263. if ( arguments.length > 0 ) {
  3264. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3265. }
  3266. }
  3267. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3268. const te = this.elements;
  3269. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3270. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3271. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3272. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3273. return this;
  3274. }
  3275. identity() {
  3276. this.set(
  3277. 1, 0, 0, 0,
  3278. 0, 1, 0, 0,
  3279. 0, 0, 1, 0,
  3280. 0, 0, 0, 1
  3281. );
  3282. return this;
  3283. }
  3284. clone() {
  3285. return new Matrix4().fromArray( this.elements );
  3286. }
  3287. copy( m ) {
  3288. const te = this.elements;
  3289. const me = m.elements;
  3290. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3291. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3292. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3293. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3294. return this;
  3295. }
  3296. copyPosition( m ) {
  3297. const te = this.elements, me = m.elements;
  3298. te[ 12 ] = me[ 12 ];
  3299. te[ 13 ] = me[ 13 ];
  3300. te[ 14 ] = me[ 14 ];
  3301. return this;
  3302. }
  3303. setFromMatrix3( m ) {
  3304. const me = m.elements;
  3305. this.set(
  3306. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3307. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3308. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3309. 0, 0, 0, 1
  3310. );
  3311. return this;
  3312. }
  3313. extractBasis( xAxis, yAxis, zAxis ) {
  3314. xAxis.setFromMatrixColumn( this, 0 );
  3315. yAxis.setFromMatrixColumn( this, 1 );
  3316. zAxis.setFromMatrixColumn( this, 2 );
  3317. return this;
  3318. }
  3319. makeBasis( xAxis, yAxis, zAxis ) {
  3320. this.set(
  3321. xAxis.x, yAxis.x, zAxis.x, 0,
  3322. xAxis.y, yAxis.y, zAxis.y, 0,
  3323. xAxis.z, yAxis.z, zAxis.z, 0,
  3324. 0, 0, 0, 1
  3325. );
  3326. return this;
  3327. }
  3328. extractRotation( m ) {
  3329. // this method does not support reflection matrices
  3330. const te = this.elements;
  3331. const me = m.elements;
  3332. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3333. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3334. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3335. te[ 0 ] = me[ 0 ] * scaleX;
  3336. te[ 1 ] = me[ 1 ] * scaleX;
  3337. te[ 2 ] = me[ 2 ] * scaleX;
  3338. te[ 3 ] = 0;
  3339. te[ 4 ] = me[ 4 ] * scaleY;
  3340. te[ 5 ] = me[ 5 ] * scaleY;
  3341. te[ 6 ] = me[ 6 ] * scaleY;
  3342. te[ 7 ] = 0;
  3343. te[ 8 ] = me[ 8 ] * scaleZ;
  3344. te[ 9 ] = me[ 9 ] * scaleZ;
  3345. te[ 10 ] = me[ 10 ] * scaleZ;
  3346. te[ 11 ] = 0;
  3347. te[ 12 ] = 0;
  3348. te[ 13 ] = 0;
  3349. te[ 14 ] = 0;
  3350. te[ 15 ] = 1;
  3351. return this;
  3352. }
  3353. makeRotationFromEuler( euler ) {
  3354. if ( ! ( euler && euler.isEuler ) ) {
  3355. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3356. }
  3357. const te = this.elements;
  3358. const x = euler.x, y = euler.y, z = euler.z;
  3359. const a = Math.cos( x ), b = Math.sin( x );
  3360. const c = Math.cos( y ), d = Math.sin( y );
  3361. const e = Math.cos( z ), f = Math.sin( z );
  3362. if ( euler.order === 'XYZ' ) {
  3363. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3364. te[ 0 ] = c * e;
  3365. te[ 4 ] = - c * f;
  3366. te[ 8 ] = d;
  3367. te[ 1 ] = af + be * d;
  3368. te[ 5 ] = ae - bf * d;
  3369. te[ 9 ] = - b * c;
  3370. te[ 2 ] = bf - ae * d;
  3371. te[ 6 ] = be + af * d;
  3372. te[ 10 ] = a * c;
  3373. } else if ( euler.order === 'YXZ' ) {
  3374. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3375. te[ 0 ] = ce + df * b;
  3376. te[ 4 ] = de * b - cf;
  3377. te[ 8 ] = a * d;
  3378. te[ 1 ] = a * f;
  3379. te[ 5 ] = a * e;
  3380. te[ 9 ] = - b;
  3381. te[ 2 ] = cf * b - de;
  3382. te[ 6 ] = df + ce * b;
  3383. te[ 10 ] = a * c;
  3384. } else if ( euler.order === 'ZXY' ) {
  3385. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3386. te[ 0 ] = ce - df * b;
  3387. te[ 4 ] = - a * f;
  3388. te[ 8 ] = de + cf * b;
  3389. te[ 1 ] = cf + de * b;
  3390. te[ 5 ] = a * e;
  3391. te[ 9 ] = df - ce * b;
  3392. te[ 2 ] = - a * d;
  3393. te[ 6 ] = b;
  3394. te[ 10 ] = a * c;
  3395. } else if ( euler.order === 'ZYX' ) {
  3396. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3397. te[ 0 ] = c * e;
  3398. te[ 4 ] = be * d - af;
  3399. te[ 8 ] = ae * d + bf;
  3400. te[ 1 ] = c * f;
  3401. te[ 5 ] = bf * d + ae;
  3402. te[ 9 ] = af * d - be;
  3403. te[ 2 ] = - d;
  3404. te[ 6 ] = b * c;
  3405. te[ 10 ] = a * c;
  3406. } else if ( euler.order === 'YZX' ) {
  3407. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3408. te[ 0 ] = c * e;
  3409. te[ 4 ] = bd - ac * f;
  3410. te[ 8 ] = bc * f + ad;
  3411. te[ 1 ] = f;
  3412. te[ 5 ] = a * e;
  3413. te[ 9 ] = - b * e;
  3414. te[ 2 ] = - d * e;
  3415. te[ 6 ] = ad * f + bc;
  3416. te[ 10 ] = ac - bd * f;
  3417. } else if ( euler.order === 'XZY' ) {
  3418. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3419. te[ 0 ] = c * e;
  3420. te[ 4 ] = - f;
  3421. te[ 8 ] = d * e;
  3422. te[ 1 ] = ac * f + bd;
  3423. te[ 5 ] = a * e;
  3424. te[ 9 ] = ad * f - bc;
  3425. te[ 2 ] = bc * f - ad;
  3426. te[ 6 ] = b * e;
  3427. te[ 10 ] = bd * f + ac;
  3428. }
  3429. // bottom row
  3430. te[ 3 ] = 0;
  3431. te[ 7 ] = 0;
  3432. te[ 11 ] = 0;
  3433. // last column
  3434. te[ 12 ] = 0;
  3435. te[ 13 ] = 0;
  3436. te[ 14 ] = 0;
  3437. te[ 15 ] = 1;
  3438. return this;
  3439. }
  3440. makeRotationFromQuaternion( q ) {
  3441. return this.compose( _zero, q, _one );
  3442. }
  3443. lookAt( eye, target, up ) {
  3444. const te = this.elements;
  3445. _z.subVectors( eye, target );
  3446. if ( _z.lengthSq() === 0 ) {
  3447. // eye and target are in the same position
  3448. _z.z = 1;
  3449. }
  3450. _z.normalize();
  3451. _x.crossVectors( up, _z );
  3452. if ( _x.lengthSq() === 0 ) {
  3453. // up and z are parallel
  3454. if ( Math.abs( up.z ) === 1 ) {
  3455. _z.x += 0.0001;
  3456. } else {
  3457. _z.z += 0.0001;
  3458. }
  3459. _z.normalize();
  3460. _x.crossVectors( up, _z );
  3461. }
  3462. _x.normalize();
  3463. _y.crossVectors( _z, _x );
  3464. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3465. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3466. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3467. return this;
  3468. }
  3469. multiply( m, n ) {
  3470. if ( n !== undefined ) {
  3471. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3472. return this.multiplyMatrices( m, n );
  3473. }
  3474. return this.multiplyMatrices( this, m );
  3475. }
  3476. premultiply( m ) {
  3477. return this.multiplyMatrices( m, this );
  3478. }
  3479. multiplyMatrices( a, b ) {
  3480. const ae = a.elements;
  3481. const be = b.elements;
  3482. const te = this.elements;
  3483. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3484. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3485. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3486. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3487. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3488. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3489. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3490. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3491. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3492. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3493. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3494. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3495. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3496. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3497. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3498. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3499. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3500. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3501. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3502. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3503. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3504. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3505. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3506. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3507. return this;
  3508. }
  3509. multiplyScalar( s ) {
  3510. const te = this.elements;
  3511. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3512. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3513. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3514. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3515. return this;
  3516. }
  3517. determinant() {
  3518. const te = this.elements;
  3519. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3520. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3521. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3522. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3523. //TODO: make this more efficient
  3524. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3525. return (
  3526. n41 * (
  3527. + n14 * n23 * n32
  3528. - n13 * n24 * n32
  3529. - n14 * n22 * n33
  3530. + n12 * n24 * n33
  3531. + n13 * n22 * n34
  3532. - n12 * n23 * n34
  3533. ) +
  3534. n42 * (
  3535. + n11 * n23 * n34
  3536. - n11 * n24 * n33
  3537. + n14 * n21 * n33
  3538. - n13 * n21 * n34
  3539. + n13 * n24 * n31
  3540. - n14 * n23 * n31
  3541. ) +
  3542. n43 * (
  3543. + n11 * n24 * n32
  3544. - n11 * n22 * n34
  3545. - n14 * n21 * n32
  3546. + n12 * n21 * n34
  3547. + n14 * n22 * n31
  3548. - n12 * n24 * n31
  3549. ) +
  3550. n44 * (
  3551. - n13 * n22 * n31
  3552. - n11 * n23 * n32
  3553. + n11 * n22 * n33
  3554. + n13 * n21 * n32
  3555. - n12 * n21 * n33
  3556. + n12 * n23 * n31
  3557. )
  3558. );
  3559. }
  3560. transpose() {
  3561. const te = this.elements;
  3562. let tmp;
  3563. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3564. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3565. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3566. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3567. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3568. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3569. return this;
  3570. }
  3571. setPosition( x, y, z ) {
  3572. const te = this.elements;
  3573. if ( x.isVector3 ) {
  3574. te[ 12 ] = x.x;
  3575. te[ 13 ] = x.y;
  3576. te[ 14 ] = x.z;
  3577. } else {
  3578. te[ 12 ] = x;
  3579. te[ 13 ] = y;
  3580. te[ 14 ] = z;
  3581. }
  3582. return this;
  3583. }
  3584. invert() {
  3585. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3586. const te = this.elements,
  3587. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3588. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3589. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3590. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3591. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3592. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3593. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3594. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3595. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3596. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3597. const detInv = 1 / det;
  3598. te[ 0 ] = t11 * detInv;
  3599. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3600. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3601. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3602. te[ 4 ] = t12 * detInv;
  3603. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3604. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3605. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3606. te[ 8 ] = t13 * detInv;
  3607. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3608. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3609. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3610. te[ 12 ] = t14 * detInv;
  3611. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3612. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3613. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3614. return this;
  3615. }
  3616. scale( v ) {
  3617. const te = this.elements;
  3618. const x = v.x, y = v.y, z = v.z;
  3619. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3620. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3621. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3622. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3623. return this;
  3624. }
  3625. getMaxScaleOnAxis() {
  3626. const te = this.elements;
  3627. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3628. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3629. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3630. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3631. }
  3632. makeTranslation( x, y, z ) {
  3633. this.set(
  3634. 1, 0, 0, x,
  3635. 0, 1, 0, y,
  3636. 0, 0, 1, z,
  3637. 0, 0, 0, 1
  3638. );
  3639. return this;
  3640. }
  3641. makeRotationX( theta ) {
  3642. const c = Math.cos( theta ), s = Math.sin( theta );
  3643. this.set(
  3644. 1, 0, 0, 0,
  3645. 0, c, - s, 0,
  3646. 0, s, c, 0,
  3647. 0, 0, 0, 1
  3648. );
  3649. return this;
  3650. }
  3651. makeRotationY( theta ) {
  3652. const c = Math.cos( theta ), s = Math.sin( theta );
  3653. this.set(
  3654. c, 0, s, 0,
  3655. 0, 1, 0, 0,
  3656. - s, 0, c, 0,
  3657. 0, 0, 0, 1
  3658. );
  3659. return this;
  3660. }
  3661. makeRotationZ( theta ) {
  3662. const c = Math.cos( theta ), s = Math.sin( theta );
  3663. this.set(
  3664. c, - s, 0, 0,
  3665. s, c, 0, 0,
  3666. 0, 0, 1, 0,
  3667. 0, 0, 0, 1
  3668. );
  3669. return this;
  3670. }
  3671. makeRotationAxis( axis, angle ) {
  3672. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3673. const c = Math.cos( angle );
  3674. const s = Math.sin( angle );
  3675. const t = 1 - c;
  3676. const x = axis.x, y = axis.y, z = axis.z;
  3677. const tx = t * x, ty = t * y;
  3678. this.set(
  3679. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3680. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3681. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3682. 0, 0, 0, 1
  3683. );
  3684. return this;
  3685. }
  3686. makeScale( x, y, z ) {
  3687. this.set(
  3688. x, 0, 0, 0,
  3689. 0, y, 0, 0,
  3690. 0, 0, z, 0,
  3691. 0, 0, 0, 1
  3692. );
  3693. return this;
  3694. }
  3695. makeShear( xy, xz, yx, yz, zx, zy ) {
  3696. this.set(
  3697. 1, yx, zx, 0,
  3698. xy, 1, zy, 0,
  3699. xz, yz, 1, 0,
  3700. 0, 0, 0, 1
  3701. );
  3702. return this;
  3703. }
  3704. compose( position, quaternion, scale ) {
  3705. const te = this.elements;
  3706. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3707. const x2 = x + x, y2 = y + y, z2 = z + z;
  3708. const xx = x * x2, xy = x * y2, xz = x * z2;
  3709. const yy = y * y2, yz = y * z2, zz = z * z2;
  3710. const wx = w * x2, wy = w * y2, wz = w * z2;
  3711. const sx = scale.x, sy = scale.y, sz = scale.z;
  3712. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3713. te[ 1 ] = ( xy + wz ) * sx;
  3714. te[ 2 ] = ( xz - wy ) * sx;
  3715. te[ 3 ] = 0;
  3716. te[ 4 ] = ( xy - wz ) * sy;
  3717. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3718. te[ 6 ] = ( yz + wx ) * sy;
  3719. te[ 7 ] = 0;
  3720. te[ 8 ] = ( xz + wy ) * sz;
  3721. te[ 9 ] = ( yz - wx ) * sz;
  3722. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3723. te[ 11 ] = 0;
  3724. te[ 12 ] = position.x;
  3725. te[ 13 ] = position.y;
  3726. te[ 14 ] = position.z;
  3727. te[ 15 ] = 1;
  3728. return this;
  3729. }
  3730. decompose( position, quaternion, scale ) {
  3731. const te = this.elements;
  3732. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3733. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3734. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3735. // if determine is negative, we need to invert one scale
  3736. const det = this.determinant();
  3737. if ( det < 0 ) sx = - sx;
  3738. position.x = te[ 12 ];
  3739. position.y = te[ 13 ];
  3740. position.z = te[ 14 ];
  3741. // scale the rotation part
  3742. _m1$2.copy( this );
  3743. const invSX = 1 / sx;
  3744. const invSY = 1 / sy;
  3745. const invSZ = 1 / sz;
  3746. _m1$2.elements[ 0 ] *= invSX;
  3747. _m1$2.elements[ 1 ] *= invSX;
  3748. _m1$2.elements[ 2 ] *= invSX;
  3749. _m1$2.elements[ 4 ] *= invSY;
  3750. _m1$2.elements[ 5 ] *= invSY;
  3751. _m1$2.elements[ 6 ] *= invSY;
  3752. _m1$2.elements[ 8 ] *= invSZ;
  3753. _m1$2.elements[ 9 ] *= invSZ;
  3754. _m1$2.elements[ 10 ] *= invSZ;
  3755. quaternion.setFromRotationMatrix( _m1$2 );
  3756. scale.x = sx;
  3757. scale.y = sy;
  3758. scale.z = sz;
  3759. return this;
  3760. }
  3761. makePerspective( left, right, top, bottom, near, far ) {
  3762. if ( far === undefined ) {
  3763. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3764. }
  3765. const te = this.elements;
  3766. const x = 2 * near / ( right - left );
  3767. const y = 2 * near / ( top - bottom );
  3768. const a = ( right + left ) / ( right - left );
  3769. const b = ( top + bottom ) / ( top - bottom );
  3770. const c = - ( far + near ) / ( far - near );
  3771. const d = - 2 * far * near / ( far - near );
  3772. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3773. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3774. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3775. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3776. return this;
  3777. }
  3778. makeOrthographic( left, right, top, bottom, near, far ) {
  3779. const te = this.elements;
  3780. const w = 1.0 / ( right - left );
  3781. const h = 1.0 / ( top - bottom );
  3782. const p = 1.0 / ( far - near );
  3783. const x = ( right + left ) * w;
  3784. const y = ( top + bottom ) * h;
  3785. const z = ( far + near ) * p;
  3786. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3787. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3788. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3789. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3790. return this;
  3791. }
  3792. equals( matrix ) {
  3793. const te = this.elements;
  3794. const me = matrix.elements;
  3795. for ( let i = 0; i < 16; i ++ ) {
  3796. if ( te[ i ] !== me[ i ] ) return false;
  3797. }
  3798. return true;
  3799. }
  3800. fromArray( array, offset = 0 ) {
  3801. for ( let i = 0; i < 16; i ++ ) {
  3802. this.elements[ i ] = array[ i + offset ];
  3803. }
  3804. return this;
  3805. }
  3806. toArray( array = [], offset = 0 ) {
  3807. const te = this.elements;
  3808. array[ offset ] = te[ 0 ];
  3809. array[ offset + 1 ] = te[ 1 ];
  3810. array[ offset + 2 ] = te[ 2 ];
  3811. array[ offset + 3 ] = te[ 3 ];
  3812. array[ offset + 4 ] = te[ 4 ];
  3813. array[ offset + 5 ] = te[ 5 ];
  3814. array[ offset + 6 ] = te[ 6 ];
  3815. array[ offset + 7 ] = te[ 7 ];
  3816. array[ offset + 8 ] = te[ 8 ];
  3817. array[ offset + 9 ] = te[ 9 ];
  3818. array[ offset + 10 ] = te[ 10 ];
  3819. array[ offset + 11 ] = te[ 11 ];
  3820. array[ offset + 12 ] = te[ 12 ];
  3821. array[ offset + 13 ] = te[ 13 ];
  3822. array[ offset + 14 ] = te[ 14 ];
  3823. array[ offset + 15 ] = te[ 15 ];
  3824. return array;
  3825. }
  3826. }
  3827. Matrix4.prototype.isMatrix4 = true;
  3828. const _v1$5 = /*@__PURE__*/ new Vector3();
  3829. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3830. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3831. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3832. const _x = /*@__PURE__*/ new Vector3();
  3833. const _y = /*@__PURE__*/ new Vector3();
  3834. const _z = /*@__PURE__*/ new Vector3();
  3835. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3836. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3837. class Euler {
  3838. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3839. this._x = x;
  3840. this._y = y;
  3841. this._z = z;
  3842. this._order = order;
  3843. }
  3844. get x() {
  3845. return this._x;
  3846. }
  3847. set x( value ) {
  3848. this._x = value;
  3849. this._onChangeCallback();
  3850. }
  3851. get y() {
  3852. return this._y;
  3853. }
  3854. set y( value ) {
  3855. this._y = value;
  3856. this._onChangeCallback();
  3857. }
  3858. get z() {
  3859. return this._z;
  3860. }
  3861. set z( value ) {
  3862. this._z = value;
  3863. this._onChangeCallback();
  3864. }
  3865. get order() {
  3866. return this._order;
  3867. }
  3868. set order( value ) {
  3869. this._order = value;
  3870. this._onChangeCallback();
  3871. }
  3872. set( x, y, z, order = this._order ) {
  3873. this._x = x;
  3874. this._y = y;
  3875. this._z = z;
  3876. this._order = order;
  3877. this._onChangeCallback();
  3878. return this;
  3879. }
  3880. clone() {
  3881. return new this.constructor( this._x, this._y, this._z, this._order );
  3882. }
  3883. copy( euler ) {
  3884. this._x = euler._x;
  3885. this._y = euler._y;
  3886. this._z = euler._z;
  3887. this._order = euler._order;
  3888. this._onChangeCallback();
  3889. return this;
  3890. }
  3891. setFromRotationMatrix( m, order = this._order, update = true ) {
  3892. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3893. const te = m.elements;
  3894. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3895. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3896. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3897. switch ( order ) {
  3898. case 'XYZ':
  3899. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3900. if ( Math.abs( m13 ) < 0.9999999 ) {
  3901. this._x = Math.atan2( - m23, m33 );
  3902. this._z = Math.atan2( - m12, m11 );
  3903. } else {
  3904. this._x = Math.atan2( m32, m22 );
  3905. this._z = 0;
  3906. }
  3907. break;
  3908. case 'YXZ':
  3909. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3910. if ( Math.abs( m23 ) < 0.9999999 ) {
  3911. this._y = Math.atan2( m13, m33 );
  3912. this._z = Math.atan2( m21, m22 );
  3913. } else {
  3914. this._y = Math.atan2( - m31, m11 );
  3915. this._z = 0;
  3916. }
  3917. break;
  3918. case 'ZXY':
  3919. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3920. if ( Math.abs( m32 ) < 0.9999999 ) {
  3921. this._y = Math.atan2( - m31, m33 );
  3922. this._z = Math.atan2( - m12, m22 );
  3923. } else {
  3924. this._y = 0;
  3925. this._z = Math.atan2( m21, m11 );
  3926. }
  3927. break;
  3928. case 'ZYX':
  3929. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3930. if ( Math.abs( m31 ) < 0.9999999 ) {
  3931. this._x = Math.atan2( m32, m33 );
  3932. this._z = Math.atan2( m21, m11 );
  3933. } else {
  3934. this._x = 0;
  3935. this._z = Math.atan2( - m12, m22 );
  3936. }
  3937. break;
  3938. case 'YZX':
  3939. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3940. if ( Math.abs( m21 ) < 0.9999999 ) {
  3941. this._x = Math.atan2( - m23, m22 );
  3942. this._y = Math.atan2( - m31, m11 );
  3943. } else {
  3944. this._x = 0;
  3945. this._y = Math.atan2( m13, m33 );
  3946. }
  3947. break;
  3948. case 'XZY':
  3949. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3950. if ( Math.abs( m12 ) < 0.9999999 ) {
  3951. this._x = Math.atan2( m32, m22 );
  3952. this._y = Math.atan2( m13, m11 );
  3953. } else {
  3954. this._x = Math.atan2( - m23, m33 );
  3955. this._y = 0;
  3956. }
  3957. break;
  3958. default:
  3959. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3960. }
  3961. this._order = order;
  3962. if ( update === true ) this._onChangeCallback();
  3963. return this;
  3964. }
  3965. setFromQuaternion( q, order, update ) {
  3966. _matrix$1.makeRotationFromQuaternion( q );
  3967. return this.setFromRotationMatrix( _matrix$1, order, update );
  3968. }
  3969. setFromVector3( v, order = this._order ) {
  3970. return this.set( v.x, v.y, v.z, order );
  3971. }
  3972. reorder( newOrder ) {
  3973. // WARNING: this discards revolution information -bhouston
  3974. _quaternion$3.setFromEuler( this );
  3975. return this.setFromQuaternion( _quaternion$3, newOrder );
  3976. }
  3977. equals( euler ) {
  3978. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3979. }
  3980. fromArray( array ) {
  3981. this._x = array[ 0 ];
  3982. this._y = array[ 1 ];
  3983. this._z = array[ 2 ];
  3984. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3985. this._onChangeCallback();
  3986. return this;
  3987. }
  3988. toArray( array = [], offset = 0 ) {
  3989. array[ offset ] = this._x;
  3990. array[ offset + 1 ] = this._y;
  3991. array[ offset + 2 ] = this._z;
  3992. array[ offset + 3 ] = this._order;
  3993. return array;
  3994. }
  3995. toVector3( optionalResult ) {
  3996. if ( optionalResult ) {
  3997. return optionalResult.set( this._x, this._y, this._z );
  3998. } else {
  3999. return new Vector3( this._x, this._y, this._z );
  4000. }
  4001. }
  4002. _onChange( callback ) {
  4003. this._onChangeCallback = callback;
  4004. return this;
  4005. }
  4006. _onChangeCallback() {}
  4007. }
  4008. Euler.prototype.isEuler = true;
  4009. Euler.DefaultOrder = 'XYZ';
  4010. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4011. class Layers {
  4012. constructor() {
  4013. this.mask = 1 | 0;
  4014. }
  4015. set( channel ) {
  4016. this.mask = ( 1 << channel | 0 ) >>> 0;
  4017. }
  4018. enable( channel ) {
  4019. this.mask |= 1 << channel | 0;
  4020. }
  4021. enableAll() {
  4022. this.mask = 0xffffffff | 0;
  4023. }
  4024. toggle( channel ) {
  4025. this.mask ^= 1 << channel | 0;
  4026. }
  4027. disable( channel ) {
  4028. this.mask &= ~ ( 1 << channel | 0 );
  4029. }
  4030. disableAll() {
  4031. this.mask = 0;
  4032. }
  4033. test( layers ) {
  4034. return ( this.mask & layers.mask ) !== 0;
  4035. }
  4036. isEnabled( channel ) {
  4037. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4038. }
  4039. }
  4040. let _object3DId = 0;
  4041. const _v1$4 = /*@__PURE__*/ new Vector3();
  4042. const _q1 = /*@__PURE__*/ new Quaternion();
  4043. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4044. const _target = /*@__PURE__*/ new Vector3();
  4045. const _position$3 = /*@__PURE__*/ new Vector3();
  4046. const _scale$2 = /*@__PURE__*/ new Vector3();
  4047. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4048. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4049. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4050. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4051. const _addedEvent = { type: 'added' };
  4052. const _removedEvent = { type: 'removed' };
  4053. class Object3D extends EventDispatcher {
  4054. constructor() {
  4055. super();
  4056. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4057. this.uuid = generateUUID();
  4058. this.name = '';
  4059. this.type = 'Object3D';
  4060. this.parent = null;
  4061. this.children = [];
  4062. this.up = Object3D.DefaultUp.clone();
  4063. const position = new Vector3();
  4064. const rotation = new Euler();
  4065. const quaternion = new Quaternion();
  4066. const scale = new Vector3( 1, 1, 1 );
  4067. function onRotationChange() {
  4068. quaternion.setFromEuler( rotation, false );
  4069. }
  4070. function onQuaternionChange() {
  4071. rotation.setFromQuaternion( quaternion, undefined, false );
  4072. }
  4073. rotation._onChange( onRotationChange );
  4074. quaternion._onChange( onQuaternionChange );
  4075. Object.defineProperties( this, {
  4076. position: {
  4077. configurable: true,
  4078. enumerable: true,
  4079. value: position
  4080. },
  4081. rotation: {
  4082. configurable: true,
  4083. enumerable: true,
  4084. value: rotation
  4085. },
  4086. quaternion: {
  4087. configurable: true,
  4088. enumerable: true,
  4089. value: quaternion
  4090. },
  4091. scale: {
  4092. configurable: true,
  4093. enumerable: true,
  4094. value: scale
  4095. },
  4096. modelViewMatrix: {
  4097. value: new Matrix4()
  4098. },
  4099. normalMatrix: {
  4100. value: new Matrix3()
  4101. }
  4102. } );
  4103. this.matrix = new Matrix4();
  4104. this.matrixWorld = new Matrix4();
  4105. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4106. this.matrixWorldNeedsUpdate = false;
  4107. this.layers = new Layers();
  4108. this.visible = true;
  4109. this.castShadow = false;
  4110. this.receiveShadow = false;
  4111. this.frustumCulled = true;
  4112. this.renderOrder = 0;
  4113. this.animations = [];
  4114. this.userData = {};
  4115. }
  4116. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4117. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4118. applyMatrix4( matrix ) {
  4119. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4120. this.matrix.premultiply( matrix );
  4121. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4122. }
  4123. applyQuaternion( q ) {
  4124. this.quaternion.premultiply( q );
  4125. return this;
  4126. }
  4127. setRotationFromAxisAngle( axis, angle ) {
  4128. // assumes axis is normalized
  4129. this.quaternion.setFromAxisAngle( axis, angle );
  4130. }
  4131. setRotationFromEuler( euler ) {
  4132. this.quaternion.setFromEuler( euler, true );
  4133. }
  4134. setRotationFromMatrix( m ) {
  4135. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4136. this.quaternion.setFromRotationMatrix( m );
  4137. }
  4138. setRotationFromQuaternion( q ) {
  4139. // assumes q is normalized
  4140. this.quaternion.copy( q );
  4141. }
  4142. rotateOnAxis( axis, angle ) {
  4143. // rotate object on axis in object space
  4144. // axis is assumed to be normalized
  4145. _q1.setFromAxisAngle( axis, angle );
  4146. this.quaternion.multiply( _q1 );
  4147. return this;
  4148. }
  4149. rotateOnWorldAxis( axis, angle ) {
  4150. // rotate object on axis in world space
  4151. // axis is assumed to be normalized
  4152. // method assumes no rotated parent
  4153. _q1.setFromAxisAngle( axis, angle );
  4154. this.quaternion.premultiply( _q1 );
  4155. return this;
  4156. }
  4157. rotateX( angle ) {
  4158. return this.rotateOnAxis( _xAxis, angle );
  4159. }
  4160. rotateY( angle ) {
  4161. return this.rotateOnAxis( _yAxis, angle );
  4162. }
  4163. rotateZ( angle ) {
  4164. return this.rotateOnAxis( _zAxis, angle );
  4165. }
  4166. translateOnAxis( axis, distance ) {
  4167. // translate object by distance along axis in object space
  4168. // axis is assumed to be normalized
  4169. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4170. this.position.add( _v1$4.multiplyScalar( distance ) );
  4171. return this;
  4172. }
  4173. translateX( distance ) {
  4174. return this.translateOnAxis( _xAxis, distance );
  4175. }
  4176. translateY( distance ) {
  4177. return this.translateOnAxis( _yAxis, distance );
  4178. }
  4179. translateZ( distance ) {
  4180. return this.translateOnAxis( _zAxis, distance );
  4181. }
  4182. localToWorld( vector ) {
  4183. return vector.applyMatrix4( this.matrixWorld );
  4184. }
  4185. worldToLocal( vector ) {
  4186. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4187. }
  4188. lookAt( x, y, z ) {
  4189. // This method does not support objects having non-uniformly-scaled parent(s)
  4190. if ( x.isVector3 ) {
  4191. _target.copy( x );
  4192. } else {
  4193. _target.set( x, y, z );
  4194. }
  4195. const parent = this.parent;
  4196. this.updateWorldMatrix( true, false );
  4197. _position$3.setFromMatrixPosition( this.matrixWorld );
  4198. if ( this.isCamera || this.isLight ) {
  4199. _m1$1.lookAt( _position$3, _target, this.up );
  4200. } else {
  4201. _m1$1.lookAt( _target, _position$3, this.up );
  4202. }
  4203. this.quaternion.setFromRotationMatrix( _m1$1 );
  4204. if ( parent ) {
  4205. _m1$1.extractRotation( parent.matrixWorld );
  4206. _q1.setFromRotationMatrix( _m1$1 );
  4207. this.quaternion.premultiply( _q1.invert() );
  4208. }
  4209. }
  4210. add( object ) {
  4211. if ( arguments.length > 1 ) {
  4212. for ( let i = 0; i < arguments.length; i ++ ) {
  4213. this.add( arguments[ i ] );
  4214. }
  4215. return this;
  4216. }
  4217. if ( object === this ) {
  4218. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4219. return this;
  4220. }
  4221. if ( object && object.isObject3D ) {
  4222. if ( object.parent !== null ) {
  4223. object.parent.remove( object );
  4224. }
  4225. object.parent = this;
  4226. this.children.push( object );
  4227. object.dispatchEvent( _addedEvent );
  4228. } else {
  4229. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4230. }
  4231. return this;
  4232. }
  4233. remove( object ) {
  4234. if ( arguments.length > 1 ) {
  4235. for ( let i = 0; i < arguments.length; i ++ ) {
  4236. this.remove( arguments[ i ] );
  4237. }
  4238. return this;
  4239. }
  4240. const index = this.children.indexOf( object );
  4241. if ( index !== - 1 ) {
  4242. object.parent = null;
  4243. this.children.splice( index, 1 );
  4244. object.dispatchEvent( _removedEvent );
  4245. }
  4246. return this;
  4247. }
  4248. removeFromParent() {
  4249. const parent = this.parent;
  4250. if ( parent !== null ) {
  4251. parent.remove( this );
  4252. }
  4253. return this;
  4254. }
  4255. clear() {
  4256. for ( let i = 0; i < this.children.length; i ++ ) {
  4257. const object = this.children[ i ];
  4258. object.parent = null;
  4259. object.dispatchEvent( _removedEvent );
  4260. }
  4261. this.children.length = 0;
  4262. return this;
  4263. }
  4264. attach( object ) {
  4265. // adds object as a child of this, while maintaining the object's world transform
  4266. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4267. this.updateWorldMatrix( true, false );
  4268. _m1$1.copy( this.matrixWorld ).invert();
  4269. if ( object.parent !== null ) {
  4270. object.parent.updateWorldMatrix( true, false );
  4271. _m1$1.multiply( object.parent.matrixWorld );
  4272. }
  4273. object.applyMatrix4( _m1$1 );
  4274. this.add( object );
  4275. object.updateWorldMatrix( false, true );
  4276. return this;
  4277. }
  4278. getObjectById( id ) {
  4279. return this.getObjectByProperty( 'id', id );
  4280. }
  4281. getObjectByName( name ) {
  4282. return this.getObjectByProperty( 'name', name );
  4283. }
  4284. getObjectByProperty( name, value ) {
  4285. if ( this[ name ] === value ) return this;
  4286. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4287. const child = this.children[ i ];
  4288. const object = child.getObjectByProperty( name, value );
  4289. if ( object !== undefined ) {
  4290. return object;
  4291. }
  4292. }
  4293. return undefined;
  4294. }
  4295. getWorldPosition( target ) {
  4296. this.updateWorldMatrix( true, false );
  4297. return target.setFromMatrixPosition( this.matrixWorld );
  4298. }
  4299. getWorldQuaternion( target ) {
  4300. this.updateWorldMatrix( true, false );
  4301. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4302. return target;
  4303. }
  4304. getWorldScale( target ) {
  4305. this.updateWorldMatrix( true, false );
  4306. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4307. return target;
  4308. }
  4309. getWorldDirection( target ) {
  4310. this.updateWorldMatrix( true, false );
  4311. const e = this.matrixWorld.elements;
  4312. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4313. }
  4314. raycast() {}
  4315. traverse( callback ) {
  4316. callback( this );
  4317. const children = this.children;
  4318. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4319. children[ i ].traverse( callback );
  4320. }
  4321. }
  4322. traverseVisible( callback ) {
  4323. if ( this.visible === false ) return;
  4324. callback( this );
  4325. const children = this.children;
  4326. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4327. children[ i ].traverseVisible( callback );
  4328. }
  4329. }
  4330. traverseAncestors( callback ) {
  4331. const parent = this.parent;
  4332. if ( parent !== null ) {
  4333. callback( parent );
  4334. parent.traverseAncestors( callback );
  4335. }
  4336. }
  4337. updateMatrix() {
  4338. this.matrix.compose( this.position, this.quaternion, this.scale );
  4339. this.matrixWorldNeedsUpdate = true;
  4340. }
  4341. updateMatrixWorld( force ) {
  4342. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4343. if ( this.matrixWorldNeedsUpdate || force ) {
  4344. if ( this.parent === null ) {
  4345. this.matrixWorld.copy( this.matrix );
  4346. } else {
  4347. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4348. }
  4349. this.matrixWorldNeedsUpdate = false;
  4350. force = true;
  4351. }
  4352. // update children
  4353. const children = this.children;
  4354. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4355. children[ i ].updateMatrixWorld( force );
  4356. }
  4357. }
  4358. updateWorldMatrix( updateParents, updateChildren ) {
  4359. const parent = this.parent;
  4360. if ( updateParents === true && parent !== null ) {
  4361. parent.updateWorldMatrix( true, false );
  4362. }
  4363. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4364. if ( this.parent === null ) {
  4365. this.matrixWorld.copy( this.matrix );
  4366. } else {
  4367. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4368. }
  4369. // update children
  4370. if ( updateChildren === true ) {
  4371. const children = this.children;
  4372. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4373. children[ i ].updateWorldMatrix( false, true );
  4374. }
  4375. }
  4376. }
  4377. toJSON( meta ) {
  4378. // meta is a string when called from JSON.stringify
  4379. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4380. const output = {};
  4381. // meta is a hash used to collect geometries, materials.
  4382. // not providing it implies that this is the root object
  4383. // being serialized.
  4384. if ( isRootObject ) {
  4385. // initialize meta obj
  4386. meta = {
  4387. geometries: {},
  4388. materials: {},
  4389. textures: {},
  4390. images: {},
  4391. shapes: {},
  4392. skeletons: {},
  4393. animations: {}
  4394. };
  4395. output.metadata = {
  4396. version: 4.5,
  4397. type: 'Object',
  4398. generator: 'Object3D.toJSON'
  4399. };
  4400. }
  4401. // standard Object3D serialization
  4402. const object = {};
  4403. object.uuid = this.uuid;
  4404. object.type = this.type;
  4405. if ( this.name !== '' ) object.name = this.name;
  4406. if ( this.castShadow === true ) object.castShadow = true;
  4407. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4408. if ( this.visible === false ) object.visible = false;
  4409. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4410. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4411. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4412. object.layers = this.layers.mask;
  4413. object.matrix = this.matrix.toArray();
  4414. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4415. // object specific properties
  4416. if ( this.isInstancedMesh ) {
  4417. object.type = 'InstancedMesh';
  4418. object.count = this.count;
  4419. object.instanceMatrix = this.instanceMatrix.toJSON();
  4420. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4421. }
  4422. //
  4423. function serialize( library, element ) {
  4424. if ( library[ element.uuid ] === undefined ) {
  4425. library[ element.uuid ] = element.toJSON( meta );
  4426. }
  4427. return element.uuid;
  4428. }
  4429. if ( this.isScene ) {
  4430. if ( this.background ) {
  4431. if ( this.background.isColor ) {
  4432. object.background = this.background.toJSON();
  4433. } else if ( this.background.isTexture ) {
  4434. object.background = this.background.toJSON( meta ).uuid;
  4435. }
  4436. }
  4437. if ( this.environment && this.environment.isTexture ) {
  4438. object.environment = this.environment.toJSON( meta ).uuid;
  4439. }
  4440. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4441. object.geometry = serialize( meta.geometries, this.geometry );
  4442. const parameters = this.geometry.parameters;
  4443. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4444. const shapes = parameters.shapes;
  4445. if ( Array.isArray( shapes ) ) {
  4446. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4447. const shape = shapes[ i ];
  4448. serialize( meta.shapes, shape );
  4449. }
  4450. } else {
  4451. serialize( meta.shapes, shapes );
  4452. }
  4453. }
  4454. }
  4455. if ( this.isSkinnedMesh ) {
  4456. object.bindMode = this.bindMode;
  4457. object.bindMatrix = this.bindMatrix.toArray();
  4458. if ( this.skeleton !== undefined ) {
  4459. serialize( meta.skeletons, this.skeleton );
  4460. object.skeleton = this.skeleton.uuid;
  4461. }
  4462. }
  4463. if ( this.material !== undefined ) {
  4464. if ( Array.isArray( this.material ) ) {
  4465. const uuids = [];
  4466. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4467. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4468. }
  4469. object.material = uuids;
  4470. } else {
  4471. object.material = serialize( meta.materials, this.material );
  4472. }
  4473. }
  4474. //
  4475. if ( this.children.length > 0 ) {
  4476. object.children = [];
  4477. for ( let i = 0; i < this.children.length; i ++ ) {
  4478. object.children.push( this.children[ i ].toJSON( meta ).object );
  4479. }
  4480. }
  4481. //
  4482. if ( this.animations.length > 0 ) {
  4483. object.animations = [];
  4484. for ( let i = 0; i < this.animations.length; i ++ ) {
  4485. const animation = this.animations[ i ];
  4486. object.animations.push( serialize( meta.animations, animation ) );
  4487. }
  4488. }
  4489. if ( isRootObject ) {
  4490. const geometries = extractFromCache( meta.geometries );
  4491. const materials = extractFromCache( meta.materials );
  4492. const textures = extractFromCache( meta.textures );
  4493. const images = extractFromCache( meta.images );
  4494. const shapes = extractFromCache( meta.shapes );
  4495. const skeletons = extractFromCache( meta.skeletons );
  4496. const animations = extractFromCache( meta.animations );
  4497. if ( geometries.length > 0 ) output.geometries = geometries;
  4498. if ( materials.length > 0 ) output.materials = materials;
  4499. if ( textures.length > 0 ) output.textures = textures;
  4500. if ( images.length > 0 ) output.images = images;
  4501. if ( shapes.length > 0 ) output.shapes = shapes;
  4502. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4503. if ( animations.length > 0 ) output.animations = animations;
  4504. }
  4505. output.object = object;
  4506. return output;
  4507. // extract data from the cache hash
  4508. // remove metadata on each item
  4509. // and return as array
  4510. function extractFromCache( cache ) {
  4511. const values = [];
  4512. for ( const key in cache ) {
  4513. const data = cache[ key ];
  4514. delete data.metadata;
  4515. values.push( data );
  4516. }
  4517. return values;
  4518. }
  4519. }
  4520. clone( recursive ) {
  4521. return new this.constructor().copy( this, recursive );
  4522. }
  4523. copy( source, recursive = true ) {
  4524. this.name = source.name;
  4525. this.up.copy( source.up );
  4526. this.position.copy( source.position );
  4527. this.rotation.order = source.rotation.order;
  4528. this.quaternion.copy( source.quaternion );
  4529. this.scale.copy( source.scale );
  4530. this.matrix.copy( source.matrix );
  4531. this.matrixWorld.copy( source.matrixWorld );
  4532. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4533. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4534. this.layers.mask = source.layers.mask;
  4535. this.visible = source.visible;
  4536. this.castShadow = source.castShadow;
  4537. this.receiveShadow = source.receiveShadow;
  4538. this.frustumCulled = source.frustumCulled;
  4539. this.renderOrder = source.renderOrder;
  4540. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4541. if ( recursive === true ) {
  4542. for ( let i = 0; i < source.children.length; i ++ ) {
  4543. const child = source.children[ i ];
  4544. this.add( child.clone() );
  4545. }
  4546. }
  4547. return this;
  4548. }
  4549. }
  4550. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4551. Object3D.DefaultMatrixAutoUpdate = true;
  4552. Object3D.prototype.isObject3D = true;
  4553. const _v0$1 = /*@__PURE__*/ new Vector3();
  4554. const _v1$3 = /*@__PURE__*/ new Vector3();
  4555. const _v2$2 = /*@__PURE__*/ new Vector3();
  4556. const _v3$1 = /*@__PURE__*/ new Vector3();
  4557. const _vab = /*@__PURE__*/ new Vector3();
  4558. const _vac = /*@__PURE__*/ new Vector3();
  4559. const _vbc = /*@__PURE__*/ new Vector3();
  4560. const _vap = /*@__PURE__*/ new Vector3();
  4561. const _vbp = /*@__PURE__*/ new Vector3();
  4562. const _vcp = /*@__PURE__*/ new Vector3();
  4563. class Triangle {
  4564. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4565. this.a = a;
  4566. this.b = b;
  4567. this.c = c;
  4568. }
  4569. static getNormal( a, b, c, target ) {
  4570. target.subVectors( c, b );
  4571. _v0$1.subVectors( a, b );
  4572. target.cross( _v0$1 );
  4573. const targetLengthSq = target.lengthSq();
  4574. if ( targetLengthSq > 0 ) {
  4575. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4576. }
  4577. return target.set( 0, 0, 0 );
  4578. }
  4579. // static/instance method to calculate barycentric coordinates
  4580. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4581. static getBarycoord( point, a, b, c, target ) {
  4582. _v0$1.subVectors( c, a );
  4583. _v1$3.subVectors( b, a );
  4584. _v2$2.subVectors( point, a );
  4585. const dot00 = _v0$1.dot( _v0$1 );
  4586. const dot01 = _v0$1.dot( _v1$3 );
  4587. const dot02 = _v0$1.dot( _v2$2 );
  4588. const dot11 = _v1$3.dot( _v1$3 );
  4589. const dot12 = _v1$3.dot( _v2$2 );
  4590. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4591. // collinear or singular triangle
  4592. if ( denom === 0 ) {
  4593. // arbitrary location outside of triangle?
  4594. // not sure if this is the best idea, maybe should be returning undefined
  4595. return target.set( - 2, - 1, - 1 );
  4596. }
  4597. const invDenom = 1 / denom;
  4598. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4599. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4600. // barycentric coordinates must always sum to 1
  4601. return target.set( 1 - u - v, v, u );
  4602. }
  4603. static containsPoint( point, a, b, c ) {
  4604. this.getBarycoord( point, a, b, c, _v3$1 );
  4605. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4606. }
  4607. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4608. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4609. target.set( 0, 0 );
  4610. target.addScaledVector( uv1, _v3$1.x );
  4611. target.addScaledVector( uv2, _v3$1.y );
  4612. target.addScaledVector( uv3, _v3$1.z );
  4613. return target;
  4614. }
  4615. static isFrontFacing( a, b, c, direction ) {
  4616. _v0$1.subVectors( c, b );
  4617. _v1$3.subVectors( a, b );
  4618. // strictly front facing
  4619. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4620. }
  4621. set( a, b, c ) {
  4622. this.a.copy( a );
  4623. this.b.copy( b );
  4624. this.c.copy( c );
  4625. return this;
  4626. }
  4627. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4628. this.a.copy( points[ i0 ] );
  4629. this.b.copy( points[ i1 ] );
  4630. this.c.copy( points[ i2 ] );
  4631. return this;
  4632. }
  4633. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4634. this.a.fromBufferAttribute( attribute, i0 );
  4635. this.b.fromBufferAttribute( attribute, i1 );
  4636. this.c.fromBufferAttribute( attribute, i2 );
  4637. return this;
  4638. }
  4639. clone() {
  4640. return new this.constructor().copy( this );
  4641. }
  4642. copy( triangle ) {
  4643. this.a.copy( triangle.a );
  4644. this.b.copy( triangle.b );
  4645. this.c.copy( triangle.c );
  4646. return this;
  4647. }
  4648. getArea() {
  4649. _v0$1.subVectors( this.c, this.b );
  4650. _v1$3.subVectors( this.a, this.b );
  4651. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4652. }
  4653. getMidpoint( target ) {
  4654. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4655. }
  4656. getNormal( target ) {
  4657. return Triangle.getNormal( this.a, this.b, this.c, target );
  4658. }
  4659. getPlane( target ) {
  4660. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4661. }
  4662. getBarycoord( point, target ) {
  4663. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4664. }
  4665. getUV( point, uv1, uv2, uv3, target ) {
  4666. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4667. }
  4668. containsPoint( point ) {
  4669. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4670. }
  4671. isFrontFacing( direction ) {
  4672. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4673. }
  4674. intersectsBox( box ) {
  4675. return box.intersectsTriangle( this );
  4676. }
  4677. closestPointToPoint( p, target ) {
  4678. const a = this.a, b = this.b, c = this.c;
  4679. let v, w;
  4680. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4681. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4682. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4683. // basically, we're distinguishing which of the voronoi regions of the triangle
  4684. // the point lies in with the minimum amount of redundant computation.
  4685. _vab.subVectors( b, a );
  4686. _vac.subVectors( c, a );
  4687. _vap.subVectors( p, a );
  4688. const d1 = _vab.dot( _vap );
  4689. const d2 = _vac.dot( _vap );
  4690. if ( d1 <= 0 && d2 <= 0 ) {
  4691. // vertex region of A; barycentric coords (1, 0, 0)
  4692. return target.copy( a );
  4693. }
  4694. _vbp.subVectors( p, b );
  4695. const d3 = _vab.dot( _vbp );
  4696. const d4 = _vac.dot( _vbp );
  4697. if ( d3 >= 0 && d4 <= d3 ) {
  4698. // vertex region of B; barycentric coords (0, 1, 0)
  4699. return target.copy( b );
  4700. }
  4701. const vc = d1 * d4 - d3 * d2;
  4702. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4703. v = d1 / ( d1 - d3 );
  4704. // edge region of AB; barycentric coords (1-v, v, 0)
  4705. return target.copy( a ).addScaledVector( _vab, v );
  4706. }
  4707. _vcp.subVectors( p, c );
  4708. const d5 = _vab.dot( _vcp );
  4709. const d6 = _vac.dot( _vcp );
  4710. if ( d6 >= 0 && d5 <= d6 ) {
  4711. // vertex region of C; barycentric coords (0, 0, 1)
  4712. return target.copy( c );
  4713. }
  4714. const vb = d5 * d2 - d1 * d6;
  4715. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4716. w = d2 / ( d2 - d6 );
  4717. // edge region of AC; barycentric coords (1-w, 0, w)
  4718. return target.copy( a ).addScaledVector( _vac, w );
  4719. }
  4720. const va = d3 * d6 - d5 * d4;
  4721. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4722. _vbc.subVectors( c, b );
  4723. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4724. // edge region of BC; barycentric coords (0, 1-w, w)
  4725. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4726. }
  4727. // face region
  4728. const denom = 1 / ( va + vb + vc );
  4729. // u = va * denom
  4730. v = vb * denom;
  4731. w = vc * denom;
  4732. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4733. }
  4734. equals( triangle ) {
  4735. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4736. }
  4737. }
  4738. let materialId = 0;
  4739. class Material extends EventDispatcher {
  4740. constructor() {
  4741. super();
  4742. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4743. this.uuid = generateUUID();
  4744. this.name = '';
  4745. this.type = 'Material';
  4746. this.fog = true;
  4747. this.blending = NormalBlending;
  4748. this.side = FrontSide;
  4749. this.vertexColors = false;
  4750. this.opacity = 1;
  4751. this.format = RGBAFormat;
  4752. this.transparent = false;
  4753. this.blendSrc = SrcAlphaFactor;
  4754. this.blendDst = OneMinusSrcAlphaFactor;
  4755. this.blendEquation = AddEquation;
  4756. this.blendSrcAlpha = null;
  4757. this.blendDstAlpha = null;
  4758. this.blendEquationAlpha = null;
  4759. this.depthFunc = LessEqualDepth;
  4760. this.depthTest = true;
  4761. this.depthWrite = true;
  4762. this.stencilWriteMask = 0xff;
  4763. this.stencilFunc = AlwaysStencilFunc;
  4764. this.stencilRef = 0;
  4765. this.stencilFuncMask = 0xff;
  4766. this.stencilFail = KeepStencilOp;
  4767. this.stencilZFail = KeepStencilOp;
  4768. this.stencilZPass = KeepStencilOp;
  4769. this.stencilWrite = false;
  4770. this.clippingPlanes = null;
  4771. this.clipIntersection = false;
  4772. this.clipShadows = false;
  4773. this.shadowSide = null;
  4774. this.colorWrite = true;
  4775. this.precision = null; // override the renderer's default precision for this material
  4776. this.polygonOffset = false;
  4777. this.polygonOffsetFactor = 0;
  4778. this.polygonOffsetUnits = 0;
  4779. this.dithering = false;
  4780. this.alphaToCoverage = false;
  4781. this.premultipliedAlpha = false;
  4782. this.visible = true;
  4783. this.toneMapped = true;
  4784. this.userData = {};
  4785. this.version = 0;
  4786. this._alphaTest = 0;
  4787. }
  4788. get alphaTest() {
  4789. return this._alphaTest;
  4790. }
  4791. set alphaTest( value ) {
  4792. if ( this._alphaTest > 0 !== value > 0 ) {
  4793. this.version ++;
  4794. }
  4795. this._alphaTest = value;
  4796. }
  4797. onBuild( /* shaderobject, renderer */ ) {}
  4798. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4799. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4800. customProgramCacheKey() {
  4801. return this.onBeforeCompile.toString();
  4802. }
  4803. setValues( values ) {
  4804. if ( values === undefined ) return;
  4805. for ( const key in values ) {
  4806. const newValue = values[ key ];
  4807. if ( newValue === undefined ) {
  4808. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4809. continue;
  4810. }
  4811. // for backward compatability if shading is set in the constructor
  4812. if ( key === 'shading' ) {
  4813. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4814. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4815. continue;
  4816. }
  4817. const currentValue = this[ key ];
  4818. if ( currentValue === undefined ) {
  4819. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4820. continue;
  4821. }
  4822. if ( currentValue && currentValue.isColor ) {
  4823. currentValue.set( newValue );
  4824. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4825. currentValue.copy( newValue );
  4826. } else {
  4827. this[ key ] = newValue;
  4828. }
  4829. }
  4830. }
  4831. toJSON( meta ) {
  4832. const isRoot = ( meta === undefined || typeof meta === 'string' );
  4833. if ( isRoot ) {
  4834. meta = {
  4835. textures: {},
  4836. images: {}
  4837. };
  4838. }
  4839. const data = {
  4840. metadata: {
  4841. version: 4.5,
  4842. type: 'Material',
  4843. generator: 'Material.toJSON'
  4844. }
  4845. };
  4846. // standard Material serialization
  4847. data.uuid = this.uuid;
  4848. data.type = this.type;
  4849. if ( this.name !== '' ) data.name = this.name;
  4850. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4851. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4852. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4853. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  4854. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  4855. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  4856. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4857. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  4858. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4859. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  4860. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  4861. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4862. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  4863. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  4864. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  4865. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  4866. }
  4867. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  4868. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  4869. }
  4870. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  4871. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  4872. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4873. }
  4874. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4875. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  4876. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4877. if ( this.lightMap && this.lightMap.isTexture ) {
  4878. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4879. data.lightMapIntensity = this.lightMapIntensity;
  4880. }
  4881. if ( this.aoMap && this.aoMap.isTexture ) {
  4882. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  4883. data.aoMapIntensity = this.aoMapIntensity;
  4884. }
  4885. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4886. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4887. data.bumpScale = this.bumpScale;
  4888. }
  4889. if ( this.normalMap && this.normalMap.isTexture ) {
  4890. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4891. data.normalMapType = this.normalMapType;
  4892. data.normalScale = this.normalScale.toArray();
  4893. }
  4894. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4895. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4896. data.displacementScale = this.displacementScale;
  4897. data.displacementBias = this.displacementBias;
  4898. }
  4899. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4900. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4901. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4902. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4903. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  4904. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  4905. if ( this.envMap && this.envMap.isTexture ) {
  4906. data.envMap = this.envMap.toJSON( meta ).uuid;
  4907. if ( this.combine !== undefined ) data.combine = this.combine;
  4908. }
  4909. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  4910. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  4911. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  4912. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4913. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4914. }
  4915. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  4916. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  4917. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  4918. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  4919. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  4920. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  4921. if ( this.size !== undefined ) data.size = this.size;
  4922. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  4923. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4924. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4925. if ( this.side !== FrontSide ) data.side = this.side;
  4926. if ( this.vertexColors ) data.vertexColors = true;
  4927. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4928. if ( this.format !== RGBAFormat ) data.format = this.format;
  4929. if ( this.transparent === true ) data.transparent = this.transparent;
  4930. data.depthFunc = this.depthFunc;
  4931. data.depthTest = this.depthTest;
  4932. data.depthWrite = this.depthWrite;
  4933. data.colorWrite = this.colorWrite;
  4934. data.stencilWrite = this.stencilWrite;
  4935. data.stencilWriteMask = this.stencilWriteMask;
  4936. data.stencilFunc = this.stencilFunc;
  4937. data.stencilRef = this.stencilRef;
  4938. data.stencilFuncMask = this.stencilFuncMask;
  4939. data.stencilFail = this.stencilFail;
  4940. data.stencilZFail = this.stencilZFail;
  4941. data.stencilZPass = this.stencilZPass;
  4942. // rotation (SpriteMaterial)
  4943. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  4944. if ( this.polygonOffset === true ) data.polygonOffset = true;
  4945. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4946. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4947. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  4948. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  4949. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  4950. if ( this.scale !== undefined ) data.scale = this.scale;
  4951. if ( this.dithering === true ) data.dithering = true;
  4952. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4953. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  4954. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4955. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4956. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4957. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4958. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4959. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4960. if ( this.visible === false ) data.visible = false;
  4961. if ( this.toneMapped === false ) data.toneMapped = false;
  4962. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4963. // TODO: Copied from Object3D.toJSON
  4964. function extractFromCache( cache ) {
  4965. const values = [];
  4966. for ( const key in cache ) {
  4967. const data = cache[ key ];
  4968. delete data.metadata;
  4969. values.push( data );
  4970. }
  4971. return values;
  4972. }
  4973. if ( isRoot ) {
  4974. const textures = extractFromCache( meta.textures );
  4975. const images = extractFromCache( meta.images );
  4976. if ( textures.length > 0 ) data.textures = textures;
  4977. if ( images.length > 0 ) data.images = images;
  4978. }
  4979. return data;
  4980. }
  4981. clone() {
  4982. return new this.constructor().copy( this );
  4983. }
  4984. copy( source ) {
  4985. this.name = source.name;
  4986. this.fog = source.fog;
  4987. this.blending = source.blending;
  4988. this.side = source.side;
  4989. this.vertexColors = source.vertexColors;
  4990. this.opacity = source.opacity;
  4991. this.format = source.format;
  4992. this.transparent = source.transparent;
  4993. this.blendSrc = source.blendSrc;
  4994. this.blendDst = source.blendDst;
  4995. this.blendEquation = source.blendEquation;
  4996. this.blendSrcAlpha = source.blendSrcAlpha;
  4997. this.blendDstAlpha = source.blendDstAlpha;
  4998. this.blendEquationAlpha = source.blendEquationAlpha;
  4999. this.depthFunc = source.depthFunc;
  5000. this.depthTest = source.depthTest;
  5001. this.depthWrite = source.depthWrite;
  5002. this.stencilWriteMask = source.stencilWriteMask;
  5003. this.stencilFunc = source.stencilFunc;
  5004. this.stencilRef = source.stencilRef;
  5005. this.stencilFuncMask = source.stencilFuncMask;
  5006. this.stencilFail = source.stencilFail;
  5007. this.stencilZFail = source.stencilZFail;
  5008. this.stencilZPass = source.stencilZPass;
  5009. this.stencilWrite = source.stencilWrite;
  5010. const srcPlanes = source.clippingPlanes;
  5011. let dstPlanes = null;
  5012. if ( srcPlanes !== null ) {
  5013. const n = srcPlanes.length;
  5014. dstPlanes = new Array( n );
  5015. for ( let i = 0; i !== n; ++ i ) {
  5016. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5017. }
  5018. }
  5019. this.clippingPlanes = dstPlanes;
  5020. this.clipIntersection = source.clipIntersection;
  5021. this.clipShadows = source.clipShadows;
  5022. this.shadowSide = source.shadowSide;
  5023. this.colorWrite = source.colorWrite;
  5024. this.precision = source.precision;
  5025. this.polygonOffset = source.polygonOffset;
  5026. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5027. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5028. this.dithering = source.dithering;
  5029. this.alphaTest = source.alphaTest;
  5030. this.alphaToCoverage = source.alphaToCoverage;
  5031. this.premultipliedAlpha = source.premultipliedAlpha;
  5032. this.visible = source.visible;
  5033. this.toneMapped = source.toneMapped;
  5034. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5035. return this;
  5036. }
  5037. dispose() {
  5038. this.dispatchEvent( { type: 'dispose' } );
  5039. }
  5040. set needsUpdate( value ) {
  5041. if ( value === true ) this.version ++;
  5042. }
  5043. }
  5044. Material.prototype.isMaterial = true;
  5045. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5046. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5047. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5048. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5049. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5050. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5051. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5052. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5053. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5054. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5055. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5056. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5057. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5058. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5059. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5060. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5061. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5062. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5063. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5064. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5065. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5066. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5067. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5068. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5069. const _hslA = { h: 0, s: 0, l: 0 };
  5070. const _hslB = { h: 0, s: 0, l: 0 };
  5071. function hue2rgb( p, q, t ) {
  5072. if ( t < 0 ) t += 1;
  5073. if ( t > 1 ) t -= 1;
  5074. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5075. if ( t < 1 / 2 ) return q;
  5076. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5077. return p;
  5078. }
  5079. function SRGBToLinear( c ) {
  5080. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5081. }
  5082. function LinearToSRGB( c ) {
  5083. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5084. }
  5085. class Color {
  5086. constructor( r, g, b ) {
  5087. if ( g === undefined && b === undefined ) {
  5088. // r is THREE.Color, hex or string
  5089. return this.set( r );
  5090. }
  5091. return this.setRGB( r, g, b );
  5092. }
  5093. set( value ) {
  5094. if ( value && value.isColor ) {
  5095. this.copy( value );
  5096. } else if ( typeof value === 'number' ) {
  5097. this.setHex( value );
  5098. } else if ( typeof value === 'string' ) {
  5099. this.setStyle( value );
  5100. }
  5101. return this;
  5102. }
  5103. setScalar( scalar ) {
  5104. this.r = scalar;
  5105. this.g = scalar;
  5106. this.b = scalar;
  5107. return this;
  5108. }
  5109. setHex( hex ) {
  5110. hex = Math.floor( hex );
  5111. this.r = ( hex >> 16 & 255 ) / 255;
  5112. this.g = ( hex >> 8 & 255 ) / 255;
  5113. this.b = ( hex & 255 ) / 255;
  5114. return this;
  5115. }
  5116. setRGB( r, g, b ) {
  5117. this.r = r;
  5118. this.g = g;
  5119. this.b = b;
  5120. return this;
  5121. }
  5122. setHSL( h, s, l ) {
  5123. // h,s,l ranges are in 0.0 - 1.0
  5124. h = euclideanModulo( h, 1 );
  5125. s = clamp( s, 0, 1 );
  5126. l = clamp( l, 0, 1 );
  5127. if ( s === 0 ) {
  5128. this.r = this.g = this.b = l;
  5129. } else {
  5130. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5131. const q = ( 2 * l ) - p;
  5132. this.r = hue2rgb( q, p, h + 1 / 3 );
  5133. this.g = hue2rgb( q, p, h );
  5134. this.b = hue2rgb( q, p, h - 1 / 3 );
  5135. }
  5136. return this;
  5137. }
  5138. setStyle( style ) {
  5139. function handleAlpha( string ) {
  5140. if ( string === undefined ) return;
  5141. if ( parseFloat( string ) < 1 ) {
  5142. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5143. }
  5144. }
  5145. let m;
  5146. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  5147. // rgb / hsl
  5148. let color;
  5149. const name = m[ 1 ];
  5150. const components = m[ 2 ];
  5151. switch ( name ) {
  5152. case 'rgb':
  5153. case 'rgba':
  5154. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5155. // rgb(255,0,0) rgba(255,0,0,0.5)
  5156. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5157. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5158. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5159. handleAlpha( color[ 4 ] );
  5160. return this;
  5161. }
  5162. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5163. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5164. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5165. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5166. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5167. handleAlpha( color[ 4 ] );
  5168. return this;
  5169. }
  5170. break;
  5171. case 'hsl':
  5172. case 'hsla':
  5173. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5174. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5175. const h = parseFloat( color[ 1 ] ) / 360;
  5176. const s = parseInt( color[ 2 ], 10 ) / 100;
  5177. const l = parseInt( color[ 3 ], 10 ) / 100;
  5178. handleAlpha( color[ 4 ] );
  5179. return this.setHSL( h, s, l );
  5180. }
  5181. break;
  5182. }
  5183. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5184. // hex color
  5185. const hex = m[ 1 ];
  5186. const size = hex.length;
  5187. if ( size === 3 ) {
  5188. // #ff0
  5189. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5190. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5191. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5192. return this;
  5193. } else if ( size === 6 ) {
  5194. // #ff0000
  5195. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5196. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5197. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5198. return this;
  5199. }
  5200. }
  5201. if ( style && style.length > 0 ) {
  5202. return this.setColorName( style );
  5203. }
  5204. return this;
  5205. }
  5206. setColorName( style ) {
  5207. // color keywords
  5208. const hex = _colorKeywords[ style.toLowerCase() ];
  5209. if ( hex !== undefined ) {
  5210. // red
  5211. this.setHex( hex );
  5212. } else {
  5213. // unknown color
  5214. console.warn( 'THREE.Color: Unknown color ' + style );
  5215. }
  5216. return this;
  5217. }
  5218. clone() {
  5219. return new this.constructor( this.r, this.g, this.b );
  5220. }
  5221. copy( color ) {
  5222. this.r = color.r;
  5223. this.g = color.g;
  5224. this.b = color.b;
  5225. return this;
  5226. }
  5227. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5228. this.r = Math.pow( color.r, gammaFactor );
  5229. this.g = Math.pow( color.g, gammaFactor );
  5230. this.b = Math.pow( color.b, gammaFactor );
  5231. return this;
  5232. }
  5233. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5234. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5235. this.r = Math.pow( color.r, safeInverse );
  5236. this.g = Math.pow( color.g, safeInverse );
  5237. this.b = Math.pow( color.b, safeInverse );
  5238. return this;
  5239. }
  5240. convertGammaToLinear( gammaFactor ) {
  5241. this.copyGammaToLinear( this, gammaFactor );
  5242. return this;
  5243. }
  5244. convertLinearToGamma( gammaFactor ) {
  5245. this.copyLinearToGamma( this, gammaFactor );
  5246. return this;
  5247. }
  5248. copySRGBToLinear( color ) {
  5249. this.r = SRGBToLinear( color.r );
  5250. this.g = SRGBToLinear( color.g );
  5251. this.b = SRGBToLinear( color.b );
  5252. return this;
  5253. }
  5254. copyLinearToSRGB( color ) {
  5255. this.r = LinearToSRGB( color.r );
  5256. this.g = LinearToSRGB( color.g );
  5257. this.b = LinearToSRGB( color.b );
  5258. return this;
  5259. }
  5260. convertSRGBToLinear() {
  5261. this.copySRGBToLinear( this );
  5262. return this;
  5263. }
  5264. convertLinearToSRGB() {
  5265. this.copyLinearToSRGB( this );
  5266. return this;
  5267. }
  5268. getHex() {
  5269. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5270. }
  5271. getHexString() {
  5272. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5273. }
  5274. getHSL( target ) {
  5275. // h,s,l ranges are in 0.0 - 1.0
  5276. const r = this.r, g = this.g, b = this.b;
  5277. const max = Math.max( r, g, b );
  5278. const min = Math.min( r, g, b );
  5279. let hue, saturation;
  5280. const lightness = ( min + max ) / 2.0;
  5281. if ( min === max ) {
  5282. hue = 0;
  5283. saturation = 0;
  5284. } else {
  5285. const delta = max - min;
  5286. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5287. switch ( max ) {
  5288. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5289. case g: hue = ( b - r ) / delta + 2; break;
  5290. case b: hue = ( r - g ) / delta + 4; break;
  5291. }
  5292. hue /= 6;
  5293. }
  5294. target.h = hue;
  5295. target.s = saturation;
  5296. target.l = lightness;
  5297. return target;
  5298. }
  5299. getStyle() {
  5300. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5301. }
  5302. offsetHSL( h, s, l ) {
  5303. this.getHSL( _hslA );
  5304. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5305. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5306. return this;
  5307. }
  5308. add( color ) {
  5309. this.r += color.r;
  5310. this.g += color.g;
  5311. this.b += color.b;
  5312. return this;
  5313. }
  5314. addColors( color1, color2 ) {
  5315. this.r = color1.r + color2.r;
  5316. this.g = color1.g + color2.g;
  5317. this.b = color1.b + color2.b;
  5318. return this;
  5319. }
  5320. addScalar( s ) {
  5321. this.r += s;
  5322. this.g += s;
  5323. this.b += s;
  5324. return this;
  5325. }
  5326. sub( color ) {
  5327. this.r = Math.max( 0, this.r - color.r );
  5328. this.g = Math.max( 0, this.g - color.g );
  5329. this.b = Math.max( 0, this.b - color.b );
  5330. return this;
  5331. }
  5332. multiply( color ) {
  5333. this.r *= color.r;
  5334. this.g *= color.g;
  5335. this.b *= color.b;
  5336. return this;
  5337. }
  5338. multiplyScalar( s ) {
  5339. this.r *= s;
  5340. this.g *= s;
  5341. this.b *= s;
  5342. return this;
  5343. }
  5344. lerp( color, alpha ) {
  5345. this.r += ( color.r - this.r ) * alpha;
  5346. this.g += ( color.g - this.g ) * alpha;
  5347. this.b += ( color.b - this.b ) * alpha;
  5348. return this;
  5349. }
  5350. lerpColors( color1, color2, alpha ) {
  5351. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5352. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5353. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5354. return this;
  5355. }
  5356. lerpHSL( color, alpha ) {
  5357. this.getHSL( _hslA );
  5358. color.getHSL( _hslB );
  5359. const h = lerp( _hslA.h, _hslB.h, alpha );
  5360. const s = lerp( _hslA.s, _hslB.s, alpha );
  5361. const l = lerp( _hslA.l, _hslB.l, alpha );
  5362. this.setHSL( h, s, l );
  5363. return this;
  5364. }
  5365. equals( c ) {
  5366. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5367. }
  5368. fromArray( array, offset = 0 ) {
  5369. this.r = array[ offset ];
  5370. this.g = array[ offset + 1 ];
  5371. this.b = array[ offset + 2 ];
  5372. return this;
  5373. }
  5374. toArray( array = [], offset = 0 ) {
  5375. array[ offset ] = this.r;
  5376. array[ offset + 1 ] = this.g;
  5377. array[ offset + 2 ] = this.b;
  5378. return array;
  5379. }
  5380. fromBufferAttribute( attribute, index ) {
  5381. this.r = attribute.getX( index );
  5382. this.g = attribute.getY( index );
  5383. this.b = attribute.getZ( index );
  5384. if ( attribute.normalized === true ) {
  5385. // assuming Uint8Array
  5386. this.r /= 255;
  5387. this.g /= 255;
  5388. this.b /= 255;
  5389. }
  5390. return this;
  5391. }
  5392. toJSON() {
  5393. return this.getHex();
  5394. }
  5395. }
  5396. Color.NAMES = _colorKeywords;
  5397. Color.prototype.isColor = true;
  5398. Color.prototype.r = 1;
  5399. Color.prototype.g = 1;
  5400. Color.prototype.b = 1;
  5401. /**
  5402. * parameters = {
  5403. * color: <hex>,
  5404. * opacity: <float>,
  5405. * map: new THREE.Texture( <Image> ),
  5406. *
  5407. * lightMap: new THREE.Texture( <Image> ),
  5408. * lightMapIntensity: <float>
  5409. *
  5410. * aoMap: new THREE.Texture( <Image> ),
  5411. * aoMapIntensity: <float>
  5412. *
  5413. * specularMap: new THREE.Texture( <Image> ),
  5414. *
  5415. * alphaMap: new THREE.Texture( <Image> ),
  5416. *
  5417. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5418. * combine: THREE.Multiply,
  5419. * reflectivity: <float>,
  5420. * refractionRatio: <float>,
  5421. *
  5422. * depthTest: <bool>,
  5423. * depthWrite: <bool>,
  5424. *
  5425. * wireframe: <boolean>,
  5426. * wireframeLinewidth: <float>,
  5427. * }
  5428. */
  5429. class MeshBasicMaterial extends Material {
  5430. constructor( parameters ) {
  5431. super();
  5432. this.type = 'MeshBasicMaterial';
  5433. this.color = new Color( 0xffffff ); // emissive
  5434. this.map = null;
  5435. this.lightMap = null;
  5436. this.lightMapIntensity = 1.0;
  5437. this.aoMap = null;
  5438. this.aoMapIntensity = 1.0;
  5439. this.specularMap = null;
  5440. this.alphaMap = null;
  5441. this.envMap = null;
  5442. this.combine = MultiplyOperation;
  5443. this.reflectivity = 1;
  5444. this.refractionRatio = 0.98;
  5445. this.wireframe = false;
  5446. this.wireframeLinewidth = 1;
  5447. this.wireframeLinecap = 'round';
  5448. this.wireframeLinejoin = 'round';
  5449. this.setValues( parameters );
  5450. }
  5451. copy( source ) {
  5452. super.copy( source );
  5453. this.color.copy( source.color );
  5454. this.map = source.map;
  5455. this.lightMap = source.lightMap;
  5456. this.lightMapIntensity = source.lightMapIntensity;
  5457. this.aoMap = source.aoMap;
  5458. this.aoMapIntensity = source.aoMapIntensity;
  5459. this.specularMap = source.specularMap;
  5460. this.alphaMap = source.alphaMap;
  5461. this.envMap = source.envMap;
  5462. this.combine = source.combine;
  5463. this.reflectivity = source.reflectivity;
  5464. this.refractionRatio = source.refractionRatio;
  5465. this.wireframe = source.wireframe;
  5466. this.wireframeLinewidth = source.wireframeLinewidth;
  5467. this.wireframeLinecap = source.wireframeLinecap;
  5468. this.wireframeLinejoin = source.wireframeLinejoin;
  5469. return this;
  5470. }
  5471. }
  5472. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5473. const _vector$9 = /*@__PURE__*/ new Vector3();
  5474. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5475. class BufferAttribute {
  5476. constructor( array, itemSize, normalized ) {
  5477. if ( Array.isArray( array ) ) {
  5478. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5479. }
  5480. this.name = '';
  5481. this.array = array;
  5482. this.itemSize = itemSize;
  5483. this.count = array !== undefined ? array.length / itemSize : 0;
  5484. this.normalized = normalized === true;
  5485. this.usage = StaticDrawUsage;
  5486. this.updateRange = { offset: 0, count: - 1 };
  5487. this.version = 0;
  5488. }
  5489. onUploadCallback() {}
  5490. set needsUpdate( value ) {
  5491. if ( value === true ) this.version ++;
  5492. }
  5493. setUsage( value ) {
  5494. this.usage = value;
  5495. return this;
  5496. }
  5497. copy( source ) {
  5498. this.name = source.name;
  5499. this.array = new source.array.constructor( source.array );
  5500. this.itemSize = source.itemSize;
  5501. this.count = source.count;
  5502. this.normalized = source.normalized;
  5503. this.usage = source.usage;
  5504. return this;
  5505. }
  5506. copyAt( index1, attribute, index2 ) {
  5507. index1 *= this.itemSize;
  5508. index2 *= attribute.itemSize;
  5509. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5510. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5511. }
  5512. return this;
  5513. }
  5514. copyArray( array ) {
  5515. this.array.set( array );
  5516. return this;
  5517. }
  5518. copyColorsArray( colors ) {
  5519. const array = this.array;
  5520. let offset = 0;
  5521. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5522. let color = colors[ i ];
  5523. if ( color === undefined ) {
  5524. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5525. color = new Color();
  5526. }
  5527. array[ offset ++ ] = color.r;
  5528. array[ offset ++ ] = color.g;
  5529. array[ offset ++ ] = color.b;
  5530. }
  5531. return this;
  5532. }
  5533. copyVector2sArray( vectors ) {
  5534. const array = this.array;
  5535. let offset = 0;
  5536. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5537. let vector = vectors[ i ];
  5538. if ( vector === undefined ) {
  5539. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5540. vector = new Vector2();
  5541. }
  5542. array[ offset ++ ] = vector.x;
  5543. array[ offset ++ ] = vector.y;
  5544. }
  5545. return this;
  5546. }
  5547. copyVector3sArray( vectors ) {
  5548. const array = this.array;
  5549. let offset = 0;
  5550. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5551. let vector = vectors[ i ];
  5552. if ( vector === undefined ) {
  5553. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5554. vector = new Vector3();
  5555. }
  5556. array[ offset ++ ] = vector.x;
  5557. array[ offset ++ ] = vector.y;
  5558. array[ offset ++ ] = vector.z;
  5559. }
  5560. return this;
  5561. }
  5562. copyVector4sArray( vectors ) {
  5563. const array = this.array;
  5564. let offset = 0;
  5565. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5566. let vector = vectors[ i ];
  5567. if ( vector === undefined ) {
  5568. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5569. vector = new Vector4();
  5570. }
  5571. array[ offset ++ ] = vector.x;
  5572. array[ offset ++ ] = vector.y;
  5573. array[ offset ++ ] = vector.z;
  5574. array[ offset ++ ] = vector.w;
  5575. }
  5576. return this;
  5577. }
  5578. applyMatrix3( m ) {
  5579. if ( this.itemSize === 2 ) {
  5580. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5581. _vector2$1.fromBufferAttribute( this, i );
  5582. _vector2$1.applyMatrix3( m );
  5583. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5584. }
  5585. } else if ( this.itemSize === 3 ) {
  5586. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5587. _vector$9.fromBufferAttribute( this, i );
  5588. _vector$9.applyMatrix3( m );
  5589. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5590. }
  5591. }
  5592. return this;
  5593. }
  5594. applyMatrix4( m ) {
  5595. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5596. _vector$9.x = this.getX( i );
  5597. _vector$9.y = this.getY( i );
  5598. _vector$9.z = this.getZ( i );
  5599. _vector$9.applyMatrix4( m );
  5600. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5601. }
  5602. return this;
  5603. }
  5604. applyNormalMatrix( m ) {
  5605. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5606. _vector$9.x = this.getX( i );
  5607. _vector$9.y = this.getY( i );
  5608. _vector$9.z = this.getZ( i );
  5609. _vector$9.applyNormalMatrix( m );
  5610. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5611. }
  5612. return this;
  5613. }
  5614. transformDirection( m ) {
  5615. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5616. _vector$9.x = this.getX( i );
  5617. _vector$9.y = this.getY( i );
  5618. _vector$9.z = this.getZ( i );
  5619. _vector$9.transformDirection( m );
  5620. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5621. }
  5622. return this;
  5623. }
  5624. set( value, offset = 0 ) {
  5625. this.array.set( value, offset );
  5626. return this;
  5627. }
  5628. getX( index ) {
  5629. return this.array[ index * this.itemSize ];
  5630. }
  5631. setX( index, x ) {
  5632. this.array[ index * this.itemSize ] = x;
  5633. return this;
  5634. }
  5635. getY( index ) {
  5636. return this.array[ index * this.itemSize + 1 ];
  5637. }
  5638. setY( index, y ) {
  5639. this.array[ index * this.itemSize + 1 ] = y;
  5640. return this;
  5641. }
  5642. getZ( index ) {
  5643. return this.array[ index * this.itemSize + 2 ];
  5644. }
  5645. setZ( index, z ) {
  5646. this.array[ index * this.itemSize + 2 ] = z;
  5647. return this;
  5648. }
  5649. getW( index ) {
  5650. return this.array[ index * this.itemSize + 3 ];
  5651. }
  5652. setW( index, w ) {
  5653. this.array[ index * this.itemSize + 3 ] = w;
  5654. return this;
  5655. }
  5656. setXY( index, x, y ) {
  5657. index *= this.itemSize;
  5658. this.array[ index + 0 ] = x;
  5659. this.array[ index + 1 ] = y;
  5660. return this;
  5661. }
  5662. setXYZ( index, x, y, z ) {
  5663. index *= this.itemSize;
  5664. this.array[ index + 0 ] = x;
  5665. this.array[ index + 1 ] = y;
  5666. this.array[ index + 2 ] = z;
  5667. return this;
  5668. }
  5669. setXYZW( index, x, y, z, w ) {
  5670. index *= this.itemSize;
  5671. this.array[ index + 0 ] = x;
  5672. this.array[ index + 1 ] = y;
  5673. this.array[ index + 2 ] = z;
  5674. this.array[ index + 3 ] = w;
  5675. return this;
  5676. }
  5677. onUpload( callback ) {
  5678. this.onUploadCallback = callback;
  5679. return this;
  5680. }
  5681. clone() {
  5682. return new this.constructor( this.array, this.itemSize ).copy( this );
  5683. }
  5684. toJSON() {
  5685. const data = {
  5686. itemSize: this.itemSize,
  5687. type: this.array.constructor.name,
  5688. array: Array.prototype.slice.call( this.array ),
  5689. normalized: this.normalized
  5690. };
  5691. if ( this.name !== '' ) data.name = this.name;
  5692. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5693. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5694. return data;
  5695. }
  5696. }
  5697. BufferAttribute.prototype.isBufferAttribute = true;
  5698. //
  5699. class Int8BufferAttribute extends BufferAttribute {
  5700. constructor( array, itemSize, normalized ) {
  5701. super( new Int8Array( array ), itemSize, normalized );
  5702. }
  5703. }
  5704. class Uint8BufferAttribute extends BufferAttribute {
  5705. constructor( array, itemSize, normalized ) {
  5706. super( new Uint8Array( array ), itemSize, normalized );
  5707. }
  5708. }
  5709. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5710. constructor( array, itemSize, normalized ) {
  5711. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5712. }
  5713. }
  5714. class Int16BufferAttribute extends BufferAttribute {
  5715. constructor( array, itemSize, normalized ) {
  5716. super( new Int16Array( array ), itemSize, normalized );
  5717. }
  5718. }
  5719. class Uint16BufferAttribute extends BufferAttribute {
  5720. constructor( array, itemSize, normalized ) {
  5721. super( new Uint16Array( array ), itemSize, normalized );
  5722. }
  5723. }
  5724. class Int32BufferAttribute extends BufferAttribute {
  5725. constructor( array, itemSize, normalized ) {
  5726. super( new Int32Array( array ), itemSize, normalized );
  5727. }
  5728. }
  5729. class Uint32BufferAttribute extends BufferAttribute {
  5730. constructor( array, itemSize, normalized ) {
  5731. super( new Uint32Array( array ), itemSize, normalized );
  5732. }
  5733. }
  5734. class Float16BufferAttribute extends BufferAttribute {
  5735. constructor( array, itemSize, normalized ) {
  5736. super( new Uint16Array( array ), itemSize, normalized );
  5737. }
  5738. }
  5739. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5740. class Float32BufferAttribute extends BufferAttribute {
  5741. constructor( array, itemSize, normalized ) {
  5742. super( new Float32Array( array ), itemSize, normalized );
  5743. }
  5744. }
  5745. class Float64BufferAttribute extends BufferAttribute {
  5746. constructor( array, itemSize, normalized ) {
  5747. super( new Float64Array( array ), itemSize, normalized );
  5748. }
  5749. }
  5750. let _id = 0;
  5751. const _m1 = /*@__PURE__*/ new Matrix4();
  5752. const _obj = /*@__PURE__*/ new Object3D();
  5753. const _offset = /*@__PURE__*/ new Vector3();
  5754. const _box$1 = /*@__PURE__*/ new Box3();
  5755. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5756. const _vector$8 = /*@__PURE__*/ new Vector3();
  5757. class BufferGeometry extends EventDispatcher {
  5758. constructor() {
  5759. super();
  5760. Object.defineProperty( this, 'id', { value: _id ++ } );
  5761. this.uuid = generateUUID();
  5762. this.name = '';
  5763. this.type = 'BufferGeometry';
  5764. this.index = null;
  5765. this.attributes = {};
  5766. this.morphAttributes = {};
  5767. this.morphTargetsRelative = false;
  5768. this.groups = [];
  5769. this.boundingBox = null;
  5770. this.boundingSphere = null;
  5771. this.drawRange = { start: 0, count: Infinity };
  5772. this.userData = {};
  5773. }
  5774. getIndex() {
  5775. return this.index;
  5776. }
  5777. setIndex( index ) {
  5778. if ( Array.isArray( index ) ) {
  5779. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5780. } else {
  5781. this.index = index;
  5782. }
  5783. return this;
  5784. }
  5785. getAttribute( name ) {
  5786. return this.attributes[ name ];
  5787. }
  5788. setAttribute( name, attribute ) {
  5789. this.attributes[ name ] = attribute;
  5790. return this;
  5791. }
  5792. deleteAttribute( name ) {
  5793. delete this.attributes[ name ];
  5794. return this;
  5795. }
  5796. hasAttribute( name ) {
  5797. return this.attributes[ name ] !== undefined;
  5798. }
  5799. addGroup( start, count, materialIndex = 0 ) {
  5800. this.groups.push( {
  5801. start: start,
  5802. count: count,
  5803. materialIndex: materialIndex
  5804. } );
  5805. }
  5806. clearGroups() {
  5807. this.groups = [];
  5808. }
  5809. setDrawRange( start, count ) {
  5810. this.drawRange.start = start;
  5811. this.drawRange.count = count;
  5812. }
  5813. applyMatrix4( matrix ) {
  5814. const position = this.attributes.position;
  5815. if ( position !== undefined ) {
  5816. position.applyMatrix4( matrix );
  5817. position.needsUpdate = true;
  5818. }
  5819. const normal = this.attributes.normal;
  5820. if ( normal !== undefined ) {
  5821. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5822. normal.applyNormalMatrix( normalMatrix );
  5823. normal.needsUpdate = true;
  5824. }
  5825. const tangent = this.attributes.tangent;
  5826. if ( tangent !== undefined ) {
  5827. tangent.transformDirection( matrix );
  5828. tangent.needsUpdate = true;
  5829. }
  5830. if ( this.boundingBox !== null ) {
  5831. this.computeBoundingBox();
  5832. }
  5833. if ( this.boundingSphere !== null ) {
  5834. this.computeBoundingSphere();
  5835. }
  5836. return this;
  5837. }
  5838. applyQuaternion( q ) {
  5839. _m1.makeRotationFromQuaternion( q );
  5840. this.applyMatrix4( _m1 );
  5841. return this;
  5842. }
  5843. rotateX( angle ) {
  5844. // rotate geometry around world x-axis
  5845. _m1.makeRotationX( angle );
  5846. this.applyMatrix4( _m1 );
  5847. return this;
  5848. }
  5849. rotateY( angle ) {
  5850. // rotate geometry around world y-axis
  5851. _m1.makeRotationY( angle );
  5852. this.applyMatrix4( _m1 );
  5853. return this;
  5854. }
  5855. rotateZ( angle ) {
  5856. // rotate geometry around world z-axis
  5857. _m1.makeRotationZ( angle );
  5858. this.applyMatrix4( _m1 );
  5859. return this;
  5860. }
  5861. translate( x, y, z ) {
  5862. // translate geometry
  5863. _m1.makeTranslation( x, y, z );
  5864. this.applyMatrix4( _m1 );
  5865. return this;
  5866. }
  5867. scale( x, y, z ) {
  5868. // scale geometry
  5869. _m1.makeScale( x, y, z );
  5870. this.applyMatrix4( _m1 );
  5871. return this;
  5872. }
  5873. lookAt( vector ) {
  5874. _obj.lookAt( vector );
  5875. _obj.updateMatrix();
  5876. this.applyMatrix4( _obj.matrix );
  5877. return this;
  5878. }
  5879. center() {
  5880. this.computeBoundingBox();
  5881. this.boundingBox.getCenter( _offset ).negate();
  5882. this.translate( _offset.x, _offset.y, _offset.z );
  5883. return this;
  5884. }
  5885. setFromPoints( points ) {
  5886. const position = [];
  5887. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5888. const point = points[ i ];
  5889. position.push( point.x, point.y, point.z || 0 );
  5890. }
  5891. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5892. return this;
  5893. }
  5894. computeBoundingBox() {
  5895. if ( this.boundingBox === null ) {
  5896. this.boundingBox = new Box3();
  5897. }
  5898. const position = this.attributes.position;
  5899. const morphAttributesPosition = this.morphAttributes.position;
  5900. if ( position && position.isGLBufferAttribute ) {
  5901. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5902. this.boundingBox.set(
  5903. new Vector3( - Infinity, - Infinity, - Infinity ),
  5904. new Vector3( + Infinity, + Infinity, + Infinity )
  5905. );
  5906. return;
  5907. }
  5908. if ( position !== undefined ) {
  5909. this.boundingBox.setFromBufferAttribute( position );
  5910. // process morph attributes if present
  5911. if ( morphAttributesPosition ) {
  5912. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5913. const morphAttribute = morphAttributesPosition[ i ];
  5914. _box$1.setFromBufferAttribute( morphAttribute );
  5915. if ( this.morphTargetsRelative ) {
  5916. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5917. this.boundingBox.expandByPoint( _vector$8 );
  5918. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5919. this.boundingBox.expandByPoint( _vector$8 );
  5920. } else {
  5921. this.boundingBox.expandByPoint( _box$1.min );
  5922. this.boundingBox.expandByPoint( _box$1.max );
  5923. }
  5924. }
  5925. }
  5926. } else {
  5927. this.boundingBox.makeEmpty();
  5928. }
  5929. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5930. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5931. }
  5932. }
  5933. computeBoundingSphere() {
  5934. if ( this.boundingSphere === null ) {
  5935. this.boundingSphere = new Sphere();
  5936. }
  5937. const position = this.attributes.position;
  5938. const morphAttributesPosition = this.morphAttributes.position;
  5939. if ( position && position.isGLBufferAttribute ) {
  5940. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5941. this.boundingSphere.set( new Vector3(), Infinity );
  5942. return;
  5943. }
  5944. if ( position ) {
  5945. // first, find the center of the bounding sphere
  5946. const center = this.boundingSphere.center;
  5947. _box$1.setFromBufferAttribute( position );
  5948. // process morph attributes if present
  5949. if ( morphAttributesPosition ) {
  5950. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5951. const morphAttribute = morphAttributesPosition[ i ];
  5952. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  5953. if ( this.morphTargetsRelative ) {
  5954. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  5955. _box$1.expandByPoint( _vector$8 );
  5956. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  5957. _box$1.expandByPoint( _vector$8 );
  5958. } else {
  5959. _box$1.expandByPoint( _boxMorphTargets.min );
  5960. _box$1.expandByPoint( _boxMorphTargets.max );
  5961. }
  5962. }
  5963. }
  5964. _box$1.getCenter( center );
  5965. // second, try to find a boundingSphere with a radius smaller than the
  5966. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5967. let maxRadiusSq = 0;
  5968. for ( let i = 0, il = position.count; i < il; i ++ ) {
  5969. _vector$8.fromBufferAttribute( position, i );
  5970. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5971. }
  5972. // process morph attributes if present
  5973. if ( morphAttributesPosition ) {
  5974. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5975. const morphAttribute = morphAttributesPosition[ i ];
  5976. const morphTargetsRelative = this.morphTargetsRelative;
  5977. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  5978. _vector$8.fromBufferAttribute( morphAttribute, j );
  5979. if ( morphTargetsRelative ) {
  5980. _offset.fromBufferAttribute( position, j );
  5981. _vector$8.add( _offset );
  5982. }
  5983. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5984. }
  5985. }
  5986. }
  5987. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5988. if ( isNaN( this.boundingSphere.radius ) ) {
  5989. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5990. }
  5991. }
  5992. }
  5993. computeTangents() {
  5994. const index = this.index;
  5995. const attributes = this.attributes;
  5996. // based on http://www.terathon.com/code/tangent.html
  5997. // (per vertex tangents)
  5998. if ( index === null ||
  5999. attributes.position === undefined ||
  6000. attributes.normal === undefined ||
  6001. attributes.uv === undefined ) {
  6002. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6003. return;
  6004. }
  6005. const indices = index.array;
  6006. const positions = attributes.position.array;
  6007. const normals = attributes.normal.array;
  6008. const uvs = attributes.uv.array;
  6009. const nVertices = positions.length / 3;
  6010. if ( attributes.tangent === undefined ) {
  6011. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6012. }
  6013. const tangents = attributes.tangent.array;
  6014. const tan1 = [], tan2 = [];
  6015. for ( let i = 0; i < nVertices; i ++ ) {
  6016. tan1[ i ] = new Vector3();
  6017. tan2[ i ] = new Vector3();
  6018. }
  6019. const vA = new Vector3(),
  6020. vB = new Vector3(),
  6021. vC = new Vector3(),
  6022. uvA = new Vector2(),
  6023. uvB = new Vector2(),
  6024. uvC = new Vector2(),
  6025. sdir = new Vector3(),
  6026. tdir = new Vector3();
  6027. function handleTriangle( a, b, c ) {
  6028. vA.fromArray( positions, a * 3 );
  6029. vB.fromArray( positions, b * 3 );
  6030. vC.fromArray( positions, c * 3 );
  6031. uvA.fromArray( uvs, a * 2 );
  6032. uvB.fromArray( uvs, b * 2 );
  6033. uvC.fromArray( uvs, c * 2 );
  6034. vB.sub( vA );
  6035. vC.sub( vA );
  6036. uvB.sub( uvA );
  6037. uvC.sub( uvA );
  6038. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6039. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6040. if ( ! isFinite( r ) ) return;
  6041. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6042. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6043. tan1[ a ].add( sdir );
  6044. tan1[ b ].add( sdir );
  6045. tan1[ c ].add( sdir );
  6046. tan2[ a ].add( tdir );
  6047. tan2[ b ].add( tdir );
  6048. tan2[ c ].add( tdir );
  6049. }
  6050. let groups = this.groups;
  6051. if ( groups.length === 0 ) {
  6052. groups = [ {
  6053. start: 0,
  6054. count: indices.length
  6055. } ];
  6056. }
  6057. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6058. const group = groups[ i ];
  6059. const start = group.start;
  6060. const count = group.count;
  6061. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6062. handleTriangle(
  6063. indices[ j + 0 ],
  6064. indices[ j + 1 ],
  6065. indices[ j + 2 ]
  6066. );
  6067. }
  6068. }
  6069. const tmp = new Vector3(), tmp2 = new Vector3();
  6070. const n = new Vector3(), n2 = new Vector3();
  6071. function handleVertex( v ) {
  6072. n.fromArray( normals, v * 3 );
  6073. n2.copy( n );
  6074. const t = tan1[ v ];
  6075. // Gram-Schmidt orthogonalize
  6076. tmp.copy( t );
  6077. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6078. // Calculate handedness
  6079. tmp2.crossVectors( n2, t );
  6080. const test = tmp2.dot( tan2[ v ] );
  6081. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6082. tangents[ v * 4 ] = tmp.x;
  6083. tangents[ v * 4 + 1 ] = tmp.y;
  6084. tangents[ v * 4 + 2 ] = tmp.z;
  6085. tangents[ v * 4 + 3 ] = w;
  6086. }
  6087. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6088. const group = groups[ i ];
  6089. const start = group.start;
  6090. const count = group.count;
  6091. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6092. handleVertex( indices[ j + 0 ] );
  6093. handleVertex( indices[ j + 1 ] );
  6094. handleVertex( indices[ j + 2 ] );
  6095. }
  6096. }
  6097. }
  6098. computeVertexNormals() {
  6099. const index = this.index;
  6100. const positionAttribute = this.getAttribute( 'position' );
  6101. if ( positionAttribute !== undefined ) {
  6102. let normalAttribute = this.getAttribute( 'normal' );
  6103. if ( normalAttribute === undefined ) {
  6104. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6105. this.setAttribute( 'normal', normalAttribute );
  6106. } else {
  6107. // reset existing normals to zero
  6108. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6109. normalAttribute.setXYZ( i, 0, 0, 0 );
  6110. }
  6111. }
  6112. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6113. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6114. const cb = new Vector3(), ab = new Vector3();
  6115. // indexed elements
  6116. if ( index ) {
  6117. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6118. const vA = index.getX( i + 0 );
  6119. const vB = index.getX( i + 1 );
  6120. const vC = index.getX( i + 2 );
  6121. pA.fromBufferAttribute( positionAttribute, vA );
  6122. pB.fromBufferAttribute( positionAttribute, vB );
  6123. pC.fromBufferAttribute( positionAttribute, vC );
  6124. cb.subVectors( pC, pB );
  6125. ab.subVectors( pA, pB );
  6126. cb.cross( ab );
  6127. nA.fromBufferAttribute( normalAttribute, vA );
  6128. nB.fromBufferAttribute( normalAttribute, vB );
  6129. nC.fromBufferAttribute( normalAttribute, vC );
  6130. nA.add( cb );
  6131. nB.add( cb );
  6132. nC.add( cb );
  6133. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6134. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6135. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6136. }
  6137. } else {
  6138. // non-indexed elements (unconnected triangle soup)
  6139. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6140. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6141. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6142. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6143. cb.subVectors( pC, pB );
  6144. ab.subVectors( pA, pB );
  6145. cb.cross( ab );
  6146. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6147. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6148. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6149. }
  6150. }
  6151. this.normalizeNormals();
  6152. normalAttribute.needsUpdate = true;
  6153. }
  6154. }
  6155. merge( geometry, offset ) {
  6156. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6157. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6158. return;
  6159. }
  6160. if ( offset === undefined ) {
  6161. offset = 0;
  6162. console.warn(
  6163. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6164. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6165. );
  6166. }
  6167. const attributes = this.attributes;
  6168. for ( const key in attributes ) {
  6169. if ( geometry.attributes[ key ] === undefined ) continue;
  6170. const attribute1 = attributes[ key ];
  6171. const attributeArray1 = attribute1.array;
  6172. const attribute2 = geometry.attributes[ key ];
  6173. const attributeArray2 = attribute2.array;
  6174. const attributeOffset = attribute2.itemSize * offset;
  6175. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6176. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6177. attributeArray1[ j ] = attributeArray2[ i ];
  6178. }
  6179. }
  6180. return this;
  6181. }
  6182. normalizeNormals() {
  6183. const normals = this.attributes.normal;
  6184. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6185. _vector$8.fromBufferAttribute( normals, i );
  6186. _vector$8.normalize();
  6187. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6188. }
  6189. }
  6190. toNonIndexed() {
  6191. function convertBufferAttribute( attribute, indices ) {
  6192. const array = attribute.array;
  6193. const itemSize = attribute.itemSize;
  6194. const normalized = attribute.normalized;
  6195. const array2 = new array.constructor( indices.length * itemSize );
  6196. let index = 0, index2 = 0;
  6197. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6198. if ( attribute.isInterleavedBufferAttribute ) {
  6199. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6200. } else {
  6201. index = indices[ i ] * itemSize;
  6202. }
  6203. for ( let j = 0; j < itemSize; j ++ ) {
  6204. array2[ index2 ++ ] = array[ index ++ ];
  6205. }
  6206. }
  6207. return new BufferAttribute( array2, itemSize, normalized );
  6208. }
  6209. //
  6210. if ( this.index === null ) {
  6211. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6212. return this;
  6213. }
  6214. const geometry2 = new BufferGeometry();
  6215. const indices = this.index.array;
  6216. const attributes = this.attributes;
  6217. // attributes
  6218. for ( const name in attributes ) {
  6219. const attribute = attributes[ name ];
  6220. const newAttribute = convertBufferAttribute( attribute, indices );
  6221. geometry2.setAttribute( name, newAttribute );
  6222. }
  6223. // morph attributes
  6224. const morphAttributes = this.morphAttributes;
  6225. for ( const name in morphAttributes ) {
  6226. const morphArray = [];
  6227. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6228. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6229. const attribute = morphAttribute[ i ];
  6230. const newAttribute = convertBufferAttribute( attribute, indices );
  6231. morphArray.push( newAttribute );
  6232. }
  6233. geometry2.morphAttributes[ name ] = morphArray;
  6234. }
  6235. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6236. // groups
  6237. const groups = this.groups;
  6238. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6239. const group = groups[ i ];
  6240. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6241. }
  6242. return geometry2;
  6243. }
  6244. toJSON() {
  6245. const data = {
  6246. metadata: {
  6247. version: 4.5,
  6248. type: 'BufferGeometry',
  6249. generator: 'BufferGeometry.toJSON'
  6250. }
  6251. };
  6252. // standard BufferGeometry serialization
  6253. data.uuid = this.uuid;
  6254. data.type = this.type;
  6255. if ( this.name !== '' ) data.name = this.name;
  6256. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6257. if ( this.parameters !== undefined ) {
  6258. const parameters = this.parameters;
  6259. for ( const key in parameters ) {
  6260. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6261. }
  6262. return data;
  6263. }
  6264. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6265. data.data = { attributes: {} };
  6266. const index = this.index;
  6267. if ( index !== null ) {
  6268. data.data.index = {
  6269. type: index.array.constructor.name,
  6270. array: Array.prototype.slice.call( index.array )
  6271. };
  6272. }
  6273. const attributes = this.attributes;
  6274. for ( const key in attributes ) {
  6275. const attribute = attributes[ key ];
  6276. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6277. }
  6278. const morphAttributes = {};
  6279. let hasMorphAttributes = false;
  6280. for ( const key in this.morphAttributes ) {
  6281. const attributeArray = this.morphAttributes[ key ];
  6282. const array = [];
  6283. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6284. const attribute = attributeArray[ i ];
  6285. array.push( attribute.toJSON( data.data ) );
  6286. }
  6287. if ( array.length > 0 ) {
  6288. morphAttributes[ key ] = array;
  6289. hasMorphAttributes = true;
  6290. }
  6291. }
  6292. if ( hasMorphAttributes ) {
  6293. data.data.morphAttributes = morphAttributes;
  6294. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6295. }
  6296. const groups = this.groups;
  6297. if ( groups.length > 0 ) {
  6298. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6299. }
  6300. const boundingSphere = this.boundingSphere;
  6301. if ( boundingSphere !== null ) {
  6302. data.data.boundingSphere = {
  6303. center: boundingSphere.center.toArray(),
  6304. radius: boundingSphere.radius
  6305. };
  6306. }
  6307. return data;
  6308. }
  6309. clone() {
  6310. return new this.constructor().copy( this );
  6311. }
  6312. copy( source ) {
  6313. // reset
  6314. this.index = null;
  6315. this.attributes = {};
  6316. this.morphAttributes = {};
  6317. this.groups = [];
  6318. this.boundingBox = null;
  6319. this.boundingSphere = null;
  6320. // used for storing cloned, shared data
  6321. const data = {};
  6322. // name
  6323. this.name = source.name;
  6324. // index
  6325. const index = source.index;
  6326. if ( index !== null ) {
  6327. this.setIndex( index.clone( data ) );
  6328. }
  6329. // attributes
  6330. const attributes = source.attributes;
  6331. for ( const name in attributes ) {
  6332. const attribute = attributes[ name ];
  6333. this.setAttribute( name, attribute.clone( data ) );
  6334. }
  6335. // morph attributes
  6336. const morphAttributes = source.morphAttributes;
  6337. for ( const name in morphAttributes ) {
  6338. const array = [];
  6339. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6340. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6341. array.push( morphAttribute[ i ].clone( data ) );
  6342. }
  6343. this.morphAttributes[ name ] = array;
  6344. }
  6345. this.morphTargetsRelative = source.morphTargetsRelative;
  6346. // groups
  6347. const groups = source.groups;
  6348. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6349. const group = groups[ i ];
  6350. this.addGroup( group.start, group.count, group.materialIndex );
  6351. }
  6352. // bounding box
  6353. const boundingBox = source.boundingBox;
  6354. if ( boundingBox !== null ) {
  6355. this.boundingBox = boundingBox.clone();
  6356. }
  6357. // bounding sphere
  6358. const boundingSphere = source.boundingSphere;
  6359. if ( boundingSphere !== null ) {
  6360. this.boundingSphere = boundingSphere.clone();
  6361. }
  6362. // draw range
  6363. this.drawRange.start = source.drawRange.start;
  6364. this.drawRange.count = source.drawRange.count;
  6365. // user data
  6366. this.userData = source.userData;
  6367. // geometry generator parameters
  6368. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6369. return this;
  6370. }
  6371. dispose() {
  6372. this.dispatchEvent( { type: 'dispose' } );
  6373. }
  6374. }
  6375. BufferGeometry.prototype.isBufferGeometry = true;
  6376. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6377. const _ray$2 = /*@__PURE__*/ new Ray();
  6378. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6379. const _vA$1 = /*@__PURE__*/ new Vector3();
  6380. const _vB$1 = /*@__PURE__*/ new Vector3();
  6381. const _vC$1 = /*@__PURE__*/ new Vector3();
  6382. const _tempA = /*@__PURE__*/ new Vector3();
  6383. const _tempB = /*@__PURE__*/ new Vector3();
  6384. const _tempC = /*@__PURE__*/ new Vector3();
  6385. const _morphA = /*@__PURE__*/ new Vector3();
  6386. const _morphB = /*@__PURE__*/ new Vector3();
  6387. const _morphC = /*@__PURE__*/ new Vector3();
  6388. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6389. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6390. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6391. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6392. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6393. class Mesh extends Object3D {
  6394. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6395. super();
  6396. this.type = 'Mesh';
  6397. this.geometry = geometry;
  6398. this.material = material;
  6399. this.updateMorphTargets();
  6400. }
  6401. copy( source ) {
  6402. super.copy( source );
  6403. if ( source.morphTargetInfluences !== undefined ) {
  6404. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6405. }
  6406. if ( source.morphTargetDictionary !== undefined ) {
  6407. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6408. }
  6409. this.material = source.material;
  6410. this.geometry = source.geometry;
  6411. return this;
  6412. }
  6413. updateMorphTargets() {
  6414. const geometry = this.geometry;
  6415. if ( geometry.isBufferGeometry ) {
  6416. const morphAttributes = geometry.morphAttributes;
  6417. const keys = Object.keys( morphAttributes );
  6418. if ( keys.length > 0 ) {
  6419. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6420. if ( morphAttribute !== undefined ) {
  6421. this.morphTargetInfluences = [];
  6422. this.morphTargetDictionary = {};
  6423. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6424. const name = morphAttribute[ m ].name || String( m );
  6425. this.morphTargetInfluences.push( 0 );
  6426. this.morphTargetDictionary[ name ] = m;
  6427. }
  6428. }
  6429. }
  6430. } else {
  6431. const morphTargets = geometry.morphTargets;
  6432. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6433. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6434. }
  6435. }
  6436. }
  6437. raycast( raycaster, intersects ) {
  6438. const geometry = this.geometry;
  6439. const material = this.material;
  6440. const matrixWorld = this.matrixWorld;
  6441. if ( material === undefined ) return;
  6442. // Checking boundingSphere distance to ray
  6443. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6444. _sphere$3.copy( geometry.boundingSphere );
  6445. _sphere$3.applyMatrix4( matrixWorld );
  6446. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6447. //
  6448. _inverseMatrix$2.copy( matrixWorld ).invert();
  6449. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6450. // Check boundingBox before continuing
  6451. if ( geometry.boundingBox !== null ) {
  6452. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6453. }
  6454. let intersection;
  6455. if ( geometry.isBufferGeometry ) {
  6456. const index = geometry.index;
  6457. const position = geometry.attributes.position;
  6458. const morphPosition = geometry.morphAttributes.position;
  6459. const morphTargetsRelative = geometry.morphTargetsRelative;
  6460. const uv = geometry.attributes.uv;
  6461. const uv2 = geometry.attributes.uv2;
  6462. const groups = geometry.groups;
  6463. const drawRange = geometry.drawRange;
  6464. if ( index !== null ) {
  6465. // indexed buffer geometry
  6466. if ( Array.isArray( material ) ) {
  6467. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6468. const group = groups[ i ];
  6469. const groupMaterial = material[ group.materialIndex ];
  6470. const start = Math.max( group.start, drawRange.start );
  6471. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6472. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6473. const a = index.getX( j );
  6474. const b = index.getX( j + 1 );
  6475. const c = index.getX( j + 2 );
  6476. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6477. if ( intersection ) {
  6478. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6479. intersection.face.materialIndex = group.materialIndex;
  6480. intersects.push( intersection );
  6481. }
  6482. }
  6483. }
  6484. } else {
  6485. const start = Math.max( 0, drawRange.start );
  6486. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6487. for ( let i = start, il = end; i < il; i += 3 ) {
  6488. const a = index.getX( i );
  6489. const b = index.getX( i + 1 );
  6490. const c = index.getX( i + 2 );
  6491. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6492. if ( intersection ) {
  6493. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6494. intersects.push( intersection );
  6495. }
  6496. }
  6497. }
  6498. } else if ( position !== undefined ) {
  6499. // non-indexed buffer geometry
  6500. if ( Array.isArray( material ) ) {
  6501. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6502. const group = groups[ i ];
  6503. const groupMaterial = material[ group.materialIndex ];
  6504. const start = Math.max( group.start, drawRange.start );
  6505. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6506. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6507. const a = j;
  6508. const b = j + 1;
  6509. const c = j + 2;
  6510. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6511. if ( intersection ) {
  6512. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6513. intersection.face.materialIndex = group.materialIndex;
  6514. intersects.push( intersection );
  6515. }
  6516. }
  6517. }
  6518. } else {
  6519. const start = Math.max( 0, drawRange.start );
  6520. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6521. for ( let i = start, il = end; i < il; i += 3 ) {
  6522. const a = i;
  6523. const b = i + 1;
  6524. const c = i + 2;
  6525. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6526. if ( intersection ) {
  6527. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6528. intersects.push( intersection );
  6529. }
  6530. }
  6531. }
  6532. }
  6533. } else if ( geometry.isGeometry ) {
  6534. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6535. }
  6536. }
  6537. }
  6538. Mesh.prototype.isMesh = true;
  6539. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6540. let intersect;
  6541. if ( material.side === BackSide ) {
  6542. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6543. } else {
  6544. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6545. }
  6546. if ( intersect === null ) return null;
  6547. _intersectionPointWorld.copy( point );
  6548. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6549. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6550. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6551. return {
  6552. distance: distance,
  6553. point: _intersectionPointWorld.clone(),
  6554. object: object
  6555. };
  6556. }
  6557. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6558. _vA$1.fromBufferAttribute( position, a );
  6559. _vB$1.fromBufferAttribute( position, b );
  6560. _vC$1.fromBufferAttribute( position, c );
  6561. const morphInfluences = object.morphTargetInfluences;
  6562. if ( morphPosition && morphInfluences ) {
  6563. _morphA.set( 0, 0, 0 );
  6564. _morphB.set( 0, 0, 0 );
  6565. _morphC.set( 0, 0, 0 );
  6566. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6567. const influence = morphInfluences[ i ];
  6568. const morphAttribute = morphPosition[ i ];
  6569. if ( influence === 0 ) continue;
  6570. _tempA.fromBufferAttribute( morphAttribute, a );
  6571. _tempB.fromBufferAttribute( morphAttribute, b );
  6572. _tempC.fromBufferAttribute( morphAttribute, c );
  6573. if ( morphTargetsRelative ) {
  6574. _morphA.addScaledVector( _tempA, influence );
  6575. _morphB.addScaledVector( _tempB, influence );
  6576. _morphC.addScaledVector( _tempC, influence );
  6577. } else {
  6578. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6579. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6580. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6581. }
  6582. }
  6583. _vA$1.add( _morphA );
  6584. _vB$1.add( _morphB );
  6585. _vC$1.add( _morphC );
  6586. }
  6587. if ( object.isSkinnedMesh ) {
  6588. object.boneTransform( a, _vA$1 );
  6589. object.boneTransform( b, _vB$1 );
  6590. object.boneTransform( c, _vC$1 );
  6591. }
  6592. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6593. if ( intersection ) {
  6594. if ( uv ) {
  6595. _uvA$1.fromBufferAttribute( uv, a );
  6596. _uvB$1.fromBufferAttribute( uv, b );
  6597. _uvC$1.fromBufferAttribute( uv, c );
  6598. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6599. }
  6600. if ( uv2 ) {
  6601. _uvA$1.fromBufferAttribute( uv2, a );
  6602. _uvB$1.fromBufferAttribute( uv2, b );
  6603. _uvC$1.fromBufferAttribute( uv2, c );
  6604. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6605. }
  6606. const face = {
  6607. a: a,
  6608. b: b,
  6609. c: c,
  6610. normal: new Vector3(),
  6611. materialIndex: 0
  6612. };
  6613. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6614. intersection.face = face;
  6615. }
  6616. return intersection;
  6617. }
  6618. class BoxGeometry extends BufferGeometry {
  6619. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6620. super();
  6621. this.type = 'BoxGeometry';
  6622. this.parameters = {
  6623. width: width,
  6624. height: height,
  6625. depth: depth,
  6626. widthSegments: widthSegments,
  6627. heightSegments: heightSegments,
  6628. depthSegments: depthSegments
  6629. };
  6630. const scope = this;
  6631. // segments
  6632. widthSegments = Math.floor( widthSegments );
  6633. heightSegments = Math.floor( heightSegments );
  6634. depthSegments = Math.floor( depthSegments );
  6635. // buffers
  6636. const indices = [];
  6637. const vertices = [];
  6638. const normals = [];
  6639. const uvs = [];
  6640. // helper variables
  6641. let numberOfVertices = 0;
  6642. let groupStart = 0;
  6643. // build each side of the box geometry
  6644. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6645. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6646. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6647. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6648. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6649. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6650. // build geometry
  6651. this.setIndex( indices );
  6652. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6653. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6654. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6655. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6656. const segmentWidth = width / gridX;
  6657. const segmentHeight = height / gridY;
  6658. const widthHalf = width / 2;
  6659. const heightHalf = height / 2;
  6660. const depthHalf = depth / 2;
  6661. const gridX1 = gridX + 1;
  6662. const gridY1 = gridY + 1;
  6663. let vertexCounter = 0;
  6664. let groupCount = 0;
  6665. const vector = new Vector3();
  6666. // generate vertices, normals and uvs
  6667. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6668. const y = iy * segmentHeight - heightHalf;
  6669. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6670. const x = ix * segmentWidth - widthHalf;
  6671. // set values to correct vector component
  6672. vector[ u ] = x * udir;
  6673. vector[ v ] = y * vdir;
  6674. vector[ w ] = depthHalf;
  6675. // now apply vector to vertex buffer
  6676. vertices.push( vector.x, vector.y, vector.z );
  6677. // set values to correct vector component
  6678. vector[ u ] = 0;
  6679. vector[ v ] = 0;
  6680. vector[ w ] = depth > 0 ? 1 : - 1;
  6681. // now apply vector to normal buffer
  6682. normals.push( vector.x, vector.y, vector.z );
  6683. // uvs
  6684. uvs.push( ix / gridX );
  6685. uvs.push( 1 - ( iy / gridY ) );
  6686. // counters
  6687. vertexCounter += 1;
  6688. }
  6689. }
  6690. // indices
  6691. // 1. you need three indices to draw a single face
  6692. // 2. a single segment consists of two faces
  6693. // 3. so we need to generate six (2*3) indices per segment
  6694. for ( let iy = 0; iy < gridY; iy ++ ) {
  6695. for ( let ix = 0; ix < gridX; ix ++ ) {
  6696. const a = numberOfVertices + ix + gridX1 * iy;
  6697. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6698. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6699. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6700. // faces
  6701. indices.push( a, b, d );
  6702. indices.push( b, c, d );
  6703. // increase counter
  6704. groupCount += 6;
  6705. }
  6706. }
  6707. // add a group to the geometry. this will ensure multi material support
  6708. scope.addGroup( groupStart, groupCount, materialIndex );
  6709. // calculate new start value for groups
  6710. groupStart += groupCount;
  6711. // update total number of vertices
  6712. numberOfVertices += vertexCounter;
  6713. }
  6714. }
  6715. static fromJSON( data ) {
  6716. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6717. }
  6718. }
  6719. /**
  6720. * Uniform Utilities
  6721. */
  6722. function cloneUniforms( src ) {
  6723. const dst = {};
  6724. for ( const u in src ) {
  6725. dst[ u ] = {};
  6726. for ( const p in src[ u ] ) {
  6727. const property = src[ u ][ p ];
  6728. if ( property && ( property.isColor ||
  6729. property.isMatrix3 || property.isMatrix4 ||
  6730. property.isVector2 || property.isVector3 || property.isVector4 ||
  6731. property.isTexture || property.isQuaternion ) ) {
  6732. dst[ u ][ p ] = property.clone();
  6733. } else if ( Array.isArray( property ) ) {
  6734. dst[ u ][ p ] = property.slice();
  6735. } else {
  6736. dst[ u ][ p ] = property;
  6737. }
  6738. }
  6739. }
  6740. return dst;
  6741. }
  6742. function mergeUniforms( uniforms ) {
  6743. const merged = {};
  6744. for ( let u = 0; u < uniforms.length; u ++ ) {
  6745. const tmp = cloneUniforms( uniforms[ u ] );
  6746. for ( const p in tmp ) {
  6747. merged[ p ] = tmp[ p ];
  6748. }
  6749. }
  6750. return merged;
  6751. }
  6752. // Legacy
  6753. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6754. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6755. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6756. /**
  6757. * parameters = {
  6758. * defines: { "label" : "value" },
  6759. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6760. *
  6761. * fragmentShader: <string>,
  6762. * vertexShader: <string>,
  6763. *
  6764. * wireframe: <boolean>,
  6765. * wireframeLinewidth: <float>,
  6766. *
  6767. * lights: <bool>
  6768. * }
  6769. */
  6770. class ShaderMaterial extends Material {
  6771. constructor( parameters ) {
  6772. super();
  6773. this.type = 'ShaderMaterial';
  6774. this.defines = {};
  6775. this.uniforms = {};
  6776. this.vertexShader = default_vertex;
  6777. this.fragmentShader = default_fragment;
  6778. this.linewidth = 1;
  6779. this.wireframe = false;
  6780. this.wireframeLinewidth = 1;
  6781. this.fog = false; // set to use scene fog
  6782. this.lights = false; // set to use scene lights
  6783. this.clipping = false; // set to use user-defined clipping planes
  6784. this.extensions = {
  6785. derivatives: false, // set to use derivatives
  6786. fragDepth: false, // set to use fragment depth values
  6787. drawBuffers: false, // set to use draw buffers
  6788. shaderTextureLOD: false // set to use shader texture LOD
  6789. };
  6790. // When rendered geometry doesn't include these attributes but the material does,
  6791. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6792. this.defaultAttributeValues = {
  6793. 'color': [ 1, 1, 1 ],
  6794. 'uv': [ 0, 0 ],
  6795. 'uv2': [ 0, 0 ]
  6796. };
  6797. this.index0AttributeName = undefined;
  6798. this.uniformsNeedUpdate = false;
  6799. this.glslVersion = null;
  6800. if ( parameters !== undefined ) {
  6801. if ( parameters.attributes !== undefined ) {
  6802. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6803. }
  6804. this.setValues( parameters );
  6805. }
  6806. }
  6807. copy( source ) {
  6808. super.copy( source );
  6809. this.fragmentShader = source.fragmentShader;
  6810. this.vertexShader = source.vertexShader;
  6811. this.uniforms = cloneUniforms( source.uniforms );
  6812. this.defines = Object.assign( {}, source.defines );
  6813. this.wireframe = source.wireframe;
  6814. this.wireframeLinewidth = source.wireframeLinewidth;
  6815. this.lights = source.lights;
  6816. this.clipping = source.clipping;
  6817. this.extensions = Object.assign( {}, source.extensions );
  6818. this.glslVersion = source.glslVersion;
  6819. return this;
  6820. }
  6821. toJSON( meta ) {
  6822. const data = super.toJSON( meta );
  6823. data.glslVersion = this.glslVersion;
  6824. data.uniforms = {};
  6825. for ( const name in this.uniforms ) {
  6826. const uniform = this.uniforms[ name ];
  6827. const value = uniform.value;
  6828. if ( value && value.isTexture ) {
  6829. data.uniforms[ name ] = {
  6830. type: 't',
  6831. value: value.toJSON( meta ).uuid
  6832. };
  6833. } else if ( value && value.isColor ) {
  6834. data.uniforms[ name ] = {
  6835. type: 'c',
  6836. value: value.getHex()
  6837. };
  6838. } else if ( value && value.isVector2 ) {
  6839. data.uniforms[ name ] = {
  6840. type: 'v2',
  6841. value: value.toArray()
  6842. };
  6843. } else if ( value && value.isVector3 ) {
  6844. data.uniforms[ name ] = {
  6845. type: 'v3',
  6846. value: value.toArray()
  6847. };
  6848. } else if ( value && value.isVector4 ) {
  6849. data.uniforms[ name ] = {
  6850. type: 'v4',
  6851. value: value.toArray()
  6852. };
  6853. } else if ( value && value.isMatrix3 ) {
  6854. data.uniforms[ name ] = {
  6855. type: 'm3',
  6856. value: value.toArray()
  6857. };
  6858. } else if ( value && value.isMatrix4 ) {
  6859. data.uniforms[ name ] = {
  6860. type: 'm4',
  6861. value: value.toArray()
  6862. };
  6863. } else {
  6864. data.uniforms[ name ] = {
  6865. value: value
  6866. };
  6867. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6868. }
  6869. }
  6870. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6871. data.vertexShader = this.vertexShader;
  6872. data.fragmentShader = this.fragmentShader;
  6873. const extensions = {};
  6874. for ( const key in this.extensions ) {
  6875. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6876. }
  6877. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6878. return data;
  6879. }
  6880. }
  6881. ShaderMaterial.prototype.isShaderMaterial = true;
  6882. class Camera extends Object3D {
  6883. constructor() {
  6884. super();
  6885. this.type = 'Camera';
  6886. this.matrixWorldInverse = new Matrix4();
  6887. this.projectionMatrix = new Matrix4();
  6888. this.projectionMatrixInverse = new Matrix4();
  6889. }
  6890. copy( source, recursive ) {
  6891. super.copy( source, recursive );
  6892. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6893. this.projectionMatrix.copy( source.projectionMatrix );
  6894. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6895. return this;
  6896. }
  6897. getWorldDirection( target ) {
  6898. this.updateWorldMatrix( true, false );
  6899. const e = this.matrixWorld.elements;
  6900. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6901. }
  6902. updateMatrixWorld( force ) {
  6903. super.updateMatrixWorld( force );
  6904. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6905. }
  6906. updateWorldMatrix( updateParents, updateChildren ) {
  6907. super.updateWorldMatrix( updateParents, updateChildren );
  6908. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6909. }
  6910. clone() {
  6911. return new this.constructor().copy( this );
  6912. }
  6913. }
  6914. Camera.prototype.isCamera = true;
  6915. class PerspectiveCamera extends Camera {
  6916. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6917. super();
  6918. this.type = 'PerspectiveCamera';
  6919. this.fov = fov;
  6920. this.zoom = 1;
  6921. this.near = near;
  6922. this.far = far;
  6923. this.focus = 10;
  6924. this.aspect = aspect;
  6925. this.view = null;
  6926. this.filmGauge = 35; // width of the film (default in millimeters)
  6927. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6928. this.updateProjectionMatrix();
  6929. }
  6930. copy( source, recursive ) {
  6931. super.copy( source, recursive );
  6932. this.fov = source.fov;
  6933. this.zoom = source.zoom;
  6934. this.near = source.near;
  6935. this.far = source.far;
  6936. this.focus = source.focus;
  6937. this.aspect = source.aspect;
  6938. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6939. this.filmGauge = source.filmGauge;
  6940. this.filmOffset = source.filmOffset;
  6941. return this;
  6942. }
  6943. /**
  6944. * Sets the FOV by focal length in respect to the current .filmGauge.
  6945. *
  6946. * The default film gauge is 35, so that the focal length can be specified for
  6947. * a 35mm (full frame) camera.
  6948. *
  6949. * Values for focal length and film gauge must have the same unit.
  6950. */
  6951. setFocalLength( focalLength ) {
  6952. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6953. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6954. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6955. this.updateProjectionMatrix();
  6956. }
  6957. /**
  6958. * Calculates the focal length from the current .fov and .filmGauge.
  6959. */
  6960. getFocalLength() {
  6961. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6962. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6963. }
  6964. getEffectiveFOV() {
  6965. return RAD2DEG * 2 * Math.atan(
  6966. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6967. }
  6968. getFilmWidth() {
  6969. // film not completely covered in portrait format (aspect < 1)
  6970. return this.filmGauge * Math.min( this.aspect, 1 );
  6971. }
  6972. getFilmHeight() {
  6973. // film not completely covered in landscape format (aspect > 1)
  6974. return this.filmGauge / Math.max( this.aspect, 1 );
  6975. }
  6976. /**
  6977. * Sets an offset in a larger frustum. This is useful for multi-window or
  6978. * multi-monitor/multi-machine setups.
  6979. *
  6980. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6981. * the monitors are in grid like this
  6982. *
  6983. * +---+---+---+
  6984. * | A | B | C |
  6985. * +---+---+---+
  6986. * | D | E | F |
  6987. * +---+---+---+
  6988. *
  6989. * then for each monitor you would call it like this
  6990. *
  6991. * const w = 1920;
  6992. * const h = 1080;
  6993. * const fullWidth = w * 3;
  6994. * const fullHeight = h * 2;
  6995. *
  6996. * --A--
  6997. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6998. * --B--
  6999. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7000. * --C--
  7001. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7002. * --D--
  7003. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7004. * --E--
  7005. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7006. * --F--
  7007. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7008. *
  7009. * Note there is no reason monitors have to be the same size or in a grid.
  7010. */
  7011. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7012. this.aspect = fullWidth / fullHeight;
  7013. if ( this.view === null ) {
  7014. this.view = {
  7015. enabled: true,
  7016. fullWidth: 1,
  7017. fullHeight: 1,
  7018. offsetX: 0,
  7019. offsetY: 0,
  7020. width: 1,
  7021. height: 1
  7022. };
  7023. }
  7024. this.view.enabled = true;
  7025. this.view.fullWidth = fullWidth;
  7026. this.view.fullHeight = fullHeight;
  7027. this.view.offsetX = x;
  7028. this.view.offsetY = y;
  7029. this.view.width = width;
  7030. this.view.height = height;
  7031. this.updateProjectionMatrix();
  7032. }
  7033. clearViewOffset() {
  7034. if ( this.view !== null ) {
  7035. this.view.enabled = false;
  7036. }
  7037. this.updateProjectionMatrix();
  7038. }
  7039. updateProjectionMatrix() {
  7040. const near = this.near;
  7041. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7042. let height = 2 * top;
  7043. let width = this.aspect * height;
  7044. let left = - 0.5 * width;
  7045. const view = this.view;
  7046. if ( this.view !== null && this.view.enabled ) {
  7047. const fullWidth = view.fullWidth,
  7048. fullHeight = view.fullHeight;
  7049. left += view.offsetX * width / fullWidth;
  7050. top -= view.offsetY * height / fullHeight;
  7051. width *= view.width / fullWidth;
  7052. height *= view.height / fullHeight;
  7053. }
  7054. const skew = this.filmOffset;
  7055. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7056. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7057. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7058. }
  7059. toJSON( meta ) {
  7060. const data = super.toJSON( meta );
  7061. data.object.fov = this.fov;
  7062. data.object.zoom = this.zoom;
  7063. data.object.near = this.near;
  7064. data.object.far = this.far;
  7065. data.object.focus = this.focus;
  7066. data.object.aspect = this.aspect;
  7067. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7068. data.object.filmGauge = this.filmGauge;
  7069. data.object.filmOffset = this.filmOffset;
  7070. return data;
  7071. }
  7072. }
  7073. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7074. const fov = 90, aspect = 1;
  7075. class CubeCamera extends Object3D {
  7076. constructor( near, far, renderTarget ) {
  7077. super();
  7078. this.type = 'CubeCamera';
  7079. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7080. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7081. return;
  7082. }
  7083. this.renderTarget = renderTarget;
  7084. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7085. cameraPX.layers = this.layers;
  7086. cameraPX.up.set( 0, - 1, 0 );
  7087. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7088. this.add( cameraPX );
  7089. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7090. cameraNX.layers = this.layers;
  7091. cameraNX.up.set( 0, - 1, 0 );
  7092. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7093. this.add( cameraNX );
  7094. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7095. cameraPY.layers = this.layers;
  7096. cameraPY.up.set( 0, 0, 1 );
  7097. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7098. this.add( cameraPY );
  7099. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7100. cameraNY.layers = this.layers;
  7101. cameraNY.up.set( 0, 0, - 1 );
  7102. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7103. this.add( cameraNY );
  7104. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7105. cameraPZ.layers = this.layers;
  7106. cameraPZ.up.set( 0, - 1, 0 );
  7107. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7108. this.add( cameraPZ );
  7109. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7110. cameraNZ.layers = this.layers;
  7111. cameraNZ.up.set( 0, - 1, 0 );
  7112. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7113. this.add( cameraNZ );
  7114. }
  7115. update( renderer, scene ) {
  7116. if ( this.parent === null ) this.updateMatrixWorld();
  7117. const renderTarget = this.renderTarget;
  7118. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7119. const currentXrEnabled = renderer.xr.enabled;
  7120. const currentRenderTarget = renderer.getRenderTarget();
  7121. renderer.xr.enabled = false;
  7122. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7123. renderTarget.texture.generateMipmaps = false;
  7124. renderer.setRenderTarget( renderTarget, 0 );
  7125. renderer.render( scene, cameraPX );
  7126. renderer.setRenderTarget( renderTarget, 1 );
  7127. renderer.render( scene, cameraNX );
  7128. renderer.setRenderTarget( renderTarget, 2 );
  7129. renderer.render( scene, cameraPY );
  7130. renderer.setRenderTarget( renderTarget, 3 );
  7131. renderer.render( scene, cameraNY );
  7132. renderer.setRenderTarget( renderTarget, 4 );
  7133. renderer.render( scene, cameraPZ );
  7134. renderTarget.texture.generateMipmaps = generateMipmaps;
  7135. renderer.setRenderTarget( renderTarget, 5 );
  7136. renderer.render( scene, cameraNZ );
  7137. renderer.setRenderTarget( currentRenderTarget );
  7138. renderer.xr.enabled = currentXrEnabled;
  7139. }
  7140. }
  7141. class CubeTexture extends Texture {
  7142. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7143. images = images !== undefined ? images : [];
  7144. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7145. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7146. this.flipY = false;
  7147. }
  7148. get images() {
  7149. return this.image;
  7150. }
  7151. set images( value ) {
  7152. this.image = value;
  7153. }
  7154. }
  7155. CubeTexture.prototype.isCubeTexture = true;
  7156. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7157. constructor( size, options, dummy ) {
  7158. if ( Number.isInteger( options ) ) {
  7159. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7160. options = dummy;
  7161. }
  7162. super( size, size, options );
  7163. options = options || {};
  7164. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7165. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7166. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7167. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7168. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7169. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7170. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7171. this.texture.isRenderTargetTexture = true;
  7172. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7173. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7174. this.texture._needsFlipEnvMap = false;
  7175. }
  7176. fromEquirectangularTexture( renderer, texture ) {
  7177. this.texture.type = texture.type;
  7178. this.texture.format = RGBAFormat; // see #18859
  7179. this.texture.encoding = texture.encoding;
  7180. this.texture.generateMipmaps = texture.generateMipmaps;
  7181. this.texture.minFilter = texture.minFilter;
  7182. this.texture.magFilter = texture.magFilter;
  7183. const shader = {
  7184. uniforms: {
  7185. tEquirect: { value: null },
  7186. },
  7187. vertexShader: /* glsl */`
  7188. varying vec3 vWorldDirection;
  7189. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7190. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7191. }
  7192. void main() {
  7193. vWorldDirection = transformDirection( position, modelMatrix );
  7194. #include <begin_vertex>
  7195. #include <project_vertex>
  7196. }
  7197. `,
  7198. fragmentShader: /* glsl */`
  7199. uniform sampler2D tEquirect;
  7200. varying vec3 vWorldDirection;
  7201. #include <common>
  7202. void main() {
  7203. vec3 direction = normalize( vWorldDirection );
  7204. vec2 sampleUV = equirectUv( direction );
  7205. gl_FragColor = texture2D( tEquirect, sampleUV );
  7206. }
  7207. `
  7208. };
  7209. const geometry = new BoxGeometry( 5, 5, 5 );
  7210. const material = new ShaderMaterial( {
  7211. name: 'CubemapFromEquirect',
  7212. uniforms: cloneUniforms( shader.uniforms ),
  7213. vertexShader: shader.vertexShader,
  7214. fragmentShader: shader.fragmentShader,
  7215. side: BackSide,
  7216. blending: NoBlending
  7217. } );
  7218. material.uniforms.tEquirect.value = texture;
  7219. const mesh = new Mesh( geometry, material );
  7220. const currentMinFilter = texture.minFilter;
  7221. // Avoid blurred poles
  7222. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7223. const camera = new CubeCamera( 1, 10, this );
  7224. camera.update( renderer, mesh );
  7225. texture.minFilter = currentMinFilter;
  7226. mesh.geometry.dispose();
  7227. mesh.material.dispose();
  7228. return this;
  7229. }
  7230. clear( renderer, color, depth, stencil ) {
  7231. const currentRenderTarget = renderer.getRenderTarget();
  7232. for ( let i = 0; i < 6; i ++ ) {
  7233. renderer.setRenderTarget( this, i );
  7234. renderer.clear( color, depth, stencil );
  7235. }
  7236. renderer.setRenderTarget( currentRenderTarget );
  7237. }
  7238. }
  7239. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7240. const _vector1 = /*@__PURE__*/ new Vector3();
  7241. const _vector2 = /*@__PURE__*/ new Vector3();
  7242. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7243. class Plane {
  7244. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7245. // normal is assumed to be normalized
  7246. this.normal = normal;
  7247. this.constant = constant;
  7248. }
  7249. set( normal, constant ) {
  7250. this.normal.copy( normal );
  7251. this.constant = constant;
  7252. return this;
  7253. }
  7254. setComponents( x, y, z, w ) {
  7255. this.normal.set( x, y, z );
  7256. this.constant = w;
  7257. return this;
  7258. }
  7259. setFromNormalAndCoplanarPoint( normal, point ) {
  7260. this.normal.copy( normal );
  7261. this.constant = - point.dot( this.normal );
  7262. return this;
  7263. }
  7264. setFromCoplanarPoints( a, b, c ) {
  7265. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7266. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7267. this.setFromNormalAndCoplanarPoint( normal, a );
  7268. return this;
  7269. }
  7270. copy( plane ) {
  7271. this.normal.copy( plane.normal );
  7272. this.constant = plane.constant;
  7273. return this;
  7274. }
  7275. normalize() {
  7276. // Note: will lead to a divide by zero if the plane is invalid.
  7277. const inverseNormalLength = 1.0 / this.normal.length();
  7278. this.normal.multiplyScalar( inverseNormalLength );
  7279. this.constant *= inverseNormalLength;
  7280. return this;
  7281. }
  7282. negate() {
  7283. this.constant *= - 1;
  7284. this.normal.negate();
  7285. return this;
  7286. }
  7287. distanceToPoint( point ) {
  7288. return this.normal.dot( point ) + this.constant;
  7289. }
  7290. distanceToSphere( sphere ) {
  7291. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7292. }
  7293. projectPoint( point, target ) {
  7294. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7295. }
  7296. intersectLine( line, target ) {
  7297. const direction = line.delta( _vector1 );
  7298. const denominator = this.normal.dot( direction );
  7299. if ( denominator === 0 ) {
  7300. // line is coplanar, return origin
  7301. if ( this.distanceToPoint( line.start ) === 0 ) {
  7302. return target.copy( line.start );
  7303. }
  7304. // Unsure if this is the correct method to handle this case.
  7305. return null;
  7306. }
  7307. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7308. if ( t < 0 || t > 1 ) {
  7309. return null;
  7310. }
  7311. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7312. }
  7313. intersectsLine( line ) {
  7314. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7315. const startSign = this.distanceToPoint( line.start );
  7316. const endSign = this.distanceToPoint( line.end );
  7317. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7318. }
  7319. intersectsBox( box ) {
  7320. return box.intersectsPlane( this );
  7321. }
  7322. intersectsSphere( sphere ) {
  7323. return sphere.intersectsPlane( this );
  7324. }
  7325. coplanarPoint( target ) {
  7326. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7327. }
  7328. applyMatrix4( matrix, optionalNormalMatrix ) {
  7329. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7330. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7331. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7332. this.constant = - referencePoint.dot( normal );
  7333. return this;
  7334. }
  7335. translate( offset ) {
  7336. this.constant -= offset.dot( this.normal );
  7337. return this;
  7338. }
  7339. equals( plane ) {
  7340. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7341. }
  7342. clone() {
  7343. return new this.constructor().copy( this );
  7344. }
  7345. }
  7346. Plane.prototype.isPlane = true;
  7347. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7348. const _vector$7 = /*@__PURE__*/ new Vector3();
  7349. class Frustum {
  7350. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7351. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7352. }
  7353. set( p0, p1, p2, p3, p4, p5 ) {
  7354. const planes = this.planes;
  7355. planes[ 0 ].copy( p0 );
  7356. planes[ 1 ].copy( p1 );
  7357. planes[ 2 ].copy( p2 );
  7358. planes[ 3 ].copy( p3 );
  7359. planes[ 4 ].copy( p4 );
  7360. planes[ 5 ].copy( p5 );
  7361. return this;
  7362. }
  7363. copy( frustum ) {
  7364. const planes = this.planes;
  7365. for ( let i = 0; i < 6; i ++ ) {
  7366. planes[ i ].copy( frustum.planes[ i ] );
  7367. }
  7368. return this;
  7369. }
  7370. setFromProjectionMatrix( m ) {
  7371. const planes = this.planes;
  7372. const me = m.elements;
  7373. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7374. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7375. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7376. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7377. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7378. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7379. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7380. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7381. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7382. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7383. return this;
  7384. }
  7385. intersectsObject( object ) {
  7386. const geometry = object.geometry;
  7387. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7388. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7389. return this.intersectsSphere( _sphere$2 );
  7390. }
  7391. intersectsSprite( sprite ) {
  7392. _sphere$2.center.set( 0, 0, 0 );
  7393. _sphere$2.radius = 0.7071067811865476;
  7394. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7395. return this.intersectsSphere( _sphere$2 );
  7396. }
  7397. intersectsSphere( sphere ) {
  7398. const planes = this.planes;
  7399. const center = sphere.center;
  7400. const negRadius = - sphere.radius;
  7401. for ( let i = 0; i < 6; i ++ ) {
  7402. const distance = planes[ i ].distanceToPoint( center );
  7403. if ( distance < negRadius ) {
  7404. return false;
  7405. }
  7406. }
  7407. return true;
  7408. }
  7409. intersectsBox( box ) {
  7410. const planes = this.planes;
  7411. for ( let i = 0; i < 6; i ++ ) {
  7412. const plane = planes[ i ];
  7413. // corner at max distance
  7414. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7415. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7416. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7417. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7418. return false;
  7419. }
  7420. }
  7421. return true;
  7422. }
  7423. containsPoint( point ) {
  7424. const planes = this.planes;
  7425. for ( let i = 0; i < 6; i ++ ) {
  7426. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7427. return false;
  7428. }
  7429. }
  7430. return true;
  7431. }
  7432. clone() {
  7433. return new this.constructor().copy( this );
  7434. }
  7435. }
  7436. function WebGLAnimation() {
  7437. let context = null;
  7438. let isAnimating = false;
  7439. let animationLoop = null;
  7440. let requestId = null;
  7441. function onAnimationFrame( time, frame ) {
  7442. animationLoop( time, frame );
  7443. requestId = context.requestAnimationFrame( onAnimationFrame );
  7444. }
  7445. return {
  7446. start: function () {
  7447. if ( isAnimating === true ) return;
  7448. if ( animationLoop === null ) return;
  7449. requestId = context.requestAnimationFrame( onAnimationFrame );
  7450. isAnimating = true;
  7451. },
  7452. stop: function () {
  7453. context.cancelAnimationFrame( requestId );
  7454. isAnimating = false;
  7455. },
  7456. setAnimationLoop: function ( callback ) {
  7457. animationLoop = callback;
  7458. },
  7459. setContext: function ( value ) {
  7460. context = value;
  7461. }
  7462. };
  7463. }
  7464. function WebGLAttributes( gl, capabilities ) {
  7465. const isWebGL2 = capabilities.isWebGL2;
  7466. const buffers = new WeakMap();
  7467. function createBuffer( attribute, bufferType ) {
  7468. const array = attribute.array;
  7469. const usage = attribute.usage;
  7470. const buffer = gl.createBuffer();
  7471. gl.bindBuffer( bufferType, buffer );
  7472. gl.bufferData( bufferType, array, usage );
  7473. attribute.onUploadCallback();
  7474. let type = 5126;
  7475. if ( array instanceof Float32Array ) {
  7476. type = 5126;
  7477. } else if ( array instanceof Float64Array ) {
  7478. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7479. } else if ( array instanceof Uint16Array ) {
  7480. if ( attribute.isFloat16BufferAttribute ) {
  7481. if ( isWebGL2 ) {
  7482. type = 5131;
  7483. } else {
  7484. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7485. }
  7486. } else {
  7487. type = 5123;
  7488. }
  7489. } else if ( array instanceof Int16Array ) {
  7490. type = 5122;
  7491. } else if ( array instanceof Uint32Array ) {
  7492. type = 5125;
  7493. } else if ( array instanceof Int32Array ) {
  7494. type = 5124;
  7495. } else if ( array instanceof Int8Array ) {
  7496. type = 5120;
  7497. } else if ( array instanceof Uint8Array ) {
  7498. type = 5121;
  7499. } else if ( array instanceof Uint8ClampedArray ) {
  7500. type = 5121;
  7501. }
  7502. return {
  7503. buffer: buffer,
  7504. type: type,
  7505. bytesPerElement: array.BYTES_PER_ELEMENT,
  7506. version: attribute.version
  7507. };
  7508. }
  7509. function updateBuffer( buffer, attribute, bufferType ) {
  7510. const array = attribute.array;
  7511. const updateRange = attribute.updateRange;
  7512. gl.bindBuffer( bufferType, buffer );
  7513. if ( updateRange.count === - 1 ) {
  7514. // Not using update ranges
  7515. gl.bufferSubData( bufferType, 0, array );
  7516. } else {
  7517. if ( isWebGL2 ) {
  7518. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7519. array, updateRange.offset, updateRange.count );
  7520. } else {
  7521. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7522. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7523. }
  7524. updateRange.count = - 1; // reset range
  7525. }
  7526. }
  7527. //
  7528. function get( attribute ) {
  7529. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7530. return buffers.get( attribute );
  7531. }
  7532. function remove( attribute ) {
  7533. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7534. const data = buffers.get( attribute );
  7535. if ( data ) {
  7536. gl.deleteBuffer( data.buffer );
  7537. buffers.delete( attribute );
  7538. }
  7539. }
  7540. function update( attribute, bufferType ) {
  7541. if ( attribute.isGLBufferAttribute ) {
  7542. const cached = buffers.get( attribute );
  7543. if ( ! cached || cached.version < attribute.version ) {
  7544. buffers.set( attribute, {
  7545. buffer: attribute.buffer,
  7546. type: attribute.type,
  7547. bytesPerElement: attribute.elementSize,
  7548. version: attribute.version
  7549. } );
  7550. }
  7551. return;
  7552. }
  7553. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7554. const data = buffers.get( attribute );
  7555. if ( data === undefined ) {
  7556. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7557. } else if ( data.version < attribute.version ) {
  7558. updateBuffer( data.buffer, attribute, bufferType );
  7559. data.version = attribute.version;
  7560. }
  7561. }
  7562. return {
  7563. get: get,
  7564. remove: remove,
  7565. update: update
  7566. };
  7567. }
  7568. class PlaneGeometry extends BufferGeometry {
  7569. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7570. super();
  7571. this.type = 'PlaneGeometry';
  7572. this.parameters = {
  7573. width: width,
  7574. height: height,
  7575. widthSegments: widthSegments,
  7576. heightSegments: heightSegments
  7577. };
  7578. const width_half = width / 2;
  7579. const height_half = height / 2;
  7580. const gridX = Math.floor( widthSegments );
  7581. const gridY = Math.floor( heightSegments );
  7582. const gridX1 = gridX + 1;
  7583. const gridY1 = gridY + 1;
  7584. const segment_width = width / gridX;
  7585. const segment_height = height / gridY;
  7586. //
  7587. const indices = [];
  7588. const vertices = [];
  7589. const normals = [];
  7590. const uvs = [];
  7591. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7592. const y = iy * segment_height - height_half;
  7593. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7594. const x = ix * segment_width - width_half;
  7595. vertices.push( x, - y, 0 );
  7596. normals.push( 0, 0, 1 );
  7597. uvs.push( ix / gridX );
  7598. uvs.push( 1 - ( iy / gridY ) );
  7599. }
  7600. }
  7601. for ( let iy = 0; iy < gridY; iy ++ ) {
  7602. for ( let ix = 0; ix < gridX; ix ++ ) {
  7603. const a = ix + gridX1 * iy;
  7604. const b = ix + gridX1 * ( iy + 1 );
  7605. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7606. const d = ( ix + 1 ) + gridX1 * iy;
  7607. indices.push( a, b, d );
  7608. indices.push( b, c, d );
  7609. }
  7610. }
  7611. this.setIndex( indices );
  7612. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7613. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7614. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7615. }
  7616. static fromJSON( data ) {
  7617. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7618. }
  7619. }
  7620. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7621. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7622. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7623. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7624. 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";
  7625. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7626. var begin_vertex = "vec3 transformed = vec3( position );";
  7627. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7628. 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";
  7629. 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";
  7630. 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";
  7631. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7632. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7633. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7634. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7635. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7636. 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";
  7637. 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";
  7638. 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}";
  7639. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.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\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\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\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\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_maxMipLevel );\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";
  7640. 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";
  7641. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7642. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7643. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7644. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7645. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7646. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\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}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}";
  7647. 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\tenvColor = envMapTexelToLinear( envColor );\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";
  7648. 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";
  7649. 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";
  7650. 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";
  7651. 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";
  7652. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7653. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7654. 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";
  7655. 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";
  7656. 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 texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7657. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7658. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7659. 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";
  7660. 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";
  7661. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\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;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\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";
  7662. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7663. 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)";
  7664. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7665. 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)";
  7666. 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 *= specularColorMapTexelToLinear( 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 *= sheenColorMapTexelToLinear( 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";
  7667. 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 );\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\treflectedLight.directSpecular += 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\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}";
  7668. 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";
  7669. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\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";
  7670. 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";
  7671. 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";
  7672. 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";
  7673. 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";
  7674. 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";
  7675. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7676. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7677. 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\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7678. 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";
  7679. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7680. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7681. 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, 2 ) * 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";
  7682. 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 vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\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";
  7683. 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\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\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";
  7684. 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;";
  7685. 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";
  7686. 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";
  7687. 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";
  7688. 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";
  7689. 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";
  7690. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7691. 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";
  7692. 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";
  7693. 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 );";
  7694. 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}";
  7695. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7696. 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;";
  7697. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7698. 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";
  7699. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7700. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7701. 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";
  7702. 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";
  7703. 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";
  7704. 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}";
  7705. 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";
  7706. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  7707. 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";
  7708. 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";
  7709. 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";
  7710. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7711. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7712. 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; }";
  7713. 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";
  7714. 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( vec3 n, vec3 v, float thickness, float ior, 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( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\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( vec3 radiance, float transmissionDistance, vec3 attenuationColor, 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( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, 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";
  7715. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7716. 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";
  7717. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7718. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7719. 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";
  7720. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7721. 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";
  7722. 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}";
  7723. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7724. 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}";
  7725. 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}";
  7726. 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}";
  7727. 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}";
  7728. 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}";
  7729. 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}";
  7730. 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}";
  7731. 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\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7732. 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 <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}";
  7733. 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}";
  7734. 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#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}";
  7735. 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 += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\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}";
  7736. 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 <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}";
  7737. 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}";
  7738. 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 <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}";
  7739. 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\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 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}";
  7740. 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}";
  7741. 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}";
  7742. 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 <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}";
  7743. 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}";
  7744. 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 <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}";
  7745. 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_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}";
  7746. 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 <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}";
  7747. 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}";
  7748. 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 <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}";
  7749. 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}";
  7750. 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}";
  7751. 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}";
  7752. 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}";
  7753. 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}";
  7754. const ShaderChunk = {
  7755. alphamap_fragment: alphamap_fragment,
  7756. alphamap_pars_fragment: alphamap_pars_fragment,
  7757. alphatest_fragment: alphatest_fragment,
  7758. alphatest_pars_fragment: alphatest_pars_fragment,
  7759. aomap_fragment: aomap_fragment,
  7760. aomap_pars_fragment: aomap_pars_fragment,
  7761. begin_vertex: begin_vertex,
  7762. beginnormal_vertex: beginnormal_vertex,
  7763. bsdfs: bsdfs,
  7764. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7765. clipping_planes_fragment: clipping_planes_fragment,
  7766. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7767. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7768. clipping_planes_vertex: clipping_planes_vertex,
  7769. color_fragment: color_fragment,
  7770. color_pars_fragment: color_pars_fragment,
  7771. color_pars_vertex: color_pars_vertex,
  7772. color_vertex: color_vertex,
  7773. common: common,
  7774. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7775. defaultnormal_vertex: defaultnormal_vertex,
  7776. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7777. displacementmap_vertex: displacementmap_vertex,
  7778. emissivemap_fragment: emissivemap_fragment,
  7779. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7780. encodings_fragment: encodings_fragment,
  7781. encodings_pars_fragment: encodings_pars_fragment,
  7782. envmap_fragment: envmap_fragment,
  7783. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7784. envmap_pars_fragment: envmap_pars_fragment,
  7785. envmap_pars_vertex: envmap_pars_vertex,
  7786. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7787. envmap_vertex: envmap_vertex,
  7788. fog_vertex: fog_vertex,
  7789. fog_pars_vertex: fog_pars_vertex,
  7790. fog_fragment: fog_fragment,
  7791. fog_pars_fragment: fog_pars_fragment,
  7792. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7793. lightmap_fragment: lightmap_fragment,
  7794. lightmap_pars_fragment: lightmap_pars_fragment,
  7795. lights_lambert_vertex: lights_lambert_vertex,
  7796. lights_pars_begin: lights_pars_begin,
  7797. lights_toon_fragment: lights_toon_fragment,
  7798. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7799. lights_phong_fragment: lights_phong_fragment,
  7800. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7801. lights_physical_fragment: lights_physical_fragment,
  7802. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7803. lights_fragment_begin: lights_fragment_begin,
  7804. lights_fragment_maps: lights_fragment_maps,
  7805. lights_fragment_end: lights_fragment_end,
  7806. logdepthbuf_fragment: logdepthbuf_fragment,
  7807. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7808. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7809. logdepthbuf_vertex: logdepthbuf_vertex,
  7810. map_fragment: map_fragment,
  7811. map_pars_fragment: map_pars_fragment,
  7812. map_particle_fragment: map_particle_fragment,
  7813. map_particle_pars_fragment: map_particle_pars_fragment,
  7814. metalnessmap_fragment: metalnessmap_fragment,
  7815. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7816. morphnormal_vertex: morphnormal_vertex,
  7817. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7818. morphtarget_vertex: morphtarget_vertex,
  7819. normal_fragment_begin: normal_fragment_begin,
  7820. normal_fragment_maps: normal_fragment_maps,
  7821. normal_pars_fragment: normal_pars_fragment,
  7822. normal_pars_vertex: normal_pars_vertex,
  7823. normal_vertex: normal_vertex,
  7824. normalmap_pars_fragment: normalmap_pars_fragment,
  7825. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7826. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7827. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7828. output_fragment: output_fragment,
  7829. packing: packing,
  7830. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7831. project_vertex: project_vertex,
  7832. dithering_fragment: dithering_fragment,
  7833. dithering_pars_fragment: dithering_pars_fragment,
  7834. roughnessmap_fragment: roughnessmap_fragment,
  7835. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7836. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7837. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7838. shadowmap_vertex: shadowmap_vertex,
  7839. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7840. skinbase_vertex: skinbase_vertex,
  7841. skinning_pars_vertex: skinning_pars_vertex,
  7842. skinning_vertex: skinning_vertex,
  7843. skinnormal_vertex: skinnormal_vertex,
  7844. specularmap_fragment: specularmap_fragment,
  7845. specularmap_pars_fragment: specularmap_pars_fragment,
  7846. tonemapping_fragment: tonemapping_fragment,
  7847. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7848. transmission_fragment: transmission_fragment,
  7849. transmission_pars_fragment: transmission_pars_fragment,
  7850. uv_pars_fragment: uv_pars_fragment,
  7851. uv_pars_vertex: uv_pars_vertex,
  7852. uv_vertex: uv_vertex,
  7853. uv2_pars_fragment: uv2_pars_fragment,
  7854. uv2_pars_vertex: uv2_pars_vertex,
  7855. uv2_vertex: uv2_vertex,
  7856. worldpos_vertex: worldpos_vertex,
  7857. background_vert: vertex$g,
  7858. background_frag: fragment$g,
  7859. cube_vert: vertex$f,
  7860. cube_frag: fragment$f,
  7861. depth_vert: vertex$e,
  7862. depth_frag: fragment$e,
  7863. distanceRGBA_vert: vertex$d,
  7864. distanceRGBA_frag: fragment$d,
  7865. equirect_vert: vertex$c,
  7866. equirect_frag: fragment$c,
  7867. linedashed_vert: vertex$b,
  7868. linedashed_frag: fragment$b,
  7869. meshbasic_vert: vertex$a,
  7870. meshbasic_frag: fragment$a,
  7871. meshlambert_vert: vertex$9,
  7872. meshlambert_frag: fragment$9,
  7873. meshmatcap_vert: vertex$8,
  7874. meshmatcap_frag: fragment$8,
  7875. meshnormal_vert: vertex$7,
  7876. meshnormal_frag: fragment$7,
  7877. meshphong_vert: vertex$6,
  7878. meshphong_frag: fragment$6,
  7879. meshphysical_vert: vertex$5,
  7880. meshphysical_frag: fragment$5,
  7881. meshtoon_vert: vertex$4,
  7882. meshtoon_frag: fragment$4,
  7883. points_vert: vertex$3,
  7884. points_frag: fragment$3,
  7885. shadow_vert: vertex$2,
  7886. shadow_frag: fragment$2,
  7887. sprite_vert: vertex$1,
  7888. sprite_frag: fragment$1
  7889. };
  7890. /**
  7891. * Uniforms library for shared webgl shaders
  7892. */
  7893. const UniformsLib = {
  7894. common: {
  7895. diffuse: { value: new Color( 0xffffff ) },
  7896. opacity: { value: 1.0 },
  7897. map: { value: null },
  7898. uvTransform: { value: new Matrix3() },
  7899. uv2Transform: { value: new Matrix3() },
  7900. alphaMap: { value: null },
  7901. alphaTest: { value: 0 }
  7902. },
  7903. specularmap: {
  7904. specularMap: { value: null },
  7905. },
  7906. envmap: {
  7907. envMap: { value: null },
  7908. flipEnvMap: { value: - 1 },
  7909. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7910. ior: { value: 1.5 }, // standard, physical
  7911. refractionRatio: { value: 0.98 }
  7912. },
  7913. aomap: {
  7914. aoMap: { value: null },
  7915. aoMapIntensity: { value: 1 }
  7916. },
  7917. lightmap: {
  7918. lightMap: { value: null },
  7919. lightMapIntensity: { value: 1 }
  7920. },
  7921. emissivemap: {
  7922. emissiveMap: { value: null }
  7923. },
  7924. bumpmap: {
  7925. bumpMap: { value: null },
  7926. bumpScale: { value: 1 }
  7927. },
  7928. normalmap: {
  7929. normalMap: { value: null },
  7930. normalScale: { value: new Vector2( 1, 1 ) }
  7931. },
  7932. displacementmap: {
  7933. displacementMap: { value: null },
  7934. displacementScale: { value: 1 },
  7935. displacementBias: { value: 0 }
  7936. },
  7937. roughnessmap: {
  7938. roughnessMap: { value: null }
  7939. },
  7940. metalnessmap: {
  7941. metalnessMap: { value: null }
  7942. },
  7943. gradientmap: {
  7944. gradientMap: { value: null }
  7945. },
  7946. fog: {
  7947. fogDensity: { value: 0.00025 },
  7948. fogNear: { value: 1 },
  7949. fogFar: { value: 2000 },
  7950. fogColor: { value: new Color( 0xffffff ) }
  7951. },
  7952. lights: {
  7953. ambientLightColor: { value: [] },
  7954. lightProbe: { value: [] },
  7955. directionalLights: { value: [], properties: {
  7956. direction: {},
  7957. color: {}
  7958. } },
  7959. directionalLightShadows: { value: [], properties: {
  7960. shadowBias: {},
  7961. shadowNormalBias: {},
  7962. shadowRadius: {},
  7963. shadowMapSize: {}
  7964. } },
  7965. directionalShadowMap: { value: [] },
  7966. directionalShadowMatrix: { value: [] },
  7967. spotLights: { value: [], properties: {
  7968. color: {},
  7969. position: {},
  7970. direction: {},
  7971. distance: {},
  7972. coneCos: {},
  7973. penumbraCos: {},
  7974. decay: {}
  7975. } },
  7976. spotLightShadows: { value: [], properties: {
  7977. shadowBias: {},
  7978. shadowNormalBias: {},
  7979. shadowRadius: {},
  7980. shadowMapSize: {}
  7981. } },
  7982. spotShadowMap: { value: [] },
  7983. spotShadowMatrix: { value: [] },
  7984. pointLights: { value: [], properties: {
  7985. color: {},
  7986. position: {},
  7987. decay: {},
  7988. distance: {}
  7989. } },
  7990. pointLightShadows: { value: [], properties: {
  7991. shadowBias: {},
  7992. shadowNormalBias: {},
  7993. shadowRadius: {},
  7994. shadowMapSize: {},
  7995. shadowCameraNear: {},
  7996. shadowCameraFar: {}
  7997. } },
  7998. pointShadowMap: { value: [] },
  7999. pointShadowMatrix: { value: [] },
  8000. hemisphereLights: { value: [], properties: {
  8001. direction: {},
  8002. skyColor: {},
  8003. groundColor: {}
  8004. } },
  8005. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8006. rectAreaLights: { value: [], properties: {
  8007. color: {},
  8008. position: {},
  8009. width: {},
  8010. height: {}
  8011. } },
  8012. ltc_1: { value: null },
  8013. ltc_2: { value: null }
  8014. },
  8015. points: {
  8016. diffuse: { value: new Color( 0xffffff ) },
  8017. opacity: { value: 1.0 },
  8018. size: { value: 1.0 },
  8019. scale: { value: 1.0 },
  8020. map: { value: null },
  8021. alphaMap: { value: null },
  8022. alphaTest: { value: 0 },
  8023. uvTransform: { value: new Matrix3() }
  8024. },
  8025. sprite: {
  8026. diffuse: { value: new Color( 0xffffff ) },
  8027. opacity: { value: 1.0 },
  8028. center: { value: new Vector2( 0.5, 0.5 ) },
  8029. rotation: { value: 0.0 },
  8030. map: { value: null },
  8031. alphaMap: { value: null },
  8032. alphaTest: { value: 0 },
  8033. uvTransform: { value: new Matrix3() }
  8034. }
  8035. };
  8036. const ShaderLib = {
  8037. basic: {
  8038. uniforms: mergeUniforms( [
  8039. UniformsLib.common,
  8040. UniformsLib.specularmap,
  8041. UniformsLib.envmap,
  8042. UniformsLib.aomap,
  8043. UniformsLib.lightmap,
  8044. UniformsLib.fog
  8045. ] ),
  8046. vertexShader: ShaderChunk.meshbasic_vert,
  8047. fragmentShader: ShaderChunk.meshbasic_frag
  8048. },
  8049. lambert: {
  8050. uniforms: mergeUniforms( [
  8051. UniformsLib.common,
  8052. UniformsLib.specularmap,
  8053. UniformsLib.envmap,
  8054. UniformsLib.aomap,
  8055. UniformsLib.lightmap,
  8056. UniformsLib.emissivemap,
  8057. UniformsLib.fog,
  8058. UniformsLib.lights,
  8059. {
  8060. emissive: { value: new Color( 0x000000 ) }
  8061. }
  8062. ] ),
  8063. vertexShader: ShaderChunk.meshlambert_vert,
  8064. fragmentShader: ShaderChunk.meshlambert_frag
  8065. },
  8066. phong: {
  8067. uniforms: mergeUniforms( [
  8068. UniformsLib.common,
  8069. UniformsLib.specularmap,
  8070. UniformsLib.envmap,
  8071. UniformsLib.aomap,
  8072. UniformsLib.lightmap,
  8073. UniformsLib.emissivemap,
  8074. UniformsLib.bumpmap,
  8075. UniformsLib.normalmap,
  8076. UniformsLib.displacementmap,
  8077. UniformsLib.fog,
  8078. UniformsLib.lights,
  8079. {
  8080. emissive: { value: new Color( 0x000000 ) },
  8081. specular: { value: new Color( 0x111111 ) },
  8082. shininess: { value: 30 }
  8083. }
  8084. ] ),
  8085. vertexShader: ShaderChunk.meshphong_vert,
  8086. fragmentShader: ShaderChunk.meshphong_frag
  8087. },
  8088. standard: {
  8089. uniforms: mergeUniforms( [
  8090. UniformsLib.common,
  8091. UniformsLib.envmap,
  8092. UniformsLib.aomap,
  8093. UniformsLib.lightmap,
  8094. UniformsLib.emissivemap,
  8095. UniformsLib.bumpmap,
  8096. UniformsLib.normalmap,
  8097. UniformsLib.displacementmap,
  8098. UniformsLib.roughnessmap,
  8099. UniformsLib.metalnessmap,
  8100. UniformsLib.fog,
  8101. UniformsLib.lights,
  8102. {
  8103. emissive: { value: new Color( 0x000000 ) },
  8104. roughness: { value: 1.0 },
  8105. metalness: { value: 0.0 },
  8106. envMapIntensity: { value: 1 } // temporary
  8107. }
  8108. ] ),
  8109. vertexShader: ShaderChunk.meshphysical_vert,
  8110. fragmentShader: ShaderChunk.meshphysical_frag
  8111. },
  8112. toon: {
  8113. uniforms: mergeUniforms( [
  8114. UniformsLib.common,
  8115. UniformsLib.aomap,
  8116. UniformsLib.lightmap,
  8117. UniformsLib.emissivemap,
  8118. UniformsLib.bumpmap,
  8119. UniformsLib.normalmap,
  8120. UniformsLib.displacementmap,
  8121. UniformsLib.gradientmap,
  8122. UniformsLib.fog,
  8123. UniformsLib.lights,
  8124. {
  8125. emissive: { value: new Color( 0x000000 ) }
  8126. }
  8127. ] ),
  8128. vertexShader: ShaderChunk.meshtoon_vert,
  8129. fragmentShader: ShaderChunk.meshtoon_frag
  8130. },
  8131. matcap: {
  8132. uniforms: mergeUniforms( [
  8133. UniformsLib.common,
  8134. UniformsLib.bumpmap,
  8135. UniformsLib.normalmap,
  8136. UniformsLib.displacementmap,
  8137. UniformsLib.fog,
  8138. {
  8139. matcap: { value: null }
  8140. }
  8141. ] ),
  8142. vertexShader: ShaderChunk.meshmatcap_vert,
  8143. fragmentShader: ShaderChunk.meshmatcap_frag
  8144. },
  8145. points: {
  8146. uniforms: mergeUniforms( [
  8147. UniformsLib.points,
  8148. UniformsLib.fog
  8149. ] ),
  8150. vertexShader: ShaderChunk.points_vert,
  8151. fragmentShader: ShaderChunk.points_frag
  8152. },
  8153. dashed: {
  8154. uniforms: mergeUniforms( [
  8155. UniformsLib.common,
  8156. UniformsLib.fog,
  8157. {
  8158. scale: { value: 1 },
  8159. dashSize: { value: 1 },
  8160. totalSize: { value: 2 }
  8161. }
  8162. ] ),
  8163. vertexShader: ShaderChunk.linedashed_vert,
  8164. fragmentShader: ShaderChunk.linedashed_frag
  8165. },
  8166. depth: {
  8167. uniforms: mergeUniforms( [
  8168. UniformsLib.common,
  8169. UniformsLib.displacementmap
  8170. ] ),
  8171. vertexShader: ShaderChunk.depth_vert,
  8172. fragmentShader: ShaderChunk.depth_frag
  8173. },
  8174. normal: {
  8175. uniforms: mergeUniforms( [
  8176. UniformsLib.common,
  8177. UniformsLib.bumpmap,
  8178. UniformsLib.normalmap,
  8179. UniformsLib.displacementmap,
  8180. {
  8181. opacity: { value: 1.0 }
  8182. }
  8183. ] ),
  8184. vertexShader: ShaderChunk.meshnormal_vert,
  8185. fragmentShader: ShaderChunk.meshnormal_frag
  8186. },
  8187. sprite: {
  8188. uniforms: mergeUniforms( [
  8189. UniformsLib.sprite,
  8190. UniformsLib.fog
  8191. ] ),
  8192. vertexShader: ShaderChunk.sprite_vert,
  8193. fragmentShader: ShaderChunk.sprite_frag
  8194. },
  8195. background: {
  8196. uniforms: {
  8197. uvTransform: { value: new Matrix3() },
  8198. t2D: { value: null },
  8199. },
  8200. vertexShader: ShaderChunk.background_vert,
  8201. fragmentShader: ShaderChunk.background_frag
  8202. },
  8203. /* -------------------------------------------------------------------------
  8204. // Cube map shader
  8205. ------------------------------------------------------------------------- */
  8206. cube: {
  8207. uniforms: mergeUniforms( [
  8208. UniformsLib.envmap,
  8209. {
  8210. opacity: { value: 1.0 }
  8211. }
  8212. ] ),
  8213. vertexShader: ShaderChunk.cube_vert,
  8214. fragmentShader: ShaderChunk.cube_frag
  8215. },
  8216. equirect: {
  8217. uniforms: {
  8218. tEquirect: { value: null },
  8219. },
  8220. vertexShader: ShaderChunk.equirect_vert,
  8221. fragmentShader: ShaderChunk.equirect_frag
  8222. },
  8223. distanceRGBA: {
  8224. uniforms: mergeUniforms( [
  8225. UniformsLib.common,
  8226. UniformsLib.displacementmap,
  8227. {
  8228. referencePosition: { value: new Vector3() },
  8229. nearDistance: { value: 1 },
  8230. farDistance: { value: 1000 }
  8231. }
  8232. ] ),
  8233. vertexShader: ShaderChunk.distanceRGBA_vert,
  8234. fragmentShader: ShaderChunk.distanceRGBA_frag
  8235. },
  8236. shadow: {
  8237. uniforms: mergeUniforms( [
  8238. UniformsLib.lights,
  8239. UniformsLib.fog,
  8240. {
  8241. color: { value: new Color( 0x00000 ) },
  8242. opacity: { value: 1.0 }
  8243. },
  8244. ] ),
  8245. vertexShader: ShaderChunk.shadow_vert,
  8246. fragmentShader: ShaderChunk.shadow_frag
  8247. }
  8248. };
  8249. ShaderLib.physical = {
  8250. uniforms: mergeUniforms( [
  8251. ShaderLib.standard.uniforms,
  8252. {
  8253. clearcoat: { value: 0 },
  8254. clearcoatMap: { value: null },
  8255. clearcoatRoughness: { value: 0 },
  8256. clearcoatRoughnessMap: { value: null },
  8257. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8258. clearcoatNormalMap: { value: null },
  8259. sheen: { value: 0 },
  8260. sheenColor: { value: new Color( 0x000000 ) },
  8261. sheenColorMap: { value: null },
  8262. sheenRoughness: { value: 0 },
  8263. sheenRoughnessMap: { value: null },
  8264. transmission: { value: 0 },
  8265. transmissionMap: { value: null },
  8266. transmissionSamplerSize: { value: new Vector2() },
  8267. transmissionSamplerMap: { value: null },
  8268. thickness: { value: 0 },
  8269. thicknessMap: { value: null },
  8270. attenuationDistance: { value: 0 },
  8271. attenuationColor: { value: new Color( 0x000000 ) },
  8272. specularIntensity: { value: 0 },
  8273. specularIntensityMap: { value: null },
  8274. specularColor: { value: new Color( 1, 1, 1 ) },
  8275. specularColorMap: { value: null },
  8276. }
  8277. ] ),
  8278. vertexShader: ShaderChunk.meshphysical_vert,
  8279. fragmentShader: ShaderChunk.meshphysical_frag
  8280. };
  8281. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8282. const clearColor = new Color( 0x000000 );
  8283. let clearAlpha = 0;
  8284. let planeMesh;
  8285. let boxMesh;
  8286. let currentBackground = null;
  8287. let currentBackgroundVersion = 0;
  8288. let currentTonemapping = null;
  8289. function render( renderList, scene ) {
  8290. let forceClear = false;
  8291. let background = scene.isScene === true ? scene.background : null;
  8292. if ( background && background.isTexture ) {
  8293. background = cubemaps.get( background );
  8294. }
  8295. // Ignore background in AR
  8296. // TODO: Reconsider this.
  8297. const xr = renderer.xr;
  8298. const session = xr.getSession && xr.getSession();
  8299. if ( session && session.environmentBlendMode === 'additive' ) {
  8300. background = null;
  8301. }
  8302. if ( background === null ) {
  8303. setClear( clearColor, clearAlpha );
  8304. } else if ( background && background.isColor ) {
  8305. setClear( background, 1 );
  8306. forceClear = true;
  8307. }
  8308. if ( renderer.autoClear || forceClear ) {
  8309. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8310. }
  8311. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8312. if ( boxMesh === undefined ) {
  8313. boxMesh = new Mesh(
  8314. new BoxGeometry( 1, 1, 1 ),
  8315. new ShaderMaterial( {
  8316. name: 'BackgroundCubeMaterial',
  8317. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8318. vertexShader: ShaderLib.cube.vertexShader,
  8319. fragmentShader: ShaderLib.cube.fragmentShader,
  8320. side: BackSide,
  8321. depthTest: false,
  8322. depthWrite: false,
  8323. fog: false
  8324. } )
  8325. );
  8326. boxMesh.geometry.deleteAttribute( 'normal' );
  8327. boxMesh.geometry.deleteAttribute( 'uv' );
  8328. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8329. this.matrixWorld.copyPosition( camera.matrixWorld );
  8330. };
  8331. // enable code injection for non-built-in material
  8332. Object.defineProperty( boxMesh.material, 'envMap', {
  8333. get: function () {
  8334. return this.uniforms.envMap.value;
  8335. }
  8336. } );
  8337. objects.update( boxMesh );
  8338. }
  8339. boxMesh.material.uniforms.envMap.value = background;
  8340. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8341. if ( currentBackground !== background ||
  8342. currentBackgroundVersion !== background.version ||
  8343. currentTonemapping !== renderer.toneMapping ) {
  8344. boxMesh.material.needsUpdate = true;
  8345. currentBackground = background;
  8346. currentBackgroundVersion = background.version;
  8347. currentTonemapping = renderer.toneMapping;
  8348. }
  8349. // push to the pre-sorted opaque render list
  8350. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8351. } else if ( background && background.isTexture ) {
  8352. if ( planeMesh === undefined ) {
  8353. planeMesh = new Mesh(
  8354. new PlaneGeometry( 2, 2 ),
  8355. new ShaderMaterial( {
  8356. name: 'BackgroundMaterial',
  8357. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8358. vertexShader: ShaderLib.background.vertexShader,
  8359. fragmentShader: ShaderLib.background.fragmentShader,
  8360. side: FrontSide,
  8361. depthTest: false,
  8362. depthWrite: false,
  8363. fog: false
  8364. } )
  8365. );
  8366. planeMesh.geometry.deleteAttribute( 'normal' );
  8367. // enable code injection for non-built-in material
  8368. Object.defineProperty( planeMesh.material, 'map', {
  8369. get: function () {
  8370. return this.uniforms.t2D.value;
  8371. }
  8372. } );
  8373. objects.update( planeMesh );
  8374. }
  8375. planeMesh.material.uniforms.t2D.value = background;
  8376. if ( background.matrixAutoUpdate === true ) {
  8377. background.updateMatrix();
  8378. }
  8379. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8380. if ( currentBackground !== background ||
  8381. currentBackgroundVersion !== background.version ||
  8382. currentTonemapping !== renderer.toneMapping ) {
  8383. planeMesh.material.needsUpdate = true;
  8384. currentBackground = background;
  8385. currentBackgroundVersion = background.version;
  8386. currentTonemapping = renderer.toneMapping;
  8387. }
  8388. // push to the pre-sorted opaque render list
  8389. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8390. }
  8391. }
  8392. function setClear( color, alpha ) {
  8393. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8394. }
  8395. return {
  8396. getClearColor: function () {
  8397. return clearColor;
  8398. },
  8399. setClearColor: function ( color, alpha = 1 ) {
  8400. clearColor.set( color );
  8401. clearAlpha = alpha;
  8402. setClear( clearColor, clearAlpha );
  8403. },
  8404. getClearAlpha: function () {
  8405. return clearAlpha;
  8406. },
  8407. setClearAlpha: function ( alpha ) {
  8408. clearAlpha = alpha;
  8409. setClear( clearColor, clearAlpha );
  8410. },
  8411. render: render
  8412. };
  8413. }
  8414. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8415. const maxVertexAttributes = gl.getParameter( 34921 );
  8416. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8417. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8418. const bindingStates = {};
  8419. const defaultState = createBindingState( null );
  8420. let currentState = defaultState;
  8421. function setup( object, material, program, geometry, index ) {
  8422. let updateBuffers = false;
  8423. if ( vaoAvailable ) {
  8424. const state = getBindingState( geometry, program, material );
  8425. if ( currentState !== state ) {
  8426. currentState = state;
  8427. bindVertexArrayObject( currentState.object );
  8428. }
  8429. updateBuffers = needsUpdate( geometry, index );
  8430. if ( updateBuffers ) saveCache( geometry, index );
  8431. } else {
  8432. const wireframe = ( material.wireframe === true );
  8433. if ( currentState.geometry !== geometry.id ||
  8434. currentState.program !== program.id ||
  8435. currentState.wireframe !== wireframe ) {
  8436. currentState.geometry = geometry.id;
  8437. currentState.program = program.id;
  8438. currentState.wireframe = wireframe;
  8439. updateBuffers = true;
  8440. }
  8441. }
  8442. if ( object.isInstancedMesh === true ) {
  8443. updateBuffers = true;
  8444. }
  8445. if ( index !== null ) {
  8446. attributes.update( index, 34963 );
  8447. }
  8448. if ( updateBuffers ) {
  8449. setupVertexAttributes( object, material, program, geometry );
  8450. if ( index !== null ) {
  8451. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8452. }
  8453. }
  8454. }
  8455. function createVertexArrayObject() {
  8456. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8457. return extension.createVertexArrayOES();
  8458. }
  8459. function bindVertexArrayObject( vao ) {
  8460. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8461. return extension.bindVertexArrayOES( vao );
  8462. }
  8463. function deleteVertexArrayObject( vao ) {
  8464. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8465. return extension.deleteVertexArrayOES( vao );
  8466. }
  8467. function getBindingState( geometry, program, material ) {
  8468. const wireframe = ( material.wireframe === true );
  8469. let programMap = bindingStates[ geometry.id ];
  8470. if ( programMap === undefined ) {
  8471. programMap = {};
  8472. bindingStates[ geometry.id ] = programMap;
  8473. }
  8474. let stateMap = programMap[ program.id ];
  8475. if ( stateMap === undefined ) {
  8476. stateMap = {};
  8477. programMap[ program.id ] = stateMap;
  8478. }
  8479. let state = stateMap[ wireframe ];
  8480. if ( state === undefined ) {
  8481. state = createBindingState( createVertexArrayObject() );
  8482. stateMap[ wireframe ] = state;
  8483. }
  8484. return state;
  8485. }
  8486. function createBindingState( vao ) {
  8487. const newAttributes = [];
  8488. const enabledAttributes = [];
  8489. const attributeDivisors = [];
  8490. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8491. newAttributes[ i ] = 0;
  8492. enabledAttributes[ i ] = 0;
  8493. attributeDivisors[ i ] = 0;
  8494. }
  8495. return {
  8496. // for backward compatibility on non-VAO support browser
  8497. geometry: null,
  8498. program: null,
  8499. wireframe: false,
  8500. newAttributes: newAttributes,
  8501. enabledAttributes: enabledAttributes,
  8502. attributeDivisors: attributeDivisors,
  8503. object: vao,
  8504. attributes: {},
  8505. index: null
  8506. };
  8507. }
  8508. function needsUpdate( geometry, index ) {
  8509. const cachedAttributes = currentState.attributes;
  8510. const geometryAttributes = geometry.attributes;
  8511. let attributesNum = 0;
  8512. for ( const key in geometryAttributes ) {
  8513. const cachedAttribute = cachedAttributes[ key ];
  8514. const geometryAttribute = geometryAttributes[ key ];
  8515. if ( cachedAttribute === undefined ) return true;
  8516. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8517. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8518. attributesNum ++;
  8519. }
  8520. if ( currentState.attributesNum !== attributesNum ) return true;
  8521. if ( currentState.index !== index ) return true;
  8522. return false;
  8523. }
  8524. function saveCache( geometry, index ) {
  8525. const cache = {};
  8526. const attributes = geometry.attributes;
  8527. let attributesNum = 0;
  8528. for ( const key in attributes ) {
  8529. const attribute = attributes[ key ];
  8530. const data = {};
  8531. data.attribute = attribute;
  8532. if ( attribute.data ) {
  8533. data.data = attribute.data;
  8534. }
  8535. cache[ key ] = data;
  8536. attributesNum ++;
  8537. }
  8538. currentState.attributes = cache;
  8539. currentState.attributesNum = attributesNum;
  8540. currentState.index = index;
  8541. }
  8542. function initAttributes() {
  8543. const newAttributes = currentState.newAttributes;
  8544. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8545. newAttributes[ i ] = 0;
  8546. }
  8547. }
  8548. function enableAttribute( attribute ) {
  8549. enableAttributeAndDivisor( attribute, 0 );
  8550. }
  8551. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8552. const newAttributes = currentState.newAttributes;
  8553. const enabledAttributes = currentState.enabledAttributes;
  8554. const attributeDivisors = currentState.attributeDivisors;
  8555. newAttributes[ attribute ] = 1;
  8556. if ( enabledAttributes[ attribute ] === 0 ) {
  8557. gl.enableVertexAttribArray( attribute );
  8558. enabledAttributes[ attribute ] = 1;
  8559. }
  8560. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8561. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8562. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8563. attributeDivisors[ attribute ] = meshPerAttribute;
  8564. }
  8565. }
  8566. function disableUnusedAttributes() {
  8567. const newAttributes = currentState.newAttributes;
  8568. const enabledAttributes = currentState.enabledAttributes;
  8569. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8570. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8571. gl.disableVertexAttribArray( i );
  8572. enabledAttributes[ i ] = 0;
  8573. }
  8574. }
  8575. }
  8576. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8577. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8578. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8579. } else {
  8580. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8581. }
  8582. }
  8583. function setupVertexAttributes( object, material, program, geometry ) {
  8584. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8585. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8586. }
  8587. initAttributes();
  8588. const geometryAttributes = geometry.attributes;
  8589. const programAttributes = program.getAttributes();
  8590. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8591. for ( const name in programAttributes ) {
  8592. const programAttribute = programAttributes[ name ];
  8593. if ( programAttribute.location >= 0 ) {
  8594. let geometryAttribute = geometryAttributes[ name ];
  8595. if ( geometryAttribute === undefined ) {
  8596. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8597. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8598. }
  8599. if ( geometryAttribute !== undefined ) {
  8600. const normalized = geometryAttribute.normalized;
  8601. const size = geometryAttribute.itemSize;
  8602. const attribute = attributes.get( geometryAttribute );
  8603. // TODO Attribute may not be available on context restore
  8604. if ( attribute === undefined ) continue;
  8605. const buffer = attribute.buffer;
  8606. const type = attribute.type;
  8607. const bytesPerElement = attribute.bytesPerElement;
  8608. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8609. const data = geometryAttribute.data;
  8610. const stride = data.stride;
  8611. const offset = geometryAttribute.offset;
  8612. if ( data && data.isInstancedInterleavedBuffer ) {
  8613. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8614. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8615. }
  8616. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8617. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8618. }
  8619. } else {
  8620. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8621. enableAttribute( programAttribute.location + i );
  8622. }
  8623. }
  8624. gl.bindBuffer( 34962, buffer );
  8625. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8626. vertexAttribPointer(
  8627. programAttribute.location + i,
  8628. size / programAttribute.locationSize,
  8629. type,
  8630. normalized,
  8631. stride * bytesPerElement,
  8632. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8633. );
  8634. }
  8635. } else {
  8636. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8637. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8638. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8639. }
  8640. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8641. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8642. }
  8643. } else {
  8644. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8645. enableAttribute( programAttribute.location + i );
  8646. }
  8647. }
  8648. gl.bindBuffer( 34962, buffer );
  8649. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8650. vertexAttribPointer(
  8651. programAttribute.location + i,
  8652. size / programAttribute.locationSize,
  8653. type,
  8654. normalized,
  8655. size * bytesPerElement,
  8656. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8657. );
  8658. }
  8659. }
  8660. } else if ( materialDefaultAttributeValues !== undefined ) {
  8661. const value = materialDefaultAttributeValues[ name ];
  8662. if ( value !== undefined ) {
  8663. switch ( value.length ) {
  8664. case 2:
  8665. gl.vertexAttrib2fv( programAttribute.location, value );
  8666. break;
  8667. case 3:
  8668. gl.vertexAttrib3fv( programAttribute.location, value );
  8669. break;
  8670. case 4:
  8671. gl.vertexAttrib4fv( programAttribute.location, value );
  8672. break;
  8673. default:
  8674. gl.vertexAttrib1fv( programAttribute.location, value );
  8675. }
  8676. }
  8677. }
  8678. }
  8679. }
  8680. disableUnusedAttributes();
  8681. }
  8682. function dispose() {
  8683. reset();
  8684. for ( const geometryId in bindingStates ) {
  8685. const programMap = bindingStates[ geometryId ];
  8686. for ( const programId in programMap ) {
  8687. const stateMap = programMap[ programId ];
  8688. for ( const wireframe in stateMap ) {
  8689. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8690. delete stateMap[ wireframe ];
  8691. }
  8692. delete programMap[ programId ];
  8693. }
  8694. delete bindingStates[ geometryId ];
  8695. }
  8696. }
  8697. function releaseStatesOfGeometry( geometry ) {
  8698. if ( bindingStates[ geometry.id ] === undefined ) return;
  8699. const programMap = bindingStates[ geometry.id ];
  8700. for ( const programId in programMap ) {
  8701. const stateMap = programMap[ programId ];
  8702. for ( const wireframe in stateMap ) {
  8703. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8704. delete stateMap[ wireframe ];
  8705. }
  8706. delete programMap[ programId ];
  8707. }
  8708. delete bindingStates[ geometry.id ];
  8709. }
  8710. function releaseStatesOfProgram( program ) {
  8711. for ( const geometryId in bindingStates ) {
  8712. const programMap = bindingStates[ geometryId ];
  8713. if ( programMap[ program.id ] === undefined ) continue;
  8714. const stateMap = programMap[ program.id ];
  8715. for ( const wireframe in stateMap ) {
  8716. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8717. delete stateMap[ wireframe ];
  8718. }
  8719. delete programMap[ program.id ];
  8720. }
  8721. }
  8722. function reset() {
  8723. resetDefaultState();
  8724. if ( currentState === defaultState ) return;
  8725. currentState = defaultState;
  8726. bindVertexArrayObject( currentState.object );
  8727. }
  8728. // for backward-compatilibity
  8729. function resetDefaultState() {
  8730. defaultState.geometry = null;
  8731. defaultState.program = null;
  8732. defaultState.wireframe = false;
  8733. }
  8734. return {
  8735. setup: setup,
  8736. reset: reset,
  8737. resetDefaultState: resetDefaultState,
  8738. dispose: dispose,
  8739. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8740. releaseStatesOfProgram: releaseStatesOfProgram,
  8741. initAttributes: initAttributes,
  8742. enableAttribute: enableAttribute,
  8743. disableUnusedAttributes: disableUnusedAttributes
  8744. };
  8745. }
  8746. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8747. const isWebGL2 = capabilities.isWebGL2;
  8748. let mode;
  8749. function setMode( value ) {
  8750. mode = value;
  8751. }
  8752. function render( start, count ) {
  8753. gl.drawArrays( mode, start, count );
  8754. info.update( count, mode, 1 );
  8755. }
  8756. function renderInstances( start, count, primcount ) {
  8757. if ( primcount === 0 ) return;
  8758. let extension, methodName;
  8759. if ( isWebGL2 ) {
  8760. extension = gl;
  8761. methodName = 'drawArraysInstanced';
  8762. } else {
  8763. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8764. methodName = 'drawArraysInstancedANGLE';
  8765. if ( extension === null ) {
  8766. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8767. return;
  8768. }
  8769. }
  8770. extension[ methodName ]( mode, start, count, primcount );
  8771. info.update( count, mode, primcount );
  8772. }
  8773. //
  8774. this.setMode = setMode;
  8775. this.render = render;
  8776. this.renderInstances = renderInstances;
  8777. }
  8778. function WebGLCapabilities( gl, extensions, parameters ) {
  8779. let maxAnisotropy;
  8780. function getMaxAnisotropy() {
  8781. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8782. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8783. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8784. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8785. } else {
  8786. maxAnisotropy = 0;
  8787. }
  8788. return maxAnisotropy;
  8789. }
  8790. function getMaxPrecision( precision ) {
  8791. if ( precision === 'highp' ) {
  8792. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8793. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8794. return 'highp';
  8795. }
  8796. precision = 'mediump';
  8797. }
  8798. if ( precision === 'mediump' ) {
  8799. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8800. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8801. return 'mediump';
  8802. }
  8803. }
  8804. return 'lowp';
  8805. }
  8806. /* eslint-disable no-undef */
  8807. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8808. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8809. /* eslint-enable no-undef */
  8810. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8811. const maxPrecision = getMaxPrecision( precision );
  8812. if ( maxPrecision !== precision ) {
  8813. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8814. precision = maxPrecision;
  8815. }
  8816. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8817. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8818. const maxTextures = gl.getParameter( 34930 );
  8819. const maxVertexTextures = gl.getParameter( 35660 );
  8820. const maxTextureSize = gl.getParameter( 3379 );
  8821. const maxCubemapSize = gl.getParameter( 34076 );
  8822. const maxAttributes = gl.getParameter( 34921 );
  8823. const maxVertexUniforms = gl.getParameter( 36347 );
  8824. const maxVaryings = gl.getParameter( 36348 );
  8825. const maxFragmentUniforms = gl.getParameter( 36349 );
  8826. const vertexTextures = maxVertexTextures > 0;
  8827. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8828. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8829. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8830. return {
  8831. isWebGL2: isWebGL2,
  8832. drawBuffers: drawBuffers,
  8833. getMaxAnisotropy: getMaxAnisotropy,
  8834. getMaxPrecision: getMaxPrecision,
  8835. precision: precision,
  8836. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8837. maxTextures: maxTextures,
  8838. maxVertexTextures: maxVertexTextures,
  8839. maxTextureSize: maxTextureSize,
  8840. maxCubemapSize: maxCubemapSize,
  8841. maxAttributes: maxAttributes,
  8842. maxVertexUniforms: maxVertexUniforms,
  8843. maxVaryings: maxVaryings,
  8844. maxFragmentUniforms: maxFragmentUniforms,
  8845. vertexTextures: vertexTextures,
  8846. floatFragmentTextures: floatFragmentTextures,
  8847. floatVertexTextures: floatVertexTextures,
  8848. maxSamples: maxSamples
  8849. };
  8850. }
  8851. function WebGLClipping( properties ) {
  8852. const scope = this;
  8853. let globalState = null,
  8854. numGlobalPlanes = 0,
  8855. localClippingEnabled = false,
  8856. renderingShadows = false;
  8857. const plane = new Plane(),
  8858. viewNormalMatrix = new Matrix3(),
  8859. uniform = { value: null, needsUpdate: false };
  8860. this.uniform = uniform;
  8861. this.numPlanes = 0;
  8862. this.numIntersection = 0;
  8863. this.init = function ( planes, enableLocalClipping, camera ) {
  8864. const enabled =
  8865. planes.length !== 0 ||
  8866. enableLocalClipping ||
  8867. // enable state of previous frame - the clipping code has to
  8868. // run another frame in order to reset the state:
  8869. numGlobalPlanes !== 0 ||
  8870. localClippingEnabled;
  8871. localClippingEnabled = enableLocalClipping;
  8872. globalState = projectPlanes( planes, camera, 0 );
  8873. numGlobalPlanes = planes.length;
  8874. return enabled;
  8875. };
  8876. this.beginShadows = function () {
  8877. renderingShadows = true;
  8878. projectPlanes( null );
  8879. };
  8880. this.endShadows = function () {
  8881. renderingShadows = false;
  8882. resetGlobalState();
  8883. };
  8884. this.setState = function ( material, camera, useCache ) {
  8885. const planes = material.clippingPlanes,
  8886. clipIntersection = material.clipIntersection,
  8887. clipShadows = material.clipShadows;
  8888. const materialProperties = properties.get( material );
  8889. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8890. // there's no local clipping
  8891. if ( renderingShadows ) {
  8892. // there's no global clipping
  8893. projectPlanes( null );
  8894. } else {
  8895. resetGlobalState();
  8896. }
  8897. } else {
  8898. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8899. lGlobal = nGlobal * 4;
  8900. let dstArray = materialProperties.clippingState || null;
  8901. uniform.value = dstArray; // ensure unique state
  8902. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8903. for ( let i = 0; i !== lGlobal; ++ i ) {
  8904. dstArray[ i ] = globalState[ i ];
  8905. }
  8906. materialProperties.clippingState = dstArray;
  8907. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8908. this.numPlanes += nGlobal;
  8909. }
  8910. };
  8911. function resetGlobalState() {
  8912. if ( uniform.value !== globalState ) {
  8913. uniform.value = globalState;
  8914. uniform.needsUpdate = numGlobalPlanes > 0;
  8915. }
  8916. scope.numPlanes = numGlobalPlanes;
  8917. scope.numIntersection = 0;
  8918. }
  8919. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8920. const nPlanes = planes !== null ? planes.length : 0;
  8921. let dstArray = null;
  8922. if ( nPlanes !== 0 ) {
  8923. dstArray = uniform.value;
  8924. if ( skipTransform !== true || dstArray === null ) {
  8925. const flatSize = dstOffset + nPlanes * 4,
  8926. viewMatrix = camera.matrixWorldInverse;
  8927. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8928. if ( dstArray === null || dstArray.length < flatSize ) {
  8929. dstArray = new Float32Array( flatSize );
  8930. }
  8931. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8932. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8933. plane.normal.toArray( dstArray, i4 );
  8934. dstArray[ i4 + 3 ] = plane.constant;
  8935. }
  8936. }
  8937. uniform.value = dstArray;
  8938. uniform.needsUpdate = true;
  8939. }
  8940. scope.numPlanes = nPlanes;
  8941. scope.numIntersection = 0;
  8942. return dstArray;
  8943. }
  8944. }
  8945. function WebGLCubeMaps( renderer ) {
  8946. let cubemaps = new WeakMap();
  8947. function mapTextureMapping( texture, mapping ) {
  8948. if ( mapping === EquirectangularReflectionMapping ) {
  8949. texture.mapping = CubeReflectionMapping;
  8950. } else if ( mapping === EquirectangularRefractionMapping ) {
  8951. texture.mapping = CubeRefractionMapping;
  8952. }
  8953. return texture;
  8954. }
  8955. function get( texture ) {
  8956. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8957. const mapping = texture.mapping;
  8958. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8959. if ( cubemaps.has( texture ) ) {
  8960. const cubemap = cubemaps.get( texture ).texture;
  8961. return mapTextureMapping( cubemap, texture.mapping );
  8962. } else {
  8963. const image = texture.image;
  8964. if ( image && image.height > 0 ) {
  8965. const currentRenderTarget = renderer.getRenderTarget();
  8966. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8967. renderTarget.fromEquirectangularTexture( renderer, texture );
  8968. cubemaps.set( texture, renderTarget );
  8969. renderer.setRenderTarget( currentRenderTarget );
  8970. texture.addEventListener( 'dispose', onTextureDispose );
  8971. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8972. } else {
  8973. // image not yet ready. try the conversion next frame
  8974. return null;
  8975. }
  8976. }
  8977. }
  8978. }
  8979. return texture;
  8980. }
  8981. function onTextureDispose( event ) {
  8982. const texture = event.target;
  8983. texture.removeEventListener( 'dispose', onTextureDispose );
  8984. const cubemap = cubemaps.get( texture );
  8985. if ( cubemap !== undefined ) {
  8986. cubemaps.delete( texture );
  8987. cubemap.dispose();
  8988. }
  8989. }
  8990. function dispose() {
  8991. cubemaps = new WeakMap();
  8992. }
  8993. return {
  8994. get: get,
  8995. dispose: dispose
  8996. };
  8997. }
  8998. class OrthographicCamera extends Camera {
  8999. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9000. super();
  9001. this.type = 'OrthographicCamera';
  9002. this.zoom = 1;
  9003. this.view = null;
  9004. this.left = left;
  9005. this.right = right;
  9006. this.top = top;
  9007. this.bottom = bottom;
  9008. this.near = near;
  9009. this.far = far;
  9010. this.updateProjectionMatrix();
  9011. }
  9012. copy( source, recursive ) {
  9013. super.copy( source, recursive );
  9014. this.left = source.left;
  9015. this.right = source.right;
  9016. this.top = source.top;
  9017. this.bottom = source.bottom;
  9018. this.near = source.near;
  9019. this.far = source.far;
  9020. this.zoom = source.zoom;
  9021. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9022. return this;
  9023. }
  9024. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9025. if ( this.view === null ) {
  9026. this.view = {
  9027. enabled: true,
  9028. fullWidth: 1,
  9029. fullHeight: 1,
  9030. offsetX: 0,
  9031. offsetY: 0,
  9032. width: 1,
  9033. height: 1
  9034. };
  9035. }
  9036. this.view.enabled = true;
  9037. this.view.fullWidth = fullWidth;
  9038. this.view.fullHeight = fullHeight;
  9039. this.view.offsetX = x;
  9040. this.view.offsetY = y;
  9041. this.view.width = width;
  9042. this.view.height = height;
  9043. this.updateProjectionMatrix();
  9044. }
  9045. clearViewOffset() {
  9046. if ( this.view !== null ) {
  9047. this.view.enabled = false;
  9048. }
  9049. this.updateProjectionMatrix();
  9050. }
  9051. updateProjectionMatrix() {
  9052. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9053. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9054. const cx = ( this.right + this.left ) / 2;
  9055. const cy = ( this.top + this.bottom ) / 2;
  9056. let left = cx - dx;
  9057. let right = cx + dx;
  9058. let top = cy + dy;
  9059. let bottom = cy - dy;
  9060. if ( this.view !== null && this.view.enabled ) {
  9061. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9062. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9063. left += scaleW * this.view.offsetX;
  9064. right = left + scaleW * this.view.width;
  9065. top -= scaleH * this.view.offsetY;
  9066. bottom = top - scaleH * this.view.height;
  9067. }
  9068. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9069. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9070. }
  9071. toJSON( meta ) {
  9072. const data = super.toJSON( meta );
  9073. data.object.zoom = this.zoom;
  9074. data.object.left = this.left;
  9075. data.object.right = this.right;
  9076. data.object.top = this.top;
  9077. data.object.bottom = this.bottom;
  9078. data.object.near = this.near;
  9079. data.object.far = this.far;
  9080. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9081. return data;
  9082. }
  9083. }
  9084. OrthographicCamera.prototype.isOrthographicCamera = true;
  9085. class RawShaderMaterial extends ShaderMaterial {
  9086. constructor( parameters ) {
  9087. super( parameters );
  9088. this.type = 'RawShaderMaterial';
  9089. }
  9090. }
  9091. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9092. const LOD_MIN = 4;
  9093. const LOD_MAX = 8;
  9094. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  9095. // The standard deviations (radians) associated with the extra mips. These are
  9096. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9097. // geometric shadowing function. These sigma values squared must match the
  9098. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9099. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9100. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9101. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9102. // samples and exit early, but not recompile the shader.
  9103. const MAX_SAMPLES = 20;
  9104. const ENCODINGS = {
  9105. [ LinearEncoding ]: 0,
  9106. [ sRGBEncoding ]: 1,
  9107. [ RGBEEncoding ]: 2,
  9108. [ RGBM7Encoding ]: 3,
  9109. [ RGBM16Encoding ]: 4,
  9110. [ RGBDEncoding ]: 5,
  9111. [ GammaEncoding ]: 6
  9112. };
  9113. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9114. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  9115. const _clearColor = /*@__PURE__*/ new Color();
  9116. let _oldTarget = null;
  9117. // Golden Ratio
  9118. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9119. const INV_PHI = 1 / PHI;
  9120. // Vertices of a dodecahedron (except the opposites, which represent the
  9121. // same axis), used as axis directions evenly spread on a sphere.
  9122. const _axisDirections = [
  9123. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9124. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9125. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9126. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9127. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9128. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9129. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9130. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9131. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9132. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9133. /**
  9134. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9135. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9136. * blur to be quickly accessed based on material roughness. It is packed into a
  9137. * special CubeUV format that allows us to perform custom interpolation so that
  9138. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9139. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9140. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9141. * higher roughness levels. In this way we maintain resolution to smoothly
  9142. * interpolate diffuse lighting while limiting sampling computation.
  9143. *
  9144. * Paper: Fast, Accurate Image-Based Lighting
  9145. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9146. */
  9147. class PMREMGenerator {
  9148. constructor( renderer ) {
  9149. this._renderer = renderer;
  9150. this._pingPongRenderTarget = null;
  9151. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  9152. this._equirectShader = null;
  9153. this._cubemapShader = null;
  9154. this._compileMaterial( this._blurMaterial );
  9155. }
  9156. /**
  9157. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9158. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9159. * in radians to be applied to the scene before PMREM generation. Optional near
  9160. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9161. * is placed at the origin).
  9162. */
  9163. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9164. _oldTarget = this._renderer.getRenderTarget();
  9165. const cubeUVRenderTarget = this._allocateTargets();
  9166. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9167. if ( sigma > 0 ) {
  9168. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9169. }
  9170. this._applyPMREM( cubeUVRenderTarget );
  9171. this._cleanup( cubeUVRenderTarget );
  9172. return cubeUVRenderTarget;
  9173. }
  9174. /**
  9175. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9176. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9177. * as this matches best with the 256 x 256 cubemap output.
  9178. */
  9179. fromEquirectangular( equirectangular ) {
  9180. return this._fromTexture( equirectangular );
  9181. }
  9182. /**
  9183. * Generates a PMREM from an cubemap texture, which can be either LDR
  9184. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9185. * as this matches best with the 256 x 256 cubemap output.
  9186. */
  9187. fromCubemap( cubemap ) {
  9188. return this._fromTexture( cubemap );
  9189. }
  9190. /**
  9191. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9192. * your texture's network fetch for increased concurrency.
  9193. */
  9194. compileCubemapShader() {
  9195. if ( this._cubemapShader === null ) {
  9196. this._cubemapShader = _getCubemapShader();
  9197. this._compileMaterial( this._cubemapShader );
  9198. }
  9199. }
  9200. /**
  9201. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9202. * your texture's network fetch for increased concurrency.
  9203. */
  9204. compileEquirectangularShader() {
  9205. if ( this._equirectShader === null ) {
  9206. this._equirectShader = _getEquirectShader();
  9207. this._compileMaterial( this._equirectShader );
  9208. }
  9209. }
  9210. /**
  9211. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9212. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9213. * one of them will cause any others to also become unusable.
  9214. */
  9215. dispose() {
  9216. this._blurMaterial.dispose();
  9217. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  9218. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  9219. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  9220. _lodPlanes[ i ].dispose();
  9221. }
  9222. }
  9223. // private interface
  9224. _cleanup( outputTarget ) {
  9225. this._pingPongRenderTarget.dispose();
  9226. this._renderer.setRenderTarget( _oldTarget );
  9227. outputTarget.scissorTest = false;
  9228. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9229. }
  9230. _fromTexture( texture ) {
  9231. _oldTarget = this._renderer.getRenderTarget();
  9232. const cubeUVRenderTarget = this._allocateTargets( texture );
  9233. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9234. this._applyPMREM( cubeUVRenderTarget );
  9235. this._cleanup( cubeUVRenderTarget );
  9236. return cubeUVRenderTarget;
  9237. }
  9238. _allocateTargets( texture ) { // warning: null texture is valid
  9239. const params = {
  9240. magFilter: NearestFilter,
  9241. minFilter: NearestFilter,
  9242. generateMipmaps: false,
  9243. type: UnsignedByteType,
  9244. format: RGBEFormat,
  9245. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  9246. depthBuffer: false
  9247. };
  9248. const cubeUVRenderTarget = _createRenderTarget( params );
  9249. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9250. this._pingPongRenderTarget = _createRenderTarget( params );
  9251. return cubeUVRenderTarget;
  9252. }
  9253. _compileMaterial( material ) {
  9254. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  9255. this._renderer.compile( tmpMesh, _flatCamera );
  9256. }
  9257. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9258. const fov = 90;
  9259. const aspect = 1;
  9260. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9261. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9262. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9263. const renderer = this._renderer;
  9264. const originalAutoClear = renderer.autoClear;
  9265. const outputEncoding = renderer.outputEncoding;
  9266. const toneMapping = renderer.toneMapping;
  9267. renderer.getClearColor( _clearColor );
  9268. renderer.toneMapping = NoToneMapping;
  9269. renderer.outputEncoding = LinearEncoding;
  9270. renderer.autoClear = false;
  9271. const backgroundMaterial = new MeshBasicMaterial( {
  9272. name: 'PMREM.Background',
  9273. side: BackSide,
  9274. depthWrite: false,
  9275. depthTest: false,
  9276. } );
  9277. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9278. let useSolidColor = false;
  9279. const background = scene.background;
  9280. if ( background ) {
  9281. if ( background.isColor ) {
  9282. backgroundMaterial.color.copy( background );
  9283. scene.background = null;
  9284. useSolidColor = true;
  9285. }
  9286. } else {
  9287. backgroundMaterial.color.copy( _clearColor );
  9288. useSolidColor = true;
  9289. }
  9290. for ( let i = 0; i < 6; i ++ ) {
  9291. const col = i % 3;
  9292. if ( col == 0 ) {
  9293. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9294. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9295. } else if ( col == 1 ) {
  9296. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9297. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9298. } else {
  9299. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9300. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9301. }
  9302. _setViewport( cubeUVRenderTarget,
  9303. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  9304. renderer.setRenderTarget( cubeUVRenderTarget );
  9305. if ( useSolidColor ) {
  9306. renderer.render( backgroundBox, cubeCamera );
  9307. }
  9308. renderer.render( scene, cubeCamera );
  9309. }
  9310. backgroundBox.geometry.dispose();
  9311. backgroundBox.material.dispose();
  9312. renderer.toneMapping = toneMapping;
  9313. renderer.outputEncoding = outputEncoding;
  9314. renderer.autoClear = originalAutoClear;
  9315. scene.background = background;
  9316. }
  9317. _setEncoding( uniform, texture ) {
  9318. /* if ( this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding ) {
  9319. uniform.value = ENCODINGS[ LinearEncoding ];
  9320. } else {
  9321. uniform.value = ENCODINGS[ texture.encoding ];
  9322. } */
  9323. uniform.value = ENCODINGS[ texture.encoding ];
  9324. }
  9325. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9326. const renderer = this._renderer;
  9327. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9328. if ( isCubeTexture ) {
  9329. if ( this._cubemapShader == null ) {
  9330. this._cubemapShader = _getCubemapShader();
  9331. }
  9332. } else {
  9333. if ( this._equirectShader == null ) {
  9334. this._equirectShader = _getEquirectShader();
  9335. }
  9336. }
  9337. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  9338. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  9339. const uniforms = material.uniforms;
  9340. uniforms[ 'envMap' ].value = texture;
  9341. if ( ! isCubeTexture ) {
  9342. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  9343. }
  9344. this._setEncoding( uniforms[ 'inputEncoding' ], texture );
  9345. this._setEncoding( uniforms[ 'outputEncoding' ], cubeUVRenderTarget.texture );
  9346. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  9347. renderer.setRenderTarget( cubeUVRenderTarget );
  9348. renderer.render( mesh, _flatCamera );
  9349. }
  9350. _applyPMREM( cubeUVRenderTarget ) {
  9351. const renderer = this._renderer;
  9352. const autoClear = renderer.autoClear;
  9353. renderer.autoClear = false;
  9354. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  9355. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  9356. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9357. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9358. }
  9359. renderer.autoClear = autoClear;
  9360. }
  9361. /**
  9362. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9363. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9364. * the blur latitudinally (around the poles), and then longitudinally (towards
  9365. * the poles) to approximate the orthogonally-separable blur. It is least
  9366. * accurate at the poles, but still does a decent job.
  9367. */
  9368. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9369. const pingPongRenderTarget = this._pingPongRenderTarget;
  9370. this._halfBlur(
  9371. cubeUVRenderTarget,
  9372. pingPongRenderTarget,
  9373. lodIn,
  9374. lodOut,
  9375. sigma,
  9376. 'latitudinal',
  9377. poleAxis );
  9378. this._halfBlur(
  9379. pingPongRenderTarget,
  9380. cubeUVRenderTarget,
  9381. lodOut,
  9382. lodOut,
  9383. sigma,
  9384. 'longitudinal',
  9385. poleAxis );
  9386. }
  9387. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9388. const renderer = this._renderer;
  9389. const blurMaterial = this._blurMaterial;
  9390. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9391. console.error(
  9392. 'blur direction must be either latitudinal or longitudinal!' );
  9393. }
  9394. // Number of standard deviations at which to cut off the discrete approximation.
  9395. const STANDARD_DEVIATIONS = 3;
  9396. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  9397. const blurUniforms = blurMaterial.uniforms;
  9398. const pixels = _sizeLods[ lodIn ] - 1;
  9399. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9400. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9401. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9402. if ( samples > MAX_SAMPLES ) {
  9403. console.warn( `sigmaRadians, ${
  9404. sigmaRadians}, is too large and will clip, as it requested ${
  9405. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9406. }
  9407. const weights = [];
  9408. let sum = 0;
  9409. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9410. const x = i / sigmaPixels;
  9411. const weight = Math.exp( - x * x / 2 );
  9412. weights.push( weight );
  9413. if ( i == 0 ) {
  9414. sum += weight;
  9415. } else if ( i < samples ) {
  9416. sum += 2 * weight;
  9417. }
  9418. }
  9419. for ( let i = 0; i < weights.length; i ++ ) {
  9420. weights[ i ] = weights[ i ] / sum;
  9421. }
  9422. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9423. blurUniforms[ 'samples' ].value = samples;
  9424. blurUniforms[ 'weights' ].value = weights;
  9425. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9426. if ( poleAxis ) {
  9427. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9428. }
  9429. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9430. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  9431. this._setEncoding( blurUniforms[ 'inputEncoding' ], targetIn.texture );
  9432. this._setEncoding( blurUniforms[ 'outputEncoding' ], targetIn.texture );
  9433. const outputSize = _sizeLods[ lodOut ];
  9434. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  9435. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  9436. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9437. renderer.setRenderTarget( targetOut );
  9438. renderer.render( blurMesh, _flatCamera );
  9439. }
  9440. }
  9441. function _isLDR( texture ) {
  9442. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  9443. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9444. }
  9445. function _createPlanes() {
  9446. const _lodPlanes = [];
  9447. const _sizeLods = [];
  9448. const _sigmas = [];
  9449. let lod = LOD_MAX;
  9450. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  9451. const sizeLod = Math.pow( 2, lod );
  9452. _sizeLods.push( sizeLod );
  9453. let sigma = 1.0 / sizeLod;
  9454. if ( i > LOD_MAX - LOD_MIN ) {
  9455. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  9456. } else if ( i == 0 ) {
  9457. sigma = 0;
  9458. }
  9459. _sigmas.push( sigma );
  9460. const texelSize = 1.0 / ( sizeLod - 1 );
  9461. const min = - texelSize / 2;
  9462. const max = 1 + texelSize / 2;
  9463. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9464. const cubeFaces = 6;
  9465. const vertices = 6;
  9466. const positionSize = 3;
  9467. const uvSize = 2;
  9468. const faceIndexSize = 1;
  9469. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9470. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9471. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9472. for ( let face = 0; face < cubeFaces; face ++ ) {
  9473. const x = ( face % 3 ) * 2 / 3 - 1;
  9474. const y = face > 2 ? 0 : - 1;
  9475. const coordinates = [
  9476. x, y, 0,
  9477. x + 2 / 3, y, 0,
  9478. x + 2 / 3, y + 1, 0,
  9479. x, y, 0,
  9480. x + 2 / 3, y + 1, 0,
  9481. x, y + 1, 0
  9482. ];
  9483. position.set( coordinates, positionSize * vertices * face );
  9484. uv.set( uv1, uvSize * vertices * face );
  9485. const fill = [ face, face, face, face, face, face ];
  9486. faceIndex.set( fill, faceIndexSize * vertices * face );
  9487. }
  9488. const planes = new BufferGeometry();
  9489. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9490. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9491. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9492. _lodPlanes.push( planes );
  9493. if ( lod > LOD_MIN ) {
  9494. lod --;
  9495. }
  9496. }
  9497. return { _lodPlanes, _sizeLods, _sigmas };
  9498. }
  9499. function _createRenderTarget( params ) {
  9500. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  9501. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9502. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9503. cubeUVRenderTarget.scissorTest = true;
  9504. return cubeUVRenderTarget;
  9505. }
  9506. function _setViewport( target, x, y, width, height ) {
  9507. target.viewport.set( x, y, width, height );
  9508. target.scissor.set( x, y, width, height );
  9509. }
  9510. function _getBlurShader( maxSamples ) {
  9511. const weights = new Float32Array( maxSamples );
  9512. const poleAxis = new Vector3( 0, 1, 0 );
  9513. const shaderMaterial = new RawShaderMaterial( {
  9514. name: 'SphericalGaussianBlur',
  9515. defines: { 'n': maxSamples },
  9516. uniforms: {
  9517. 'envMap': { value: null },
  9518. 'samples': { value: 1 },
  9519. 'weights': { value: weights },
  9520. 'latitudinal': { value: false },
  9521. 'dTheta': { value: 0 },
  9522. 'mipInt': { value: 0 },
  9523. 'poleAxis': { value: poleAxis },
  9524. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9525. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9526. },
  9527. vertexShader: _getCommonVertexShader(),
  9528. fragmentShader: /* glsl */`
  9529. precision mediump float;
  9530. precision mediump int;
  9531. varying vec3 vOutputDirection;
  9532. uniform sampler2D envMap;
  9533. uniform int samples;
  9534. uniform float weights[ n ];
  9535. uniform bool latitudinal;
  9536. uniform float dTheta;
  9537. uniform float mipInt;
  9538. uniform vec3 poleAxis;
  9539. ${ _getEncodings() }
  9540. #define ENVMAP_TYPE_CUBE_UV
  9541. #include <cube_uv_reflection_fragment>
  9542. vec3 getSample( float theta, vec3 axis ) {
  9543. float cosTheta = cos( theta );
  9544. // Rodrigues' axis-angle rotation
  9545. vec3 sampleDirection = vOutputDirection * cosTheta
  9546. + cross( axis, vOutputDirection ) * sin( theta )
  9547. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9548. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9549. }
  9550. void main() {
  9551. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9552. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9553. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9554. }
  9555. axis = normalize( axis );
  9556. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9557. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9558. for ( int i = 1; i < n; i++ ) {
  9559. if ( i >= samples ) {
  9560. break;
  9561. }
  9562. float theta = dTheta * float( i );
  9563. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9564. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9565. }
  9566. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9567. }
  9568. `,
  9569. blending: NoBlending,
  9570. depthTest: false,
  9571. depthWrite: false
  9572. } );
  9573. return shaderMaterial;
  9574. }
  9575. function _getEquirectShader() {
  9576. const texelSize = new Vector2( 1, 1 );
  9577. const shaderMaterial = new RawShaderMaterial( {
  9578. name: 'EquirectangularToCubeUV',
  9579. uniforms: {
  9580. 'envMap': { value: null },
  9581. 'texelSize': { value: texelSize },
  9582. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9583. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9584. },
  9585. vertexShader: _getCommonVertexShader(),
  9586. fragmentShader: /* glsl */`
  9587. precision mediump float;
  9588. precision mediump int;
  9589. varying vec3 vOutputDirection;
  9590. uniform sampler2D envMap;
  9591. uniform vec2 texelSize;
  9592. ${ _getEncodings() }
  9593. #include <common>
  9594. void main() {
  9595. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9596. vec3 outputDirection = normalize( vOutputDirection );
  9597. vec2 uv = equirectUv( outputDirection );
  9598. vec2 f = fract( uv / texelSize - 0.5 );
  9599. uv -= f * texelSize;
  9600. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9601. uv.x += texelSize.x;
  9602. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9603. uv.y += texelSize.y;
  9604. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9605. uv.x -= texelSize.x;
  9606. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9607. vec3 tm = mix( tl, tr, f.x );
  9608. vec3 bm = mix( bl, br, f.x );
  9609. gl_FragColor.rgb = mix( tm, bm, f.y );
  9610. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9611. }
  9612. `,
  9613. blending: NoBlending,
  9614. depthTest: false,
  9615. depthWrite: false
  9616. } );
  9617. return shaderMaterial;
  9618. }
  9619. function _getCubemapShader() {
  9620. const shaderMaterial = new RawShaderMaterial( {
  9621. name: 'CubemapToCubeUV',
  9622. uniforms: {
  9623. 'envMap': { value: null },
  9624. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9625. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9626. },
  9627. vertexShader: _getCommonVertexShader(),
  9628. fragmentShader: /* glsl */`
  9629. precision mediump float;
  9630. precision mediump int;
  9631. varying vec3 vOutputDirection;
  9632. uniform samplerCube envMap;
  9633. ${ _getEncodings() }
  9634. void main() {
  9635. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9636. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9637. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9638. }
  9639. `,
  9640. blending: NoBlending,
  9641. depthTest: false,
  9642. depthWrite: false
  9643. } );
  9644. return shaderMaterial;
  9645. }
  9646. function _getCommonVertexShader() {
  9647. return /* glsl */`
  9648. precision mediump float;
  9649. precision mediump int;
  9650. attribute vec3 position;
  9651. attribute vec2 uv;
  9652. attribute float faceIndex;
  9653. varying vec3 vOutputDirection;
  9654. // RH coordinate system; PMREM face-indexing convention
  9655. vec3 getDirection( vec2 uv, float face ) {
  9656. uv = 2.0 * uv - 1.0;
  9657. vec3 direction = vec3( uv, 1.0 );
  9658. if ( face == 0.0 ) {
  9659. direction = direction.zyx; // ( 1, v, u ) pos x
  9660. } else if ( face == 1.0 ) {
  9661. direction = direction.xzy;
  9662. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9663. } else if ( face == 2.0 ) {
  9664. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9665. } else if ( face == 3.0 ) {
  9666. direction = direction.zyx;
  9667. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9668. } else if ( face == 4.0 ) {
  9669. direction = direction.xzy;
  9670. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9671. } else if ( face == 5.0 ) {
  9672. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9673. }
  9674. return direction;
  9675. }
  9676. void main() {
  9677. vOutputDirection = getDirection( uv, faceIndex );
  9678. gl_Position = vec4( position, 1.0 );
  9679. }
  9680. `;
  9681. }
  9682. function _getEncodings() {
  9683. return /* glsl */`
  9684. uniform int inputEncoding;
  9685. uniform int outputEncoding;
  9686. #include <encodings_pars_fragment>
  9687. vec4 inputTexelToLinear( vec4 value ) {
  9688. if ( inputEncoding == 0 ) {
  9689. return value;
  9690. } else if ( inputEncoding == 1 ) {
  9691. return sRGBToLinear( value );
  9692. } else if ( inputEncoding == 2 ) {
  9693. return RGBEToLinear( value );
  9694. } else if ( inputEncoding == 3 ) {
  9695. return RGBMToLinear( value, 7.0 );
  9696. } else if ( inputEncoding == 4 ) {
  9697. return RGBMToLinear( value, 16.0 );
  9698. } else if ( inputEncoding == 5 ) {
  9699. return RGBDToLinear( value, 256.0 );
  9700. } else {
  9701. return GammaToLinear( value, 2.2 );
  9702. }
  9703. }
  9704. vec4 linearToOutputTexel( vec4 value ) {
  9705. if ( outputEncoding == 0 ) {
  9706. return value;
  9707. } else if ( outputEncoding == 1 ) {
  9708. return LinearTosRGB( value );
  9709. } else if ( outputEncoding == 2 ) {
  9710. return LinearToRGBE( value );
  9711. } else if ( outputEncoding == 3 ) {
  9712. return LinearToRGBM( value, 7.0 );
  9713. } else if ( outputEncoding == 4 ) {
  9714. return LinearToRGBM( value, 16.0 );
  9715. } else if ( outputEncoding == 5 ) {
  9716. return LinearToRGBD( value, 256.0 );
  9717. } else {
  9718. return LinearToGamma( value, 2.2 );
  9719. }
  9720. }
  9721. vec4 envMapTexelToLinear( vec4 color ) {
  9722. return inputTexelToLinear( color );
  9723. }
  9724. `;
  9725. }
  9726. function WebGLCubeUVMaps( renderer ) {
  9727. let cubeUVmaps = new WeakMap();
  9728. let pmremGenerator = null;
  9729. function get( texture ) {
  9730. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9731. const mapping = texture.mapping;
  9732. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9733. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9734. if ( isEquirectMap || isCubeMap ) {
  9735. // equirect/cube map to cubeUV conversion
  9736. if ( cubeUVmaps.has( texture ) ) {
  9737. return cubeUVmaps.get( texture ).texture;
  9738. } else {
  9739. const image = texture.image;
  9740. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9741. const currentRenderTarget = renderer.getRenderTarget();
  9742. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9743. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9744. cubeUVmaps.set( texture, renderTarget );
  9745. renderer.setRenderTarget( currentRenderTarget );
  9746. texture.addEventListener( 'dispose', onTextureDispose );
  9747. return renderTarget.texture;
  9748. } else {
  9749. // image not yet ready. try the conversion next frame
  9750. return null;
  9751. }
  9752. }
  9753. }
  9754. }
  9755. return texture;
  9756. }
  9757. function isCubeTextureComplete( image ) {
  9758. let count = 0;
  9759. const length = 6;
  9760. for ( let i = 0; i < length; i ++ ) {
  9761. if ( image[ i ] !== undefined ) count ++;
  9762. }
  9763. return count === length;
  9764. }
  9765. function onTextureDispose( event ) {
  9766. const texture = event.target;
  9767. texture.removeEventListener( 'dispose', onTextureDispose );
  9768. const cubemapUV = cubeUVmaps.get( texture );
  9769. if ( cubemapUV !== undefined ) {
  9770. cubeUVmaps.delete( texture );
  9771. cubemapUV.dispose();
  9772. }
  9773. }
  9774. function dispose() {
  9775. cubeUVmaps = new WeakMap();
  9776. if ( pmremGenerator !== null ) {
  9777. pmremGenerator.dispose();
  9778. pmremGenerator = null;
  9779. }
  9780. }
  9781. return {
  9782. get: get,
  9783. dispose: dispose
  9784. };
  9785. }
  9786. function WebGLExtensions( gl ) {
  9787. const extensions = {};
  9788. function getExtension( name ) {
  9789. if ( extensions[ name ] !== undefined ) {
  9790. return extensions[ name ];
  9791. }
  9792. let extension;
  9793. switch ( name ) {
  9794. case 'WEBGL_depth_texture':
  9795. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9796. break;
  9797. case 'EXT_texture_filter_anisotropic':
  9798. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9799. break;
  9800. case 'WEBGL_compressed_texture_s3tc':
  9801. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9802. break;
  9803. case 'WEBGL_compressed_texture_pvrtc':
  9804. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9805. break;
  9806. default:
  9807. extension = gl.getExtension( name );
  9808. }
  9809. extensions[ name ] = extension;
  9810. return extension;
  9811. }
  9812. return {
  9813. has: function ( name ) {
  9814. return getExtension( name ) !== null;
  9815. },
  9816. init: function ( capabilities ) {
  9817. if ( capabilities.isWebGL2 ) {
  9818. getExtension( 'EXT_color_buffer_float' );
  9819. } else {
  9820. getExtension( 'WEBGL_depth_texture' );
  9821. getExtension( 'OES_texture_float' );
  9822. getExtension( 'OES_texture_half_float' );
  9823. getExtension( 'OES_texture_half_float_linear' );
  9824. getExtension( 'OES_standard_derivatives' );
  9825. getExtension( 'OES_element_index_uint' );
  9826. getExtension( 'OES_vertex_array_object' );
  9827. getExtension( 'ANGLE_instanced_arrays' );
  9828. }
  9829. getExtension( 'OES_texture_float_linear' );
  9830. getExtension( 'EXT_color_buffer_half_float' );
  9831. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9832. },
  9833. get: function ( name ) {
  9834. const extension = getExtension( name );
  9835. if ( extension === null ) {
  9836. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9837. }
  9838. return extension;
  9839. }
  9840. };
  9841. }
  9842. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9843. const geometries = {};
  9844. const wireframeAttributes = new WeakMap();
  9845. function onGeometryDispose( event ) {
  9846. const geometry = event.target;
  9847. if ( geometry.index !== null ) {
  9848. attributes.remove( geometry.index );
  9849. }
  9850. for ( const name in geometry.attributes ) {
  9851. attributes.remove( geometry.attributes[ name ] );
  9852. }
  9853. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9854. delete geometries[ geometry.id ];
  9855. const attribute = wireframeAttributes.get( geometry );
  9856. if ( attribute ) {
  9857. attributes.remove( attribute );
  9858. wireframeAttributes.delete( geometry );
  9859. }
  9860. bindingStates.releaseStatesOfGeometry( geometry );
  9861. if ( geometry.isInstancedBufferGeometry === true ) {
  9862. delete geometry._maxInstanceCount;
  9863. }
  9864. //
  9865. info.memory.geometries --;
  9866. }
  9867. function get( object, geometry ) {
  9868. if ( geometries[ geometry.id ] === true ) return geometry;
  9869. geometry.addEventListener( 'dispose', onGeometryDispose );
  9870. geometries[ geometry.id ] = true;
  9871. info.memory.geometries ++;
  9872. return geometry;
  9873. }
  9874. function update( geometry ) {
  9875. const geometryAttributes = geometry.attributes;
  9876. // Updating index buffer in VAO now. See WebGLBindingStates.
  9877. for ( const name in geometryAttributes ) {
  9878. attributes.update( geometryAttributes[ name ], 34962 );
  9879. }
  9880. // morph targets
  9881. const morphAttributes = geometry.morphAttributes;
  9882. for ( const name in morphAttributes ) {
  9883. const array = morphAttributes[ name ];
  9884. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9885. attributes.update( array[ i ], 34962 );
  9886. }
  9887. }
  9888. }
  9889. function updateWireframeAttribute( geometry ) {
  9890. const indices = [];
  9891. const geometryIndex = geometry.index;
  9892. const geometryPosition = geometry.attributes.position;
  9893. let version = 0;
  9894. if ( geometryIndex !== null ) {
  9895. const array = geometryIndex.array;
  9896. version = geometryIndex.version;
  9897. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9898. const a = array[ i + 0 ];
  9899. const b = array[ i + 1 ];
  9900. const c = array[ i + 2 ];
  9901. indices.push( a, b, b, c, c, a );
  9902. }
  9903. } else {
  9904. const array = geometryPosition.array;
  9905. version = geometryPosition.version;
  9906. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9907. const a = i + 0;
  9908. const b = i + 1;
  9909. const c = i + 2;
  9910. indices.push( a, b, b, c, c, a );
  9911. }
  9912. }
  9913. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9914. attribute.version = version;
  9915. // Updating index buffer in VAO now. See WebGLBindingStates
  9916. //
  9917. const previousAttribute = wireframeAttributes.get( geometry );
  9918. if ( previousAttribute ) attributes.remove( previousAttribute );
  9919. //
  9920. wireframeAttributes.set( geometry, attribute );
  9921. }
  9922. function getWireframeAttribute( geometry ) {
  9923. const currentAttribute = wireframeAttributes.get( geometry );
  9924. if ( currentAttribute ) {
  9925. const geometryIndex = geometry.index;
  9926. if ( geometryIndex !== null ) {
  9927. // if the attribute is obsolete, create a new one
  9928. if ( currentAttribute.version < geometryIndex.version ) {
  9929. updateWireframeAttribute( geometry );
  9930. }
  9931. }
  9932. } else {
  9933. updateWireframeAttribute( geometry );
  9934. }
  9935. return wireframeAttributes.get( geometry );
  9936. }
  9937. return {
  9938. get: get,
  9939. update: update,
  9940. getWireframeAttribute: getWireframeAttribute
  9941. };
  9942. }
  9943. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9944. const isWebGL2 = capabilities.isWebGL2;
  9945. let mode;
  9946. function setMode( value ) {
  9947. mode = value;
  9948. }
  9949. let type, bytesPerElement;
  9950. function setIndex( value ) {
  9951. type = value.type;
  9952. bytesPerElement = value.bytesPerElement;
  9953. }
  9954. function render( start, count ) {
  9955. gl.drawElements( mode, count, type, start * bytesPerElement );
  9956. info.update( count, mode, 1 );
  9957. }
  9958. function renderInstances( start, count, primcount ) {
  9959. if ( primcount === 0 ) return;
  9960. let extension, methodName;
  9961. if ( isWebGL2 ) {
  9962. extension = gl;
  9963. methodName = 'drawElementsInstanced';
  9964. } else {
  9965. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9966. methodName = 'drawElementsInstancedANGLE';
  9967. if ( extension === null ) {
  9968. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9969. return;
  9970. }
  9971. }
  9972. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9973. info.update( count, mode, primcount );
  9974. }
  9975. //
  9976. this.setMode = setMode;
  9977. this.setIndex = setIndex;
  9978. this.render = render;
  9979. this.renderInstances = renderInstances;
  9980. }
  9981. function WebGLInfo( gl ) {
  9982. const memory = {
  9983. geometries: 0,
  9984. textures: 0
  9985. };
  9986. const render = {
  9987. frame: 0,
  9988. calls: 0,
  9989. triangles: 0,
  9990. points: 0,
  9991. lines: 0
  9992. };
  9993. function update( count, mode, instanceCount ) {
  9994. render.calls ++;
  9995. switch ( mode ) {
  9996. case 4:
  9997. render.triangles += instanceCount * ( count / 3 );
  9998. break;
  9999. case 1:
  10000. render.lines += instanceCount * ( count / 2 );
  10001. break;
  10002. case 3:
  10003. render.lines += instanceCount * ( count - 1 );
  10004. break;
  10005. case 2:
  10006. render.lines += instanceCount * count;
  10007. break;
  10008. case 0:
  10009. render.points += instanceCount * count;
  10010. break;
  10011. default:
  10012. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10013. break;
  10014. }
  10015. }
  10016. function reset() {
  10017. render.frame ++;
  10018. render.calls = 0;
  10019. render.triangles = 0;
  10020. render.points = 0;
  10021. render.lines = 0;
  10022. }
  10023. return {
  10024. memory: memory,
  10025. render: render,
  10026. programs: null,
  10027. autoReset: true,
  10028. reset: reset,
  10029. update: update
  10030. };
  10031. }
  10032. class DataTexture2DArray extends Texture {
  10033. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10034. super( null );
  10035. this.image = { data, width, height, depth };
  10036. this.magFilter = NearestFilter;
  10037. this.minFilter = NearestFilter;
  10038. this.wrapR = ClampToEdgeWrapping;
  10039. this.generateMipmaps = false;
  10040. this.flipY = false;
  10041. this.unpackAlignment = 1;
  10042. this.needsUpdate = true;
  10043. }
  10044. }
  10045. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10046. function numericalSort( a, b ) {
  10047. return a[ 0 ] - b[ 0 ];
  10048. }
  10049. function absNumericalSort( a, b ) {
  10050. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10051. }
  10052. function denormalize( morph, attribute ) {
  10053. let denominator = 1;
  10054. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10055. if ( array instanceof Int8Array ) denominator = 127;
  10056. else if ( array instanceof Int16Array ) denominator = 32767;
  10057. else if ( array instanceof Int32Array ) denominator = 2147483647;
  10058. else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array );
  10059. morph.divideScalar( denominator );
  10060. }
  10061. function WebGLMorphtargets( gl, capabilities, textures ) {
  10062. const influencesList = {};
  10063. const morphInfluences = new Float32Array( 8 );
  10064. const morphTextures = new WeakMap();
  10065. const morph = new Vector3();
  10066. const workInfluences = [];
  10067. for ( let i = 0; i < 8; i ++ ) {
  10068. workInfluences[ i ] = [ i, 0 ];
  10069. }
  10070. function update( object, geometry, material, program ) {
  10071. const objectInfluences = object.morphTargetInfluences;
  10072. if ( capabilities.isWebGL2 === true ) {
  10073. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10074. // into an array of data textures. Each layer represents a single morph target.
  10075. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  10076. let entry = morphTextures.get( geometry );
  10077. if ( entry === undefined || entry.count !== numberOfMorphTargets ) {
  10078. if ( entry !== undefined ) entry.texture.dispose();
  10079. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10080. const morphTargets = geometry.morphAttributes.position;
  10081. const morphNormals = geometry.morphAttributes.normal || [];
  10082. const numberOfVertices = geometry.attributes.position.count;
  10083. const numberOfVertexData = ( hasMorphNormals === true ) ? 2 : 1; // (v,n) vs. (v)
  10084. let width = numberOfVertices * numberOfVertexData;
  10085. let height = 1;
  10086. if ( width > capabilities.maxTextureSize ) {
  10087. height = Math.ceil( width / capabilities.maxTextureSize );
  10088. width = capabilities.maxTextureSize;
  10089. }
  10090. const buffer = new Float32Array( width * height * 4 * numberOfMorphTargets );
  10091. const texture = new DataTexture2DArray( buffer, width, height, numberOfMorphTargets );
  10092. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  10093. texture.type = FloatType;
  10094. // fill buffer
  10095. const vertexDataStride = numberOfVertexData * 4;
  10096. for ( let i = 0; i < numberOfMorphTargets; i ++ ) {
  10097. const morphTarget = morphTargets[ i ];
  10098. const morphNormal = morphNormals[ i ];
  10099. const offset = width * height * 4 * i;
  10100. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10101. morph.fromBufferAttribute( morphTarget, j );
  10102. if ( morphTarget.normalized === true ) denormalize( morph, morphTarget );
  10103. const stride = j * vertexDataStride;
  10104. buffer[ offset + stride + 0 ] = morph.x;
  10105. buffer[ offset + stride + 1 ] = morph.y;
  10106. buffer[ offset + stride + 2 ] = morph.z;
  10107. buffer[ offset + stride + 3 ] = 0;
  10108. if ( hasMorphNormals === true ) {
  10109. morph.fromBufferAttribute( morphNormal, j );
  10110. if ( morphNormal.normalized === true ) denormalize( morph, morphNormal );
  10111. buffer[ offset + stride + 4 ] = morph.x;
  10112. buffer[ offset + stride + 5 ] = morph.y;
  10113. buffer[ offset + stride + 6 ] = morph.z;
  10114. buffer[ offset + stride + 7 ] = 0;
  10115. }
  10116. }
  10117. }
  10118. entry = {
  10119. count: numberOfMorphTargets,
  10120. texture: texture,
  10121. size: new Vector2( width, height )
  10122. };
  10123. morphTextures.set( geometry, entry );
  10124. }
  10125. //
  10126. let morphInfluencesSum = 0;
  10127. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10128. morphInfluencesSum += objectInfluences[ i ];
  10129. }
  10130. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10131. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10132. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10133. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10134. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10135. } else {
  10136. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10137. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10138. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10139. let influences = influencesList[ geometry.id ];
  10140. if ( influences === undefined || influences.length !== length ) {
  10141. // initialise list
  10142. influences = [];
  10143. for ( let i = 0; i < length; i ++ ) {
  10144. influences[ i ] = [ i, 0 ];
  10145. }
  10146. influencesList[ geometry.id ] = influences;
  10147. }
  10148. // Collect influences
  10149. for ( let i = 0; i < length; i ++ ) {
  10150. const influence = influences[ i ];
  10151. influence[ 0 ] = i;
  10152. influence[ 1 ] = objectInfluences[ i ];
  10153. }
  10154. influences.sort( absNumericalSort );
  10155. for ( let i = 0; i < 8; i ++ ) {
  10156. if ( i < length && influences[ i ][ 1 ] ) {
  10157. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10158. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10159. } else {
  10160. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10161. workInfluences[ i ][ 1 ] = 0;
  10162. }
  10163. }
  10164. workInfluences.sort( numericalSort );
  10165. const morphTargets = geometry.morphAttributes.position;
  10166. const morphNormals = geometry.morphAttributes.normal;
  10167. let morphInfluencesSum = 0;
  10168. for ( let i = 0; i < 8; i ++ ) {
  10169. const influence = workInfluences[ i ];
  10170. const index = influence[ 0 ];
  10171. const value = influence[ 1 ];
  10172. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10173. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10174. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10175. }
  10176. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10177. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10178. }
  10179. morphInfluences[ i ] = value;
  10180. morphInfluencesSum += value;
  10181. } else {
  10182. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10183. geometry.deleteAttribute( 'morphTarget' + i );
  10184. }
  10185. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10186. geometry.deleteAttribute( 'morphNormal' + i );
  10187. }
  10188. morphInfluences[ i ] = 0;
  10189. }
  10190. }
  10191. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10192. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10193. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10194. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10195. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10196. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10197. }
  10198. }
  10199. return {
  10200. update: update
  10201. };
  10202. }
  10203. function WebGLObjects( gl, geometries, attributes, info ) {
  10204. let updateMap = new WeakMap();
  10205. function update( object ) {
  10206. const frame = info.render.frame;
  10207. const geometry = object.geometry;
  10208. const buffergeometry = geometries.get( object, geometry );
  10209. // Update once per frame
  10210. if ( updateMap.get( buffergeometry ) !== frame ) {
  10211. geometries.update( buffergeometry );
  10212. updateMap.set( buffergeometry, frame );
  10213. }
  10214. if ( object.isInstancedMesh ) {
  10215. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10216. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10217. }
  10218. attributes.update( object.instanceMatrix, 34962 );
  10219. if ( object.instanceColor !== null ) {
  10220. attributes.update( object.instanceColor, 34962 );
  10221. }
  10222. }
  10223. return buffergeometry;
  10224. }
  10225. function dispose() {
  10226. updateMap = new WeakMap();
  10227. }
  10228. function onInstancedMeshDispose( event ) {
  10229. const instancedMesh = event.target;
  10230. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10231. attributes.remove( instancedMesh.instanceMatrix );
  10232. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10233. }
  10234. return {
  10235. update: update,
  10236. dispose: dispose
  10237. };
  10238. }
  10239. class DataTexture3D extends Texture {
  10240. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10241. // We're going to add .setXXX() methods for setting properties later.
  10242. // Users can still set in DataTexture3D directly.
  10243. //
  10244. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10245. // texture.anisotropy = 16;
  10246. //
  10247. // See #14839
  10248. super( null );
  10249. this.image = { data, width, height, depth };
  10250. this.magFilter = NearestFilter;
  10251. this.minFilter = NearestFilter;
  10252. this.wrapR = ClampToEdgeWrapping;
  10253. this.generateMipmaps = false;
  10254. this.flipY = false;
  10255. this.unpackAlignment = 1;
  10256. this.needsUpdate = true;
  10257. }
  10258. }
  10259. DataTexture3D.prototype.isDataTexture3D = true;
  10260. /**
  10261. * Uniforms of a program.
  10262. * Those form a tree structure with a special top-level container for the root,
  10263. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10264. *
  10265. *
  10266. * Properties of inner nodes including the top-level container:
  10267. *
  10268. * .seq - array of nested uniforms
  10269. * .map - nested uniforms by name
  10270. *
  10271. *
  10272. * Methods of all nodes except the top-level container:
  10273. *
  10274. * .setValue( gl, value, [textures] )
  10275. *
  10276. * uploads a uniform value(s)
  10277. * the 'textures' parameter is needed for sampler uniforms
  10278. *
  10279. *
  10280. * Static methods of the top-level container (textures factorizations):
  10281. *
  10282. * .upload( gl, seq, values, textures )
  10283. *
  10284. * sets uniforms in 'seq' to 'values[id].value'
  10285. *
  10286. * .seqWithValue( seq, values ) : filteredSeq
  10287. *
  10288. * filters 'seq' entries with corresponding entry in values
  10289. *
  10290. *
  10291. * Methods of the top-level container (textures factorizations):
  10292. *
  10293. * .setValue( gl, name, value, textures )
  10294. *
  10295. * sets uniform with name 'name' to 'value'
  10296. *
  10297. * .setOptional( gl, obj, prop )
  10298. *
  10299. * like .set for an optional property of the object
  10300. *
  10301. */
  10302. const emptyTexture = new Texture();
  10303. const emptyTexture2dArray = new DataTexture2DArray();
  10304. const emptyTexture3d = new DataTexture3D();
  10305. const emptyCubeTexture = new CubeTexture();
  10306. // --- Utilities ---
  10307. // Array Caches (provide typed arrays for temporary by size)
  10308. const arrayCacheF32 = [];
  10309. const arrayCacheI32 = [];
  10310. // Float32Array caches used for uploading Matrix uniforms
  10311. const mat4array = new Float32Array( 16 );
  10312. const mat3array = new Float32Array( 9 );
  10313. const mat2array = new Float32Array( 4 );
  10314. // Flattening for arrays of vectors and matrices
  10315. function flatten( array, nBlocks, blockSize ) {
  10316. const firstElem = array[ 0 ];
  10317. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10318. // unoptimized: ! isNaN( firstElem )
  10319. // see http://jacksondunstan.com/articles/983
  10320. const n = nBlocks * blockSize;
  10321. let r = arrayCacheF32[ n ];
  10322. if ( r === undefined ) {
  10323. r = new Float32Array( n );
  10324. arrayCacheF32[ n ] = r;
  10325. }
  10326. if ( nBlocks !== 0 ) {
  10327. firstElem.toArray( r, 0 );
  10328. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10329. offset += blockSize;
  10330. array[ i ].toArray( r, offset );
  10331. }
  10332. }
  10333. return r;
  10334. }
  10335. function arraysEqual( a, b ) {
  10336. if ( a.length !== b.length ) return false;
  10337. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10338. if ( a[ i ] !== b[ i ] ) return false;
  10339. }
  10340. return true;
  10341. }
  10342. function copyArray( a, b ) {
  10343. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10344. a[ i ] = b[ i ];
  10345. }
  10346. }
  10347. // Texture unit allocation
  10348. function allocTexUnits( textures, n ) {
  10349. let r = arrayCacheI32[ n ];
  10350. if ( r === undefined ) {
  10351. r = new Int32Array( n );
  10352. arrayCacheI32[ n ] = r;
  10353. }
  10354. for ( let i = 0; i !== n; ++ i ) {
  10355. r[ i ] = textures.allocateTextureUnit();
  10356. }
  10357. return r;
  10358. }
  10359. // --- Setters ---
  10360. // Note: Defining these methods externally, because they come in a bunch
  10361. // and this way their names minify.
  10362. // Single scalar
  10363. function setValueV1f( gl, v ) {
  10364. const cache = this.cache;
  10365. if ( cache[ 0 ] === v ) return;
  10366. gl.uniform1f( this.addr, v );
  10367. cache[ 0 ] = v;
  10368. }
  10369. // Single float vector (from flat array or THREE.VectorN)
  10370. function setValueV2f( gl, v ) {
  10371. const cache = this.cache;
  10372. if ( v.x !== undefined ) {
  10373. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10374. gl.uniform2f( this.addr, v.x, v.y );
  10375. cache[ 0 ] = v.x;
  10376. cache[ 1 ] = v.y;
  10377. }
  10378. } else {
  10379. if ( arraysEqual( cache, v ) ) return;
  10380. gl.uniform2fv( this.addr, v );
  10381. copyArray( cache, v );
  10382. }
  10383. }
  10384. function setValueV3f( gl, v ) {
  10385. const cache = this.cache;
  10386. if ( v.x !== undefined ) {
  10387. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10388. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10389. cache[ 0 ] = v.x;
  10390. cache[ 1 ] = v.y;
  10391. cache[ 2 ] = v.z;
  10392. }
  10393. } else if ( v.r !== undefined ) {
  10394. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10395. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10396. cache[ 0 ] = v.r;
  10397. cache[ 1 ] = v.g;
  10398. cache[ 2 ] = v.b;
  10399. }
  10400. } else {
  10401. if ( arraysEqual( cache, v ) ) return;
  10402. gl.uniform3fv( this.addr, v );
  10403. copyArray( cache, v );
  10404. }
  10405. }
  10406. function setValueV4f( gl, v ) {
  10407. const cache = this.cache;
  10408. if ( v.x !== undefined ) {
  10409. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10410. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10411. cache[ 0 ] = v.x;
  10412. cache[ 1 ] = v.y;
  10413. cache[ 2 ] = v.z;
  10414. cache[ 3 ] = v.w;
  10415. }
  10416. } else {
  10417. if ( arraysEqual( cache, v ) ) return;
  10418. gl.uniform4fv( this.addr, v );
  10419. copyArray( cache, v );
  10420. }
  10421. }
  10422. // Single matrix (from flat array or THREE.MatrixN)
  10423. function setValueM2( gl, v ) {
  10424. const cache = this.cache;
  10425. const elements = v.elements;
  10426. if ( elements === undefined ) {
  10427. if ( arraysEqual( cache, v ) ) return;
  10428. gl.uniformMatrix2fv( this.addr, false, v );
  10429. copyArray( cache, v );
  10430. } else {
  10431. if ( arraysEqual( cache, elements ) ) return;
  10432. mat2array.set( elements );
  10433. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10434. copyArray( cache, elements );
  10435. }
  10436. }
  10437. function setValueM3( gl, v ) {
  10438. const cache = this.cache;
  10439. const elements = v.elements;
  10440. if ( elements === undefined ) {
  10441. if ( arraysEqual( cache, v ) ) return;
  10442. gl.uniformMatrix3fv( this.addr, false, v );
  10443. copyArray( cache, v );
  10444. } else {
  10445. if ( arraysEqual( cache, elements ) ) return;
  10446. mat3array.set( elements );
  10447. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10448. copyArray( cache, elements );
  10449. }
  10450. }
  10451. function setValueM4( gl, v ) {
  10452. const cache = this.cache;
  10453. const elements = v.elements;
  10454. if ( elements === undefined ) {
  10455. if ( arraysEqual( cache, v ) ) return;
  10456. gl.uniformMatrix4fv( this.addr, false, v );
  10457. copyArray( cache, v );
  10458. } else {
  10459. if ( arraysEqual( cache, elements ) ) return;
  10460. mat4array.set( elements );
  10461. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10462. copyArray( cache, elements );
  10463. }
  10464. }
  10465. // Single integer / boolean
  10466. function setValueV1i( gl, v ) {
  10467. const cache = this.cache;
  10468. if ( cache[ 0 ] === v ) return;
  10469. gl.uniform1i( this.addr, v );
  10470. cache[ 0 ] = v;
  10471. }
  10472. // Single integer / boolean vector (from flat array)
  10473. function setValueV2i( gl, v ) {
  10474. const cache = this.cache;
  10475. if ( arraysEqual( cache, v ) ) return;
  10476. gl.uniform2iv( this.addr, v );
  10477. copyArray( cache, v );
  10478. }
  10479. function setValueV3i( gl, v ) {
  10480. const cache = this.cache;
  10481. if ( arraysEqual( cache, v ) ) return;
  10482. gl.uniform3iv( this.addr, v );
  10483. copyArray( cache, v );
  10484. }
  10485. function setValueV4i( gl, v ) {
  10486. const cache = this.cache;
  10487. if ( arraysEqual( cache, v ) ) return;
  10488. gl.uniform4iv( this.addr, v );
  10489. copyArray( cache, v );
  10490. }
  10491. // Single unsigned integer
  10492. function setValueV1ui( gl, v ) {
  10493. const cache = this.cache;
  10494. if ( cache[ 0 ] === v ) return;
  10495. gl.uniform1ui( this.addr, v );
  10496. cache[ 0 ] = v;
  10497. }
  10498. // Single unsigned integer vector (from flat array)
  10499. function setValueV2ui( gl, v ) {
  10500. const cache = this.cache;
  10501. if ( arraysEqual( cache, v ) ) return;
  10502. gl.uniform2uiv( this.addr, v );
  10503. copyArray( cache, v );
  10504. }
  10505. function setValueV3ui( gl, v ) {
  10506. const cache = this.cache;
  10507. if ( arraysEqual( cache, v ) ) return;
  10508. gl.uniform3uiv( this.addr, v );
  10509. copyArray( cache, v );
  10510. }
  10511. function setValueV4ui( gl, v ) {
  10512. const cache = this.cache;
  10513. if ( arraysEqual( cache, v ) ) return;
  10514. gl.uniform4uiv( this.addr, v );
  10515. copyArray( cache, v );
  10516. }
  10517. // Single texture (2D / Cube)
  10518. function setValueT1( gl, v, textures ) {
  10519. const cache = this.cache;
  10520. const unit = textures.allocateTextureUnit();
  10521. if ( cache[ 0 ] !== unit ) {
  10522. gl.uniform1i( this.addr, unit );
  10523. cache[ 0 ] = unit;
  10524. }
  10525. textures.safeSetTexture2D( v || emptyTexture, unit );
  10526. }
  10527. function setValueT3D1( gl, v, textures ) {
  10528. const cache = this.cache;
  10529. const unit = textures.allocateTextureUnit();
  10530. if ( cache[ 0 ] !== unit ) {
  10531. gl.uniform1i( this.addr, unit );
  10532. cache[ 0 ] = unit;
  10533. }
  10534. textures.setTexture3D( v || emptyTexture3d, unit );
  10535. }
  10536. function setValueT6( gl, v, textures ) {
  10537. const cache = this.cache;
  10538. const unit = textures.allocateTextureUnit();
  10539. if ( cache[ 0 ] !== unit ) {
  10540. gl.uniform1i( this.addr, unit );
  10541. cache[ 0 ] = unit;
  10542. }
  10543. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10544. }
  10545. function setValueT2DArray1( gl, v, textures ) {
  10546. const cache = this.cache;
  10547. const unit = textures.allocateTextureUnit();
  10548. if ( cache[ 0 ] !== unit ) {
  10549. gl.uniform1i( this.addr, unit );
  10550. cache[ 0 ] = unit;
  10551. }
  10552. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10553. }
  10554. // Helper to pick the right setter for the singular case
  10555. function getSingularSetter( type ) {
  10556. switch ( type ) {
  10557. case 0x1406: return setValueV1f; // FLOAT
  10558. case 0x8b50: return setValueV2f; // _VEC2
  10559. case 0x8b51: return setValueV3f; // _VEC3
  10560. case 0x8b52: return setValueV4f; // _VEC4
  10561. case 0x8b5a: return setValueM2; // _MAT2
  10562. case 0x8b5b: return setValueM3; // _MAT3
  10563. case 0x8b5c: return setValueM4; // _MAT4
  10564. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10565. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10566. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10567. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10568. case 0x1405: return setValueV1ui; // UINT
  10569. case 0x8dc6: return setValueV2ui; // _VEC2
  10570. case 0x8dc7: return setValueV3ui; // _VEC3
  10571. case 0x8dc8: return setValueV4ui; // _VEC4
  10572. case 0x8b5e: // SAMPLER_2D
  10573. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10574. case 0x8dca: // INT_SAMPLER_2D
  10575. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10576. case 0x8b62: // SAMPLER_2D_SHADOW
  10577. return setValueT1;
  10578. case 0x8b5f: // SAMPLER_3D
  10579. case 0x8dcb: // INT_SAMPLER_3D
  10580. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10581. return setValueT3D1;
  10582. case 0x8b60: // SAMPLER_CUBE
  10583. case 0x8dcc: // INT_SAMPLER_CUBE
  10584. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10585. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10586. return setValueT6;
  10587. case 0x8dc1: // SAMPLER_2D_ARRAY
  10588. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10589. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10590. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10591. return setValueT2DArray1;
  10592. }
  10593. }
  10594. // Array of scalars
  10595. function setValueV1fArray( gl, v ) {
  10596. gl.uniform1fv( this.addr, v );
  10597. }
  10598. // Array of vectors (from flat array or array of THREE.VectorN)
  10599. function setValueV2fArray( gl, v ) {
  10600. const data = flatten( v, this.size, 2 );
  10601. gl.uniform2fv( this.addr, data );
  10602. }
  10603. function setValueV3fArray( gl, v ) {
  10604. const data = flatten( v, this.size, 3 );
  10605. gl.uniform3fv( this.addr, data );
  10606. }
  10607. function setValueV4fArray( gl, v ) {
  10608. const data = flatten( v, this.size, 4 );
  10609. gl.uniform4fv( this.addr, data );
  10610. }
  10611. // Array of matrices (from flat array or array of THREE.MatrixN)
  10612. function setValueM2Array( gl, v ) {
  10613. const data = flatten( v, this.size, 4 );
  10614. gl.uniformMatrix2fv( this.addr, false, data );
  10615. }
  10616. function setValueM3Array( gl, v ) {
  10617. const data = flatten( v, this.size, 9 );
  10618. gl.uniformMatrix3fv( this.addr, false, data );
  10619. }
  10620. function setValueM4Array( gl, v ) {
  10621. const data = flatten( v, this.size, 16 );
  10622. gl.uniformMatrix4fv( this.addr, false, data );
  10623. }
  10624. // Array of integer / boolean
  10625. function setValueV1iArray( gl, v ) {
  10626. gl.uniform1iv( this.addr, v );
  10627. }
  10628. // Array of integer / boolean vectors (from flat array)
  10629. function setValueV2iArray( gl, v ) {
  10630. gl.uniform2iv( this.addr, v );
  10631. }
  10632. function setValueV3iArray( gl, v ) {
  10633. gl.uniform3iv( this.addr, v );
  10634. }
  10635. function setValueV4iArray( gl, v ) {
  10636. gl.uniform4iv( this.addr, v );
  10637. }
  10638. // Array of unsigned integer
  10639. function setValueV1uiArray( gl, v ) {
  10640. gl.uniform1uiv( this.addr, v );
  10641. }
  10642. // Array of unsigned integer vectors (from flat array)
  10643. function setValueV2uiArray( gl, v ) {
  10644. gl.uniform2uiv( this.addr, v );
  10645. }
  10646. function setValueV3uiArray( gl, v ) {
  10647. gl.uniform3uiv( this.addr, v );
  10648. }
  10649. function setValueV4uiArray( gl, v ) {
  10650. gl.uniform4uiv( this.addr, v );
  10651. }
  10652. // Array of textures (2D / 3D / Cube / 2DArray)
  10653. function setValueT1Array( gl, v, textures ) {
  10654. const n = v.length;
  10655. const units = allocTexUnits( textures, n );
  10656. gl.uniform1iv( this.addr, units );
  10657. for ( let i = 0; i !== n; ++ i ) {
  10658. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10659. }
  10660. }
  10661. function setValueT3DArray( gl, v, textures ) {
  10662. const n = v.length;
  10663. const units = allocTexUnits( textures, n );
  10664. gl.uniform1iv( this.addr, units );
  10665. for ( let i = 0; i !== n; ++ i ) {
  10666. textures.setTexture3D( v[ i ] || emptyTexture3d, units[ i ] );
  10667. }
  10668. }
  10669. function setValueT6Array( gl, v, textures ) {
  10670. const n = v.length;
  10671. const units = allocTexUnits( textures, n );
  10672. gl.uniform1iv( this.addr, units );
  10673. for ( let i = 0; i !== n; ++ i ) {
  10674. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10675. }
  10676. }
  10677. function setValueT2DArrayArray( gl, v, textures ) {
  10678. const n = v.length;
  10679. const units = allocTexUnits( textures, n );
  10680. gl.uniform1iv( this.addr, units );
  10681. for ( let i = 0; i !== n; ++ i ) {
  10682. textures.setTexture2DArray( v[ i ] || emptyTexture2dArray, units[ i ] );
  10683. }
  10684. }
  10685. // Helper to pick the right setter for a pure (bottom-level) array
  10686. function getPureArraySetter( type ) {
  10687. switch ( type ) {
  10688. case 0x1406: return setValueV1fArray; // FLOAT
  10689. case 0x8b50: return setValueV2fArray; // _VEC2
  10690. case 0x8b51: return setValueV3fArray; // _VEC3
  10691. case 0x8b52: return setValueV4fArray; // _VEC4
  10692. case 0x8b5a: return setValueM2Array; // _MAT2
  10693. case 0x8b5b: return setValueM3Array; // _MAT3
  10694. case 0x8b5c: return setValueM4Array; // _MAT4
  10695. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10696. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10697. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10698. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10699. case 0x1405: return setValueV1uiArray; // UINT
  10700. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10701. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10702. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10703. case 0x8b5e: // SAMPLER_2D
  10704. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10705. case 0x8dca: // INT_SAMPLER_2D
  10706. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10707. case 0x8b62: // SAMPLER_2D_SHADOW
  10708. return setValueT1Array;
  10709. case 0x8b5f: // SAMPLER_3D
  10710. case 0x8dcb: // INT_SAMPLER_3D
  10711. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10712. return setValueT3DArray;
  10713. case 0x8b60: // SAMPLER_CUBE
  10714. case 0x8dcc: // INT_SAMPLER_CUBE
  10715. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10716. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10717. return setValueT6Array;
  10718. case 0x8dc1: // SAMPLER_2D_ARRAY
  10719. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10720. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10721. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10722. return setValueT2DArrayArray;
  10723. }
  10724. }
  10725. // --- Uniform Classes ---
  10726. function SingleUniform( id, activeInfo, addr ) {
  10727. this.id = id;
  10728. this.addr = addr;
  10729. this.cache = [];
  10730. this.setValue = getSingularSetter( activeInfo.type );
  10731. // this.path = activeInfo.name; // DEBUG
  10732. }
  10733. function PureArrayUniform( id, activeInfo, addr ) {
  10734. this.id = id;
  10735. this.addr = addr;
  10736. this.cache = [];
  10737. this.size = activeInfo.size;
  10738. this.setValue = getPureArraySetter( activeInfo.type );
  10739. // this.path = activeInfo.name; // DEBUG
  10740. }
  10741. PureArrayUniform.prototype.updateCache = function ( data ) {
  10742. const cache = this.cache;
  10743. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10744. this.cache = new Float32Array( data.length );
  10745. }
  10746. copyArray( cache, data );
  10747. };
  10748. function StructuredUniform( id ) {
  10749. this.id = id;
  10750. this.seq = [];
  10751. this.map = {};
  10752. }
  10753. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10754. const seq = this.seq;
  10755. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10756. const u = seq[ i ];
  10757. u.setValue( gl, value[ u.id ], textures );
  10758. }
  10759. };
  10760. // --- Top-level ---
  10761. // Parser - builds up the property tree from the path strings
  10762. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10763. // extracts
  10764. // - the identifier (member name or array index)
  10765. // - followed by an optional right bracket (found when array index)
  10766. // - followed by an optional left bracket or dot (type of subscript)
  10767. //
  10768. // Note: These portions can be read in a non-overlapping fashion and
  10769. // allow straightforward parsing of the hierarchy that WebGL encodes
  10770. // in the uniform names.
  10771. function addUniform( container, uniformObject ) {
  10772. container.seq.push( uniformObject );
  10773. container.map[ uniformObject.id ] = uniformObject;
  10774. }
  10775. function parseUniform( activeInfo, addr, container ) {
  10776. const path = activeInfo.name,
  10777. pathLength = path.length;
  10778. // reset RegExp object, because of the early exit of a previous run
  10779. RePathPart.lastIndex = 0;
  10780. while ( true ) {
  10781. const match = RePathPart.exec( path ),
  10782. matchEnd = RePathPart.lastIndex;
  10783. let id = match[ 1 ];
  10784. const idIsIndex = match[ 2 ] === ']',
  10785. subscript = match[ 3 ];
  10786. if ( idIsIndex ) id = id | 0; // convert to integer
  10787. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10788. // bare name or "pure" bottom-level array "[0]" suffix
  10789. addUniform( container, subscript === undefined ?
  10790. new SingleUniform( id, activeInfo, addr ) :
  10791. new PureArrayUniform( id, activeInfo, addr ) );
  10792. break;
  10793. } else {
  10794. // step into inner node / create it in case it doesn't exist
  10795. const map = container.map;
  10796. let next = map[ id ];
  10797. if ( next === undefined ) {
  10798. next = new StructuredUniform( id );
  10799. addUniform( container, next );
  10800. }
  10801. container = next;
  10802. }
  10803. }
  10804. }
  10805. // Root Container
  10806. function WebGLUniforms( gl, program ) {
  10807. this.seq = [];
  10808. this.map = {};
  10809. const n = gl.getProgramParameter( program, 35718 );
  10810. for ( let i = 0; i < n; ++ i ) {
  10811. const info = gl.getActiveUniform( program, i ),
  10812. addr = gl.getUniformLocation( program, info.name );
  10813. parseUniform( info, addr, this );
  10814. }
  10815. }
  10816. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10817. const u = this.map[ name ];
  10818. if ( u !== undefined ) u.setValue( gl, value, textures );
  10819. };
  10820. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10821. const v = object[ name ];
  10822. if ( v !== undefined ) this.setValue( gl, name, v );
  10823. };
  10824. // Static interface
  10825. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10826. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10827. const u = seq[ i ],
  10828. v = values[ u.id ];
  10829. if ( v.needsUpdate !== false ) {
  10830. // note: always updating when .needsUpdate is undefined
  10831. u.setValue( gl, v.value, textures );
  10832. }
  10833. }
  10834. };
  10835. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10836. const r = [];
  10837. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10838. const u = seq[ i ];
  10839. if ( u.id in values ) r.push( u );
  10840. }
  10841. return r;
  10842. };
  10843. function WebGLShader( gl, type, string ) {
  10844. const shader = gl.createShader( type );
  10845. gl.shaderSource( shader, string );
  10846. gl.compileShader( shader );
  10847. return shader;
  10848. }
  10849. let programIdCount = 0;
  10850. function addLineNumbers( string ) {
  10851. const lines = string.split( '\n' );
  10852. for ( let i = 0; i < lines.length; i ++ ) {
  10853. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10854. }
  10855. return lines.join( '\n' );
  10856. }
  10857. function getEncodingComponents( encoding ) {
  10858. switch ( encoding ) {
  10859. case LinearEncoding:
  10860. return [ 'Linear', '( value )' ];
  10861. case sRGBEncoding:
  10862. return [ 'sRGB', '( value )' ];
  10863. case RGBEEncoding:
  10864. return [ 'RGBE', '( value )' ];
  10865. case RGBM7Encoding:
  10866. return [ 'RGBM', '( value, 7.0 )' ];
  10867. case RGBM16Encoding:
  10868. return [ 'RGBM', '( value, 16.0 )' ];
  10869. case RGBDEncoding:
  10870. return [ 'RGBD', '( value, 256.0 )' ];
  10871. case GammaEncoding:
  10872. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10873. default:
  10874. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10875. return [ 'Linear', '( value )' ];
  10876. }
  10877. }
  10878. function getShaderErrors( gl, shader, type ) {
  10879. const status = gl.getShaderParameter( shader, 35713 );
  10880. const errors = gl.getShaderInfoLog( shader ).trim();
  10881. if ( status && errors === '' ) return '';
  10882. // --enable-privileged-webgl-extension
  10883. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10884. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers( gl.getShaderSource( shader ) );
  10885. }
  10886. function getTexelDecodingFunction( functionName, encoding ) {
  10887. const components = getEncodingComponents( encoding );
  10888. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10889. }
  10890. function getTexelEncodingFunction( functionName, encoding ) {
  10891. const components = getEncodingComponents( encoding );
  10892. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10893. }
  10894. function getToneMappingFunction( functionName, toneMapping ) {
  10895. let toneMappingName;
  10896. switch ( toneMapping ) {
  10897. case LinearToneMapping:
  10898. toneMappingName = 'Linear';
  10899. break;
  10900. case ReinhardToneMapping:
  10901. toneMappingName = 'Reinhard';
  10902. break;
  10903. case CineonToneMapping:
  10904. toneMappingName = 'OptimizedCineon';
  10905. break;
  10906. case ACESFilmicToneMapping:
  10907. toneMappingName = 'ACESFilmic';
  10908. break;
  10909. case CustomToneMapping:
  10910. toneMappingName = 'Custom';
  10911. break;
  10912. default:
  10913. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10914. toneMappingName = 'Linear';
  10915. }
  10916. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10917. }
  10918. function generateExtensions( parameters ) {
  10919. const chunks = [
  10920. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10921. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10922. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10923. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10924. ];
  10925. return chunks.filter( filterEmptyLine ).join( '\n' );
  10926. }
  10927. function generateDefines( defines ) {
  10928. const chunks = [];
  10929. for ( const name in defines ) {
  10930. const value = defines[ name ];
  10931. if ( value === false ) continue;
  10932. chunks.push( '#define ' + name + ' ' + value );
  10933. }
  10934. return chunks.join( '\n' );
  10935. }
  10936. function fetchAttributeLocations( gl, program ) {
  10937. const attributes = {};
  10938. const n = gl.getProgramParameter( program, 35721 );
  10939. for ( let i = 0; i < n; i ++ ) {
  10940. const info = gl.getActiveAttrib( program, i );
  10941. const name = info.name;
  10942. let locationSize = 1;
  10943. if ( info.type === 35674 ) locationSize = 2;
  10944. if ( info.type === 35675 ) locationSize = 3;
  10945. if ( info.type === 35676 ) locationSize = 4;
  10946. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10947. attributes[ name ] = {
  10948. type: info.type,
  10949. location: gl.getAttribLocation( program, name ),
  10950. locationSize: locationSize
  10951. };
  10952. }
  10953. return attributes;
  10954. }
  10955. function filterEmptyLine( string ) {
  10956. return string !== '';
  10957. }
  10958. function replaceLightNums( string, parameters ) {
  10959. return string
  10960. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10961. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10962. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10963. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10964. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10965. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10966. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10967. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10968. }
  10969. function replaceClippingPlaneNums( string, parameters ) {
  10970. return string
  10971. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10972. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10973. }
  10974. // Resolve Includes
  10975. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10976. function resolveIncludes( string ) {
  10977. return string.replace( includePattern, includeReplacer );
  10978. }
  10979. function includeReplacer( match, include ) {
  10980. const string = ShaderChunk[ include ];
  10981. if ( string === undefined ) {
  10982. throw new Error( 'Can not resolve #include <' + include + '>' );
  10983. }
  10984. return resolveIncludes( string );
  10985. }
  10986. // Unroll Loops
  10987. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10988. 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;
  10989. function unrollLoops( string ) {
  10990. return string
  10991. .replace( unrollLoopPattern, loopReplacer )
  10992. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10993. }
  10994. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10995. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10996. return loopReplacer( match, start, end, snippet );
  10997. }
  10998. function loopReplacer( match, start, end, snippet ) {
  10999. let string = '';
  11000. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11001. string += snippet
  11002. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11003. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11004. }
  11005. return string;
  11006. }
  11007. //
  11008. function generatePrecision( parameters ) {
  11009. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11010. if ( parameters.precision === 'highp' ) {
  11011. precisionstring += '\n#define HIGH_PRECISION';
  11012. } else if ( parameters.precision === 'mediump' ) {
  11013. precisionstring += '\n#define MEDIUM_PRECISION';
  11014. } else if ( parameters.precision === 'lowp' ) {
  11015. precisionstring += '\n#define LOW_PRECISION';
  11016. }
  11017. return precisionstring;
  11018. }
  11019. function generateShadowMapTypeDefine( parameters ) {
  11020. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11021. if ( parameters.shadowMapType === PCFShadowMap ) {
  11022. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11023. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11024. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11025. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11026. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11027. }
  11028. return shadowMapTypeDefine;
  11029. }
  11030. function generateEnvMapTypeDefine( parameters ) {
  11031. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11032. if ( parameters.envMap ) {
  11033. switch ( parameters.envMapMode ) {
  11034. case CubeReflectionMapping:
  11035. case CubeRefractionMapping:
  11036. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11037. break;
  11038. case CubeUVReflectionMapping:
  11039. case CubeUVRefractionMapping:
  11040. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11041. break;
  11042. }
  11043. }
  11044. return envMapTypeDefine;
  11045. }
  11046. function generateEnvMapModeDefine( parameters ) {
  11047. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11048. if ( parameters.envMap ) {
  11049. switch ( parameters.envMapMode ) {
  11050. case CubeRefractionMapping:
  11051. case CubeUVRefractionMapping:
  11052. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11053. break;
  11054. }
  11055. }
  11056. return envMapModeDefine;
  11057. }
  11058. function generateEnvMapBlendingDefine( parameters ) {
  11059. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11060. if ( parameters.envMap ) {
  11061. switch ( parameters.combine ) {
  11062. case MultiplyOperation:
  11063. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11064. break;
  11065. case MixOperation:
  11066. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11067. break;
  11068. case AddOperation:
  11069. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11070. break;
  11071. }
  11072. }
  11073. return envMapBlendingDefine;
  11074. }
  11075. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11076. // TODO Send this event to Three.js DevTools
  11077. // console.log( 'WebGLProgram', cacheKey );
  11078. const gl = renderer.getContext();
  11079. const defines = parameters.defines;
  11080. let vertexShader = parameters.vertexShader;
  11081. let fragmentShader = parameters.fragmentShader;
  11082. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11083. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11084. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11085. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11086. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  11087. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11088. const customDefines = generateDefines( defines );
  11089. const program = gl.createProgram();
  11090. let prefixVertex, prefixFragment;
  11091. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11092. if ( parameters.isRawShaderMaterial ) {
  11093. prefixVertex = [
  11094. customDefines
  11095. ].filter( filterEmptyLine ).join( '\n' );
  11096. if ( prefixVertex.length > 0 ) {
  11097. prefixVertex += '\n';
  11098. }
  11099. prefixFragment = [
  11100. customExtensions,
  11101. customDefines
  11102. ].filter( filterEmptyLine ).join( '\n' );
  11103. if ( prefixFragment.length > 0 ) {
  11104. prefixFragment += '\n';
  11105. }
  11106. } else {
  11107. prefixVertex = [
  11108. generatePrecision( parameters ),
  11109. '#define SHADER_NAME ' + parameters.shaderName,
  11110. customDefines,
  11111. parameters.instancing ? '#define USE_INSTANCING' : '',
  11112. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11113. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11114. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11115. '#define MAX_BONES ' + parameters.maxBones,
  11116. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11117. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11118. parameters.map ? '#define USE_MAP' : '',
  11119. parameters.envMap ? '#define USE_ENVMAP' : '',
  11120. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11121. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11122. parameters.aoMap ? '#define USE_AOMAP' : '',
  11123. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11124. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11125. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11126. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11127. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11128. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11129. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11130. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11131. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11132. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11133. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11134. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11135. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11136. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11137. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11138. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11139. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11140. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11141. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11142. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11143. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11144. parameters.vertexColors ? '#define USE_COLOR' : '',
  11145. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11146. parameters.vertexUvs ? '#define USE_UV' : '',
  11147. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11148. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11149. parameters.skinning ? '#define USE_SKINNING' : '',
  11150. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  11151. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11152. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11153. ( parameters.morphTargets && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11154. ( parameters.morphTargets && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11155. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11156. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11157. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11158. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11159. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11160. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11161. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11162. 'uniform mat4 modelMatrix;',
  11163. 'uniform mat4 modelViewMatrix;',
  11164. 'uniform mat4 projectionMatrix;',
  11165. 'uniform mat4 viewMatrix;',
  11166. 'uniform mat3 normalMatrix;',
  11167. 'uniform vec3 cameraPosition;',
  11168. 'uniform bool isOrthographic;',
  11169. '#ifdef USE_INSTANCING',
  11170. ' attribute mat4 instanceMatrix;',
  11171. '#endif',
  11172. '#ifdef USE_INSTANCING_COLOR',
  11173. ' attribute vec3 instanceColor;',
  11174. '#endif',
  11175. 'attribute vec3 position;',
  11176. 'attribute vec3 normal;',
  11177. 'attribute vec2 uv;',
  11178. '#ifdef USE_TANGENT',
  11179. ' attribute vec4 tangent;',
  11180. '#endif',
  11181. '#if defined( USE_COLOR_ALPHA )',
  11182. ' attribute vec4 color;',
  11183. '#elif defined( USE_COLOR )',
  11184. ' attribute vec3 color;',
  11185. '#endif',
  11186. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11187. ' attribute vec3 morphTarget0;',
  11188. ' attribute vec3 morphTarget1;',
  11189. ' attribute vec3 morphTarget2;',
  11190. ' attribute vec3 morphTarget3;',
  11191. ' #ifdef USE_MORPHNORMALS',
  11192. ' attribute vec3 morphNormal0;',
  11193. ' attribute vec3 morphNormal1;',
  11194. ' attribute vec3 morphNormal2;',
  11195. ' attribute vec3 morphNormal3;',
  11196. ' #else',
  11197. ' attribute vec3 morphTarget4;',
  11198. ' attribute vec3 morphTarget5;',
  11199. ' attribute vec3 morphTarget6;',
  11200. ' attribute vec3 morphTarget7;',
  11201. ' #endif',
  11202. '#endif',
  11203. '#ifdef USE_SKINNING',
  11204. ' attribute vec4 skinIndex;',
  11205. ' attribute vec4 skinWeight;',
  11206. '#endif',
  11207. '\n'
  11208. ].filter( filterEmptyLine ).join( '\n' );
  11209. prefixFragment = [
  11210. customExtensions,
  11211. generatePrecision( parameters ),
  11212. '#define SHADER_NAME ' + parameters.shaderName,
  11213. customDefines,
  11214. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11215. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11216. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11217. parameters.map ? '#define USE_MAP' : '',
  11218. parameters.matcap ? '#define USE_MATCAP' : '',
  11219. parameters.envMap ? '#define USE_ENVMAP' : '',
  11220. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11221. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11222. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11223. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11224. parameters.aoMap ? '#define USE_AOMAP' : '',
  11225. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11226. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11227. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11228. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11229. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11230. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11231. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11232. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11233. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11234. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11235. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11236. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11237. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11238. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11239. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11240. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11241. parameters.sheen ? '#define USE_SHEEN' : '',
  11242. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11243. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11244. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11245. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11246. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11247. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11248. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11249. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11250. parameters.vertexUvs ? '#define USE_UV' : '',
  11251. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11252. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11253. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11254. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11255. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11256. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11257. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11258. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11259. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11260. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11261. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11262. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11263. 'uniform mat4 viewMatrix;',
  11264. 'uniform vec3 cameraPosition;',
  11265. 'uniform bool isOrthographic;',
  11266. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11267. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11268. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11269. parameters.dithering ? '#define DITHERING' : '',
  11270. parameters.format === RGBFormat ? '#define OPAQUE' : '',
  11271. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11272. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11273. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11274. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11275. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11276. parameters.specularColorMap ? getTexelDecodingFunction( 'specularColorMapTexelToLinear', parameters.specularColorMapEncoding ) : '',
  11277. parameters.sheenColorMap ? getTexelDecodingFunction( 'sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding ) : '',
  11278. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11279. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11280. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11281. '\n'
  11282. ].filter( filterEmptyLine ).join( '\n' );
  11283. }
  11284. vertexShader = resolveIncludes( vertexShader );
  11285. vertexShader = replaceLightNums( vertexShader, parameters );
  11286. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11287. fragmentShader = resolveIncludes( fragmentShader );
  11288. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11289. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11290. vertexShader = unrollLoops( vertexShader );
  11291. fragmentShader = unrollLoops( fragmentShader );
  11292. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11293. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11294. versionString = '#version 300 es\n';
  11295. prefixVertex = [
  11296. 'precision mediump sampler2DArray;',
  11297. '#define attribute in',
  11298. '#define varying out',
  11299. '#define texture2D texture'
  11300. ].join( '\n' ) + '\n' + prefixVertex;
  11301. prefixFragment = [
  11302. '#define varying in',
  11303. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11304. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11305. '#define gl_FragDepthEXT gl_FragDepth',
  11306. '#define texture2D texture',
  11307. '#define textureCube texture',
  11308. '#define texture2DProj textureProj',
  11309. '#define texture2DLodEXT textureLod',
  11310. '#define texture2DProjLodEXT textureProjLod',
  11311. '#define textureCubeLodEXT textureLod',
  11312. '#define texture2DGradEXT textureGrad',
  11313. '#define texture2DProjGradEXT textureProjGrad',
  11314. '#define textureCubeGradEXT textureGrad'
  11315. ].join( '\n' ) + '\n' + prefixFragment;
  11316. }
  11317. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11318. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11319. // console.log( '*VERTEX*', vertexGlsl );
  11320. // console.log( '*FRAGMENT*', fragmentGlsl );
  11321. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11322. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11323. gl.attachShader( program, glVertexShader );
  11324. gl.attachShader( program, glFragmentShader );
  11325. // Force a particular attribute to index 0.
  11326. if ( parameters.index0AttributeName !== undefined ) {
  11327. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11328. } else if ( parameters.morphTargets === true ) {
  11329. // programs with morphTargets displace position out of attribute 0
  11330. gl.bindAttribLocation( program, 0, 'position' );
  11331. }
  11332. gl.linkProgram( program );
  11333. // check for link errors
  11334. if ( renderer.debug.checkShaderErrors ) {
  11335. const programLog = gl.getProgramInfoLog( program ).trim();
  11336. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11337. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11338. let runnable = true;
  11339. let haveDiagnostics = true;
  11340. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11341. runnable = false;
  11342. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11343. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11344. console.error(
  11345. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11346. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11347. 'Program Info Log: ' + programLog + '\n' +
  11348. vertexErrors + '\n' +
  11349. fragmentErrors
  11350. );
  11351. } else if ( programLog !== '' ) {
  11352. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11353. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11354. haveDiagnostics = false;
  11355. }
  11356. if ( haveDiagnostics ) {
  11357. this.diagnostics = {
  11358. runnable: runnable,
  11359. programLog: programLog,
  11360. vertexShader: {
  11361. log: vertexLog,
  11362. prefix: prefixVertex
  11363. },
  11364. fragmentShader: {
  11365. log: fragmentLog,
  11366. prefix: prefixFragment
  11367. }
  11368. };
  11369. }
  11370. }
  11371. // Clean up
  11372. // Crashes in iOS9 and iOS10. #18402
  11373. // gl.detachShader( program, glVertexShader );
  11374. // gl.detachShader( program, glFragmentShader );
  11375. gl.deleteShader( glVertexShader );
  11376. gl.deleteShader( glFragmentShader );
  11377. // set up caching for uniform locations
  11378. let cachedUniforms;
  11379. this.getUniforms = function () {
  11380. if ( cachedUniforms === undefined ) {
  11381. cachedUniforms = new WebGLUniforms( gl, program );
  11382. }
  11383. return cachedUniforms;
  11384. };
  11385. // set up caching for attribute locations
  11386. let cachedAttributes;
  11387. this.getAttributes = function () {
  11388. if ( cachedAttributes === undefined ) {
  11389. cachedAttributes = fetchAttributeLocations( gl, program );
  11390. }
  11391. return cachedAttributes;
  11392. };
  11393. // free resource
  11394. this.destroy = function () {
  11395. bindingStates.releaseStatesOfProgram( this );
  11396. gl.deleteProgram( program );
  11397. this.program = undefined;
  11398. };
  11399. //
  11400. this.name = parameters.shaderName;
  11401. this.id = programIdCount ++;
  11402. this.cacheKey = cacheKey;
  11403. this.usedTimes = 1;
  11404. this.program = program;
  11405. this.vertexShader = glVertexShader;
  11406. this.fragmentShader = glFragmentShader;
  11407. return this;
  11408. }
  11409. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11410. const programs = [];
  11411. const isWebGL2 = capabilities.isWebGL2;
  11412. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11413. const floatVertexTextures = capabilities.floatVertexTextures;
  11414. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11415. const vertexTextures = capabilities.vertexTextures;
  11416. let precision = capabilities.precision;
  11417. const shaderIDs = {
  11418. MeshDepthMaterial: 'depth',
  11419. MeshDistanceMaterial: 'distanceRGBA',
  11420. MeshNormalMaterial: 'normal',
  11421. MeshBasicMaterial: 'basic',
  11422. MeshLambertMaterial: 'lambert',
  11423. MeshPhongMaterial: 'phong',
  11424. MeshToonMaterial: 'toon',
  11425. MeshStandardMaterial: 'physical',
  11426. MeshPhysicalMaterial: 'physical',
  11427. MeshMatcapMaterial: 'matcap',
  11428. LineBasicMaterial: 'basic',
  11429. LineDashedMaterial: 'dashed',
  11430. PointsMaterial: 'points',
  11431. ShadowMaterial: 'shadow',
  11432. SpriteMaterial: 'sprite'
  11433. };
  11434. const parameterNames = [
  11435. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  11436. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  11437. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap',
  11438. 'objectSpaceNormalMap', 'tangentSpaceNormalMap',
  11439. 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap',
  11440. 'displacementMap', 'specularMap', , 'roughnessMap', 'metalnessMap', 'gradientMap',
  11441. 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  11442. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  11443. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'morphTargetsCount', 'premultipliedAlpha',
  11444. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  11445. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  11446. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  11447. 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format',
  11448. 'specularIntensityMap', 'specularColorMap', 'specularColorMapEncoding',
  11449. 'transmission', 'transmissionMap', 'thicknessMap',
  11450. 'sheen', 'sheenColorMap', 'sheenColorMapEncoding', 'sheenRoughnessMap'
  11451. ];
  11452. function getMaxBones( object ) {
  11453. const skeleton = object.skeleton;
  11454. const bones = skeleton.bones;
  11455. if ( floatVertexTextures ) {
  11456. return 1024;
  11457. } else {
  11458. // default for when object is not specified
  11459. // ( for example when prebuilding shader to be used with multiple objects )
  11460. //
  11461. // - leave some extra space for other uniforms
  11462. // - limit here is ANGLE's 254 max uniform vectors
  11463. // (up to 54 should be safe)
  11464. const nVertexUniforms = maxVertexUniforms;
  11465. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11466. const maxBones = Math.min( nVertexMatrices, bones.length );
  11467. if ( maxBones < bones.length ) {
  11468. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11469. return 0;
  11470. }
  11471. return maxBones;
  11472. }
  11473. }
  11474. function getTextureEncodingFromMap( map ) {
  11475. let encoding;
  11476. if ( map && map.isTexture ) {
  11477. encoding = map.encoding;
  11478. } else if ( map && map.isWebGLRenderTarget ) {
  11479. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  11480. encoding = map.texture.encoding;
  11481. } else {
  11482. encoding = LinearEncoding;
  11483. }
  11484. /* if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
  11485. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  11486. } */
  11487. return encoding;
  11488. }
  11489. function getParameters( material, lights, shadows, scene, object ) {
  11490. const fog = scene.fog;
  11491. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11492. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11493. const shaderID = shaderIDs[ material.type ];
  11494. // heuristics to create shader parameters according to lights in the scene
  11495. // (not to blow over maxLights budget)
  11496. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11497. if ( material.precision !== null ) {
  11498. precision = capabilities.getMaxPrecision( material.precision );
  11499. if ( precision !== material.precision ) {
  11500. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11501. }
  11502. }
  11503. let vertexShader, fragmentShader;
  11504. if ( shaderID ) {
  11505. const shader = ShaderLib[ shaderID ];
  11506. vertexShader = shader.vertexShader;
  11507. fragmentShader = shader.fragmentShader;
  11508. } else {
  11509. vertexShader = material.vertexShader;
  11510. fragmentShader = material.fragmentShader;
  11511. }
  11512. const currentRenderTarget = renderer.getRenderTarget();
  11513. const useAlphaTest = material.alphaTest > 0;
  11514. const useClearcoat = material.clearcoat > 0;
  11515. const parameters = {
  11516. isWebGL2: isWebGL2,
  11517. shaderID: shaderID,
  11518. shaderName: material.type,
  11519. vertexShader: vertexShader,
  11520. fragmentShader: fragmentShader,
  11521. defines: material.defines,
  11522. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11523. glslVersion: material.glslVersion,
  11524. precision: precision,
  11525. instancing: object.isInstancedMesh === true,
  11526. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11527. supportsVertexTextures: vertexTextures,
  11528. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11529. map: !! material.map,
  11530. mapEncoding: getTextureEncodingFromMap( material.map ),
  11531. matcap: !! material.matcap,
  11532. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11533. envMap: !! envMap,
  11534. envMapMode: envMap && envMap.mapping,
  11535. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11536. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11537. lightMap: !! material.lightMap,
  11538. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11539. aoMap: !! material.aoMap,
  11540. emissiveMap: !! material.emissiveMap,
  11541. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11542. bumpMap: !! material.bumpMap,
  11543. normalMap: !! material.normalMap,
  11544. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11545. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11546. clearcoat: useClearcoat,
  11547. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11548. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11549. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11550. displacementMap: !! material.displacementMap,
  11551. roughnessMap: !! material.roughnessMap,
  11552. metalnessMap: !! material.metalnessMap,
  11553. specularMap: !! material.specularMap,
  11554. specularIntensityMap: !! material.specularIntensityMap,
  11555. specularColorMap: !! material.specularColorMap,
  11556. specularColorMapEncoding: getTextureEncodingFromMap( material.specularColorMap ),
  11557. alphaMap: !! material.alphaMap,
  11558. alphaTest: useAlphaTest,
  11559. gradientMap: !! material.gradientMap,
  11560. sheen: material.sheen > 0,
  11561. sheenColorMap: !! material.sheenColorMap,
  11562. sheenColorMapEncoding: getTextureEncodingFromMap( material.sheenColorMap ),
  11563. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11564. transmission: material.transmission > 0,
  11565. transmissionMap: !! material.transmissionMap,
  11566. thicknessMap: !! material.thicknessMap,
  11567. combine: material.combine,
  11568. vertexTangents: ( !! material.normalMap && !! object.geometry && !! object.geometry.attributes.tangent ),
  11569. vertexColors: material.vertexColors,
  11570. vertexAlphas: material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11571. 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,
  11572. 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,
  11573. fog: !! fog,
  11574. useFog: material.fog,
  11575. fogExp2: ( fog && fog.isFogExp2 ),
  11576. flatShading: !! material.flatShading,
  11577. sizeAttenuation: material.sizeAttenuation,
  11578. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11579. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11580. maxBones: maxBones,
  11581. useVertexTexture: floatVertexTextures,
  11582. morphTargets: !! object.geometry && !! object.geometry.morphAttributes.position,
  11583. morphNormals: !! object.geometry && !! object.geometry.morphAttributes.normal,
  11584. morphTargetsCount: ( !! object.geometry && !! object.geometry.morphAttributes.position ) ? object.geometry.morphAttributes.position.length : 0,
  11585. numDirLights: lights.directional.length,
  11586. numPointLights: lights.point.length,
  11587. numSpotLights: lights.spot.length,
  11588. numRectAreaLights: lights.rectArea.length,
  11589. numHemiLights: lights.hemi.length,
  11590. numDirLightShadows: lights.directionalShadowMap.length,
  11591. numPointLightShadows: lights.pointShadowMap.length,
  11592. numSpotLightShadows: lights.spotShadowMap.length,
  11593. numClippingPlanes: clipping.numPlanes,
  11594. numClipIntersection: clipping.numIntersection,
  11595. format: material.format,
  11596. dithering: material.dithering,
  11597. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11598. shadowMapType: renderer.shadowMap.type,
  11599. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11600. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11601. premultipliedAlpha: material.premultipliedAlpha,
  11602. doubleSided: material.side === DoubleSide,
  11603. flipSided: material.side === BackSide,
  11604. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11605. index0AttributeName: material.index0AttributeName,
  11606. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11607. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11608. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11609. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11610. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11611. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11612. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11613. customProgramCacheKey: material.customProgramCacheKey()
  11614. };
  11615. return parameters;
  11616. }
  11617. function getProgramCacheKey( parameters ) {
  11618. const array = [];
  11619. if ( parameters.shaderID ) {
  11620. array.push( parameters.shaderID );
  11621. } else {
  11622. array.push( hashString( parameters.fragmentShader ) );
  11623. array.push( hashString( parameters.vertexShader ) );
  11624. }
  11625. if ( parameters.defines !== undefined ) {
  11626. for ( const name in parameters.defines ) {
  11627. array.push( name );
  11628. array.push( parameters.defines[ name ] );
  11629. }
  11630. }
  11631. if ( parameters.isRawShaderMaterial === false ) {
  11632. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11633. array.push( parameters[ parameterNames[ i ] ] );
  11634. }
  11635. array.push( renderer.outputEncoding );
  11636. array.push( renderer.gammaFactor );
  11637. }
  11638. array.push( parameters.customProgramCacheKey );
  11639. return array.join();
  11640. }
  11641. function getUniforms( material ) {
  11642. const shaderID = shaderIDs[ material.type ];
  11643. let uniforms;
  11644. if ( shaderID ) {
  11645. const shader = ShaderLib[ shaderID ];
  11646. uniforms = UniformsUtils.clone( shader.uniforms );
  11647. } else {
  11648. uniforms = material.uniforms;
  11649. }
  11650. return uniforms;
  11651. }
  11652. function acquireProgram( parameters, cacheKey ) {
  11653. let program;
  11654. // Check if code has been already compiled
  11655. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11656. const preexistingProgram = programs[ p ];
  11657. if ( preexistingProgram.cacheKey === cacheKey ) {
  11658. program = preexistingProgram;
  11659. ++ program.usedTimes;
  11660. break;
  11661. }
  11662. }
  11663. if ( program === undefined ) {
  11664. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11665. programs.push( program );
  11666. }
  11667. return program;
  11668. }
  11669. function releaseProgram( program ) {
  11670. if ( -- program.usedTimes === 0 ) {
  11671. // Remove from unordered set
  11672. const i = programs.indexOf( program );
  11673. programs[ i ] = programs[ programs.length - 1 ];
  11674. programs.pop();
  11675. // Free WebGL resources
  11676. program.destroy();
  11677. }
  11678. }
  11679. return {
  11680. getParameters: getParameters,
  11681. getProgramCacheKey: getProgramCacheKey,
  11682. getUniforms: getUniforms,
  11683. acquireProgram: acquireProgram,
  11684. releaseProgram: releaseProgram,
  11685. // Exposed for resource monitoring & error feedback via renderer.info:
  11686. programs: programs
  11687. };
  11688. }
  11689. function WebGLProperties() {
  11690. let properties = new WeakMap();
  11691. function get( object ) {
  11692. let map = properties.get( object );
  11693. if ( map === undefined ) {
  11694. map = {};
  11695. properties.set( object, map );
  11696. }
  11697. return map;
  11698. }
  11699. function remove( object ) {
  11700. properties.delete( object );
  11701. }
  11702. function update( object, key, value ) {
  11703. properties.get( object )[ key ] = value;
  11704. }
  11705. function dispose() {
  11706. properties = new WeakMap();
  11707. }
  11708. return {
  11709. get: get,
  11710. remove: remove,
  11711. update: update,
  11712. dispose: dispose
  11713. };
  11714. }
  11715. function painterSortStable( a, b ) {
  11716. if ( a.groupOrder !== b.groupOrder ) {
  11717. return a.groupOrder - b.groupOrder;
  11718. } else if ( a.renderOrder !== b.renderOrder ) {
  11719. return a.renderOrder - b.renderOrder;
  11720. } else if ( a.program !== b.program ) {
  11721. return a.program.id - b.program.id;
  11722. } else if ( a.material.id !== b.material.id ) {
  11723. return a.material.id - b.material.id;
  11724. } else if ( a.z !== b.z ) {
  11725. return a.z - b.z;
  11726. } else {
  11727. return a.id - b.id;
  11728. }
  11729. }
  11730. function reversePainterSortStable( a, b ) {
  11731. if ( a.groupOrder !== b.groupOrder ) {
  11732. return a.groupOrder - b.groupOrder;
  11733. } else if ( a.renderOrder !== b.renderOrder ) {
  11734. return a.renderOrder - b.renderOrder;
  11735. } else if ( a.z !== b.z ) {
  11736. return b.z - a.z;
  11737. } else {
  11738. return a.id - b.id;
  11739. }
  11740. }
  11741. function WebGLRenderList( properties ) {
  11742. const renderItems = [];
  11743. let renderItemsIndex = 0;
  11744. const opaque = [];
  11745. const transmissive = [];
  11746. const transparent = [];
  11747. const defaultProgram = { id: - 1 };
  11748. function init() {
  11749. renderItemsIndex = 0;
  11750. opaque.length = 0;
  11751. transmissive.length = 0;
  11752. transparent.length = 0;
  11753. }
  11754. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11755. let renderItem = renderItems[ renderItemsIndex ];
  11756. const materialProperties = properties.get( material );
  11757. if ( renderItem === undefined ) {
  11758. renderItem = {
  11759. id: object.id,
  11760. object: object,
  11761. geometry: geometry,
  11762. material: material,
  11763. program: materialProperties.program || defaultProgram,
  11764. groupOrder: groupOrder,
  11765. renderOrder: object.renderOrder,
  11766. z: z,
  11767. group: group
  11768. };
  11769. renderItems[ renderItemsIndex ] = renderItem;
  11770. } else {
  11771. renderItem.id = object.id;
  11772. renderItem.object = object;
  11773. renderItem.geometry = geometry;
  11774. renderItem.material = material;
  11775. renderItem.program = materialProperties.program || defaultProgram;
  11776. renderItem.groupOrder = groupOrder;
  11777. renderItem.renderOrder = object.renderOrder;
  11778. renderItem.z = z;
  11779. renderItem.group = group;
  11780. }
  11781. renderItemsIndex ++;
  11782. return renderItem;
  11783. }
  11784. function push( object, geometry, material, groupOrder, z, group ) {
  11785. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11786. if ( material.transmission > 0.0 ) {
  11787. transmissive.push( renderItem );
  11788. } else if ( material.transparent === true ) {
  11789. transparent.push( renderItem );
  11790. } else {
  11791. opaque.push( renderItem );
  11792. }
  11793. }
  11794. function unshift( object, geometry, material, groupOrder, z, group ) {
  11795. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11796. if ( material.transmission > 0.0 ) {
  11797. transmissive.unshift( renderItem );
  11798. } else if ( material.transparent === true ) {
  11799. transparent.unshift( renderItem );
  11800. } else {
  11801. opaque.unshift( renderItem );
  11802. }
  11803. }
  11804. function sort( customOpaqueSort, customTransparentSort ) {
  11805. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11806. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  11807. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11808. }
  11809. function finish() {
  11810. // Clear references from inactive renderItems in the list
  11811. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11812. const renderItem = renderItems[ i ];
  11813. if ( renderItem.id === null ) break;
  11814. renderItem.id = null;
  11815. renderItem.object = null;
  11816. renderItem.geometry = null;
  11817. renderItem.material = null;
  11818. renderItem.program = null;
  11819. renderItem.group = null;
  11820. }
  11821. }
  11822. return {
  11823. opaque: opaque,
  11824. transmissive: transmissive,
  11825. transparent: transparent,
  11826. init: init,
  11827. push: push,
  11828. unshift: unshift,
  11829. finish: finish,
  11830. sort: sort
  11831. };
  11832. }
  11833. function WebGLRenderLists( properties ) {
  11834. let lists = new WeakMap();
  11835. function get( scene, renderCallDepth ) {
  11836. let list;
  11837. if ( lists.has( scene ) === false ) {
  11838. list = new WebGLRenderList( properties );
  11839. lists.set( scene, [ list ] );
  11840. } else {
  11841. if ( renderCallDepth >= lists.get( scene ).length ) {
  11842. list = new WebGLRenderList( properties );
  11843. lists.get( scene ).push( list );
  11844. } else {
  11845. list = lists.get( scene )[ renderCallDepth ];
  11846. }
  11847. }
  11848. return list;
  11849. }
  11850. function dispose() {
  11851. lists = new WeakMap();
  11852. }
  11853. return {
  11854. get: get,
  11855. dispose: dispose
  11856. };
  11857. }
  11858. function UniformsCache() {
  11859. const lights = {};
  11860. return {
  11861. get: function ( light ) {
  11862. if ( lights[ light.id ] !== undefined ) {
  11863. return lights[ light.id ];
  11864. }
  11865. let uniforms;
  11866. switch ( light.type ) {
  11867. case 'DirectionalLight':
  11868. uniforms = {
  11869. direction: new Vector3(),
  11870. color: new Color()
  11871. };
  11872. break;
  11873. case 'SpotLight':
  11874. uniforms = {
  11875. position: new Vector3(),
  11876. direction: new Vector3(),
  11877. color: new Color(),
  11878. distance: 0,
  11879. coneCos: 0,
  11880. penumbraCos: 0,
  11881. decay: 0
  11882. };
  11883. break;
  11884. case 'PointLight':
  11885. uniforms = {
  11886. position: new Vector3(),
  11887. color: new Color(),
  11888. distance: 0,
  11889. decay: 0
  11890. };
  11891. break;
  11892. case 'HemisphereLight':
  11893. uniforms = {
  11894. direction: new Vector3(),
  11895. skyColor: new Color(),
  11896. groundColor: new Color()
  11897. };
  11898. break;
  11899. case 'RectAreaLight':
  11900. uniforms = {
  11901. color: new Color(),
  11902. position: new Vector3(),
  11903. halfWidth: new Vector3(),
  11904. halfHeight: new Vector3()
  11905. };
  11906. break;
  11907. }
  11908. lights[ light.id ] = uniforms;
  11909. return uniforms;
  11910. }
  11911. };
  11912. }
  11913. function ShadowUniformsCache() {
  11914. const lights = {};
  11915. return {
  11916. get: function ( light ) {
  11917. if ( lights[ light.id ] !== undefined ) {
  11918. return lights[ light.id ];
  11919. }
  11920. let uniforms;
  11921. switch ( light.type ) {
  11922. case 'DirectionalLight':
  11923. uniforms = {
  11924. shadowBias: 0,
  11925. shadowNormalBias: 0,
  11926. shadowRadius: 1,
  11927. shadowMapSize: new Vector2()
  11928. };
  11929. break;
  11930. case 'SpotLight':
  11931. uniforms = {
  11932. shadowBias: 0,
  11933. shadowNormalBias: 0,
  11934. shadowRadius: 1,
  11935. shadowMapSize: new Vector2()
  11936. };
  11937. break;
  11938. case 'PointLight':
  11939. uniforms = {
  11940. shadowBias: 0,
  11941. shadowNormalBias: 0,
  11942. shadowRadius: 1,
  11943. shadowMapSize: new Vector2(),
  11944. shadowCameraNear: 1,
  11945. shadowCameraFar: 1000
  11946. };
  11947. break;
  11948. // TODO (abelnation): set RectAreaLight shadow uniforms
  11949. }
  11950. lights[ light.id ] = uniforms;
  11951. return uniforms;
  11952. }
  11953. };
  11954. }
  11955. let nextVersion = 0;
  11956. function shadowCastingLightsFirst( lightA, lightB ) {
  11957. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11958. }
  11959. function WebGLLights( extensions, capabilities ) {
  11960. const cache = new UniformsCache();
  11961. const shadowCache = ShadowUniformsCache();
  11962. const state = {
  11963. version: 0,
  11964. hash: {
  11965. directionalLength: - 1,
  11966. pointLength: - 1,
  11967. spotLength: - 1,
  11968. rectAreaLength: - 1,
  11969. hemiLength: - 1,
  11970. numDirectionalShadows: - 1,
  11971. numPointShadows: - 1,
  11972. numSpotShadows: - 1
  11973. },
  11974. ambient: [ 0, 0, 0 ],
  11975. probe: [],
  11976. directional: [],
  11977. directionalShadow: [],
  11978. directionalShadowMap: [],
  11979. directionalShadowMatrix: [],
  11980. spot: [],
  11981. spotShadow: [],
  11982. spotShadowMap: [],
  11983. spotShadowMatrix: [],
  11984. rectArea: [],
  11985. rectAreaLTC1: null,
  11986. rectAreaLTC2: null,
  11987. point: [],
  11988. pointShadow: [],
  11989. pointShadowMap: [],
  11990. pointShadowMatrix: [],
  11991. hemi: []
  11992. };
  11993. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11994. const vector3 = new Vector3();
  11995. const matrix4 = new Matrix4();
  11996. const matrix42 = new Matrix4();
  11997. function setup( lights, physicallyCorrectLights ) {
  11998. let r = 0, g = 0, b = 0;
  11999. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12000. let directionalLength = 0;
  12001. let pointLength = 0;
  12002. let spotLength = 0;
  12003. let rectAreaLength = 0;
  12004. let hemiLength = 0;
  12005. let numDirectionalShadows = 0;
  12006. let numPointShadows = 0;
  12007. let numSpotShadows = 0;
  12008. lights.sort( shadowCastingLightsFirst );
  12009. // artist-friendly light intensity scaling factor
  12010. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12011. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12012. const light = lights[ i ];
  12013. const color = light.color;
  12014. const intensity = light.intensity;
  12015. const distance = light.distance;
  12016. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12017. if ( light.isAmbientLight ) {
  12018. r += color.r * intensity * scaleFactor;
  12019. g += color.g * intensity * scaleFactor;
  12020. b += color.b * intensity * scaleFactor;
  12021. } else if ( light.isLightProbe ) {
  12022. for ( let j = 0; j < 9; j ++ ) {
  12023. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12024. }
  12025. } else if ( light.isDirectionalLight ) {
  12026. const uniforms = cache.get( light );
  12027. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12028. if ( light.castShadow ) {
  12029. const shadow = light.shadow;
  12030. const shadowUniforms = shadowCache.get( light );
  12031. shadowUniforms.shadowBias = shadow.bias;
  12032. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12033. shadowUniforms.shadowRadius = shadow.radius;
  12034. shadowUniforms.shadowMapSize = shadow.mapSize;
  12035. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12036. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12037. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12038. numDirectionalShadows ++;
  12039. }
  12040. state.directional[ directionalLength ] = uniforms;
  12041. directionalLength ++;
  12042. } else if ( light.isSpotLight ) {
  12043. const uniforms = cache.get( light );
  12044. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12045. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12046. uniforms.distance = distance;
  12047. uniforms.coneCos = Math.cos( light.angle );
  12048. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12049. uniforms.decay = light.decay;
  12050. if ( light.castShadow ) {
  12051. const shadow = light.shadow;
  12052. const shadowUniforms = shadowCache.get( light );
  12053. shadowUniforms.shadowBias = shadow.bias;
  12054. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12055. shadowUniforms.shadowRadius = shadow.radius;
  12056. shadowUniforms.shadowMapSize = shadow.mapSize;
  12057. state.spotShadow[ spotLength ] = shadowUniforms;
  12058. state.spotShadowMap[ spotLength ] = shadowMap;
  12059. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12060. numSpotShadows ++;
  12061. }
  12062. state.spot[ spotLength ] = uniforms;
  12063. spotLength ++;
  12064. } else if ( light.isRectAreaLight ) {
  12065. const uniforms = cache.get( light );
  12066. // (a) intensity is the total visible light emitted
  12067. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12068. // (b) intensity is the brightness of the light
  12069. uniforms.color.copy( color ).multiplyScalar( intensity );
  12070. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12071. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12072. state.rectArea[ rectAreaLength ] = uniforms;
  12073. rectAreaLength ++;
  12074. } else if ( light.isPointLight ) {
  12075. const uniforms = cache.get( light );
  12076. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12077. uniforms.distance = light.distance;
  12078. uniforms.decay = light.decay;
  12079. if ( light.castShadow ) {
  12080. const shadow = light.shadow;
  12081. const shadowUniforms = shadowCache.get( light );
  12082. shadowUniforms.shadowBias = shadow.bias;
  12083. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12084. shadowUniforms.shadowRadius = shadow.radius;
  12085. shadowUniforms.shadowMapSize = shadow.mapSize;
  12086. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12087. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12088. state.pointShadow[ pointLength ] = shadowUniforms;
  12089. state.pointShadowMap[ pointLength ] = shadowMap;
  12090. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12091. numPointShadows ++;
  12092. }
  12093. state.point[ pointLength ] = uniforms;
  12094. pointLength ++;
  12095. } else if ( light.isHemisphereLight ) {
  12096. const uniforms = cache.get( light );
  12097. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12098. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12099. state.hemi[ hemiLength ] = uniforms;
  12100. hemiLength ++;
  12101. }
  12102. }
  12103. if ( rectAreaLength > 0 ) {
  12104. if ( capabilities.isWebGL2 ) {
  12105. // WebGL 2
  12106. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12107. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12108. } else {
  12109. // WebGL 1
  12110. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12111. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12112. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12113. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12114. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12115. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12116. } else {
  12117. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12118. }
  12119. }
  12120. }
  12121. state.ambient[ 0 ] = r;
  12122. state.ambient[ 1 ] = g;
  12123. state.ambient[ 2 ] = b;
  12124. const hash = state.hash;
  12125. if ( hash.directionalLength !== directionalLength ||
  12126. hash.pointLength !== pointLength ||
  12127. hash.spotLength !== spotLength ||
  12128. hash.rectAreaLength !== rectAreaLength ||
  12129. hash.hemiLength !== hemiLength ||
  12130. hash.numDirectionalShadows !== numDirectionalShadows ||
  12131. hash.numPointShadows !== numPointShadows ||
  12132. hash.numSpotShadows !== numSpotShadows ) {
  12133. state.directional.length = directionalLength;
  12134. state.spot.length = spotLength;
  12135. state.rectArea.length = rectAreaLength;
  12136. state.point.length = pointLength;
  12137. state.hemi.length = hemiLength;
  12138. state.directionalShadow.length = numDirectionalShadows;
  12139. state.directionalShadowMap.length = numDirectionalShadows;
  12140. state.pointShadow.length = numPointShadows;
  12141. state.pointShadowMap.length = numPointShadows;
  12142. state.spotShadow.length = numSpotShadows;
  12143. state.spotShadowMap.length = numSpotShadows;
  12144. state.directionalShadowMatrix.length = numDirectionalShadows;
  12145. state.pointShadowMatrix.length = numPointShadows;
  12146. state.spotShadowMatrix.length = numSpotShadows;
  12147. hash.directionalLength = directionalLength;
  12148. hash.pointLength = pointLength;
  12149. hash.spotLength = spotLength;
  12150. hash.rectAreaLength = rectAreaLength;
  12151. hash.hemiLength = hemiLength;
  12152. hash.numDirectionalShadows = numDirectionalShadows;
  12153. hash.numPointShadows = numPointShadows;
  12154. hash.numSpotShadows = numSpotShadows;
  12155. state.version = nextVersion ++;
  12156. }
  12157. }
  12158. function setupView( lights, camera ) {
  12159. let directionalLength = 0;
  12160. let pointLength = 0;
  12161. let spotLength = 0;
  12162. let rectAreaLength = 0;
  12163. let hemiLength = 0;
  12164. const viewMatrix = camera.matrixWorldInverse;
  12165. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12166. const light = lights[ i ];
  12167. if ( light.isDirectionalLight ) {
  12168. const uniforms = state.directional[ directionalLength ];
  12169. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12170. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12171. uniforms.direction.sub( vector3 );
  12172. uniforms.direction.transformDirection( viewMatrix );
  12173. directionalLength ++;
  12174. } else if ( light.isSpotLight ) {
  12175. const uniforms = state.spot[ spotLength ];
  12176. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12177. uniforms.position.applyMatrix4( viewMatrix );
  12178. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12179. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12180. uniforms.direction.sub( vector3 );
  12181. uniforms.direction.transformDirection( viewMatrix );
  12182. spotLength ++;
  12183. } else if ( light.isRectAreaLight ) {
  12184. const uniforms = state.rectArea[ rectAreaLength ];
  12185. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12186. uniforms.position.applyMatrix4( viewMatrix );
  12187. // extract local rotation of light to derive width/height half vectors
  12188. matrix42.identity();
  12189. matrix4.copy( light.matrixWorld );
  12190. matrix4.premultiply( viewMatrix );
  12191. matrix42.extractRotation( matrix4 );
  12192. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12193. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12194. uniforms.halfWidth.applyMatrix4( matrix42 );
  12195. uniforms.halfHeight.applyMatrix4( matrix42 );
  12196. rectAreaLength ++;
  12197. } else if ( light.isPointLight ) {
  12198. const uniforms = state.point[ pointLength ];
  12199. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12200. uniforms.position.applyMatrix4( viewMatrix );
  12201. pointLength ++;
  12202. } else if ( light.isHemisphereLight ) {
  12203. const uniforms = state.hemi[ hemiLength ];
  12204. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12205. uniforms.direction.transformDirection( viewMatrix );
  12206. uniforms.direction.normalize();
  12207. hemiLength ++;
  12208. }
  12209. }
  12210. }
  12211. return {
  12212. setup: setup,
  12213. setupView: setupView,
  12214. state: state
  12215. };
  12216. }
  12217. function WebGLRenderState( extensions, capabilities ) {
  12218. const lights = new WebGLLights( extensions, capabilities );
  12219. const lightsArray = [];
  12220. const shadowsArray = [];
  12221. function init() {
  12222. lightsArray.length = 0;
  12223. shadowsArray.length = 0;
  12224. }
  12225. function pushLight( light ) {
  12226. lightsArray.push( light );
  12227. }
  12228. function pushShadow( shadowLight ) {
  12229. shadowsArray.push( shadowLight );
  12230. }
  12231. function setupLights( physicallyCorrectLights ) {
  12232. lights.setup( lightsArray, physicallyCorrectLights );
  12233. }
  12234. function setupLightsView( camera ) {
  12235. lights.setupView( lightsArray, camera );
  12236. }
  12237. const state = {
  12238. lightsArray: lightsArray,
  12239. shadowsArray: shadowsArray,
  12240. lights: lights
  12241. };
  12242. return {
  12243. init: init,
  12244. state: state,
  12245. setupLights: setupLights,
  12246. setupLightsView: setupLightsView,
  12247. pushLight: pushLight,
  12248. pushShadow: pushShadow
  12249. };
  12250. }
  12251. function WebGLRenderStates( extensions, capabilities ) {
  12252. let renderStates = new WeakMap();
  12253. function get( scene, renderCallDepth = 0 ) {
  12254. let renderState;
  12255. if ( renderStates.has( scene ) === false ) {
  12256. renderState = new WebGLRenderState( extensions, capabilities );
  12257. renderStates.set( scene, [ renderState ] );
  12258. } else {
  12259. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12260. renderState = new WebGLRenderState( extensions, capabilities );
  12261. renderStates.get( scene ).push( renderState );
  12262. } else {
  12263. renderState = renderStates.get( scene )[ renderCallDepth ];
  12264. }
  12265. }
  12266. return renderState;
  12267. }
  12268. function dispose() {
  12269. renderStates = new WeakMap();
  12270. }
  12271. return {
  12272. get: get,
  12273. dispose: dispose
  12274. };
  12275. }
  12276. /**
  12277. * parameters = {
  12278. *
  12279. * opacity: <float>,
  12280. *
  12281. * map: new THREE.Texture( <Image> ),
  12282. *
  12283. * alphaMap: new THREE.Texture( <Image> ),
  12284. *
  12285. * displacementMap: new THREE.Texture( <Image> ),
  12286. * displacementScale: <float>,
  12287. * displacementBias: <float>,
  12288. *
  12289. * wireframe: <boolean>,
  12290. * wireframeLinewidth: <float>
  12291. * }
  12292. */
  12293. class MeshDepthMaterial extends Material {
  12294. constructor( parameters ) {
  12295. super();
  12296. this.type = 'MeshDepthMaterial';
  12297. this.depthPacking = BasicDepthPacking;
  12298. this.map = null;
  12299. this.alphaMap = null;
  12300. this.displacementMap = null;
  12301. this.displacementScale = 1;
  12302. this.displacementBias = 0;
  12303. this.wireframe = false;
  12304. this.wireframeLinewidth = 1;
  12305. this.fog = false;
  12306. this.setValues( parameters );
  12307. }
  12308. copy( source ) {
  12309. super.copy( source );
  12310. this.depthPacking = source.depthPacking;
  12311. this.map = source.map;
  12312. this.alphaMap = source.alphaMap;
  12313. this.displacementMap = source.displacementMap;
  12314. this.displacementScale = source.displacementScale;
  12315. this.displacementBias = source.displacementBias;
  12316. this.wireframe = source.wireframe;
  12317. this.wireframeLinewidth = source.wireframeLinewidth;
  12318. return this;
  12319. }
  12320. }
  12321. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12322. /**
  12323. * parameters = {
  12324. *
  12325. * referencePosition: <float>,
  12326. * nearDistance: <float>,
  12327. * farDistance: <float>,
  12328. *
  12329. * map: new THREE.Texture( <Image> ),
  12330. *
  12331. * alphaMap: new THREE.Texture( <Image> ),
  12332. *
  12333. * displacementMap: new THREE.Texture( <Image> ),
  12334. * displacementScale: <float>,
  12335. * displacementBias: <float>
  12336. *
  12337. * }
  12338. */
  12339. class MeshDistanceMaterial extends Material {
  12340. constructor( parameters ) {
  12341. super();
  12342. this.type = 'MeshDistanceMaterial';
  12343. this.referencePosition = new Vector3();
  12344. this.nearDistance = 1;
  12345. this.farDistance = 1000;
  12346. this.map = null;
  12347. this.alphaMap = null;
  12348. this.displacementMap = null;
  12349. this.displacementScale = 1;
  12350. this.displacementBias = 0;
  12351. this.fog = false;
  12352. this.setValues( parameters );
  12353. }
  12354. copy( source ) {
  12355. super.copy( source );
  12356. this.referencePosition.copy( source.referencePosition );
  12357. this.nearDistance = source.nearDistance;
  12358. this.farDistance = source.farDistance;
  12359. this.map = source.map;
  12360. this.alphaMap = source.alphaMap;
  12361. this.displacementMap = source.displacementMap;
  12362. this.displacementScale = source.displacementScale;
  12363. this.displacementBias = source.displacementBias;
  12364. return this;
  12365. }
  12366. }
  12367. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12368. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12369. 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}";
  12370. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12371. let _frustum = new Frustum();
  12372. const _shadowMapSize = new Vector2(),
  12373. _viewportSize = new Vector2(),
  12374. _viewport = new Vector4(),
  12375. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12376. _distanceMaterial = new MeshDistanceMaterial(),
  12377. _materialCache = {},
  12378. _maxTextureSize = _capabilities.maxTextureSize;
  12379. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12380. const shadowMaterialVertical = new ShaderMaterial( {
  12381. defines: {
  12382. VSM_SAMPLES: 8
  12383. },
  12384. uniforms: {
  12385. shadow_pass: { value: null },
  12386. resolution: { value: new Vector2() },
  12387. radius: { value: 4.0 }
  12388. },
  12389. vertexShader: vertex,
  12390. fragmentShader: fragment
  12391. } );
  12392. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12393. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12394. const fullScreenTri = new BufferGeometry();
  12395. fullScreenTri.setAttribute(
  12396. 'position',
  12397. new BufferAttribute(
  12398. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12399. 3
  12400. )
  12401. );
  12402. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12403. const scope = this;
  12404. this.enabled = false;
  12405. this.autoUpdate = true;
  12406. this.needsUpdate = false;
  12407. this.type = PCFShadowMap;
  12408. this.render = function ( lights, scene, camera ) {
  12409. if ( scope.enabled === false ) return;
  12410. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12411. if ( lights.length === 0 ) return;
  12412. const currentRenderTarget = _renderer.getRenderTarget();
  12413. const activeCubeFace = _renderer.getActiveCubeFace();
  12414. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12415. const _state = _renderer.state;
  12416. // Set GL state for depth map.
  12417. _state.setBlending( NoBlending );
  12418. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12419. _state.buffers.depth.setTest( true );
  12420. _state.setScissorTest( false );
  12421. // render depth map
  12422. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12423. const light = lights[ i ];
  12424. const shadow = light.shadow;
  12425. if ( shadow === undefined ) {
  12426. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12427. continue;
  12428. }
  12429. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12430. _shadowMapSize.copy( shadow.mapSize );
  12431. const shadowFrameExtents = shadow.getFrameExtents();
  12432. _shadowMapSize.multiply( shadowFrameExtents );
  12433. _viewportSize.copy( shadow.mapSize );
  12434. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12435. if ( _shadowMapSize.x > _maxTextureSize ) {
  12436. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12437. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12438. shadow.mapSize.x = _viewportSize.x;
  12439. }
  12440. if ( _shadowMapSize.y > _maxTextureSize ) {
  12441. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12442. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12443. shadow.mapSize.y = _viewportSize.y;
  12444. }
  12445. }
  12446. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12447. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12448. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12449. shadow.map.texture.name = light.name + '.shadowMap';
  12450. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12451. shadow.camera.updateProjectionMatrix();
  12452. }
  12453. if ( shadow.map === null ) {
  12454. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12455. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12456. shadow.map.texture.name = light.name + '.shadowMap';
  12457. shadow.camera.updateProjectionMatrix();
  12458. }
  12459. _renderer.setRenderTarget( shadow.map );
  12460. _renderer.clear();
  12461. const viewportCount = shadow.getViewportCount();
  12462. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12463. const viewport = shadow.getViewport( vp );
  12464. _viewport.set(
  12465. _viewportSize.x * viewport.x,
  12466. _viewportSize.y * viewport.y,
  12467. _viewportSize.x * viewport.z,
  12468. _viewportSize.y * viewport.w
  12469. );
  12470. _state.viewport( _viewport );
  12471. shadow.updateMatrices( light, vp );
  12472. _frustum = shadow.getFrustum();
  12473. renderObject( scene, camera, shadow.camera, light, this.type );
  12474. }
  12475. // do blur pass for VSM
  12476. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12477. VSMPass( shadow, camera );
  12478. }
  12479. shadow.needsUpdate = false;
  12480. }
  12481. scope.needsUpdate = false;
  12482. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12483. };
  12484. function VSMPass( shadow, camera ) {
  12485. const geometry = _objects.update( fullScreenMesh );
  12486. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12487. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12488. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12489. shadowMaterialVertical.needsUpdate = true;
  12490. shadowMaterialHorizontal.needsUpdate = true;
  12491. }
  12492. // vertical pass
  12493. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12494. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12495. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12496. _renderer.setRenderTarget( shadow.mapPass );
  12497. _renderer.clear();
  12498. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12499. // horizontal pass
  12500. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12501. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12502. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12503. _renderer.setRenderTarget( shadow.map );
  12504. _renderer.clear();
  12505. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12506. }
  12507. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12508. let result = null;
  12509. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12510. if ( customMaterial !== undefined ) {
  12511. result = customMaterial;
  12512. } else {
  12513. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12514. }
  12515. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  12516. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12517. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12518. // in this case we need a unique material instance reflecting the
  12519. // appropriate state
  12520. const keyA = result.uuid, keyB = material.uuid;
  12521. let materialsForVariant = _materialCache[ keyA ];
  12522. if ( materialsForVariant === undefined ) {
  12523. materialsForVariant = {};
  12524. _materialCache[ keyA ] = materialsForVariant;
  12525. }
  12526. let cachedMaterial = materialsForVariant[ keyB ];
  12527. if ( cachedMaterial === undefined ) {
  12528. cachedMaterial = result.clone();
  12529. materialsForVariant[ keyB ] = cachedMaterial;
  12530. }
  12531. result = cachedMaterial;
  12532. }
  12533. result.visible = material.visible;
  12534. result.wireframe = material.wireframe;
  12535. if ( type === VSMShadowMap ) {
  12536. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12537. } else {
  12538. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12539. }
  12540. result.alphaMap = material.alphaMap;
  12541. result.alphaTest = material.alphaTest;
  12542. result.clipShadows = material.clipShadows;
  12543. result.clippingPlanes = material.clippingPlanes;
  12544. result.clipIntersection = material.clipIntersection;
  12545. result.displacementMap = material.displacementMap;
  12546. result.displacementScale = material.displacementScale;
  12547. result.displacementBias = material.displacementBias;
  12548. result.wireframeLinewidth = material.wireframeLinewidth;
  12549. result.linewidth = material.linewidth;
  12550. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12551. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12552. result.nearDistance = shadowCameraNear;
  12553. result.farDistance = shadowCameraFar;
  12554. }
  12555. return result;
  12556. }
  12557. function renderObject( object, camera, shadowCamera, light, type ) {
  12558. if ( object.visible === false ) return;
  12559. const visible = object.layers.test( camera.layers );
  12560. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12561. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12562. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12563. const geometry = _objects.update( object );
  12564. const material = object.material;
  12565. if ( Array.isArray( material ) ) {
  12566. const groups = geometry.groups;
  12567. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12568. const group = groups[ k ];
  12569. const groupMaterial = material[ group.materialIndex ];
  12570. if ( groupMaterial && groupMaterial.visible ) {
  12571. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12572. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12573. }
  12574. }
  12575. } else if ( material.visible ) {
  12576. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12577. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12578. }
  12579. }
  12580. }
  12581. const children = object.children;
  12582. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12583. renderObject( children[ i ], camera, shadowCamera, light, type );
  12584. }
  12585. }
  12586. }
  12587. function WebGLState( gl, extensions, capabilities ) {
  12588. const isWebGL2 = capabilities.isWebGL2;
  12589. function ColorBuffer() {
  12590. let locked = false;
  12591. const color = new Vector4();
  12592. let currentColorMask = null;
  12593. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12594. return {
  12595. setMask: function ( colorMask ) {
  12596. if ( currentColorMask !== colorMask && ! locked ) {
  12597. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12598. currentColorMask = colorMask;
  12599. }
  12600. },
  12601. setLocked: function ( lock ) {
  12602. locked = lock;
  12603. },
  12604. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12605. if ( premultipliedAlpha === true ) {
  12606. r *= a; g *= a; b *= a;
  12607. }
  12608. color.set( r, g, b, a );
  12609. if ( currentColorClear.equals( color ) === false ) {
  12610. gl.clearColor( r, g, b, a );
  12611. currentColorClear.copy( color );
  12612. }
  12613. },
  12614. reset: function () {
  12615. locked = false;
  12616. currentColorMask = null;
  12617. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12618. }
  12619. };
  12620. }
  12621. function DepthBuffer() {
  12622. let locked = false;
  12623. let currentDepthMask = null;
  12624. let currentDepthFunc = null;
  12625. let currentDepthClear = null;
  12626. return {
  12627. setTest: function ( depthTest ) {
  12628. if ( depthTest ) {
  12629. enable( 2929 );
  12630. } else {
  12631. disable( 2929 );
  12632. }
  12633. },
  12634. setMask: function ( depthMask ) {
  12635. if ( currentDepthMask !== depthMask && ! locked ) {
  12636. gl.depthMask( depthMask );
  12637. currentDepthMask = depthMask;
  12638. }
  12639. },
  12640. setFunc: function ( depthFunc ) {
  12641. if ( currentDepthFunc !== depthFunc ) {
  12642. if ( depthFunc ) {
  12643. switch ( depthFunc ) {
  12644. case NeverDepth:
  12645. gl.depthFunc( 512 );
  12646. break;
  12647. case AlwaysDepth:
  12648. gl.depthFunc( 519 );
  12649. break;
  12650. case LessDepth:
  12651. gl.depthFunc( 513 );
  12652. break;
  12653. case LessEqualDepth:
  12654. gl.depthFunc( 515 );
  12655. break;
  12656. case EqualDepth:
  12657. gl.depthFunc( 514 );
  12658. break;
  12659. case GreaterEqualDepth:
  12660. gl.depthFunc( 518 );
  12661. break;
  12662. case GreaterDepth:
  12663. gl.depthFunc( 516 );
  12664. break;
  12665. case NotEqualDepth:
  12666. gl.depthFunc( 517 );
  12667. break;
  12668. default:
  12669. gl.depthFunc( 515 );
  12670. }
  12671. } else {
  12672. gl.depthFunc( 515 );
  12673. }
  12674. currentDepthFunc = depthFunc;
  12675. }
  12676. },
  12677. setLocked: function ( lock ) {
  12678. locked = lock;
  12679. },
  12680. setClear: function ( depth ) {
  12681. if ( currentDepthClear !== depth ) {
  12682. gl.clearDepth( depth );
  12683. currentDepthClear = depth;
  12684. }
  12685. },
  12686. reset: function () {
  12687. locked = false;
  12688. currentDepthMask = null;
  12689. currentDepthFunc = null;
  12690. currentDepthClear = null;
  12691. }
  12692. };
  12693. }
  12694. function StencilBuffer() {
  12695. let locked = false;
  12696. let currentStencilMask = null;
  12697. let currentStencilFunc = null;
  12698. let currentStencilRef = null;
  12699. let currentStencilFuncMask = null;
  12700. let currentStencilFail = null;
  12701. let currentStencilZFail = null;
  12702. let currentStencilZPass = null;
  12703. let currentStencilClear = null;
  12704. return {
  12705. setTest: function ( stencilTest ) {
  12706. if ( ! locked ) {
  12707. if ( stencilTest ) {
  12708. enable( 2960 );
  12709. } else {
  12710. disable( 2960 );
  12711. }
  12712. }
  12713. },
  12714. setMask: function ( stencilMask ) {
  12715. if ( currentStencilMask !== stencilMask && ! locked ) {
  12716. gl.stencilMask( stencilMask );
  12717. currentStencilMask = stencilMask;
  12718. }
  12719. },
  12720. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12721. if ( currentStencilFunc !== stencilFunc ||
  12722. currentStencilRef !== stencilRef ||
  12723. currentStencilFuncMask !== stencilMask ) {
  12724. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12725. currentStencilFunc = stencilFunc;
  12726. currentStencilRef = stencilRef;
  12727. currentStencilFuncMask = stencilMask;
  12728. }
  12729. },
  12730. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12731. if ( currentStencilFail !== stencilFail ||
  12732. currentStencilZFail !== stencilZFail ||
  12733. currentStencilZPass !== stencilZPass ) {
  12734. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12735. currentStencilFail = stencilFail;
  12736. currentStencilZFail = stencilZFail;
  12737. currentStencilZPass = stencilZPass;
  12738. }
  12739. },
  12740. setLocked: function ( lock ) {
  12741. locked = lock;
  12742. },
  12743. setClear: function ( stencil ) {
  12744. if ( currentStencilClear !== stencil ) {
  12745. gl.clearStencil( stencil );
  12746. currentStencilClear = stencil;
  12747. }
  12748. },
  12749. reset: function () {
  12750. locked = false;
  12751. currentStencilMask = null;
  12752. currentStencilFunc = null;
  12753. currentStencilRef = null;
  12754. currentStencilFuncMask = null;
  12755. currentStencilFail = null;
  12756. currentStencilZFail = null;
  12757. currentStencilZPass = null;
  12758. currentStencilClear = null;
  12759. }
  12760. };
  12761. }
  12762. //
  12763. const colorBuffer = new ColorBuffer();
  12764. const depthBuffer = new DepthBuffer();
  12765. const stencilBuffer = new StencilBuffer();
  12766. let enabledCapabilities = {};
  12767. let currentBoundFramebuffers = {};
  12768. let currentProgram = null;
  12769. let currentBlendingEnabled = false;
  12770. let currentBlending = null;
  12771. let currentBlendEquation = null;
  12772. let currentBlendSrc = null;
  12773. let currentBlendDst = null;
  12774. let currentBlendEquationAlpha = null;
  12775. let currentBlendSrcAlpha = null;
  12776. let currentBlendDstAlpha = null;
  12777. let currentPremultipledAlpha = false;
  12778. let currentFlipSided = null;
  12779. let currentCullFace = null;
  12780. let currentLineWidth = null;
  12781. let currentPolygonOffsetFactor = null;
  12782. let currentPolygonOffsetUnits = null;
  12783. const maxTextures = gl.getParameter( 35661 );
  12784. let lineWidthAvailable = false;
  12785. let version = 0;
  12786. const glVersion = gl.getParameter( 7938 );
  12787. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12788. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12789. lineWidthAvailable = ( version >= 1.0 );
  12790. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12791. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12792. lineWidthAvailable = ( version >= 2.0 );
  12793. }
  12794. let currentTextureSlot = null;
  12795. let currentBoundTextures = {};
  12796. const scissorParam = gl.getParameter( 3088 );
  12797. const viewportParam = gl.getParameter( 2978 );
  12798. const currentScissor = new Vector4().fromArray( scissorParam );
  12799. const currentViewport = new Vector4().fromArray( viewportParam );
  12800. function createTexture( type, target, count ) {
  12801. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12802. const texture = gl.createTexture();
  12803. gl.bindTexture( type, texture );
  12804. gl.texParameteri( type, 10241, 9728 );
  12805. gl.texParameteri( type, 10240, 9728 );
  12806. for ( let i = 0; i < count; i ++ ) {
  12807. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12808. }
  12809. return texture;
  12810. }
  12811. const emptyTextures = {};
  12812. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12813. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12814. // init
  12815. colorBuffer.setClear( 0, 0, 0, 1 );
  12816. depthBuffer.setClear( 1 );
  12817. stencilBuffer.setClear( 0 );
  12818. enable( 2929 );
  12819. depthBuffer.setFunc( LessEqualDepth );
  12820. setFlipSided( false );
  12821. setCullFace( CullFaceBack );
  12822. enable( 2884 );
  12823. setBlending( NoBlending );
  12824. //
  12825. function enable( id ) {
  12826. if ( enabledCapabilities[ id ] !== true ) {
  12827. gl.enable( id );
  12828. enabledCapabilities[ id ] = true;
  12829. }
  12830. }
  12831. function disable( id ) {
  12832. if ( enabledCapabilities[ id ] !== false ) {
  12833. gl.disable( id );
  12834. enabledCapabilities[ id ] = false;
  12835. }
  12836. }
  12837. function bindFramebuffer( target, framebuffer ) {
  12838. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12839. gl.bindFramebuffer( target, framebuffer );
  12840. currentBoundFramebuffers[ target ] = framebuffer;
  12841. if ( isWebGL2 ) {
  12842. // 36009 is equivalent to 36160
  12843. if ( target === 36009 ) {
  12844. currentBoundFramebuffers[ 36160 ] = framebuffer;
  12845. }
  12846. if ( target === 36160 ) {
  12847. currentBoundFramebuffers[ 36009 ] = framebuffer;
  12848. }
  12849. }
  12850. return true;
  12851. }
  12852. return false;
  12853. }
  12854. function useProgram( program ) {
  12855. if ( currentProgram !== program ) {
  12856. gl.useProgram( program );
  12857. currentProgram = program;
  12858. return true;
  12859. }
  12860. return false;
  12861. }
  12862. const equationToGL = {
  12863. [ AddEquation ]: 32774,
  12864. [ SubtractEquation ]: 32778,
  12865. [ ReverseSubtractEquation ]: 32779
  12866. };
  12867. if ( isWebGL2 ) {
  12868. equationToGL[ MinEquation ] = 32775;
  12869. equationToGL[ MaxEquation ] = 32776;
  12870. } else {
  12871. const extension = extensions.get( 'EXT_blend_minmax' );
  12872. if ( extension !== null ) {
  12873. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12874. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12875. }
  12876. }
  12877. const factorToGL = {
  12878. [ ZeroFactor ]: 0,
  12879. [ OneFactor ]: 1,
  12880. [ SrcColorFactor ]: 768,
  12881. [ SrcAlphaFactor ]: 770,
  12882. [ SrcAlphaSaturateFactor ]: 776,
  12883. [ DstColorFactor ]: 774,
  12884. [ DstAlphaFactor ]: 772,
  12885. [ OneMinusSrcColorFactor ]: 769,
  12886. [ OneMinusSrcAlphaFactor ]: 771,
  12887. [ OneMinusDstColorFactor ]: 775,
  12888. [ OneMinusDstAlphaFactor ]: 773
  12889. };
  12890. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12891. if ( blending === NoBlending ) {
  12892. if ( currentBlendingEnabled === true ) {
  12893. disable( 3042 );
  12894. currentBlendingEnabled = false;
  12895. }
  12896. return;
  12897. }
  12898. if ( currentBlendingEnabled === false ) {
  12899. enable( 3042 );
  12900. currentBlendingEnabled = true;
  12901. }
  12902. if ( blending !== CustomBlending ) {
  12903. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12904. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12905. gl.blendEquation( 32774 );
  12906. currentBlendEquation = AddEquation;
  12907. currentBlendEquationAlpha = AddEquation;
  12908. }
  12909. if ( premultipliedAlpha ) {
  12910. switch ( blending ) {
  12911. case NormalBlending:
  12912. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12913. break;
  12914. case AdditiveBlending:
  12915. gl.blendFunc( 1, 1 );
  12916. break;
  12917. case SubtractiveBlending:
  12918. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12919. break;
  12920. case MultiplyBlending:
  12921. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12922. break;
  12923. default:
  12924. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12925. break;
  12926. }
  12927. } else {
  12928. switch ( blending ) {
  12929. case NormalBlending:
  12930. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12931. break;
  12932. case AdditiveBlending:
  12933. gl.blendFunc( 770, 1 );
  12934. break;
  12935. case SubtractiveBlending:
  12936. gl.blendFunc( 0, 769 );
  12937. break;
  12938. case MultiplyBlending:
  12939. gl.blendFunc( 0, 768 );
  12940. break;
  12941. default:
  12942. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12943. break;
  12944. }
  12945. }
  12946. currentBlendSrc = null;
  12947. currentBlendDst = null;
  12948. currentBlendSrcAlpha = null;
  12949. currentBlendDstAlpha = null;
  12950. currentBlending = blending;
  12951. currentPremultipledAlpha = premultipliedAlpha;
  12952. }
  12953. return;
  12954. }
  12955. // custom blending
  12956. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12957. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12958. blendDstAlpha = blendDstAlpha || blendDst;
  12959. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12960. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12961. currentBlendEquation = blendEquation;
  12962. currentBlendEquationAlpha = blendEquationAlpha;
  12963. }
  12964. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12965. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12966. currentBlendSrc = blendSrc;
  12967. currentBlendDst = blendDst;
  12968. currentBlendSrcAlpha = blendSrcAlpha;
  12969. currentBlendDstAlpha = blendDstAlpha;
  12970. }
  12971. currentBlending = blending;
  12972. currentPremultipledAlpha = null;
  12973. }
  12974. function setMaterial( material, frontFaceCW ) {
  12975. material.side === DoubleSide
  12976. ? disable( 2884 )
  12977. : enable( 2884 );
  12978. let flipSided = ( material.side === BackSide );
  12979. if ( frontFaceCW ) flipSided = ! flipSided;
  12980. setFlipSided( flipSided );
  12981. ( material.blending === NormalBlending && material.transparent === false )
  12982. ? setBlending( NoBlending )
  12983. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12984. depthBuffer.setFunc( material.depthFunc );
  12985. depthBuffer.setTest( material.depthTest );
  12986. depthBuffer.setMask( material.depthWrite );
  12987. colorBuffer.setMask( material.colorWrite );
  12988. const stencilWrite = material.stencilWrite;
  12989. stencilBuffer.setTest( stencilWrite );
  12990. if ( stencilWrite ) {
  12991. stencilBuffer.setMask( material.stencilWriteMask );
  12992. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12993. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12994. }
  12995. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12996. material.alphaToCoverage === true
  12997. ? enable( 32926 )
  12998. : disable( 32926 );
  12999. }
  13000. //
  13001. function setFlipSided( flipSided ) {
  13002. if ( currentFlipSided !== flipSided ) {
  13003. if ( flipSided ) {
  13004. gl.frontFace( 2304 );
  13005. } else {
  13006. gl.frontFace( 2305 );
  13007. }
  13008. currentFlipSided = flipSided;
  13009. }
  13010. }
  13011. function setCullFace( cullFace ) {
  13012. if ( cullFace !== CullFaceNone ) {
  13013. enable( 2884 );
  13014. if ( cullFace !== currentCullFace ) {
  13015. if ( cullFace === CullFaceBack ) {
  13016. gl.cullFace( 1029 );
  13017. } else if ( cullFace === CullFaceFront ) {
  13018. gl.cullFace( 1028 );
  13019. } else {
  13020. gl.cullFace( 1032 );
  13021. }
  13022. }
  13023. } else {
  13024. disable( 2884 );
  13025. }
  13026. currentCullFace = cullFace;
  13027. }
  13028. function setLineWidth( width ) {
  13029. if ( width !== currentLineWidth ) {
  13030. if ( lineWidthAvailable ) gl.lineWidth( width );
  13031. currentLineWidth = width;
  13032. }
  13033. }
  13034. function setPolygonOffset( polygonOffset, factor, units ) {
  13035. if ( polygonOffset ) {
  13036. enable( 32823 );
  13037. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13038. gl.polygonOffset( factor, units );
  13039. currentPolygonOffsetFactor = factor;
  13040. currentPolygonOffsetUnits = units;
  13041. }
  13042. } else {
  13043. disable( 32823 );
  13044. }
  13045. }
  13046. function setScissorTest( scissorTest ) {
  13047. if ( scissorTest ) {
  13048. enable( 3089 );
  13049. } else {
  13050. disable( 3089 );
  13051. }
  13052. }
  13053. // texture
  13054. function activeTexture( webglSlot ) {
  13055. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13056. if ( currentTextureSlot !== webglSlot ) {
  13057. gl.activeTexture( webglSlot );
  13058. currentTextureSlot = webglSlot;
  13059. }
  13060. }
  13061. function bindTexture( webglType, webglTexture ) {
  13062. if ( currentTextureSlot === null ) {
  13063. activeTexture();
  13064. }
  13065. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  13066. if ( boundTexture === undefined ) {
  13067. boundTexture = { type: undefined, texture: undefined };
  13068. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  13069. }
  13070. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13071. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13072. boundTexture.type = webglType;
  13073. boundTexture.texture = webglTexture;
  13074. }
  13075. }
  13076. function unbindTexture() {
  13077. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13078. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13079. gl.bindTexture( boundTexture.type, null );
  13080. boundTexture.type = undefined;
  13081. boundTexture.texture = undefined;
  13082. }
  13083. }
  13084. function compressedTexImage2D() {
  13085. try {
  13086. gl.compressedTexImage2D.apply( gl, arguments );
  13087. } catch ( error ) {
  13088. console.error( 'THREE.WebGLState:', error );
  13089. }
  13090. }
  13091. function texSubImage2D() {
  13092. try {
  13093. gl.texSubImage2D.apply( gl, arguments );
  13094. } catch ( error ) {
  13095. console.error( 'THREE.WebGLState:', error );
  13096. }
  13097. }
  13098. function texStorage2D() {
  13099. try {
  13100. gl.texStorage2D.apply( gl, arguments );
  13101. } catch ( error ) {
  13102. console.error( 'THREE.WebGLState:', error );
  13103. }
  13104. }
  13105. function texImage2D() {
  13106. try {
  13107. gl.texImage2D.apply( gl, arguments );
  13108. } catch ( error ) {
  13109. console.error( 'THREE.WebGLState:', error );
  13110. }
  13111. }
  13112. function texImage3D() {
  13113. try {
  13114. gl.texImage3D.apply( gl, arguments );
  13115. } catch ( error ) {
  13116. console.error( 'THREE.WebGLState:', error );
  13117. }
  13118. }
  13119. //
  13120. function scissor( scissor ) {
  13121. if ( currentScissor.equals( scissor ) === false ) {
  13122. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13123. currentScissor.copy( scissor );
  13124. }
  13125. }
  13126. function viewport( viewport ) {
  13127. if ( currentViewport.equals( viewport ) === false ) {
  13128. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13129. currentViewport.copy( viewport );
  13130. }
  13131. }
  13132. //
  13133. function reset() {
  13134. // reset state
  13135. gl.disable( 3042 );
  13136. gl.disable( 2884 );
  13137. gl.disable( 2929 );
  13138. gl.disable( 32823 );
  13139. gl.disable( 3089 );
  13140. gl.disable( 2960 );
  13141. gl.disable( 32926 );
  13142. gl.blendEquation( 32774 );
  13143. gl.blendFunc( 1, 0 );
  13144. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13145. gl.colorMask( true, true, true, true );
  13146. gl.clearColor( 0, 0, 0, 0 );
  13147. gl.depthMask( true );
  13148. gl.depthFunc( 513 );
  13149. gl.clearDepth( 1 );
  13150. gl.stencilMask( 0xffffffff );
  13151. gl.stencilFunc( 519, 0, 0xffffffff );
  13152. gl.stencilOp( 7680, 7680, 7680 );
  13153. gl.clearStencil( 0 );
  13154. gl.cullFace( 1029 );
  13155. gl.frontFace( 2305 );
  13156. gl.polygonOffset( 0, 0 );
  13157. gl.activeTexture( 33984 );
  13158. gl.bindFramebuffer( 36160, null );
  13159. if ( isWebGL2 === true ) {
  13160. gl.bindFramebuffer( 36009, null );
  13161. gl.bindFramebuffer( 36008, null );
  13162. }
  13163. gl.useProgram( null );
  13164. gl.lineWidth( 1 );
  13165. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13166. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13167. // reset internals
  13168. enabledCapabilities = {};
  13169. currentTextureSlot = null;
  13170. currentBoundTextures = {};
  13171. currentBoundFramebuffers = {};
  13172. currentProgram = null;
  13173. currentBlendingEnabled = false;
  13174. currentBlending = null;
  13175. currentBlendEquation = null;
  13176. currentBlendSrc = null;
  13177. currentBlendDst = null;
  13178. currentBlendEquationAlpha = null;
  13179. currentBlendSrcAlpha = null;
  13180. currentBlendDstAlpha = null;
  13181. currentPremultipledAlpha = false;
  13182. currentFlipSided = null;
  13183. currentCullFace = null;
  13184. currentLineWidth = null;
  13185. currentPolygonOffsetFactor = null;
  13186. currentPolygonOffsetUnits = null;
  13187. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13188. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13189. colorBuffer.reset();
  13190. depthBuffer.reset();
  13191. stencilBuffer.reset();
  13192. }
  13193. return {
  13194. buffers: {
  13195. color: colorBuffer,
  13196. depth: depthBuffer,
  13197. stencil: stencilBuffer
  13198. },
  13199. enable: enable,
  13200. disable: disable,
  13201. bindFramebuffer: bindFramebuffer,
  13202. useProgram: useProgram,
  13203. setBlending: setBlending,
  13204. setMaterial: setMaterial,
  13205. setFlipSided: setFlipSided,
  13206. setCullFace: setCullFace,
  13207. setLineWidth: setLineWidth,
  13208. setPolygonOffset: setPolygonOffset,
  13209. setScissorTest: setScissorTest,
  13210. activeTexture: activeTexture,
  13211. bindTexture: bindTexture,
  13212. unbindTexture: unbindTexture,
  13213. compressedTexImage2D: compressedTexImage2D,
  13214. texImage2D: texImage2D,
  13215. texImage3D: texImage3D,
  13216. texStorage2D: texStorage2D,
  13217. texSubImage2D: texSubImage2D,
  13218. scissor: scissor,
  13219. viewport: viewport,
  13220. reset: reset
  13221. };
  13222. }
  13223. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13224. const isWebGL2 = capabilities.isWebGL2;
  13225. const maxTextures = capabilities.maxTextures;
  13226. const maxCubemapSize = capabilities.maxCubemapSize;
  13227. const maxTextureSize = capabilities.maxTextureSize;
  13228. const maxSamples = capabilities.maxSamples;
  13229. const hasMultisampledRenderToTexture = extensions.has( 'WEBGL_multisampled_render_to_texture' );
  13230. const MultisampledRenderToTextureExtension = hasMultisampledRenderToTexture ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : undefined;
  13231. const _videoTextures = new WeakMap();
  13232. let _canvas;
  13233. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13234. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13235. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13236. let useOffscreenCanvas = false;
  13237. try {
  13238. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13239. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13240. } catch ( err ) {
  13241. // Ignore any errors
  13242. }
  13243. function createCanvas( width, height ) {
  13244. // Use OffscreenCanvas when available. Specially needed in web workers
  13245. return useOffscreenCanvas ?
  13246. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13247. }
  13248. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13249. let scale = 1;
  13250. // handle case if texture exceeds max size
  13251. if ( image.width > maxSize || image.height > maxSize ) {
  13252. scale = maxSize / Math.max( image.width, image.height );
  13253. }
  13254. // only perform resize if necessary
  13255. if ( scale < 1 || needsPowerOfTwo === true ) {
  13256. // only perform resize for certain image types
  13257. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13258. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13259. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13260. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13261. const width = floor( scale * image.width );
  13262. const height = floor( scale * image.height );
  13263. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13264. // cube textures can't reuse the same canvas
  13265. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13266. canvas.width = width;
  13267. canvas.height = height;
  13268. const context = canvas.getContext( '2d' );
  13269. context.drawImage( image, 0, 0, width, height );
  13270. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13271. return canvas;
  13272. } else {
  13273. if ( 'data' in image ) {
  13274. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13275. }
  13276. return image;
  13277. }
  13278. }
  13279. return image;
  13280. }
  13281. function isPowerOfTwo$1( image ) {
  13282. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13283. }
  13284. function textureNeedsPowerOfTwo( texture ) {
  13285. if ( isWebGL2 ) return false;
  13286. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13287. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13288. }
  13289. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13290. return texture.generateMipmaps && supportsMips &&
  13291. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13292. }
  13293. function generateMipmap( target ) {
  13294. _gl.generateMipmap( target );
  13295. }
  13296. function getInternalFormat( internalFormatName, glFormat, glType/*, encoding*/ ) {
  13297. if ( isWebGL2 === false ) return glFormat;
  13298. if ( internalFormatName !== null ) {
  13299. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13300. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13301. }
  13302. let internalFormat = glFormat;
  13303. if ( glFormat === 6403 ) {
  13304. if ( glType === 5126 ) internalFormat = 33326;
  13305. if ( glType === 5131 ) internalFormat = 33325;
  13306. if ( glType === 5121 ) internalFormat = 33321;
  13307. }
  13308. if ( glFormat === 6407 ) {
  13309. if ( glType === 5126 ) internalFormat = 34837;
  13310. if ( glType === 5131 ) internalFormat = 34843;
  13311. if ( glType === 5121 ) internalFormat = 32849;
  13312. }
  13313. if ( glFormat === 6408 ) {
  13314. if ( glType === 5126 ) internalFormat = 34836;
  13315. if ( glType === 5131 ) internalFormat = 34842;
  13316. //if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding ) ? 35907 : 32856;
  13317. if ( glType === 5121 ) internalFormat = 32856;
  13318. }
  13319. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13320. internalFormat === 34842 || internalFormat === 34836 ) {
  13321. extensions.get( 'EXT_color_buffer_float' );
  13322. }
  13323. return internalFormat;
  13324. }
  13325. function getMipLevels( texture, image, supportsMips ) {
  13326. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true ) {
  13327. // generated mipmaps via gl.generateMipmap()
  13328. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13329. } else if ( texture.mipmaps.length > 0 ) {
  13330. // user-defined mipmaps
  13331. return texture.mipmaps.length;
  13332. } else {
  13333. // texture without mipmaps (only base level)
  13334. return 1;
  13335. }
  13336. }
  13337. // Fallback filters for non-power-of-2 textures
  13338. function filterFallback( f ) {
  13339. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13340. return 9728;
  13341. }
  13342. return 9729;
  13343. }
  13344. //
  13345. function onTextureDispose( event ) {
  13346. const texture = event.target;
  13347. texture.removeEventListener( 'dispose', onTextureDispose );
  13348. deallocateTexture( texture );
  13349. if ( texture.isVideoTexture ) {
  13350. _videoTextures.delete( texture );
  13351. }
  13352. info.memory.textures --;
  13353. }
  13354. function onRenderTargetDispose( event ) {
  13355. const renderTarget = event.target;
  13356. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13357. deallocateRenderTarget( renderTarget );
  13358. }
  13359. //
  13360. function deallocateTexture( texture ) {
  13361. const textureProperties = properties.get( texture );
  13362. if ( textureProperties.__webglInit === undefined ) return;
  13363. _gl.deleteTexture( textureProperties.__webglTexture );
  13364. properties.remove( texture );
  13365. }
  13366. function deallocateRenderTarget( renderTarget ) {
  13367. const texture = renderTarget.texture;
  13368. const renderTargetProperties = properties.get( renderTarget );
  13369. const textureProperties = properties.get( texture );
  13370. if ( ! renderTarget ) return;
  13371. if ( textureProperties.__webglTexture !== undefined ) {
  13372. _gl.deleteTexture( textureProperties.__webglTexture );
  13373. info.memory.textures --;
  13374. }
  13375. if ( renderTarget.depthTexture ) {
  13376. renderTarget.depthTexture.dispose();
  13377. }
  13378. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13379. for ( let i = 0; i < 6; i ++ ) {
  13380. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13381. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13382. }
  13383. } else {
  13384. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13385. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13386. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13387. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13388. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13389. }
  13390. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13391. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13392. const attachmentProperties = properties.get( texture[ i ] );
  13393. if ( attachmentProperties.__webglTexture ) {
  13394. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13395. info.memory.textures --;
  13396. }
  13397. properties.remove( texture[ i ] );
  13398. }
  13399. }
  13400. properties.remove( texture );
  13401. properties.remove( renderTarget );
  13402. }
  13403. //
  13404. let textureUnits = 0;
  13405. function resetTextureUnits() {
  13406. textureUnits = 0;
  13407. }
  13408. function allocateTextureUnit() {
  13409. const textureUnit = textureUnits;
  13410. if ( textureUnit >= maxTextures ) {
  13411. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13412. }
  13413. textureUnits += 1;
  13414. return textureUnit;
  13415. }
  13416. //
  13417. function setTexture2D( texture, slot ) {
  13418. const textureProperties = properties.get( texture );
  13419. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13420. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13421. const image = texture.image;
  13422. if ( image === undefined ) {
  13423. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13424. } else if ( image.complete === false ) {
  13425. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13426. } else {
  13427. uploadTexture( textureProperties, texture, slot );
  13428. return;
  13429. }
  13430. }
  13431. state.activeTexture( 33984 + slot );
  13432. state.bindTexture( 3553, textureProperties.__webglTexture );
  13433. }
  13434. function setTexture2DArray( texture, slot ) {
  13435. const textureProperties = properties.get( texture );
  13436. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13437. uploadTexture( textureProperties, texture, slot );
  13438. return;
  13439. }
  13440. state.activeTexture( 33984 + slot );
  13441. state.bindTexture( 35866, textureProperties.__webglTexture );
  13442. }
  13443. function setTexture3D( texture, slot ) {
  13444. const textureProperties = properties.get( texture );
  13445. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13446. uploadTexture( textureProperties, texture, slot );
  13447. return;
  13448. }
  13449. state.activeTexture( 33984 + slot );
  13450. state.bindTexture( 32879, textureProperties.__webglTexture );
  13451. }
  13452. function setTextureCube( texture, slot ) {
  13453. const textureProperties = properties.get( texture );
  13454. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13455. uploadCubeTexture( textureProperties, texture, slot );
  13456. return;
  13457. }
  13458. state.activeTexture( 33984 + slot );
  13459. state.bindTexture( 34067, textureProperties.__webglTexture );
  13460. }
  13461. const wrappingToGL = {
  13462. [ RepeatWrapping ]: 10497,
  13463. [ ClampToEdgeWrapping ]: 33071,
  13464. [ MirroredRepeatWrapping ]: 33648
  13465. };
  13466. const filterToGL = {
  13467. [ NearestFilter ]: 9728,
  13468. [ NearestMipmapNearestFilter ]: 9984,
  13469. [ NearestMipmapLinearFilter ]: 9986,
  13470. [ LinearFilter ]: 9729,
  13471. [ LinearMipmapNearestFilter ]: 9985,
  13472. [ LinearMipmapLinearFilter ]: 9987
  13473. };
  13474. function setTextureParameters( textureType, texture, supportsMips ) {
  13475. if ( supportsMips ) {
  13476. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13477. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13478. if ( textureType === 32879 || textureType === 35866 ) {
  13479. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13480. }
  13481. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13482. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13483. } else {
  13484. _gl.texParameteri( textureType, 10242, 33071 );
  13485. _gl.texParameteri( textureType, 10243, 33071 );
  13486. if ( textureType === 32879 || textureType === 35866 ) {
  13487. _gl.texParameteri( textureType, 32882, 33071 );
  13488. }
  13489. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13490. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13491. }
  13492. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13493. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13494. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13495. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13496. }
  13497. }
  13498. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13499. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13500. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13501. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13502. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13503. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13504. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13505. }
  13506. }
  13507. }
  13508. function initTexture( textureProperties, texture ) {
  13509. if ( textureProperties.__webglInit === undefined ) {
  13510. textureProperties.__webglInit = true;
  13511. texture.addEventListener( 'dispose', onTextureDispose );
  13512. textureProperties.__webglTexture = _gl.createTexture();
  13513. info.memory.textures ++;
  13514. }
  13515. }
  13516. function uploadTexture( textureProperties, texture, slot ) {
  13517. let textureType = 3553;
  13518. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13519. if ( texture.isDataTexture3D ) textureType = 32879;
  13520. initTexture( textureProperties, texture );
  13521. state.activeTexture( 33984 + slot );
  13522. state.bindTexture( textureType, textureProperties.__webglTexture );
  13523. _gl.pixelStorei( 37440, texture.flipY );
  13524. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13525. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13526. _gl.pixelStorei( 37443, 0 );
  13527. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13528. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13529. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13530. glFormat = utils.convert( texture.format );
  13531. let glType = utils.convert( texture.type ),
  13532. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13533. setTextureParameters( textureType, texture, supportsMips );
  13534. let mipmap;
  13535. const mipmaps = texture.mipmaps;
  13536. if ( texture.isDepthTexture ) {
  13537. // populate depth texture with dummy data
  13538. glInternalFormat = 6402;
  13539. if ( isWebGL2 ) {
  13540. if ( texture.type === FloatType ) {
  13541. glInternalFormat = 36012;
  13542. } else if ( texture.type === UnsignedIntType ) {
  13543. glInternalFormat = 33190;
  13544. } else if ( texture.type === UnsignedInt248Type ) {
  13545. glInternalFormat = 35056;
  13546. } else {
  13547. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13548. }
  13549. } else {
  13550. if ( texture.type === FloatType ) {
  13551. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13552. }
  13553. }
  13554. // validation checks for WebGL 1
  13555. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13556. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13557. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13558. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13559. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13560. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13561. texture.type = UnsignedShortType;
  13562. glType = utils.convert( texture.type );
  13563. }
  13564. }
  13565. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13566. // Depth stencil textures need the DEPTH_STENCIL internal format
  13567. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13568. glInternalFormat = 34041;
  13569. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13570. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13571. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13572. if ( texture.type !== UnsignedInt248Type ) {
  13573. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13574. texture.type = UnsignedInt248Type;
  13575. glType = utils.convert( texture.type );
  13576. }
  13577. }
  13578. //
  13579. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13580. } else if ( texture.isDataTexture ) {
  13581. // use manually created mipmaps if available
  13582. // if there are no manual mipmaps
  13583. // set 0 level mipmap and then use GL to generate other mipmap levels
  13584. if ( mipmaps.length > 0 && supportsMips ) {
  13585. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13586. mipmap = mipmaps[ i ];
  13587. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13588. }
  13589. texture.generateMipmaps = false;
  13590. } else {
  13591. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13592. }
  13593. } else if ( texture.isCompressedTexture ) {
  13594. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13595. mipmap = mipmaps[ i ];
  13596. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13597. if ( glFormat !== null ) {
  13598. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13599. } else {
  13600. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13601. }
  13602. } else {
  13603. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13604. }
  13605. }
  13606. } else if ( texture.isDataTexture2DArray ) {
  13607. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13608. } else if ( texture.isDataTexture3D ) {
  13609. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13610. } else {
  13611. // regular Texture (image, video, canvas)
  13612. // use manually created mipmaps if available
  13613. // if there are no manual mipmaps
  13614. // set 0 level mipmap and then use GL to generate other mipmap levels
  13615. const levels = getMipLevels( texture, image, supportsMips );
  13616. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13617. const allocateMemory = ( textureProperties.__version === undefined );
  13618. if ( mipmaps.length > 0 && supportsMips ) {
  13619. if ( useTexStorage && allocateMemory ) {
  13620. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13621. }
  13622. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13623. mipmap = mipmaps[ i ];
  13624. if ( useTexStorage ) {
  13625. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  13626. } else {
  13627. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13628. }
  13629. }
  13630. texture.generateMipmaps = false;
  13631. } else {
  13632. if ( useTexStorage ) {
  13633. if ( allocateMemory ) {
  13634. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13635. }
  13636. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  13637. } else {
  13638. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13639. }
  13640. }
  13641. }
  13642. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13643. generateMipmap( textureType );
  13644. }
  13645. textureProperties.__version = texture.version;
  13646. if ( texture.onUpdate ) texture.onUpdate( texture );
  13647. }
  13648. function uploadCubeTexture( textureProperties, texture, slot ) {
  13649. if ( texture.image.length !== 6 ) return;
  13650. initTexture( textureProperties, texture );
  13651. state.activeTexture( 33984 + slot );
  13652. state.bindTexture( 34067, textureProperties.__webglTexture );
  13653. _gl.pixelStorei( 37440, texture.flipY );
  13654. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13655. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13656. _gl.pixelStorei( 37443, 0 );
  13657. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13658. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13659. const cubeImage = [];
  13660. for ( let i = 0; i < 6; i ++ ) {
  13661. if ( ! isCompressed && ! isDataTexture ) {
  13662. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13663. } else {
  13664. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13665. }
  13666. }
  13667. const image = cubeImage[ 0 ],
  13668. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13669. glFormat = utils.convert( texture.format ),
  13670. glType = utils.convert( texture.type ),
  13671. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13672. setTextureParameters( 34067, texture, supportsMips );
  13673. let mipmaps;
  13674. if ( isCompressed ) {
  13675. for ( let i = 0; i < 6; i ++ ) {
  13676. mipmaps = cubeImage[ i ].mipmaps;
  13677. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13678. const mipmap = mipmaps[ j ];
  13679. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13680. if ( glFormat !== null ) {
  13681. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13682. } else {
  13683. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13684. }
  13685. } else {
  13686. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13687. }
  13688. }
  13689. }
  13690. } else {
  13691. mipmaps = texture.mipmaps;
  13692. for ( let i = 0; i < 6; i ++ ) {
  13693. if ( isDataTexture ) {
  13694. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13695. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13696. const mipmap = mipmaps[ j ];
  13697. const mipmapImage = mipmap.image[ i ].image;
  13698. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13699. }
  13700. } else {
  13701. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13702. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13703. const mipmap = mipmaps[ j ];
  13704. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13705. }
  13706. }
  13707. }
  13708. }
  13709. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13710. // We assume images for cube map have the same size.
  13711. generateMipmap( 34067 );
  13712. }
  13713. textureProperties.__version = texture.version;
  13714. if ( texture.onUpdate ) texture.onUpdate( texture );
  13715. }
  13716. // Render targets
  13717. // Setup storage for target texture and bind it to correct framebuffer
  13718. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  13719. const glFormat = utils.convert( texture.format );
  13720. const glType = utils.convert( texture.type );
  13721. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13722. const renderTargetProperties = properties.get( renderTarget );
  13723. if ( ! renderTargetProperties.__hasExternalTextures ) {
  13724. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  13725. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  13726. } else {
  13727. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13728. }
  13729. }
  13730. state.bindFramebuffer( 36160, framebuffer );
  13731. if ( renderTarget.useRenderToTexture ) {
  13732. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  13733. } else {
  13734. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  13735. }
  13736. state.bindFramebuffer( 36160, null );
  13737. }
  13738. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13739. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13740. _gl.bindRenderbuffer( 36161, renderbuffer );
  13741. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13742. let glInternalFormat = 33189;
  13743. if ( isMultisample || renderTarget.useRenderToTexture ) {
  13744. const depthTexture = renderTarget.depthTexture;
  13745. if ( depthTexture && depthTexture.isDepthTexture ) {
  13746. if ( depthTexture.type === FloatType ) {
  13747. glInternalFormat = 36012;
  13748. } else if ( depthTexture.type === UnsignedIntType ) {
  13749. glInternalFormat = 33190;
  13750. }
  13751. }
  13752. const samples = getRenderTargetSamples( renderTarget );
  13753. if ( renderTarget.useRenderToTexture ) {
  13754. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13755. } else {
  13756. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13757. }
  13758. } else {
  13759. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13760. }
  13761. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13762. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13763. const samples = getRenderTargetSamples( renderTarget );
  13764. if ( isMultisample && renderTarget.useRenderbuffer ) {
  13765. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13766. } else if ( renderTarget.useRenderToTexture ) {
  13767. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13768. } else {
  13769. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13770. }
  13771. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13772. } else {
  13773. // Use the first texture for MRT so far
  13774. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  13775. const glFormat = utils.convert( texture.format );
  13776. const glType = utils.convert( texture.type );
  13777. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13778. const samples = getRenderTargetSamples( renderTarget );
  13779. if ( isMultisample && renderTarget.useRenderbuffer ) {
  13780. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13781. } else if ( renderTarget.useRenderToTexture ) {
  13782. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13783. } else {
  13784. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13785. }
  13786. }
  13787. _gl.bindRenderbuffer( 36161, null );
  13788. }
  13789. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13790. function setupDepthTexture( framebuffer, renderTarget ) {
  13791. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13792. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13793. state.bindFramebuffer( 36160, framebuffer );
  13794. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13795. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13796. }
  13797. // upload an empty depth texture with framebuffer size
  13798. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13799. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13800. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13801. renderTarget.depthTexture.image.width = renderTarget.width;
  13802. renderTarget.depthTexture.image.height = renderTarget.height;
  13803. renderTarget.depthTexture.needsUpdate = true;
  13804. }
  13805. setTexture2D( renderTarget.depthTexture, 0 );
  13806. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13807. const samples = getRenderTargetSamples( renderTarget );
  13808. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13809. if ( renderTarget.useRenderToTexture ) {
  13810. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  13811. } else {
  13812. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13813. }
  13814. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13815. if ( renderTarget.useRenderToTexture ) {
  13816. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  13817. } else {
  13818. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13819. }
  13820. } else {
  13821. throw new Error( 'Unknown depthTexture format' );
  13822. }
  13823. }
  13824. // Setup GL resources for a non-texture depth buffer
  13825. function setupDepthRenderbuffer( renderTarget ) {
  13826. const renderTargetProperties = properties.get( renderTarget );
  13827. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13828. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  13829. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13830. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13831. } else {
  13832. if ( isCube ) {
  13833. renderTargetProperties.__webglDepthbuffer = [];
  13834. for ( let i = 0; i < 6; i ++ ) {
  13835. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13836. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13837. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13838. }
  13839. } else {
  13840. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13841. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13842. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13843. }
  13844. }
  13845. state.bindFramebuffer( 36160, null );
  13846. }
  13847. // rebind framebuffer with external textures
  13848. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  13849. const renderTargetProperties = properties.get( renderTarget );
  13850. if ( colorTexture !== undefined ) {
  13851. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  13852. }
  13853. if ( depthTexture !== undefined ) {
  13854. setupDepthRenderbuffer( renderTarget );
  13855. }
  13856. }
  13857. // Set up GL resources for the render target
  13858. function setupRenderTarget( renderTarget ) {
  13859. const texture = renderTarget.texture;
  13860. const renderTargetProperties = properties.get( renderTarget );
  13861. const textureProperties = properties.get( texture );
  13862. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13863. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  13864. if ( textureProperties.__webglTexture === undefined ) {
  13865. textureProperties.__webglTexture = _gl.createTexture();
  13866. }
  13867. textureProperties.__version = texture.version;
  13868. info.memory.textures ++;
  13869. }
  13870. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13871. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  13872. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13873. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  13874. // Handles WebGL2 RGBFormat fallback - #18858
  13875. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  13876. texture.format = RGBAFormat;
  13877. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13878. }
  13879. // Setup framebuffer
  13880. if ( isCube ) {
  13881. renderTargetProperties.__webglFramebuffer = [];
  13882. for ( let i = 0; i < 6; i ++ ) {
  13883. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13884. }
  13885. } else {
  13886. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13887. if ( isMultipleRenderTargets ) {
  13888. if ( capabilities.drawBuffers ) {
  13889. const textures = renderTarget.texture;
  13890. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13891. const attachmentProperties = properties.get( textures[ i ] );
  13892. if ( attachmentProperties.__webglTexture === undefined ) {
  13893. attachmentProperties.__webglTexture = _gl.createTexture();
  13894. info.memory.textures ++;
  13895. }
  13896. }
  13897. } else {
  13898. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  13899. }
  13900. } else if ( renderTarget.useRenderbuffer ) {
  13901. if ( isWebGL2 ) {
  13902. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13903. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13904. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13905. const glFormat = utils.convert( texture.format );
  13906. const glType = utils.convert( texture.type );
  13907. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13908. const samples = getRenderTargetSamples( renderTarget );
  13909. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13910. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13911. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13912. _gl.bindRenderbuffer( 36161, null );
  13913. if ( renderTarget.depthBuffer ) {
  13914. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13915. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13916. }
  13917. state.bindFramebuffer( 36160, null );
  13918. } else {
  13919. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13920. }
  13921. }
  13922. }
  13923. // Setup color buffer
  13924. if ( isCube ) {
  13925. state.bindTexture( 34067, textureProperties.__webglTexture );
  13926. setTextureParameters( 34067, texture, supportsMips );
  13927. for ( let i = 0; i < 6; i ++ ) {
  13928. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  13929. }
  13930. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13931. generateMipmap( 34067 );
  13932. }
  13933. state.unbindTexture();
  13934. } else if ( isMultipleRenderTargets ) {
  13935. const textures = renderTarget.texture;
  13936. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13937. const attachment = textures[ i ];
  13938. const attachmentProperties = properties.get( attachment );
  13939. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  13940. setTextureParameters( 3553, attachment, supportsMips );
  13941. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  13942. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  13943. generateMipmap( 3553 );
  13944. }
  13945. }
  13946. state.unbindTexture();
  13947. } else {
  13948. let glTextureType = 3553;
  13949. if ( isRenderTarget3D ) {
  13950. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13951. if ( isWebGL2 ) {
  13952. const isTexture3D = texture.isDataTexture3D;
  13953. glTextureType = isTexture3D ? 32879 : 35866;
  13954. } else {
  13955. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  13956. }
  13957. }
  13958. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  13959. setTextureParameters( glTextureType, texture, supportsMips );
  13960. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  13961. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13962. generateMipmap( glTextureType );
  13963. }
  13964. state.unbindTexture();
  13965. }
  13966. // Setup depth and stencil buffers
  13967. if ( renderTarget.depthBuffer ) {
  13968. setupDepthRenderbuffer( renderTarget );
  13969. }
  13970. }
  13971. function updateRenderTargetMipmap( renderTarget ) {
  13972. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  13973. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  13974. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13975. const texture = textures[ i ];
  13976. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13977. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13978. const webglTexture = properties.get( texture ).__webglTexture;
  13979. state.bindTexture( target, webglTexture );
  13980. generateMipmap( target );
  13981. state.unbindTexture();
  13982. }
  13983. }
  13984. }
  13985. function updateMultisampleRenderTarget( renderTarget ) {
  13986. if ( renderTarget.useRenderbuffer ) {
  13987. if ( isWebGL2 ) {
  13988. const width = renderTarget.width;
  13989. const height = renderTarget.height;
  13990. let mask = 16384;
  13991. const invalidationArray = [ 36064 ];
  13992. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  13993. if ( renderTarget.depthBuffer ) {
  13994. invalidationArray.push( depthStyle );
  13995. }
  13996. if ( ! renderTarget.ignoreDepthForMultisampleCopy ) {
  13997. if ( renderTarget.depthBuffer ) mask |= 256;
  13998. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13999. }
  14000. const renderTargetProperties = properties.get( renderTarget );
  14001. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14002. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14003. if ( renderTarget.ignoreDepthForMultisampleCopy ) {
  14004. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14005. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14006. }
  14007. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14008. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14009. state.bindFramebuffer( 36008, null );
  14010. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14011. } else {
  14012. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  14013. }
  14014. }
  14015. }
  14016. function getRenderTargetSamples( renderTarget ) {
  14017. return ( isWebGL2 && ( renderTarget.useRenderbuffer || renderTarget.useRenderToTexture ) ) ?
  14018. Math.min( maxSamples, renderTarget.samples ) : 0;
  14019. }
  14020. function updateVideoTexture( texture ) {
  14021. const frame = info.render.frame;
  14022. // Check the last frame we updated the VideoTexture
  14023. if ( _videoTextures.get( texture ) !== frame ) {
  14024. _videoTextures.set( texture, frame );
  14025. texture.update();
  14026. }
  14027. }
  14028. // backwards compatibility
  14029. let warnedTexture2D = false;
  14030. let warnedTextureCube = false;
  14031. function safeSetTexture2D( texture, slot ) {
  14032. if ( texture && texture.isWebGLRenderTarget ) {
  14033. if ( warnedTexture2D === false ) {
  14034. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  14035. warnedTexture2D = true;
  14036. }
  14037. texture = texture.texture;
  14038. }
  14039. setTexture2D( texture, slot );
  14040. }
  14041. function safeSetTextureCube( texture, slot ) {
  14042. if ( texture && texture.isWebGLCubeRenderTarget ) {
  14043. if ( warnedTextureCube === false ) {
  14044. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  14045. warnedTextureCube = true;
  14046. }
  14047. texture = texture.texture;
  14048. }
  14049. setTextureCube( texture, slot );
  14050. }
  14051. //
  14052. this.allocateTextureUnit = allocateTextureUnit;
  14053. this.resetTextureUnits = resetTextureUnits;
  14054. this.setTexture2D = setTexture2D;
  14055. this.setTexture2DArray = setTexture2DArray;
  14056. this.setTexture3D = setTexture3D;
  14057. this.setTextureCube = setTextureCube;
  14058. this.rebindTextures = rebindTextures;
  14059. this.setupRenderTarget = setupRenderTarget;
  14060. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14061. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14062. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14063. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14064. this.safeSetTexture2D = safeSetTexture2D;
  14065. this.safeSetTextureCube = safeSetTextureCube;
  14066. }
  14067. function WebGLUtils( gl, extensions, capabilities ) {
  14068. const isWebGL2 = capabilities.isWebGL2;
  14069. function convert( p ) {
  14070. let extension;
  14071. if ( p === UnsignedByteType ) return 5121;
  14072. if ( p === UnsignedShort4444Type ) return 32819;
  14073. if ( p === UnsignedShort5551Type ) return 32820;
  14074. if ( p === UnsignedShort565Type ) return 33635;
  14075. if ( p === ByteType ) return 5120;
  14076. if ( p === ShortType ) return 5122;
  14077. if ( p === UnsignedShortType ) return 5123;
  14078. if ( p === IntType ) return 5124;
  14079. if ( p === UnsignedIntType ) return 5125;
  14080. if ( p === FloatType ) return 5126;
  14081. if ( p === HalfFloatType ) {
  14082. if ( isWebGL2 ) return 5131;
  14083. extension = extensions.get( 'OES_texture_half_float' );
  14084. if ( extension !== null ) {
  14085. return extension.HALF_FLOAT_OES;
  14086. } else {
  14087. return null;
  14088. }
  14089. }
  14090. if ( p === AlphaFormat ) return 6406;
  14091. if ( p === RGBFormat ) return 6407;
  14092. if ( p === RGBAFormat ) return 6408;
  14093. if ( p === LuminanceFormat ) return 6409;
  14094. if ( p === LuminanceAlphaFormat ) return 6410;
  14095. if ( p === DepthFormat ) return 6402;
  14096. if ( p === DepthStencilFormat ) return 34041;
  14097. if ( p === RedFormat ) return 6403;
  14098. // WebGL2 formats.
  14099. if ( p === RedIntegerFormat ) return 36244;
  14100. if ( p === RGFormat ) return 33319;
  14101. if ( p === RGIntegerFormat ) return 33320;
  14102. if ( p === RGBIntegerFormat ) return 36248;
  14103. if ( p === RGBAIntegerFormat ) return 36249;
  14104. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  14105. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14106. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14107. if ( extension !== null ) {
  14108. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14109. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14110. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14111. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14112. } else {
  14113. return null;
  14114. }
  14115. }
  14116. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  14117. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14118. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14119. if ( extension !== null ) {
  14120. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14121. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14122. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14123. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14124. } else {
  14125. return null;
  14126. }
  14127. }
  14128. if ( p === RGB_ETC1_Format ) {
  14129. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14130. if ( extension !== null ) {
  14131. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14132. } else {
  14133. return null;
  14134. }
  14135. }
  14136. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14137. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14138. if ( extension !== null ) {
  14139. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  14140. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14141. }
  14142. }
  14143. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14144. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14145. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14146. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14147. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  14148. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  14149. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  14150. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  14151. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  14152. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  14153. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14154. if ( extension !== null ) {
  14155. // TODO Complete?
  14156. return p;
  14157. } else {
  14158. return null;
  14159. }
  14160. }
  14161. if ( p === RGBA_BPTC_Format ) {
  14162. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14163. if ( extension !== null ) {
  14164. // TODO Complete?
  14165. return p;
  14166. } else {
  14167. return null;
  14168. }
  14169. }
  14170. if ( p === UnsignedInt248Type ) {
  14171. if ( isWebGL2 ) return 34042;
  14172. extension = extensions.get( 'WEBGL_depth_texture' );
  14173. if ( extension !== null ) {
  14174. return extension.UNSIGNED_INT_24_8_WEBGL;
  14175. } else {
  14176. return null;
  14177. }
  14178. }
  14179. }
  14180. return { convert: convert };
  14181. }
  14182. class ArrayCamera extends PerspectiveCamera {
  14183. constructor( array = [] ) {
  14184. super();
  14185. this.cameras = array;
  14186. }
  14187. }
  14188. ArrayCamera.prototype.isArrayCamera = true;
  14189. class Group extends Object3D {
  14190. constructor() {
  14191. super();
  14192. this.type = 'Group';
  14193. }
  14194. }
  14195. Group.prototype.isGroup = true;
  14196. const _moveEvent = { type: 'move' };
  14197. class WebXRController {
  14198. constructor() {
  14199. this._targetRay = null;
  14200. this._grip = null;
  14201. this._hand = null;
  14202. }
  14203. getHandSpace() {
  14204. if ( this._hand === null ) {
  14205. this._hand = new Group();
  14206. this._hand.matrixAutoUpdate = false;
  14207. this._hand.visible = false;
  14208. this._hand.joints = {};
  14209. this._hand.inputState = { pinching: false };
  14210. }
  14211. return this._hand;
  14212. }
  14213. getTargetRaySpace() {
  14214. if ( this._targetRay === null ) {
  14215. this._targetRay = new Group();
  14216. this._targetRay.matrixAutoUpdate = false;
  14217. this._targetRay.visible = false;
  14218. this._targetRay.hasLinearVelocity = false;
  14219. this._targetRay.linearVelocity = new Vector3();
  14220. this._targetRay.hasAngularVelocity = false;
  14221. this._targetRay.angularVelocity = new Vector3();
  14222. }
  14223. return this._targetRay;
  14224. }
  14225. getGripSpace() {
  14226. if ( this._grip === null ) {
  14227. this._grip = new Group();
  14228. this._grip.matrixAutoUpdate = false;
  14229. this._grip.visible = false;
  14230. this._grip.hasLinearVelocity = false;
  14231. this._grip.linearVelocity = new Vector3();
  14232. this._grip.hasAngularVelocity = false;
  14233. this._grip.angularVelocity = new Vector3();
  14234. }
  14235. return this._grip;
  14236. }
  14237. dispatchEvent( event ) {
  14238. if ( this._targetRay !== null ) {
  14239. this._targetRay.dispatchEvent( event );
  14240. }
  14241. if ( this._grip !== null ) {
  14242. this._grip.dispatchEvent( event );
  14243. }
  14244. if ( this._hand !== null ) {
  14245. this._hand.dispatchEvent( event );
  14246. }
  14247. return this;
  14248. }
  14249. disconnect( inputSource ) {
  14250. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14251. if ( this._targetRay !== null ) {
  14252. this._targetRay.visible = false;
  14253. }
  14254. if ( this._grip !== null ) {
  14255. this._grip.visible = false;
  14256. }
  14257. if ( this._hand !== null ) {
  14258. this._hand.visible = false;
  14259. }
  14260. return this;
  14261. }
  14262. update( inputSource, frame, referenceSpace ) {
  14263. let inputPose = null;
  14264. let gripPose = null;
  14265. let handPose = null;
  14266. const targetRay = this._targetRay;
  14267. const grip = this._grip;
  14268. const hand = this._hand;
  14269. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14270. if ( targetRay !== null ) {
  14271. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14272. if ( inputPose !== null ) {
  14273. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14274. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14275. if ( inputPose.linearVelocity ) {
  14276. targetRay.hasLinearVelocity = true;
  14277. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14278. } else {
  14279. targetRay.hasLinearVelocity = false;
  14280. }
  14281. if ( inputPose.angularVelocity ) {
  14282. targetRay.hasAngularVelocity = true;
  14283. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14284. } else {
  14285. targetRay.hasAngularVelocity = false;
  14286. }
  14287. this.dispatchEvent( _moveEvent );
  14288. }
  14289. }
  14290. if ( hand && inputSource.hand ) {
  14291. handPose = true;
  14292. for ( const inputjoint of inputSource.hand.values() ) {
  14293. // Update the joints groups with the XRJoint poses
  14294. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14295. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14296. // The transform of this joint will be updated with the joint pose on each frame
  14297. const joint = new Group();
  14298. joint.matrixAutoUpdate = false;
  14299. joint.visible = false;
  14300. hand.joints[ inputjoint.jointName ] = joint;
  14301. // ??
  14302. hand.add( joint );
  14303. }
  14304. const joint = hand.joints[ inputjoint.jointName ];
  14305. if ( jointPose !== null ) {
  14306. joint.matrix.fromArray( jointPose.transform.matrix );
  14307. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14308. joint.jointRadius = jointPose.radius;
  14309. }
  14310. joint.visible = jointPose !== null;
  14311. }
  14312. // Custom events
  14313. // Check pinchz
  14314. const indexTip = hand.joints[ 'index-finger-tip' ];
  14315. const thumbTip = hand.joints[ 'thumb-tip' ];
  14316. const distance = indexTip.position.distanceTo( thumbTip.position );
  14317. const distanceToPinch = 0.02;
  14318. const threshold = 0.005;
  14319. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14320. hand.inputState.pinching = false;
  14321. this.dispatchEvent( {
  14322. type: 'pinchend',
  14323. handedness: inputSource.handedness,
  14324. target: this
  14325. } );
  14326. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14327. hand.inputState.pinching = true;
  14328. this.dispatchEvent( {
  14329. type: 'pinchstart',
  14330. handedness: inputSource.handedness,
  14331. target: this
  14332. } );
  14333. }
  14334. } else {
  14335. if ( grip !== null && inputSource.gripSpace ) {
  14336. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14337. if ( gripPose !== null ) {
  14338. grip.matrix.fromArray( gripPose.transform.matrix );
  14339. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14340. if ( gripPose.linearVelocity ) {
  14341. grip.hasLinearVelocity = true;
  14342. grip.linearVelocity.copy( gripPose.linearVelocity );
  14343. } else {
  14344. grip.hasLinearVelocity = false;
  14345. }
  14346. if ( gripPose.angularVelocity ) {
  14347. grip.hasAngularVelocity = true;
  14348. grip.angularVelocity.copy( gripPose.angularVelocity );
  14349. } else {
  14350. grip.hasAngularVelocity = false;
  14351. }
  14352. }
  14353. }
  14354. }
  14355. }
  14356. if ( targetRay !== null ) {
  14357. targetRay.visible = ( inputPose !== null );
  14358. }
  14359. if ( grip !== null ) {
  14360. grip.visible = ( gripPose !== null );
  14361. }
  14362. if ( hand !== null ) {
  14363. hand.visible = ( handPose !== null );
  14364. }
  14365. return this;
  14366. }
  14367. }
  14368. class DepthTexture extends Texture {
  14369. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14370. format = format !== undefined ? format : DepthFormat;
  14371. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14372. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14373. }
  14374. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14375. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14376. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14377. this.image = { width: width, height: height };
  14378. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14379. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14380. this.flipY = false;
  14381. this.generateMipmaps = false;
  14382. }
  14383. }
  14384. DepthTexture.prototype.isDepthTexture = true;
  14385. class WebXRManager extends EventDispatcher {
  14386. constructor( renderer, gl ) {
  14387. super();
  14388. const scope = this;
  14389. let session = null;
  14390. let framebufferScaleFactor = 1.0;
  14391. let referenceSpace = null;
  14392. let referenceSpaceType = 'local-floor';
  14393. const hasMultisampledRenderToTexture = renderer.extensions.has( 'WEBGL_multisampled_render_to_texture' );
  14394. let pose = null;
  14395. let glBinding = null;
  14396. let glProjLayer = null;
  14397. let glBaseLayer = null;
  14398. let isMultisample = false;
  14399. let xrFrame = null;
  14400. const attributes = gl.getContextAttributes();
  14401. let initialRenderTarget = null;
  14402. let newRenderTarget = null;
  14403. const controllers = [];
  14404. const inputSourcesMap = new Map();
  14405. //
  14406. const cameraL = new PerspectiveCamera();
  14407. cameraL.layers.enable( 1 );
  14408. cameraL.viewport = new Vector4();
  14409. const cameraR = new PerspectiveCamera();
  14410. cameraR.layers.enable( 2 );
  14411. cameraR.viewport = new Vector4();
  14412. const cameras = [ cameraL, cameraR ];
  14413. const cameraVR = new ArrayCamera();
  14414. cameraVR.layers.enable( 1 );
  14415. cameraVR.layers.enable( 2 );
  14416. let _currentDepthNear = null;
  14417. let _currentDepthFar = null;
  14418. //
  14419. this.cameraAutoUpdate = true;
  14420. this.enabled = false;
  14421. this.isPresenting = false;
  14422. this.getController = function ( index ) {
  14423. let controller = controllers[ index ];
  14424. if ( controller === undefined ) {
  14425. controller = new WebXRController();
  14426. controllers[ index ] = controller;
  14427. }
  14428. return controller.getTargetRaySpace();
  14429. };
  14430. this.getControllerGrip = function ( index ) {
  14431. let controller = controllers[ index ];
  14432. if ( controller === undefined ) {
  14433. controller = new WebXRController();
  14434. controllers[ index ] = controller;
  14435. }
  14436. return controller.getGripSpace();
  14437. };
  14438. this.getHand = function ( index ) {
  14439. let controller = controllers[ index ];
  14440. if ( controller === undefined ) {
  14441. controller = new WebXRController();
  14442. controllers[ index ] = controller;
  14443. }
  14444. return controller.getHandSpace();
  14445. };
  14446. //
  14447. function onSessionEvent( event ) {
  14448. const controller = inputSourcesMap.get( event.inputSource );
  14449. if ( controller ) {
  14450. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14451. }
  14452. }
  14453. function onSessionEnd() {
  14454. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14455. controller.disconnect( inputSource );
  14456. } );
  14457. inputSourcesMap.clear();
  14458. _currentDepthNear = null;
  14459. _currentDepthFar = null;
  14460. // restore framebuffer/rendering state
  14461. renderer.setRenderTarget( initialRenderTarget );
  14462. glBaseLayer = null;
  14463. glProjLayer = null;
  14464. glBinding = null;
  14465. session = null;
  14466. newRenderTarget = null;
  14467. //
  14468. animation.stop();
  14469. scope.isPresenting = false;
  14470. scope.dispatchEvent( { type: 'sessionend' } );
  14471. }
  14472. this.setFramebufferScaleFactor = function ( value ) {
  14473. framebufferScaleFactor = value;
  14474. if ( scope.isPresenting === true ) {
  14475. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14476. }
  14477. };
  14478. this.setReferenceSpaceType = function ( value ) {
  14479. referenceSpaceType = value;
  14480. if ( scope.isPresenting === true ) {
  14481. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14482. }
  14483. };
  14484. this.getReferenceSpace = function () {
  14485. return referenceSpace;
  14486. };
  14487. this.getBaseLayer = function () {
  14488. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14489. };
  14490. this.getBinding = function () {
  14491. return glBinding;
  14492. };
  14493. this.getFrame = function () {
  14494. return xrFrame;
  14495. };
  14496. this.getSession = function () {
  14497. return session;
  14498. };
  14499. this.setSession = async function ( value ) {
  14500. session = value;
  14501. if ( session !== null ) {
  14502. initialRenderTarget = renderer.getRenderTarget();
  14503. session.addEventListener( 'select', onSessionEvent );
  14504. session.addEventListener( 'selectstart', onSessionEvent );
  14505. session.addEventListener( 'selectend', onSessionEvent );
  14506. session.addEventListener( 'squeeze', onSessionEvent );
  14507. session.addEventListener( 'squeezestart', onSessionEvent );
  14508. session.addEventListener( 'squeezeend', onSessionEvent );
  14509. session.addEventListener( 'end', onSessionEnd );
  14510. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14511. if ( attributes.xrCompatible !== true ) {
  14512. await gl.makeXRCompatible();
  14513. }
  14514. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  14515. const layerInit = {
  14516. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  14517. alpha: attributes.alpha,
  14518. depth: attributes.depth,
  14519. stencil: attributes.stencil,
  14520. framebufferScaleFactor: framebufferScaleFactor
  14521. };
  14522. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14523. session.updateRenderState( { baseLayer: glBaseLayer } );
  14524. newRenderTarget = new WebGLRenderTarget(
  14525. glBaseLayer.framebufferWidth,
  14526. glBaseLayer.framebufferHeight
  14527. );
  14528. } else {
  14529. isMultisample = attributes.antialias;
  14530. let depthFormat = null;
  14531. let depthType = null;
  14532. let glDepthFormat = null;
  14533. if ( attributes.depth ) {
  14534. glDepthFormat = attributes.stencil ? 35056 : 33189;
  14535. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14536. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  14537. }
  14538. const projectionlayerInit = {
  14539. colorFormat: ( attributes.alpha || isMultisample ) ? 32856 : 32849,
  14540. depthFormat: glDepthFormat,
  14541. scaleFactor: framebufferScaleFactor
  14542. };
  14543. glBinding = new XRWebGLBinding( session, gl );
  14544. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  14545. session.updateRenderState( { layers: [ glProjLayer ] } );
  14546. if ( isMultisample ) {
  14547. newRenderTarget = new WebGLMultisampleRenderTarget(
  14548. glProjLayer.textureWidth,
  14549. glProjLayer.textureHeight,
  14550. {
  14551. format: RGBAFormat,
  14552. type: UnsignedByteType,
  14553. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  14554. stencilBuffer: attributes.stencil,
  14555. ignoreDepth: glProjLayer.ignoreDepthValues,
  14556. useRenderToTexture: hasMultisampledRenderToTexture,
  14557. } );
  14558. } else {
  14559. newRenderTarget = new WebGLRenderTarget(
  14560. glProjLayer.textureWidth,
  14561. glProjLayer.textureHeight,
  14562. {
  14563. format: attributes.alpha ? RGBAFormat : RGBFormat,
  14564. type: UnsignedByteType,
  14565. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  14566. stencilBuffer: attributes.stencil,
  14567. ignoreDepth: glProjLayer.ignoreDepthValues,
  14568. } );
  14569. }
  14570. }
  14571. // Set foveation to maximum.
  14572. this.setFoveation( 0 );
  14573. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  14574. animation.setContext( session );
  14575. animation.start();
  14576. scope.isPresenting = true;
  14577. scope.dispatchEvent( { type: 'sessionstart' } );
  14578. }
  14579. };
  14580. function onInputSourcesChange( event ) {
  14581. const inputSources = session.inputSources;
  14582. // Assign inputSources to available controllers
  14583. for ( let i = 0; i < controllers.length; i ++ ) {
  14584. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14585. }
  14586. // Notify disconnected
  14587. for ( let i = 0; i < event.removed.length; i ++ ) {
  14588. const inputSource = event.removed[ i ];
  14589. const controller = inputSourcesMap.get( inputSource );
  14590. if ( controller ) {
  14591. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14592. inputSourcesMap.delete( inputSource );
  14593. }
  14594. }
  14595. // Notify connected
  14596. for ( let i = 0; i < event.added.length; i ++ ) {
  14597. const inputSource = event.added[ i ];
  14598. const controller = inputSourcesMap.get( inputSource );
  14599. if ( controller ) {
  14600. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14601. }
  14602. }
  14603. }
  14604. //
  14605. const cameraLPos = new Vector3();
  14606. const cameraRPos = new Vector3();
  14607. /**
  14608. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14609. * the cameras' projection and world matrices have already been set.
  14610. * And that near and far planes are identical for both cameras.
  14611. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14612. */
  14613. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14614. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14615. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14616. const ipd = cameraLPos.distanceTo( cameraRPos );
  14617. const projL = cameraL.projectionMatrix.elements;
  14618. const projR = cameraR.projectionMatrix.elements;
  14619. // VR systems will have identical far and near planes, and
  14620. // most likely identical top and bottom frustum extents.
  14621. // Use the left camera for these values.
  14622. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14623. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14624. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14625. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14626. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14627. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14628. const left = near * leftFov;
  14629. const right = near * rightFov;
  14630. // Calculate the new camera's position offset from the
  14631. // left camera. xOffset should be roughly half `ipd`.
  14632. const zOffset = ipd / ( - leftFov + rightFov );
  14633. const xOffset = zOffset * - leftFov;
  14634. // TODO: Better way to apply this offset?
  14635. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14636. camera.translateX( xOffset );
  14637. camera.translateZ( zOffset );
  14638. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14639. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14640. // Find the union of the frustum values of the cameras and scale
  14641. // the values so that the near plane's position does not change in world space,
  14642. // although must now be relative to the new union camera.
  14643. const near2 = near + zOffset;
  14644. const far2 = far + zOffset;
  14645. const left2 = left - xOffset;
  14646. const right2 = right + ( ipd - xOffset );
  14647. const top2 = topFov * far / far2 * near2;
  14648. const bottom2 = bottomFov * far / far2 * near2;
  14649. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14650. }
  14651. function updateCamera( camera, parent ) {
  14652. if ( parent === null ) {
  14653. camera.matrixWorld.copy( camera.matrix );
  14654. } else {
  14655. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14656. }
  14657. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14658. }
  14659. this.updateCamera = function ( camera ) {
  14660. if ( session === null ) return;
  14661. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14662. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14663. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14664. // Note that the new renderState won't apply until the next frame. See #18320
  14665. session.updateRenderState( {
  14666. depthNear: cameraVR.near,
  14667. depthFar: cameraVR.far
  14668. } );
  14669. _currentDepthNear = cameraVR.near;
  14670. _currentDepthFar = cameraVR.far;
  14671. }
  14672. const parent = camera.parent;
  14673. const cameras = cameraVR.cameras;
  14674. updateCamera( cameraVR, parent );
  14675. for ( let i = 0; i < cameras.length; i ++ ) {
  14676. updateCamera( cameras[ i ], parent );
  14677. }
  14678. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  14679. // update user camera and its children
  14680. camera.position.copy( cameraVR.position );
  14681. camera.quaternion.copy( cameraVR.quaternion );
  14682. camera.scale.copy( cameraVR.scale );
  14683. camera.matrix.copy( cameraVR.matrix );
  14684. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14685. const children = camera.children;
  14686. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14687. children[ i ].updateMatrixWorld( true );
  14688. }
  14689. // update projection matrix for proper view frustum culling
  14690. if ( cameras.length === 2 ) {
  14691. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14692. } else {
  14693. // assume single camera setup (AR)
  14694. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14695. }
  14696. };
  14697. this.getCamera = function () {
  14698. return cameraVR;
  14699. };
  14700. this.getFoveation = function () {
  14701. if ( glProjLayer !== null ) {
  14702. return glProjLayer.fixedFoveation;
  14703. }
  14704. if ( glBaseLayer !== null ) {
  14705. return glBaseLayer.fixedFoveation;
  14706. }
  14707. return undefined;
  14708. };
  14709. this.setFoveation = function ( foveation ) {
  14710. // 0 = no foveation = full resolution
  14711. // 1 = maximum foveation = the edges render at lower resolution
  14712. if ( glProjLayer !== null ) {
  14713. glProjLayer.fixedFoveation = foveation;
  14714. }
  14715. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  14716. glBaseLayer.fixedFoveation = foveation;
  14717. }
  14718. };
  14719. // Animation Loop
  14720. let onAnimationFrameCallback = null;
  14721. function onAnimationFrame( time, frame ) {
  14722. pose = frame.getViewerPose( referenceSpace );
  14723. xrFrame = frame;
  14724. if ( pose !== null ) {
  14725. const views = pose.views;
  14726. if ( glBaseLayer !== null ) {
  14727. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  14728. renderer.setRenderTarget( newRenderTarget );
  14729. }
  14730. let cameraVRNeedsUpdate = false;
  14731. // check if it's necessary to rebuild cameraVR's camera list
  14732. if ( views.length !== cameraVR.cameras.length ) {
  14733. cameraVR.cameras.length = 0;
  14734. cameraVRNeedsUpdate = true;
  14735. }
  14736. for ( let i = 0; i < views.length; i ++ ) {
  14737. const view = views[ i ];
  14738. let viewport = null;
  14739. if ( glBaseLayer !== null ) {
  14740. viewport = glBaseLayer.getViewport( view );
  14741. } else {
  14742. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  14743. viewport = glSubImage.viewport;
  14744. // For side-by-side projection, we only produce a single texture for both eyes.
  14745. if ( i === 0 ) {
  14746. renderer.setRenderTargetTextures(
  14747. newRenderTarget,
  14748. glSubImage.colorTexture,
  14749. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  14750. renderer.setRenderTarget( newRenderTarget );
  14751. }
  14752. }
  14753. const camera = cameras[ i ];
  14754. camera.matrix.fromArray( view.transform.matrix );
  14755. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14756. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14757. if ( i === 0 ) {
  14758. cameraVR.matrix.copy( camera.matrix );
  14759. }
  14760. if ( cameraVRNeedsUpdate === true ) {
  14761. cameraVR.cameras.push( camera );
  14762. }
  14763. }
  14764. }
  14765. //
  14766. const inputSources = session.inputSources;
  14767. for ( let i = 0; i < controllers.length; i ++ ) {
  14768. const controller = controllers[ i ];
  14769. const inputSource = inputSources[ i ];
  14770. controller.update( inputSource, frame, referenceSpace );
  14771. }
  14772. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14773. xrFrame = null;
  14774. }
  14775. const animation = new WebGLAnimation();
  14776. animation.setAnimationLoop( onAnimationFrame );
  14777. this.setAnimationLoop = function ( callback ) {
  14778. onAnimationFrameCallback = callback;
  14779. };
  14780. this.dispose = function () {};
  14781. }
  14782. }
  14783. function WebGLMaterials( properties ) {
  14784. function refreshFogUniforms( uniforms, fog ) {
  14785. uniforms.fogColor.value.copy( fog.color );
  14786. if ( fog.isFog ) {
  14787. uniforms.fogNear.value = fog.near;
  14788. uniforms.fogFar.value = fog.far;
  14789. } else if ( fog.isFogExp2 ) {
  14790. uniforms.fogDensity.value = fog.density;
  14791. }
  14792. }
  14793. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  14794. if ( material.isMeshBasicMaterial ) {
  14795. refreshUniformsCommon( uniforms, material );
  14796. } else if ( material.isMeshLambertMaterial ) {
  14797. refreshUniformsCommon( uniforms, material );
  14798. refreshUniformsLambert( uniforms, material );
  14799. } else if ( material.isMeshToonMaterial ) {
  14800. refreshUniformsCommon( uniforms, material );
  14801. refreshUniformsToon( uniforms, material );
  14802. } else if ( material.isMeshPhongMaterial ) {
  14803. refreshUniformsCommon( uniforms, material );
  14804. refreshUniformsPhong( uniforms, material );
  14805. } else if ( material.isMeshStandardMaterial ) {
  14806. refreshUniformsCommon( uniforms, material );
  14807. if ( material.isMeshPhysicalMaterial ) {
  14808. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  14809. } else {
  14810. refreshUniformsStandard( uniforms, material );
  14811. }
  14812. } else if ( material.isMeshMatcapMaterial ) {
  14813. refreshUniformsCommon( uniforms, material );
  14814. refreshUniformsMatcap( uniforms, material );
  14815. } else if ( material.isMeshDepthMaterial ) {
  14816. refreshUniformsCommon( uniforms, material );
  14817. refreshUniformsDepth( uniforms, material );
  14818. } else if ( material.isMeshDistanceMaterial ) {
  14819. refreshUniformsCommon( uniforms, material );
  14820. refreshUniformsDistance( uniforms, material );
  14821. } else if ( material.isMeshNormalMaterial ) {
  14822. refreshUniformsCommon( uniforms, material );
  14823. refreshUniformsNormal( uniforms, material );
  14824. } else if ( material.isLineBasicMaterial ) {
  14825. refreshUniformsLine( uniforms, material );
  14826. if ( material.isLineDashedMaterial ) {
  14827. refreshUniformsDash( uniforms, material );
  14828. }
  14829. } else if ( material.isPointsMaterial ) {
  14830. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14831. } else if ( material.isSpriteMaterial ) {
  14832. refreshUniformsSprites( uniforms, material );
  14833. } else if ( material.isShadowMaterial ) {
  14834. uniforms.color.value.copy( material.color );
  14835. uniforms.opacity.value = material.opacity;
  14836. } else if ( material.isShaderMaterial ) {
  14837. material.uniformsNeedUpdate = false; // #15581
  14838. }
  14839. }
  14840. function refreshUniformsCommon( uniforms, material ) {
  14841. uniforms.opacity.value = material.opacity;
  14842. if ( material.color ) {
  14843. uniforms.diffuse.value.copy( material.color );
  14844. }
  14845. if ( material.emissive ) {
  14846. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14847. }
  14848. if ( material.map ) {
  14849. uniforms.map.value = material.map;
  14850. }
  14851. if ( material.alphaMap ) {
  14852. uniforms.alphaMap.value = material.alphaMap;
  14853. }
  14854. if ( material.specularMap ) {
  14855. uniforms.specularMap.value = material.specularMap;
  14856. }
  14857. if ( material.alphaTest > 0 ) {
  14858. uniforms.alphaTest.value = material.alphaTest;
  14859. }
  14860. const envMap = properties.get( material ).envMap;
  14861. if ( envMap ) {
  14862. uniforms.envMap.value = envMap;
  14863. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  14864. uniforms.reflectivity.value = material.reflectivity;
  14865. uniforms.ior.value = material.ior;
  14866. uniforms.refractionRatio.value = material.refractionRatio;
  14867. }
  14868. if ( material.lightMap ) {
  14869. uniforms.lightMap.value = material.lightMap;
  14870. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14871. }
  14872. if ( material.aoMap ) {
  14873. uniforms.aoMap.value = material.aoMap;
  14874. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14875. }
  14876. // uv repeat and offset setting priorities
  14877. // 1. color map
  14878. // 2. specular map
  14879. // 3. displacementMap map
  14880. // 4. normal map
  14881. // 5. bump map
  14882. // 6. roughnessMap map
  14883. // 7. metalnessMap map
  14884. // 8. alphaMap map
  14885. // 9. emissiveMap map
  14886. // 10. clearcoat map
  14887. // 11. clearcoat normal map
  14888. // 12. clearcoat roughnessMap map
  14889. // 13. specular intensity map
  14890. // 14. specular tint map
  14891. // 15. transmission map
  14892. // 16. thickness map
  14893. let uvScaleMap;
  14894. if ( material.map ) {
  14895. uvScaleMap = material.map;
  14896. } else if ( material.specularMap ) {
  14897. uvScaleMap = material.specularMap;
  14898. } else if ( material.displacementMap ) {
  14899. uvScaleMap = material.displacementMap;
  14900. } else if ( material.normalMap ) {
  14901. uvScaleMap = material.normalMap;
  14902. } else if ( material.bumpMap ) {
  14903. uvScaleMap = material.bumpMap;
  14904. } else if ( material.roughnessMap ) {
  14905. uvScaleMap = material.roughnessMap;
  14906. } else if ( material.metalnessMap ) {
  14907. uvScaleMap = material.metalnessMap;
  14908. } else if ( material.alphaMap ) {
  14909. uvScaleMap = material.alphaMap;
  14910. } else if ( material.emissiveMap ) {
  14911. uvScaleMap = material.emissiveMap;
  14912. } else if ( material.clearcoatMap ) {
  14913. uvScaleMap = material.clearcoatMap;
  14914. } else if ( material.clearcoatNormalMap ) {
  14915. uvScaleMap = material.clearcoatNormalMap;
  14916. } else if ( material.clearcoatRoughnessMap ) {
  14917. uvScaleMap = material.clearcoatRoughnessMap;
  14918. } else if ( material.specularIntensityMap ) {
  14919. uvScaleMap = material.specularIntensityMap;
  14920. } else if ( material.specularColorMap ) {
  14921. uvScaleMap = material.specularColorMap;
  14922. } else if ( material.transmissionMap ) {
  14923. uvScaleMap = material.transmissionMap;
  14924. } else if ( material.thicknessMap ) {
  14925. uvScaleMap = material.thicknessMap;
  14926. } else if ( material.sheenColorMap ) {
  14927. uvScaleMap = material.sheenColorMap;
  14928. } else if ( material.sheenRoughnessMap ) {
  14929. uvScaleMap = material.sheenRoughnessMap;
  14930. }
  14931. if ( uvScaleMap !== undefined ) {
  14932. // backwards compatibility
  14933. if ( uvScaleMap.isWebGLRenderTarget ) {
  14934. uvScaleMap = uvScaleMap.texture;
  14935. }
  14936. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14937. uvScaleMap.updateMatrix();
  14938. }
  14939. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14940. }
  14941. // uv repeat and offset setting priorities for uv2
  14942. // 1. ao map
  14943. // 2. light map
  14944. let uv2ScaleMap;
  14945. if ( material.aoMap ) {
  14946. uv2ScaleMap = material.aoMap;
  14947. } else if ( material.lightMap ) {
  14948. uv2ScaleMap = material.lightMap;
  14949. }
  14950. if ( uv2ScaleMap !== undefined ) {
  14951. // backwards compatibility
  14952. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14953. uv2ScaleMap = uv2ScaleMap.texture;
  14954. }
  14955. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14956. uv2ScaleMap.updateMatrix();
  14957. }
  14958. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14959. }
  14960. }
  14961. function refreshUniformsLine( uniforms, material ) {
  14962. uniforms.diffuse.value.copy( material.color );
  14963. uniforms.opacity.value = material.opacity;
  14964. }
  14965. function refreshUniformsDash( uniforms, material ) {
  14966. uniforms.dashSize.value = material.dashSize;
  14967. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14968. uniforms.scale.value = material.scale;
  14969. }
  14970. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14971. uniforms.diffuse.value.copy( material.color );
  14972. uniforms.opacity.value = material.opacity;
  14973. uniforms.size.value = material.size * pixelRatio;
  14974. uniforms.scale.value = height * 0.5;
  14975. if ( material.map ) {
  14976. uniforms.map.value = material.map;
  14977. }
  14978. if ( material.alphaMap ) {
  14979. uniforms.alphaMap.value = material.alphaMap;
  14980. }
  14981. if ( material.alphaTest > 0 ) {
  14982. uniforms.alphaTest.value = material.alphaTest;
  14983. }
  14984. // uv repeat and offset setting priorities
  14985. // 1. color map
  14986. // 2. alpha map
  14987. let uvScaleMap;
  14988. if ( material.map ) {
  14989. uvScaleMap = material.map;
  14990. } else if ( material.alphaMap ) {
  14991. uvScaleMap = material.alphaMap;
  14992. }
  14993. if ( uvScaleMap !== undefined ) {
  14994. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14995. uvScaleMap.updateMatrix();
  14996. }
  14997. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14998. }
  14999. }
  15000. function refreshUniformsSprites( uniforms, material ) {
  15001. uniforms.diffuse.value.copy( material.color );
  15002. uniforms.opacity.value = material.opacity;
  15003. uniforms.rotation.value = material.rotation;
  15004. if ( material.map ) {
  15005. uniforms.map.value = material.map;
  15006. }
  15007. if ( material.alphaMap ) {
  15008. uniforms.alphaMap.value = material.alphaMap;
  15009. }
  15010. if ( material.alphaTest > 0 ) {
  15011. uniforms.alphaTest.value = material.alphaTest;
  15012. }
  15013. // uv repeat and offset setting priorities
  15014. // 1. color map
  15015. // 2. alpha map
  15016. let uvScaleMap;
  15017. if ( material.map ) {
  15018. uvScaleMap = material.map;
  15019. } else if ( material.alphaMap ) {
  15020. uvScaleMap = material.alphaMap;
  15021. }
  15022. if ( uvScaleMap !== undefined ) {
  15023. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15024. uvScaleMap.updateMatrix();
  15025. }
  15026. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15027. }
  15028. }
  15029. function refreshUniformsLambert( uniforms, material ) {
  15030. if ( material.emissiveMap ) {
  15031. uniforms.emissiveMap.value = material.emissiveMap;
  15032. }
  15033. }
  15034. function refreshUniformsPhong( uniforms, material ) {
  15035. uniforms.specular.value.copy( material.specular );
  15036. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15037. if ( material.emissiveMap ) {
  15038. uniforms.emissiveMap.value = material.emissiveMap;
  15039. }
  15040. if ( material.bumpMap ) {
  15041. uniforms.bumpMap.value = material.bumpMap;
  15042. uniforms.bumpScale.value = material.bumpScale;
  15043. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15044. }
  15045. if ( material.normalMap ) {
  15046. uniforms.normalMap.value = material.normalMap;
  15047. uniforms.normalScale.value.copy( material.normalScale );
  15048. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15049. }
  15050. if ( material.displacementMap ) {
  15051. uniforms.displacementMap.value = material.displacementMap;
  15052. uniforms.displacementScale.value = material.displacementScale;
  15053. uniforms.displacementBias.value = material.displacementBias;
  15054. }
  15055. }
  15056. function refreshUniformsToon( uniforms, material ) {
  15057. if ( material.gradientMap ) {
  15058. uniforms.gradientMap.value = material.gradientMap;
  15059. }
  15060. if ( material.emissiveMap ) {
  15061. uniforms.emissiveMap.value = material.emissiveMap;
  15062. }
  15063. if ( material.bumpMap ) {
  15064. uniforms.bumpMap.value = material.bumpMap;
  15065. uniforms.bumpScale.value = material.bumpScale;
  15066. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15067. }
  15068. if ( material.normalMap ) {
  15069. uniforms.normalMap.value = material.normalMap;
  15070. uniforms.normalScale.value.copy( material.normalScale );
  15071. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15072. }
  15073. if ( material.displacementMap ) {
  15074. uniforms.displacementMap.value = material.displacementMap;
  15075. uniforms.displacementScale.value = material.displacementScale;
  15076. uniforms.displacementBias.value = material.displacementBias;
  15077. }
  15078. }
  15079. function refreshUniformsStandard( uniforms, material ) {
  15080. uniforms.roughness.value = material.roughness;
  15081. uniforms.metalness.value = material.metalness;
  15082. if ( material.roughnessMap ) {
  15083. uniforms.roughnessMap.value = material.roughnessMap;
  15084. }
  15085. if ( material.metalnessMap ) {
  15086. uniforms.metalnessMap.value = material.metalnessMap;
  15087. }
  15088. if ( material.emissiveMap ) {
  15089. uniforms.emissiveMap.value = material.emissiveMap;
  15090. }
  15091. if ( material.bumpMap ) {
  15092. uniforms.bumpMap.value = material.bumpMap;
  15093. uniforms.bumpScale.value = material.bumpScale;
  15094. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15095. }
  15096. if ( material.normalMap ) {
  15097. uniforms.normalMap.value = material.normalMap;
  15098. uniforms.normalScale.value.copy( material.normalScale );
  15099. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15100. }
  15101. if ( material.displacementMap ) {
  15102. uniforms.displacementMap.value = material.displacementMap;
  15103. uniforms.displacementScale.value = material.displacementScale;
  15104. uniforms.displacementBias.value = material.displacementBias;
  15105. }
  15106. const envMap = properties.get( material ).envMap;
  15107. if ( envMap ) {
  15108. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15109. uniforms.envMapIntensity.value = material.envMapIntensity;
  15110. }
  15111. }
  15112. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15113. refreshUniformsStandard( uniforms, material );
  15114. uniforms.ior.value = material.ior; // also part of uniforms common
  15115. if ( material.sheen > 0 ) {
  15116. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15117. uniforms.sheenRoughness.value = material.sheenRoughness;
  15118. if ( material.sheenColorMap ) {
  15119. uniforms.sheenColorMap.value = material.sheenColorMap;
  15120. }
  15121. if ( material.sheenRoughnessMap ) {
  15122. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15123. }
  15124. }
  15125. if ( material.clearcoat > 0 ) {
  15126. uniforms.clearcoat.value = material.clearcoat;
  15127. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15128. if ( material.clearcoatMap ) {
  15129. uniforms.clearcoatMap.value = material.clearcoatMap;
  15130. }
  15131. if ( material.clearcoatRoughnessMap ) {
  15132. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15133. }
  15134. if ( material.clearcoatNormalMap ) {
  15135. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15136. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15137. if ( material.side === BackSide ) {
  15138. uniforms.clearcoatNormalScale.value.negate();
  15139. }
  15140. }
  15141. }
  15142. if ( material.transmission > 0 ) {
  15143. uniforms.transmission.value = material.transmission;
  15144. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15145. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15146. if ( material.transmissionMap ) {
  15147. uniforms.transmissionMap.value = material.transmissionMap;
  15148. }
  15149. uniforms.thickness.value = material.thickness;
  15150. if ( material.thicknessMap ) {
  15151. uniforms.thicknessMap.value = material.thicknessMap;
  15152. }
  15153. uniforms.attenuationDistance.value = material.attenuationDistance;
  15154. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15155. }
  15156. uniforms.specularIntensity.value = material.specularIntensity;
  15157. uniforms.specularColor.value.copy( material.specularColor );
  15158. if ( material.specularIntensityMap ) {
  15159. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15160. }
  15161. if ( material.specularColorMap ) {
  15162. uniforms.specularColorMap.value = material.specularColorMap;
  15163. }
  15164. }
  15165. function refreshUniformsMatcap( uniforms, material ) {
  15166. if ( material.matcap ) {
  15167. uniforms.matcap.value = material.matcap;
  15168. }
  15169. if ( material.bumpMap ) {
  15170. uniforms.bumpMap.value = material.bumpMap;
  15171. uniforms.bumpScale.value = material.bumpScale;
  15172. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15173. }
  15174. if ( material.normalMap ) {
  15175. uniforms.normalMap.value = material.normalMap;
  15176. uniforms.normalScale.value.copy( material.normalScale );
  15177. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15178. }
  15179. if ( material.displacementMap ) {
  15180. uniforms.displacementMap.value = material.displacementMap;
  15181. uniforms.displacementScale.value = material.displacementScale;
  15182. uniforms.displacementBias.value = material.displacementBias;
  15183. }
  15184. }
  15185. function refreshUniformsDepth( uniforms, material ) {
  15186. if ( material.displacementMap ) {
  15187. uniforms.displacementMap.value = material.displacementMap;
  15188. uniforms.displacementScale.value = material.displacementScale;
  15189. uniforms.displacementBias.value = material.displacementBias;
  15190. }
  15191. }
  15192. function refreshUniformsDistance( uniforms, material ) {
  15193. if ( material.displacementMap ) {
  15194. uniforms.displacementMap.value = material.displacementMap;
  15195. uniforms.displacementScale.value = material.displacementScale;
  15196. uniforms.displacementBias.value = material.displacementBias;
  15197. }
  15198. uniforms.referencePosition.value.copy( material.referencePosition );
  15199. uniforms.nearDistance.value = material.nearDistance;
  15200. uniforms.farDistance.value = material.farDistance;
  15201. }
  15202. function refreshUniformsNormal( uniforms, material ) {
  15203. if ( material.bumpMap ) {
  15204. uniforms.bumpMap.value = material.bumpMap;
  15205. uniforms.bumpScale.value = material.bumpScale;
  15206. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15207. }
  15208. if ( material.normalMap ) {
  15209. uniforms.normalMap.value = material.normalMap;
  15210. uniforms.normalScale.value.copy( material.normalScale );
  15211. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15212. }
  15213. if ( material.displacementMap ) {
  15214. uniforms.displacementMap.value = material.displacementMap;
  15215. uniforms.displacementScale.value = material.displacementScale;
  15216. uniforms.displacementBias.value = material.displacementBias;
  15217. }
  15218. }
  15219. return {
  15220. refreshFogUniforms: refreshFogUniforms,
  15221. refreshMaterialUniforms: refreshMaterialUniforms
  15222. };
  15223. }
  15224. function createCanvasElement() {
  15225. const canvas = createElementNS( 'canvas' );
  15226. canvas.style.display = 'block';
  15227. return canvas;
  15228. }
  15229. function WebGLRenderer( parameters = {} ) {
  15230. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15231. _context = parameters.context !== undefined ? parameters.context : null,
  15232. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15233. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15234. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15235. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15236. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15237. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15238. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15239. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15240. let currentRenderList = null;
  15241. let currentRenderState = null;
  15242. // render() can be called from within a callback triggered by another render.
  15243. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15244. const renderListStack = [];
  15245. const renderStateStack = [];
  15246. // public properties
  15247. this.domElement = _canvas;
  15248. // Debug configuration container
  15249. this.debug = {
  15250. /**
  15251. * Enables error checking and reporting when shader programs are being compiled
  15252. * @type {boolean}
  15253. */
  15254. checkShaderErrors: true
  15255. };
  15256. // clearing
  15257. this.autoClear = true;
  15258. this.autoClearColor = true;
  15259. this.autoClearDepth = true;
  15260. this.autoClearStencil = true;
  15261. // scene graph
  15262. this.sortObjects = true;
  15263. // user-defined clipping
  15264. this.clippingPlanes = [];
  15265. this.localClippingEnabled = false;
  15266. // physically based shading
  15267. this.gammaFactor = 2.0; // for backwards compatibility
  15268. this.outputEncoding = LinearEncoding;
  15269. // physical lights
  15270. this.physicallyCorrectLights = false;
  15271. // tone mapping
  15272. this.toneMapping = NoToneMapping;
  15273. this.toneMappingExposure = 1.0;
  15274. // internal properties
  15275. const _this = this;
  15276. let _isContextLost = false;
  15277. // internal state cache
  15278. let _currentActiveCubeFace = 0;
  15279. let _currentActiveMipmapLevel = 0;
  15280. let _currentRenderTarget = null;
  15281. let _currentMaterialId = - 1;
  15282. let _currentCamera = null;
  15283. const _currentViewport = new Vector4();
  15284. const _currentScissor = new Vector4();
  15285. let _currentScissorTest = null;
  15286. //
  15287. let _width = _canvas.width;
  15288. let _height = _canvas.height;
  15289. let _pixelRatio = 1;
  15290. let _opaqueSort = null;
  15291. let _transparentSort = null;
  15292. const _viewport = new Vector4( 0, 0, _width, _height );
  15293. const _scissor = new Vector4( 0, 0, _width, _height );
  15294. let _scissorTest = false;
  15295. //
  15296. const _currentDrawBuffers = [];
  15297. // frustum
  15298. const _frustum = new Frustum();
  15299. // clipping
  15300. let _clippingEnabled = false;
  15301. let _localClippingEnabled = false;
  15302. // transmission
  15303. let _transmissionRenderTarget = null;
  15304. // camera matrices cache
  15305. const _projScreenMatrix = new Matrix4();
  15306. const _vector3 = new Vector3();
  15307. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15308. function getTargetPixelRatio() {
  15309. return _currentRenderTarget === null ? _pixelRatio : 1;
  15310. }
  15311. // initialize
  15312. let _gl = _context;
  15313. function getContext( contextNames, contextAttributes ) {
  15314. for ( let i = 0; i < contextNames.length; i ++ ) {
  15315. const contextName = contextNames[ i ];
  15316. const context = _canvas.getContext( contextName, contextAttributes );
  15317. if ( context !== null ) return context;
  15318. }
  15319. return null;
  15320. }
  15321. try {
  15322. const contextAttributes = {
  15323. alpha: _alpha,
  15324. depth: _depth,
  15325. stencil: _stencil,
  15326. antialias: _antialias,
  15327. premultipliedAlpha: _premultipliedAlpha,
  15328. preserveDrawingBuffer: _preserveDrawingBuffer,
  15329. powerPreference: _powerPreference,
  15330. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15331. };
  15332. // OffscreenCanvas does not have setAttribute, see #22811
  15333. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  15334. // event listeners must be registered before WebGL context is created, see #12753
  15335. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15336. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15337. if ( _gl === null ) {
  15338. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15339. if ( _this.isWebGL1Renderer === true ) {
  15340. contextNames.shift();
  15341. }
  15342. _gl = getContext( contextNames, contextAttributes );
  15343. if ( _gl === null ) {
  15344. if ( getContext( contextNames ) ) {
  15345. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  15346. } else {
  15347. throw new Error( 'Error creating WebGL context.' );
  15348. }
  15349. }
  15350. }
  15351. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15352. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15353. _gl.getShaderPrecisionFormat = function () {
  15354. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15355. };
  15356. }
  15357. } catch ( error ) {
  15358. console.error( 'THREE.WebGLRenderer: ' + error.message );
  15359. throw error;
  15360. }
  15361. let extensions, capabilities, state, info;
  15362. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15363. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15364. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15365. let utils, bindingStates;
  15366. function initGLContext() {
  15367. extensions = new WebGLExtensions( _gl );
  15368. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15369. extensions.init( capabilities );
  15370. utils = new WebGLUtils( _gl, extensions, capabilities );
  15371. state = new WebGLState( _gl, extensions, capabilities );
  15372. _currentDrawBuffers[ 0 ] = 1029;
  15373. info = new WebGLInfo( _gl );
  15374. properties = new WebGLProperties();
  15375. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  15376. cubemaps = new WebGLCubeMaps( _this );
  15377. cubeuvmaps = new WebGLCubeUVMaps( _this );
  15378. attributes = new WebGLAttributes( _gl, capabilities );
  15379. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  15380. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  15381. objects = new WebGLObjects( _gl, geometries, attributes, info );
  15382. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  15383. clipping = new WebGLClipping( properties );
  15384. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  15385. materials = new WebGLMaterials( properties );
  15386. renderLists = new WebGLRenderLists( properties );
  15387. renderStates = new WebGLRenderStates( extensions, capabilities );
  15388. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  15389. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  15390. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  15391. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  15392. info.programs = programCache.programs;
  15393. _this.capabilities = capabilities;
  15394. _this.extensions = extensions;
  15395. _this.properties = properties;
  15396. _this.renderLists = renderLists;
  15397. _this.shadowMap = shadowMap;
  15398. _this.state = state;
  15399. _this.info = info;
  15400. }
  15401. initGLContext();
  15402. // xr
  15403. const xr = new WebXRManager( _this, _gl );
  15404. this.xr = xr;
  15405. // API
  15406. this.getContext = function () {
  15407. return _gl;
  15408. };
  15409. this.getContextAttributes = function () {
  15410. return _gl.getContextAttributes();
  15411. };
  15412. this.forceContextLoss = function () {
  15413. const extension = extensions.get( 'WEBGL_lose_context' );
  15414. if ( extension ) extension.loseContext();
  15415. };
  15416. this.forceContextRestore = function () {
  15417. const extension = extensions.get( 'WEBGL_lose_context' );
  15418. if ( extension ) extension.restoreContext();
  15419. };
  15420. this.getPixelRatio = function () {
  15421. return _pixelRatio;
  15422. };
  15423. this.setPixelRatio = function ( value ) {
  15424. if ( value === undefined ) return;
  15425. _pixelRatio = value;
  15426. this.setSize( _width, _height, false );
  15427. };
  15428. this.getSize = function ( target ) {
  15429. return target.set( _width, _height );
  15430. };
  15431. this.setSize = function ( width, height, updateStyle ) {
  15432. if ( xr.isPresenting ) {
  15433. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  15434. return;
  15435. }
  15436. _width = width;
  15437. _height = height;
  15438. _canvas.width = Math.floor( width * _pixelRatio );
  15439. _canvas.height = Math.floor( height * _pixelRatio );
  15440. if ( updateStyle !== false ) {
  15441. _canvas.style.width = width + 'px';
  15442. _canvas.style.height = height + 'px';
  15443. }
  15444. this.setViewport( 0, 0, width, height );
  15445. };
  15446. this.getDrawingBufferSize = function ( target ) {
  15447. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  15448. };
  15449. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  15450. _width = width;
  15451. _height = height;
  15452. _pixelRatio = pixelRatio;
  15453. _canvas.width = Math.floor( width * pixelRatio );
  15454. _canvas.height = Math.floor( height * pixelRatio );
  15455. this.setViewport( 0, 0, width, height );
  15456. };
  15457. this.getCurrentViewport = function ( target ) {
  15458. return target.copy( _currentViewport );
  15459. };
  15460. this.getViewport = function ( target ) {
  15461. return target.copy( _viewport );
  15462. };
  15463. this.setViewport = function ( x, y, width, height ) {
  15464. if ( x.isVector4 ) {
  15465. _viewport.set( x.x, x.y, x.z, x.w );
  15466. } else {
  15467. _viewport.set( x, y, width, height );
  15468. }
  15469. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  15470. };
  15471. this.getScissor = function ( target ) {
  15472. return target.copy( _scissor );
  15473. };
  15474. this.setScissor = function ( x, y, width, height ) {
  15475. if ( x.isVector4 ) {
  15476. _scissor.set( x.x, x.y, x.z, x.w );
  15477. } else {
  15478. _scissor.set( x, y, width, height );
  15479. }
  15480. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  15481. };
  15482. this.getScissorTest = function () {
  15483. return _scissorTest;
  15484. };
  15485. this.setScissorTest = function ( boolean ) {
  15486. state.setScissorTest( _scissorTest = boolean );
  15487. };
  15488. this.setOpaqueSort = function ( method ) {
  15489. _opaqueSort = method;
  15490. };
  15491. this.setTransparentSort = function ( method ) {
  15492. _transparentSort = method;
  15493. };
  15494. // Clearing
  15495. this.getClearColor = function ( target ) {
  15496. return target.copy( background.getClearColor() );
  15497. };
  15498. this.setClearColor = function () {
  15499. background.setClearColor.apply( background, arguments );
  15500. };
  15501. this.getClearAlpha = function () {
  15502. return background.getClearAlpha();
  15503. };
  15504. this.setClearAlpha = function () {
  15505. background.setClearAlpha.apply( background, arguments );
  15506. };
  15507. this.clear = function ( color, depth, stencil ) {
  15508. let bits = 0;
  15509. if ( color === undefined || color ) bits |= 16384;
  15510. if ( depth === undefined || depth ) bits |= 256;
  15511. if ( stencil === undefined || stencil ) bits |= 1024;
  15512. _gl.clear( bits );
  15513. };
  15514. this.clearColor = function () {
  15515. this.clear( true, false, false );
  15516. };
  15517. this.clearDepth = function () {
  15518. this.clear( false, true, false );
  15519. };
  15520. this.clearStencil = function () {
  15521. this.clear( false, false, true );
  15522. };
  15523. //
  15524. this.dispose = function () {
  15525. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  15526. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  15527. renderLists.dispose();
  15528. renderStates.dispose();
  15529. properties.dispose();
  15530. cubemaps.dispose();
  15531. cubeuvmaps.dispose();
  15532. objects.dispose();
  15533. bindingStates.dispose();
  15534. xr.dispose();
  15535. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  15536. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  15537. if ( _transmissionRenderTarget ) {
  15538. _transmissionRenderTarget.dispose();
  15539. _transmissionRenderTarget = null;
  15540. }
  15541. animation.stop();
  15542. };
  15543. // Events
  15544. function onContextLost( event ) {
  15545. event.preventDefault();
  15546. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  15547. _isContextLost = true;
  15548. }
  15549. function onContextRestore( /* event */ ) {
  15550. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  15551. _isContextLost = false;
  15552. const infoAutoReset = info.autoReset;
  15553. const shadowMapEnabled = shadowMap.enabled;
  15554. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15555. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15556. const shadowMapType = shadowMap.type;
  15557. initGLContext();
  15558. info.autoReset = infoAutoReset;
  15559. shadowMap.enabled = shadowMapEnabled;
  15560. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15561. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15562. shadowMap.type = shadowMapType;
  15563. }
  15564. function onMaterialDispose( event ) {
  15565. const material = event.target;
  15566. material.removeEventListener( 'dispose', onMaterialDispose );
  15567. deallocateMaterial( material );
  15568. }
  15569. // Buffer deallocation
  15570. function deallocateMaterial( material ) {
  15571. releaseMaterialProgramReferences( material );
  15572. properties.remove( material );
  15573. }
  15574. function releaseMaterialProgramReferences( material ) {
  15575. const programs = properties.get( material ).programs;
  15576. if ( programs !== undefined ) {
  15577. programs.forEach( function ( program ) {
  15578. programCache.releaseProgram( program );
  15579. } );
  15580. }
  15581. }
  15582. // Buffer rendering
  15583. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15584. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15585. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15586. const program = setProgram( camera, scene, geometry, material, object );
  15587. state.setMaterial( material, frontFaceCW );
  15588. //
  15589. let index = geometry.index;
  15590. const position = geometry.attributes.position;
  15591. //
  15592. if ( index === null ) {
  15593. if ( position === undefined || position.count === 0 ) return;
  15594. } else if ( index.count === 0 ) {
  15595. return;
  15596. }
  15597. //
  15598. let rangeFactor = 1;
  15599. if ( material.wireframe === true ) {
  15600. index = geometries.getWireframeAttribute( geometry );
  15601. rangeFactor = 2;
  15602. }
  15603. bindingStates.setup( object, material, program, geometry, index );
  15604. let attribute;
  15605. let renderer = bufferRenderer;
  15606. if ( index !== null ) {
  15607. attribute = attributes.get( index );
  15608. renderer = indexedBufferRenderer;
  15609. renderer.setIndex( attribute );
  15610. }
  15611. //
  15612. const dataCount = ( index !== null ) ? index.count : position.count;
  15613. const rangeStart = geometry.drawRange.start * rangeFactor;
  15614. const rangeCount = geometry.drawRange.count * rangeFactor;
  15615. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15616. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15617. const drawStart = Math.max( rangeStart, groupStart );
  15618. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15619. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15620. if ( drawCount === 0 ) return;
  15621. //
  15622. if ( object.isMesh ) {
  15623. if ( material.wireframe === true ) {
  15624. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15625. renderer.setMode( 1 );
  15626. } else {
  15627. renderer.setMode( 4 );
  15628. }
  15629. } else if ( object.isLine ) {
  15630. let lineWidth = material.linewidth;
  15631. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15632. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15633. if ( object.isLineSegments ) {
  15634. renderer.setMode( 1 );
  15635. } else if ( object.isLineLoop ) {
  15636. renderer.setMode( 2 );
  15637. } else {
  15638. renderer.setMode( 3 );
  15639. }
  15640. } else if ( object.isPoints ) {
  15641. renderer.setMode( 0 );
  15642. } else if ( object.isSprite ) {
  15643. renderer.setMode( 4 );
  15644. }
  15645. if ( object.isInstancedMesh ) {
  15646. renderer.renderInstances( drawStart, drawCount, object.count );
  15647. } else if ( geometry.isInstancedBufferGeometry ) {
  15648. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15649. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15650. } else {
  15651. renderer.render( drawStart, drawCount );
  15652. }
  15653. };
  15654. // Compile
  15655. this.compile = function ( scene, camera ) {
  15656. currentRenderState = renderStates.get( scene );
  15657. currentRenderState.init();
  15658. renderStateStack.push( currentRenderState );
  15659. scene.traverseVisible( function ( object ) {
  15660. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15661. currentRenderState.pushLight( object );
  15662. if ( object.castShadow ) {
  15663. currentRenderState.pushShadow( object );
  15664. }
  15665. }
  15666. } );
  15667. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15668. scene.traverse( function ( object ) {
  15669. const material = object.material;
  15670. if ( material ) {
  15671. if ( Array.isArray( material ) ) {
  15672. for ( let i = 0; i < material.length; i ++ ) {
  15673. const material2 = material[ i ];
  15674. getProgram( material2, scene, object );
  15675. }
  15676. } else {
  15677. getProgram( material, scene, object );
  15678. }
  15679. }
  15680. } );
  15681. renderStateStack.pop();
  15682. currentRenderState = null;
  15683. };
  15684. // Animation Loop
  15685. let onAnimationFrameCallback = null;
  15686. function onAnimationFrame( time ) {
  15687. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15688. }
  15689. function onXRSessionStart() {
  15690. animation.stop();
  15691. }
  15692. function onXRSessionEnd() {
  15693. animation.start();
  15694. }
  15695. const animation = new WebGLAnimation();
  15696. animation.setAnimationLoop( onAnimationFrame );
  15697. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15698. this.setAnimationLoop = function ( callback ) {
  15699. onAnimationFrameCallback = callback;
  15700. xr.setAnimationLoop( callback );
  15701. ( callback === null ) ? animation.stop() : animation.start();
  15702. };
  15703. xr.addEventListener( 'sessionstart', onXRSessionStart );
  15704. xr.addEventListener( 'sessionend', onXRSessionEnd );
  15705. // Rendering
  15706. this.render = function ( scene, camera ) {
  15707. if ( camera !== undefined && camera.isCamera !== true ) {
  15708. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15709. return;
  15710. }
  15711. if ( _isContextLost === true ) return;
  15712. // update scene graph
  15713. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15714. // update camera matrices and frustum
  15715. if ( camera.parent === null ) camera.updateMatrixWorld();
  15716. if ( xr.enabled === true && xr.isPresenting === true ) {
  15717. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  15718. camera = xr.getCamera(); // use XR camera for rendering
  15719. }
  15720. //
  15721. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  15722. currentRenderState = renderStates.get( scene, renderStateStack.length );
  15723. currentRenderState.init();
  15724. renderStateStack.push( currentRenderState );
  15725. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15726. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15727. _localClippingEnabled = this.localClippingEnabled;
  15728. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15729. currentRenderList = renderLists.get( scene, renderListStack.length );
  15730. currentRenderList.init();
  15731. renderListStack.push( currentRenderList );
  15732. projectObject( scene, camera, 0, _this.sortObjects );
  15733. currentRenderList.finish();
  15734. if ( _this.sortObjects === true ) {
  15735. currentRenderList.sort( _opaqueSort, _transparentSort );
  15736. }
  15737. //
  15738. if ( _clippingEnabled === true ) clipping.beginShadows();
  15739. const shadowsArray = currentRenderState.state.shadowsArray;
  15740. shadowMap.render( shadowsArray, scene, camera );
  15741. if ( _clippingEnabled === true ) clipping.endShadows();
  15742. //
  15743. if ( this.info.autoReset === true ) this.info.reset();
  15744. //
  15745. background.render( currentRenderList, scene );
  15746. // render scene
  15747. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15748. if ( camera.isArrayCamera ) {
  15749. const cameras = camera.cameras;
  15750. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  15751. const camera2 = cameras[ i ];
  15752. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  15753. }
  15754. } else {
  15755. renderScene( currentRenderList, scene, camera );
  15756. }
  15757. //
  15758. if ( _currentRenderTarget !== null ) {
  15759. // resolve multisample renderbuffers to a single-sample texture if necessary
  15760. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15761. // Generate mipmap if we're using any kind of mipmap filtering
  15762. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15763. }
  15764. //
  15765. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15766. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15767. state.buffers.depth.setTest( true );
  15768. state.buffers.depth.setMask( true );
  15769. state.buffers.color.setMask( true );
  15770. state.setPolygonOffset( false );
  15771. // _gl.finish();
  15772. bindingStates.resetDefaultState();
  15773. _currentMaterialId = - 1;
  15774. _currentCamera = null;
  15775. renderStateStack.pop();
  15776. if ( renderStateStack.length > 0 ) {
  15777. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  15778. } else {
  15779. currentRenderState = null;
  15780. }
  15781. renderListStack.pop();
  15782. if ( renderListStack.length > 0 ) {
  15783. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  15784. } else {
  15785. currentRenderList = null;
  15786. }
  15787. };
  15788. function projectObject( object, camera, groupOrder, sortObjects ) {
  15789. if ( object.visible === false ) return;
  15790. const visible = object.layers.test( camera.layers );
  15791. if ( visible ) {
  15792. if ( object.isGroup ) {
  15793. groupOrder = object.renderOrder;
  15794. } else if ( object.isLOD ) {
  15795. if ( object.autoUpdate === true ) object.update( camera );
  15796. } else if ( object.isLight ) {
  15797. currentRenderState.pushLight( object );
  15798. if ( object.castShadow ) {
  15799. currentRenderState.pushShadow( object );
  15800. }
  15801. } else if ( object.isSprite ) {
  15802. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15803. if ( sortObjects ) {
  15804. _vector3.setFromMatrixPosition( object.matrixWorld )
  15805. .applyMatrix4( _projScreenMatrix );
  15806. }
  15807. const geometry = objects.update( object );
  15808. const material = object.material;
  15809. if ( material.visible ) {
  15810. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15811. }
  15812. }
  15813. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15814. if ( object.isSkinnedMesh ) {
  15815. // update skeleton only once in a frame
  15816. if ( object.skeleton.frame !== info.render.frame ) {
  15817. object.skeleton.update();
  15818. object.skeleton.frame = info.render.frame;
  15819. }
  15820. }
  15821. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15822. if ( sortObjects ) {
  15823. _vector3.setFromMatrixPosition( object.matrixWorld )
  15824. .applyMatrix4( _projScreenMatrix );
  15825. }
  15826. const geometry = objects.update( object );
  15827. const material = object.material;
  15828. if ( Array.isArray( material ) ) {
  15829. const groups = geometry.groups;
  15830. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15831. const group = groups[ i ];
  15832. const groupMaterial = material[ group.materialIndex ];
  15833. if ( groupMaterial && groupMaterial.visible ) {
  15834. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15835. }
  15836. }
  15837. } else if ( material.visible ) {
  15838. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15839. }
  15840. }
  15841. }
  15842. }
  15843. const children = object.children;
  15844. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15845. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15846. }
  15847. }
  15848. function renderScene( currentRenderList, scene, camera, viewport ) {
  15849. const opaqueObjects = currentRenderList.opaque;
  15850. const transmissiveObjects = currentRenderList.transmissive;
  15851. const transparentObjects = currentRenderList.transparent;
  15852. currentRenderState.setupLightsView( camera );
  15853. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  15854. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  15855. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15856. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  15857. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15858. }
  15859. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  15860. if ( _transmissionRenderTarget === null ) {
  15861. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15862. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15863. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  15864. generateMipmaps: true,
  15865. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  15866. minFilter: LinearMipmapLinearFilter,
  15867. magFilter: NearestFilter,
  15868. wrapS: ClampToEdgeWrapping,
  15869. wrapT: ClampToEdgeWrapping,
  15870. useRenderToTexture: extensions.has( 'WEBGL_multisampled_render_to_texture' )
  15871. } );
  15872. }
  15873. const currentRenderTarget = _this.getRenderTarget();
  15874. _this.setRenderTarget( _transmissionRenderTarget );
  15875. _this.clear();
  15876. // Turn off the features which can affect the frag color for opaque objects pass.
  15877. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15878. const currentToneMapping = _this.toneMapping;
  15879. _this.toneMapping = NoToneMapping;
  15880. renderObjects( opaqueObjects, scene, camera );
  15881. _this.toneMapping = currentToneMapping;
  15882. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  15883. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  15884. _this.setRenderTarget( currentRenderTarget );
  15885. }
  15886. function renderObjects( renderList, scene, camera ) {
  15887. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15888. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15889. const renderItem = renderList[ i ];
  15890. const object = renderItem.object;
  15891. const geometry = renderItem.geometry;
  15892. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15893. const group = renderItem.group;
  15894. if ( object.layers.test( camera.layers ) ) {
  15895. renderObject( object, scene, camera, geometry, material, group );
  15896. }
  15897. }
  15898. }
  15899. function renderObject( object, scene, camera, geometry, material, group ) {
  15900. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15901. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15902. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15903. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  15904. if ( material.transparent === true && material.side === DoubleSide ) {
  15905. material.side = BackSide;
  15906. material.needsUpdate = true;
  15907. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15908. material.side = FrontSide;
  15909. material.needsUpdate = true;
  15910. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15911. material.side = DoubleSide;
  15912. } else {
  15913. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15914. }
  15915. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15916. }
  15917. function getProgram( material, scene, object ) {
  15918. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15919. const materialProperties = properties.get( material );
  15920. const lights = currentRenderState.state.lights;
  15921. const shadowsArray = currentRenderState.state.shadowsArray;
  15922. const lightsStateVersion = lights.state.version;
  15923. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15924. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15925. let programs = materialProperties.programs;
  15926. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  15927. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15928. materialProperties.fog = scene.fog;
  15929. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  15930. if ( programs === undefined ) {
  15931. // new material
  15932. material.addEventListener( 'dispose', onMaterialDispose );
  15933. programs = new Map();
  15934. materialProperties.programs = programs;
  15935. }
  15936. let program = programs.get( programCacheKey );
  15937. if ( program !== undefined ) {
  15938. // early out if program and light state is identical
  15939. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  15940. updateCommonMaterialProperties( material, parameters );
  15941. return program;
  15942. }
  15943. } else {
  15944. parameters.uniforms = programCache.getUniforms( material );
  15945. material.onBuild( object, parameters, _this );
  15946. material.onBeforeCompile( parameters, _this );
  15947. program = programCache.acquireProgram( parameters, programCacheKey );
  15948. programs.set( programCacheKey, program );
  15949. materialProperties.uniforms = parameters.uniforms;
  15950. }
  15951. const uniforms = materialProperties.uniforms;
  15952. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  15953. uniforms.clippingPlanes = clipping.uniform;
  15954. }
  15955. updateCommonMaterialProperties( material, parameters );
  15956. // store the light setup it was created for
  15957. materialProperties.needsLights = materialNeedsLights( material );
  15958. materialProperties.lightsStateVersion = lightsStateVersion;
  15959. if ( materialProperties.needsLights ) {
  15960. // wire up the material to this renderer's lighting state
  15961. uniforms.ambientLightColor.value = lights.state.ambient;
  15962. uniforms.lightProbe.value = lights.state.probe;
  15963. uniforms.directionalLights.value = lights.state.directional;
  15964. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15965. uniforms.spotLights.value = lights.state.spot;
  15966. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15967. uniforms.rectAreaLights.value = lights.state.rectArea;
  15968. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15969. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15970. uniforms.pointLights.value = lights.state.point;
  15971. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15972. uniforms.hemisphereLights.value = lights.state.hemi;
  15973. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15974. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15975. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15976. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15977. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15978. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15979. // TODO (abelnation): add area lights shadow info to uniforms
  15980. }
  15981. const progUniforms = program.getUniforms();
  15982. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15983. materialProperties.currentProgram = program;
  15984. materialProperties.uniformsList = uniformsList;
  15985. return program;
  15986. }
  15987. function updateCommonMaterialProperties( material, parameters ) {
  15988. const materialProperties = properties.get( material );
  15989. materialProperties.outputEncoding = parameters.outputEncoding;
  15990. materialProperties.instancing = parameters.instancing;
  15991. materialProperties.skinning = parameters.skinning;
  15992. materialProperties.morphTargets = parameters.morphTargets;
  15993. materialProperties.morphNormals = parameters.morphNormals;
  15994. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  15995. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15996. materialProperties.numIntersection = parameters.numClipIntersection;
  15997. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15998. materialProperties.vertexTangents = parameters.vertexTangents;
  15999. }
  16000. function setProgram( camera, scene, geometry, material, object ) {
  16001. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16002. textures.resetTextureUnits();
  16003. const fog = scene.fog;
  16004. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16005. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  16006. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16007. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16008. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16009. const morphTargets = !! geometry.morphAttributes.position;
  16010. const morphNormals = !! geometry.morphAttributes.normal;
  16011. const morphTargetsCount = !! geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  16012. const materialProperties = properties.get( material );
  16013. const lights = currentRenderState.state.lights;
  16014. if ( _clippingEnabled === true ) {
  16015. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16016. const useCache =
  16017. camera === _currentCamera &&
  16018. material.id === _currentMaterialId;
  16019. // we might want to call this function with some ClippingGroup
  16020. // object instead of the material, once it becomes feasible
  16021. // (#8465, #8379)
  16022. clipping.setState( material, camera, useCache );
  16023. }
  16024. }
  16025. //
  16026. let needsProgramChange = false;
  16027. if ( material.version === materialProperties.__version ) {
  16028. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16029. needsProgramChange = true;
  16030. } else if ( materialProperties.outputEncoding !== encoding ) {
  16031. needsProgramChange = true;
  16032. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16033. needsProgramChange = true;
  16034. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16035. needsProgramChange = true;
  16036. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16037. needsProgramChange = true;
  16038. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16039. needsProgramChange = true;
  16040. } else if ( materialProperties.envMap !== envMap ) {
  16041. needsProgramChange = true;
  16042. } else if ( material.fog && materialProperties.fog !== fog ) {
  16043. needsProgramChange = true;
  16044. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16045. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16046. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16047. needsProgramChange = true;
  16048. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16049. needsProgramChange = true;
  16050. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16051. needsProgramChange = true;
  16052. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16053. needsProgramChange = true;
  16054. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16055. needsProgramChange = true;
  16056. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16057. needsProgramChange = true;
  16058. }
  16059. } else {
  16060. needsProgramChange = true;
  16061. materialProperties.__version = material.version;
  16062. }
  16063. //
  16064. let program = materialProperties.currentProgram;
  16065. if ( needsProgramChange === true ) {
  16066. program = getProgram( material, scene, object );
  16067. }
  16068. let refreshProgram = false;
  16069. let refreshMaterial = false;
  16070. let refreshLights = false;
  16071. const p_uniforms = program.getUniforms(),
  16072. m_uniforms = materialProperties.uniforms;
  16073. if ( state.useProgram( program.program ) ) {
  16074. refreshProgram = true;
  16075. refreshMaterial = true;
  16076. refreshLights = true;
  16077. }
  16078. if ( material.id !== _currentMaterialId ) {
  16079. _currentMaterialId = material.id;
  16080. refreshMaterial = true;
  16081. }
  16082. if ( refreshProgram || _currentCamera !== camera ) {
  16083. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16084. if ( capabilities.logarithmicDepthBuffer ) {
  16085. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16086. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16087. }
  16088. if ( _currentCamera !== camera ) {
  16089. _currentCamera = camera;
  16090. // lighting uniforms depend on the camera so enforce an update
  16091. // now, in case this material supports lights - or later, when
  16092. // the next material that does gets activated:
  16093. refreshMaterial = true; // set to true on material change
  16094. refreshLights = true; // remains set until update done
  16095. }
  16096. // load material specific uniforms
  16097. // (shader material also gets them for the sake of genericity)
  16098. if ( material.isShaderMaterial ||
  16099. material.isMeshPhongMaterial ||
  16100. material.isMeshToonMaterial ||
  16101. material.isMeshStandardMaterial ||
  16102. material.envMap ) {
  16103. const uCamPos = p_uniforms.map.cameraPosition;
  16104. if ( uCamPos !== undefined ) {
  16105. uCamPos.setValue( _gl,
  16106. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16107. }
  16108. }
  16109. if ( material.isMeshPhongMaterial ||
  16110. material.isMeshToonMaterial ||
  16111. material.isMeshLambertMaterial ||
  16112. material.isMeshBasicMaterial ||
  16113. material.isMeshStandardMaterial ||
  16114. material.isShaderMaterial ) {
  16115. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  16116. }
  16117. if ( material.isMeshPhongMaterial ||
  16118. material.isMeshToonMaterial ||
  16119. material.isMeshLambertMaterial ||
  16120. material.isMeshBasicMaterial ||
  16121. material.isMeshStandardMaterial ||
  16122. material.isShaderMaterial ||
  16123. material.isShadowMaterial ||
  16124. object.isSkinnedMesh ) {
  16125. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16126. }
  16127. }
  16128. // skinning and morph target uniforms must be set even if material didn't change
  16129. // auto-setting of texture unit for bone and morph texture must go before other textures
  16130. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16131. if ( object.isSkinnedMesh ) {
  16132. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16133. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16134. const skeleton = object.skeleton;
  16135. if ( skeleton ) {
  16136. if ( capabilities.floatVertexTextures ) {
  16137. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  16138. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  16139. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  16140. } else {
  16141. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  16142. }
  16143. }
  16144. }
  16145. if ( !! geometry && ( geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined ) ) {
  16146. morphtargets.update( object, geometry, material, program );
  16147. }
  16148. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  16149. materialProperties.receiveShadow = object.receiveShadow;
  16150. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  16151. }
  16152. if ( refreshMaterial ) {
  16153. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  16154. if ( materialProperties.needsLights ) {
  16155. // the current material requires lighting info
  16156. // note: all lighting uniforms are always set correctly
  16157. // they simply reference the renderer's state for their
  16158. // values
  16159. //
  16160. // use the current material's .needsUpdate flags to set
  16161. // the GL state when required
  16162. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16163. }
  16164. // refresh uniforms common to several materials
  16165. if ( fog && material.fog ) {
  16166. materials.refreshFogUniforms( m_uniforms, fog );
  16167. }
  16168. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  16169. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16170. }
  16171. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  16172. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16173. material.uniformsNeedUpdate = false;
  16174. }
  16175. if ( material.isSpriteMaterial ) {
  16176. p_uniforms.setValue( _gl, 'center', object.center );
  16177. }
  16178. // common matrices
  16179. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  16180. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  16181. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16182. return program;
  16183. }
  16184. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16185. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  16186. uniforms.ambientLightColor.needsUpdate = value;
  16187. uniforms.lightProbe.needsUpdate = value;
  16188. uniforms.directionalLights.needsUpdate = value;
  16189. uniforms.directionalLightShadows.needsUpdate = value;
  16190. uniforms.pointLights.needsUpdate = value;
  16191. uniforms.pointLightShadows.needsUpdate = value;
  16192. uniforms.spotLights.needsUpdate = value;
  16193. uniforms.spotLightShadows.needsUpdate = value;
  16194. uniforms.rectAreaLights.needsUpdate = value;
  16195. uniforms.hemisphereLights.needsUpdate = value;
  16196. }
  16197. function materialNeedsLights( material ) {
  16198. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  16199. material.isMeshStandardMaterial || material.isShadowMaterial ||
  16200. ( material.isShaderMaterial && material.lights === true );
  16201. }
  16202. this.getActiveCubeFace = function () {
  16203. return _currentActiveCubeFace;
  16204. };
  16205. this.getActiveMipmapLevel = function () {
  16206. return _currentActiveMipmapLevel;
  16207. };
  16208. this.getRenderTarget = function () {
  16209. return _currentRenderTarget;
  16210. };
  16211. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  16212. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  16213. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  16214. const renderTargetProperties = properties.get( renderTarget );
  16215. renderTargetProperties.__hasExternalTextures = true;
  16216. if ( renderTargetProperties.__hasExternalTextures ) {
  16217. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16218. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  16219. // The multisample_render_to_texture extension doesn't work properly if there
  16220. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16221. if ( renderTarget.useRenderToTexture ) {
  16222. console.warn( 'render-to-texture extension was disabled because an external texture was provided' );
  16223. renderTarget.useRenderToTexture = false;
  16224. renderTarget.useRenderbuffer = true;
  16225. }
  16226. }
  16227. }
  16228. };
  16229. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  16230. const renderTargetProperties = properties.get( renderTarget );
  16231. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16232. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16233. };
  16234. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16235. _currentRenderTarget = renderTarget;
  16236. _currentActiveCubeFace = activeCubeFace;
  16237. _currentActiveMipmapLevel = activeMipmapLevel;
  16238. let useDefaultFramebuffer = true;
  16239. if ( renderTarget ) {
  16240. const renderTargetProperties = properties.get( renderTarget );
  16241. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  16242. // We need to make sure to rebind the framebuffer.
  16243. state.bindFramebuffer( 36160, null );
  16244. useDefaultFramebuffer = false;
  16245. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  16246. textures.setupRenderTarget( renderTarget );
  16247. } else if ( renderTargetProperties.__hasExternalTextures ) {
  16248. // Color and depth texture must be rebound in order for the swapchain to update.
  16249. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  16250. }
  16251. }
  16252. let framebuffer = null;
  16253. let isCube = false;
  16254. let isRenderTarget3D = false;
  16255. if ( renderTarget ) {
  16256. const texture = renderTarget.texture;
  16257. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  16258. isRenderTarget3D = true;
  16259. }
  16260. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16261. if ( renderTarget.isWebGLCubeRenderTarget ) {
  16262. framebuffer = __webglFramebuffer[ activeCubeFace ];
  16263. isCube = true;
  16264. } else if ( renderTarget.useRenderbuffer ) {
  16265. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  16266. } else {
  16267. framebuffer = __webglFramebuffer;
  16268. }
  16269. _currentViewport.copy( renderTarget.viewport );
  16270. _currentScissor.copy( renderTarget.scissor );
  16271. _currentScissorTest = renderTarget.scissorTest;
  16272. } else {
  16273. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16274. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16275. _currentScissorTest = _scissorTest;
  16276. }
  16277. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16278. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  16279. let needsUpdate = false;
  16280. if ( renderTarget ) {
  16281. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  16282. const textures = renderTarget.texture;
  16283. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  16284. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  16285. _currentDrawBuffers[ i ] = 36064 + i;
  16286. }
  16287. _currentDrawBuffers.length = textures.length;
  16288. needsUpdate = true;
  16289. }
  16290. } else {
  16291. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  16292. _currentDrawBuffers[ 0 ] = 36064;
  16293. _currentDrawBuffers.length = 1;
  16294. needsUpdate = true;
  16295. }
  16296. }
  16297. } else {
  16298. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  16299. _currentDrawBuffers[ 0 ] = 1029;
  16300. _currentDrawBuffers.length = 1;
  16301. needsUpdate = true;
  16302. }
  16303. }
  16304. if ( needsUpdate ) {
  16305. if ( capabilities.isWebGL2 ) {
  16306. _gl.drawBuffers( _currentDrawBuffers );
  16307. } else {
  16308. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  16309. }
  16310. }
  16311. }
  16312. state.viewport( _currentViewport );
  16313. state.scissor( _currentScissor );
  16314. state.setScissorTest( _currentScissorTest );
  16315. if ( isCube ) {
  16316. const textureProperties = properties.get( renderTarget.texture );
  16317. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16318. } else if ( isRenderTarget3D ) {
  16319. const textureProperties = properties.get( renderTarget.texture );
  16320. const layer = activeCubeFace || 0;
  16321. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16322. }
  16323. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  16324. };
  16325. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  16326. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  16327. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16328. return;
  16329. }
  16330. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16331. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  16332. framebuffer = framebuffer[ activeCubeFaceIndex ];
  16333. }
  16334. if ( framebuffer ) {
  16335. state.bindFramebuffer( 36160, framebuffer );
  16336. try {
  16337. const texture = renderTarget.texture;
  16338. const textureFormat = texture.format;
  16339. const textureType = texture.type;
  16340. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  16341. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16342. return;
  16343. }
  16344. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  16345. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  16346. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16347. ! halfFloatSupportedByExt ) {
  16348. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16349. return;
  16350. }
  16351. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  16352. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16353. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16354. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  16355. }
  16356. } else {
  16357. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16358. }
  16359. } finally {
  16360. // restore framebuffer of current render target if necessary
  16361. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  16362. state.bindFramebuffer( 36160, framebuffer );
  16363. }
  16364. }
  16365. };
  16366. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  16367. const levelScale = Math.pow( 2, - level );
  16368. const width = Math.floor( texture.image.width * levelScale );
  16369. const height = Math.floor( texture.image.height * levelScale );
  16370. let glFormat = utils.convert( texture.format );
  16371. if ( capabilities.isWebGL2 ) {
  16372. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16373. // Not needed in Chrome 93+
  16374. if ( glFormat === 6407 ) glFormat = 32849;
  16375. if ( glFormat === 6408 ) glFormat = 32856;
  16376. }
  16377. textures.setTexture2D( texture, 0 );
  16378. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  16379. state.unbindTexture();
  16380. };
  16381. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  16382. const width = srcTexture.image.width;
  16383. const height = srcTexture.image.height;
  16384. const glFormat = utils.convert( dstTexture.format );
  16385. const glType = utils.convert( dstTexture.type );
  16386. textures.setTexture2D( dstTexture, 0 );
  16387. // As another texture upload may have changed pixelStorei
  16388. // parameters, make sure they are correct for the dstTexture
  16389. _gl.pixelStorei( 37440, dstTexture.flipY );
  16390. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16391. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16392. if ( srcTexture.isDataTexture ) {
  16393. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  16394. } else {
  16395. if ( srcTexture.isCompressedTexture ) {
  16396. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  16397. } else {
  16398. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  16399. }
  16400. }
  16401. // Generate mipmaps only when copying level 0
  16402. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  16403. state.unbindTexture();
  16404. };
  16405. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  16406. if ( _this.isWebGL1Renderer ) {
  16407. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  16408. return;
  16409. }
  16410. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16411. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16412. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16413. const glFormat = utils.convert( dstTexture.format );
  16414. const glType = utils.convert( dstTexture.type );
  16415. let glTarget;
  16416. if ( dstTexture.isDataTexture3D ) {
  16417. textures.setTexture3D( dstTexture, 0 );
  16418. glTarget = 32879;
  16419. } else if ( dstTexture.isDataTexture2DArray ) {
  16420. textures.setTexture2DArray( dstTexture, 0 );
  16421. glTarget = 35866;
  16422. } else {
  16423. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  16424. return;
  16425. }
  16426. _gl.pixelStorei( 37440, dstTexture.flipY );
  16427. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16428. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16429. const unpackRowLen = _gl.getParameter( 3314 );
  16430. const unpackImageHeight = _gl.getParameter( 32878 );
  16431. const unpackSkipPixels = _gl.getParameter( 3316 );
  16432. const unpackSkipRows = _gl.getParameter( 3315 );
  16433. const unpackSkipImages = _gl.getParameter( 32877 );
  16434. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  16435. _gl.pixelStorei( 3314, image.width );
  16436. _gl.pixelStorei( 32878, image.height );
  16437. _gl.pixelStorei( 3316, sourceBox.min.x );
  16438. _gl.pixelStorei( 3315, sourceBox.min.y );
  16439. _gl.pixelStorei( 32877, sourceBox.min.z );
  16440. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  16441. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  16442. } else {
  16443. if ( srcTexture.isCompressedTexture ) {
  16444. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  16445. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  16446. } else {
  16447. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  16448. }
  16449. }
  16450. _gl.pixelStorei( 3314, unpackRowLen );
  16451. _gl.pixelStorei( 32878, unpackImageHeight );
  16452. _gl.pixelStorei( 3316, unpackSkipPixels );
  16453. _gl.pixelStorei( 3315, unpackSkipRows );
  16454. _gl.pixelStorei( 32877, unpackSkipImages );
  16455. // Generate mipmaps only when copying level 0
  16456. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  16457. state.unbindTexture();
  16458. };
  16459. this.initTexture = function ( texture ) {
  16460. textures.setTexture2D( texture, 0 );
  16461. state.unbindTexture();
  16462. };
  16463. this.resetState = function () {
  16464. _currentActiveCubeFace = 0;
  16465. _currentActiveMipmapLevel = 0;
  16466. _currentRenderTarget = null;
  16467. state.reset();
  16468. bindingStates.reset();
  16469. };
  16470. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16471. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  16472. }
  16473. }
  16474. WebGLRenderer.prototype.isWebGLRenderer = true;
  16475. class WebGL1Renderer extends WebGLRenderer {}
  16476. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16477. class FogExp2 {
  16478. constructor( color, density = 0.00025 ) {
  16479. this.name = '';
  16480. this.color = new Color( color );
  16481. this.density = density;
  16482. }
  16483. clone() {
  16484. return new FogExp2( this.color, this.density );
  16485. }
  16486. toJSON( /* meta */ ) {
  16487. return {
  16488. type: 'FogExp2',
  16489. color: this.color.getHex(),
  16490. density: this.density
  16491. };
  16492. }
  16493. }
  16494. FogExp2.prototype.isFogExp2 = true;
  16495. class Fog {
  16496. constructor( color, near = 1, far = 1000 ) {
  16497. this.name = '';
  16498. this.color = new Color( color );
  16499. this.near = near;
  16500. this.far = far;
  16501. }
  16502. clone() {
  16503. return new Fog( this.color, this.near, this.far );
  16504. }
  16505. toJSON( /* meta */ ) {
  16506. return {
  16507. type: 'Fog',
  16508. color: this.color.getHex(),
  16509. near: this.near,
  16510. far: this.far
  16511. };
  16512. }
  16513. }
  16514. Fog.prototype.isFog = true;
  16515. class Scene extends Object3D {
  16516. constructor() {
  16517. super();
  16518. this.type = 'Scene';
  16519. this.background = null;
  16520. this.environment = null;
  16521. this.fog = null;
  16522. this.overrideMaterial = null;
  16523. this.autoUpdate = true; // checked by the renderer
  16524. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16525. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  16526. }
  16527. }
  16528. copy( source, recursive ) {
  16529. super.copy( source, recursive );
  16530. if ( source.background !== null ) this.background = source.background.clone();
  16531. if ( source.environment !== null ) this.environment = source.environment.clone();
  16532. if ( source.fog !== null ) this.fog = source.fog.clone();
  16533. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16534. this.autoUpdate = source.autoUpdate;
  16535. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16536. return this;
  16537. }
  16538. toJSON( meta ) {
  16539. const data = super.toJSON( meta );
  16540. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16541. return data;
  16542. }
  16543. }
  16544. Scene.prototype.isScene = true;
  16545. class InterleavedBuffer {
  16546. constructor( array, stride ) {
  16547. this.array = array;
  16548. this.stride = stride;
  16549. this.count = array !== undefined ? array.length / stride : 0;
  16550. this.usage = StaticDrawUsage;
  16551. this.updateRange = { offset: 0, count: - 1 };
  16552. this.version = 0;
  16553. this.uuid = generateUUID();
  16554. }
  16555. onUploadCallback() {}
  16556. set needsUpdate( value ) {
  16557. if ( value === true ) this.version ++;
  16558. }
  16559. setUsage( value ) {
  16560. this.usage = value;
  16561. return this;
  16562. }
  16563. copy( source ) {
  16564. this.array = new source.array.constructor( source.array );
  16565. this.count = source.count;
  16566. this.stride = source.stride;
  16567. this.usage = source.usage;
  16568. return this;
  16569. }
  16570. copyAt( index1, attribute, index2 ) {
  16571. index1 *= this.stride;
  16572. index2 *= attribute.stride;
  16573. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  16574. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  16575. }
  16576. return this;
  16577. }
  16578. set( value, offset = 0 ) {
  16579. this.array.set( value, offset );
  16580. return this;
  16581. }
  16582. clone( data ) {
  16583. if ( data.arrayBuffers === undefined ) {
  16584. data.arrayBuffers = {};
  16585. }
  16586. if ( this.array.buffer._uuid === undefined ) {
  16587. this.array.buffer._uuid = generateUUID();
  16588. }
  16589. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16590. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  16591. }
  16592. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  16593. const ib = new this.constructor( array, this.stride );
  16594. ib.setUsage( this.usage );
  16595. return ib;
  16596. }
  16597. onUpload( callback ) {
  16598. this.onUploadCallback = callback;
  16599. return this;
  16600. }
  16601. toJSON( data ) {
  16602. if ( data.arrayBuffers === undefined ) {
  16603. data.arrayBuffers = {};
  16604. }
  16605. // generate UUID for array buffer if necessary
  16606. if ( this.array.buffer._uuid === undefined ) {
  16607. this.array.buffer._uuid = generateUUID();
  16608. }
  16609. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16610. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  16611. }
  16612. //
  16613. return {
  16614. uuid: this.uuid,
  16615. buffer: this.array.buffer._uuid,
  16616. type: this.array.constructor.name,
  16617. stride: this.stride
  16618. };
  16619. }
  16620. }
  16621. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16622. const _vector$6 = /*@__PURE__*/ new Vector3();
  16623. class InterleavedBufferAttribute {
  16624. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  16625. this.name = '';
  16626. this.data = interleavedBuffer;
  16627. this.itemSize = itemSize;
  16628. this.offset = offset;
  16629. this.normalized = normalized === true;
  16630. }
  16631. get count() {
  16632. return this.data.count;
  16633. }
  16634. get array() {
  16635. return this.data.array;
  16636. }
  16637. set needsUpdate( value ) {
  16638. this.data.needsUpdate = value;
  16639. }
  16640. applyMatrix4( m ) {
  16641. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  16642. _vector$6.x = this.getX( i );
  16643. _vector$6.y = this.getY( i );
  16644. _vector$6.z = this.getZ( i );
  16645. _vector$6.applyMatrix4( m );
  16646. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16647. }
  16648. return this;
  16649. }
  16650. applyNormalMatrix( m ) {
  16651. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16652. _vector$6.x = this.getX( i );
  16653. _vector$6.y = this.getY( i );
  16654. _vector$6.z = this.getZ( i );
  16655. _vector$6.applyNormalMatrix( m );
  16656. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16657. }
  16658. return this;
  16659. }
  16660. transformDirection( m ) {
  16661. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16662. _vector$6.x = this.getX( i );
  16663. _vector$6.y = this.getY( i );
  16664. _vector$6.z = this.getZ( i );
  16665. _vector$6.transformDirection( m );
  16666. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16667. }
  16668. return this;
  16669. }
  16670. setX( index, x ) {
  16671. this.data.array[ index * this.data.stride + this.offset ] = x;
  16672. return this;
  16673. }
  16674. setY( index, y ) {
  16675. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  16676. return this;
  16677. }
  16678. setZ( index, z ) {
  16679. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  16680. return this;
  16681. }
  16682. setW( index, w ) {
  16683. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  16684. return this;
  16685. }
  16686. getX( index ) {
  16687. return this.data.array[ index * this.data.stride + this.offset ];
  16688. }
  16689. getY( index ) {
  16690. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  16691. }
  16692. getZ( index ) {
  16693. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  16694. }
  16695. getW( index ) {
  16696. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  16697. }
  16698. setXY( index, x, y ) {
  16699. index = index * this.data.stride + this.offset;
  16700. this.data.array[ index + 0 ] = x;
  16701. this.data.array[ index + 1 ] = y;
  16702. return this;
  16703. }
  16704. setXYZ( index, x, y, z ) {
  16705. index = index * this.data.stride + this.offset;
  16706. this.data.array[ index + 0 ] = x;
  16707. this.data.array[ index + 1 ] = y;
  16708. this.data.array[ index + 2 ] = z;
  16709. return this;
  16710. }
  16711. setXYZW( index, x, y, z, w ) {
  16712. index = index * this.data.stride + this.offset;
  16713. this.data.array[ index + 0 ] = x;
  16714. this.data.array[ index + 1 ] = y;
  16715. this.data.array[ index + 2 ] = z;
  16716. this.data.array[ index + 3 ] = w;
  16717. return this;
  16718. }
  16719. clone( data ) {
  16720. if ( data === undefined ) {
  16721. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16722. const array = [];
  16723. for ( let i = 0; i < this.count; i ++ ) {
  16724. const index = i * this.data.stride + this.offset;
  16725. for ( let j = 0; j < this.itemSize; j ++ ) {
  16726. array.push( this.data.array[ index + j ] );
  16727. }
  16728. }
  16729. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16730. } else {
  16731. if ( data.interleavedBuffers === undefined ) {
  16732. data.interleavedBuffers = {};
  16733. }
  16734. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16735. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16736. }
  16737. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16738. }
  16739. }
  16740. toJSON( data ) {
  16741. if ( data === undefined ) {
  16742. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16743. const array = [];
  16744. for ( let i = 0; i < this.count; i ++ ) {
  16745. const index = i * this.data.stride + this.offset;
  16746. for ( let j = 0; j < this.itemSize; j ++ ) {
  16747. array.push( this.data.array[ index + j ] );
  16748. }
  16749. }
  16750. // deinterleave data and save it as an ordinary buffer attribute for now
  16751. return {
  16752. itemSize: this.itemSize,
  16753. type: this.array.constructor.name,
  16754. array: array,
  16755. normalized: this.normalized
  16756. };
  16757. } else {
  16758. // save as true interlaved attribtue
  16759. if ( data.interleavedBuffers === undefined ) {
  16760. data.interleavedBuffers = {};
  16761. }
  16762. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16763. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16764. }
  16765. return {
  16766. isInterleavedBufferAttribute: true,
  16767. itemSize: this.itemSize,
  16768. data: this.data.uuid,
  16769. offset: this.offset,
  16770. normalized: this.normalized
  16771. };
  16772. }
  16773. }
  16774. }
  16775. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16776. /**
  16777. * parameters = {
  16778. * color: <hex>,
  16779. * map: new THREE.Texture( <Image> ),
  16780. * alphaMap: new THREE.Texture( <Image> ),
  16781. * rotation: <float>,
  16782. * sizeAttenuation: <bool>
  16783. * }
  16784. */
  16785. class SpriteMaterial extends Material {
  16786. constructor( parameters ) {
  16787. super();
  16788. this.type = 'SpriteMaterial';
  16789. this.color = new Color( 0xffffff );
  16790. this.map = null;
  16791. this.alphaMap = null;
  16792. this.rotation = 0;
  16793. this.sizeAttenuation = true;
  16794. this.transparent = true;
  16795. this.setValues( parameters );
  16796. }
  16797. copy( source ) {
  16798. super.copy( source );
  16799. this.color.copy( source.color );
  16800. this.map = source.map;
  16801. this.alphaMap = source.alphaMap;
  16802. this.rotation = source.rotation;
  16803. this.sizeAttenuation = source.sizeAttenuation;
  16804. return this;
  16805. }
  16806. }
  16807. SpriteMaterial.prototype.isSpriteMaterial = true;
  16808. let _geometry;
  16809. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16810. const _worldScale = /*@__PURE__*/ new Vector3();
  16811. const _mvPosition = /*@__PURE__*/ new Vector3();
  16812. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16813. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16814. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16815. const _vA = /*@__PURE__*/ new Vector3();
  16816. const _vB = /*@__PURE__*/ new Vector3();
  16817. const _vC = /*@__PURE__*/ new Vector3();
  16818. const _uvA = /*@__PURE__*/ new Vector2();
  16819. const _uvB = /*@__PURE__*/ new Vector2();
  16820. const _uvC = /*@__PURE__*/ new Vector2();
  16821. class Sprite extends Object3D {
  16822. constructor( material ) {
  16823. super();
  16824. this.type = 'Sprite';
  16825. if ( _geometry === undefined ) {
  16826. _geometry = new BufferGeometry();
  16827. const float32Array = new Float32Array( [
  16828. - 0.5, - 0.5, 0, 0, 0,
  16829. 0.5, - 0.5, 0, 1, 0,
  16830. 0.5, 0.5, 0, 1, 1,
  16831. - 0.5, 0.5, 0, 0, 1
  16832. ] );
  16833. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16834. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16835. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16836. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16837. }
  16838. this.geometry = _geometry;
  16839. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16840. this.center = new Vector2( 0.5, 0.5 );
  16841. }
  16842. raycast( raycaster, intersects ) {
  16843. if ( raycaster.camera === null ) {
  16844. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16845. }
  16846. _worldScale.setFromMatrixScale( this.matrixWorld );
  16847. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16848. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16849. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16850. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16851. _worldScale.multiplyScalar( - _mvPosition.z );
  16852. }
  16853. const rotation = this.material.rotation;
  16854. let sin, cos;
  16855. if ( rotation !== 0 ) {
  16856. cos = Math.cos( rotation );
  16857. sin = Math.sin( rotation );
  16858. }
  16859. const center = this.center;
  16860. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16861. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16862. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16863. _uvA.set( 0, 0 );
  16864. _uvB.set( 1, 0 );
  16865. _uvC.set( 1, 1 );
  16866. // check first triangle
  16867. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  16868. if ( intersect === null ) {
  16869. // check second triangle
  16870. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16871. _uvB.set( 0, 1 );
  16872. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  16873. if ( intersect === null ) {
  16874. return;
  16875. }
  16876. }
  16877. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16878. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16879. intersects.push( {
  16880. distance: distance,
  16881. point: _intersectPoint.clone(),
  16882. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  16883. face: null,
  16884. object: this
  16885. } );
  16886. }
  16887. copy( source ) {
  16888. super.copy( source );
  16889. if ( source.center !== undefined ) this.center.copy( source.center );
  16890. this.material = source.material;
  16891. return this;
  16892. }
  16893. }
  16894. Sprite.prototype.isSprite = true;
  16895. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16896. // compute position in camera space
  16897. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16898. // to check if rotation is not zero
  16899. if ( sin !== undefined ) {
  16900. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16901. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16902. } else {
  16903. _rotatedPosition.copy( _alignedPosition );
  16904. }
  16905. vertexPosition.copy( mvPosition );
  16906. vertexPosition.x += _rotatedPosition.x;
  16907. vertexPosition.y += _rotatedPosition.y;
  16908. // transform to world space
  16909. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16910. }
  16911. const _v1$2 = /*@__PURE__*/ new Vector3();
  16912. const _v2$1 = /*@__PURE__*/ new Vector3();
  16913. class LOD extends Object3D {
  16914. constructor() {
  16915. super();
  16916. this._currentLevel = 0;
  16917. this.type = 'LOD';
  16918. Object.defineProperties( this, {
  16919. levels: {
  16920. enumerable: true,
  16921. value: []
  16922. },
  16923. isLOD: {
  16924. value: true,
  16925. }
  16926. } );
  16927. this.autoUpdate = true;
  16928. }
  16929. copy( source ) {
  16930. super.copy( source, false );
  16931. const levels = source.levels;
  16932. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16933. const level = levels[ i ];
  16934. this.addLevel( level.object.clone(), level.distance );
  16935. }
  16936. this.autoUpdate = source.autoUpdate;
  16937. return this;
  16938. }
  16939. addLevel( object, distance = 0 ) {
  16940. distance = Math.abs( distance );
  16941. const levels = this.levels;
  16942. let l;
  16943. for ( l = 0; l < levels.length; l ++ ) {
  16944. if ( distance < levels[ l ].distance ) {
  16945. break;
  16946. }
  16947. }
  16948. levels.splice( l, 0, { distance: distance, object: object } );
  16949. this.add( object );
  16950. return this;
  16951. }
  16952. getCurrentLevel() {
  16953. return this._currentLevel;
  16954. }
  16955. getObjectForDistance( distance ) {
  16956. const levels = this.levels;
  16957. if ( levels.length > 0 ) {
  16958. let i, l;
  16959. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16960. if ( distance < levels[ i ].distance ) {
  16961. break;
  16962. }
  16963. }
  16964. return levels[ i - 1 ].object;
  16965. }
  16966. return null;
  16967. }
  16968. raycast( raycaster, intersects ) {
  16969. const levels = this.levels;
  16970. if ( levels.length > 0 ) {
  16971. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16972. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16973. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16974. }
  16975. }
  16976. update( camera ) {
  16977. const levels = this.levels;
  16978. if ( levels.length > 1 ) {
  16979. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16980. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16981. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16982. levels[ 0 ].object.visible = true;
  16983. let i, l;
  16984. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16985. if ( distance >= levels[ i ].distance ) {
  16986. levels[ i - 1 ].object.visible = false;
  16987. levels[ i ].object.visible = true;
  16988. } else {
  16989. break;
  16990. }
  16991. }
  16992. this._currentLevel = i - 1;
  16993. for ( ; i < l; i ++ ) {
  16994. levels[ i ].object.visible = false;
  16995. }
  16996. }
  16997. }
  16998. toJSON( meta ) {
  16999. const data = super.toJSON( meta );
  17000. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17001. data.object.levels = [];
  17002. const levels = this.levels;
  17003. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17004. const level = levels[ i ];
  17005. data.object.levels.push( {
  17006. object: level.object.uuid,
  17007. distance: level.distance
  17008. } );
  17009. }
  17010. return data;
  17011. }
  17012. }
  17013. const _basePosition = /*@__PURE__*/ new Vector3();
  17014. const _skinIndex = /*@__PURE__*/ new Vector4();
  17015. const _skinWeight = /*@__PURE__*/ new Vector4();
  17016. const _vector$5 = /*@__PURE__*/ new Vector3();
  17017. const _matrix = /*@__PURE__*/ new Matrix4();
  17018. class SkinnedMesh extends Mesh {
  17019. constructor( geometry, material ) {
  17020. super( geometry, material );
  17021. this.type = 'SkinnedMesh';
  17022. this.bindMode = 'attached';
  17023. this.bindMatrix = new Matrix4();
  17024. this.bindMatrixInverse = new Matrix4();
  17025. }
  17026. copy( source ) {
  17027. super.copy( source );
  17028. this.bindMode = source.bindMode;
  17029. this.bindMatrix.copy( source.bindMatrix );
  17030. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17031. this.skeleton = source.skeleton;
  17032. return this;
  17033. }
  17034. bind( skeleton, bindMatrix ) {
  17035. this.skeleton = skeleton;
  17036. if ( bindMatrix === undefined ) {
  17037. this.updateMatrixWorld( true );
  17038. this.skeleton.calculateInverses();
  17039. bindMatrix = this.matrixWorld;
  17040. }
  17041. this.bindMatrix.copy( bindMatrix );
  17042. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17043. }
  17044. pose() {
  17045. this.skeleton.pose();
  17046. }
  17047. normalizeSkinWeights() {
  17048. const vector = new Vector4();
  17049. const skinWeight = this.geometry.attributes.skinWeight;
  17050. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17051. vector.x = skinWeight.getX( i );
  17052. vector.y = skinWeight.getY( i );
  17053. vector.z = skinWeight.getZ( i );
  17054. vector.w = skinWeight.getW( i );
  17055. const scale = 1.0 / vector.manhattanLength();
  17056. if ( scale !== Infinity ) {
  17057. vector.multiplyScalar( scale );
  17058. } else {
  17059. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17060. }
  17061. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17062. }
  17063. }
  17064. updateMatrixWorld( force ) {
  17065. super.updateMatrixWorld( force );
  17066. if ( this.bindMode === 'attached' ) {
  17067. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17068. } else if ( this.bindMode === 'detached' ) {
  17069. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17070. } else {
  17071. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17072. }
  17073. }
  17074. boneTransform( index, target ) {
  17075. const skeleton = this.skeleton;
  17076. const geometry = this.geometry;
  17077. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17078. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17079. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17080. target.set( 0, 0, 0 );
  17081. for ( let i = 0; i < 4; i ++ ) {
  17082. const weight = _skinWeight.getComponent( i );
  17083. if ( weight !== 0 ) {
  17084. const boneIndex = _skinIndex.getComponent( i );
  17085. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17086. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  17087. }
  17088. }
  17089. return target.applyMatrix4( this.bindMatrixInverse );
  17090. }
  17091. }
  17092. SkinnedMesh.prototype.isSkinnedMesh = true;
  17093. class Bone extends Object3D {
  17094. constructor() {
  17095. super();
  17096. this.type = 'Bone';
  17097. }
  17098. }
  17099. Bone.prototype.isBone = true;
  17100. class DataTexture extends Texture {
  17101. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  17102. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17103. this.image = { data: data, width: width, height: height };
  17104. this.magFilter = magFilter;
  17105. this.minFilter = minFilter;
  17106. this.generateMipmaps = false;
  17107. this.flipY = false;
  17108. this.unpackAlignment = 1;
  17109. this.needsUpdate = true;
  17110. }
  17111. }
  17112. DataTexture.prototype.isDataTexture = true;
  17113. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17114. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17115. class Skeleton {
  17116. constructor( bones = [], boneInverses = [] ) {
  17117. this.uuid = generateUUID();
  17118. this.bones = bones.slice( 0 );
  17119. this.boneInverses = boneInverses;
  17120. this.boneMatrices = null;
  17121. this.boneTexture = null;
  17122. this.boneTextureSize = 0;
  17123. this.frame = - 1;
  17124. this.init();
  17125. }
  17126. init() {
  17127. const bones = this.bones;
  17128. const boneInverses = this.boneInverses;
  17129. this.boneMatrices = new Float32Array( bones.length * 16 );
  17130. // calculate inverse bone matrices if necessary
  17131. if ( boneInverses.length === 0 ) {
  17132. this.calculateInverses();
  17133. } else {
  17134. // handle special case
  17135. if ( bones.length !== boneInverses.length ) {
  17136. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17137. this.boneInverses = [];
  17138. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17139. this.boneInverses.push( new Matrix4() );
  17140. }
  17141. }
  17142. }
  17143. }
  17144. calculateInverses() {
  17145. this.boneInverses.length = 0;
  17146. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17147. const inverse = new Matrix4();
  17148. if ( this.bones[ i ] ) {
  17149. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17150. }
  17151. this.boneInverses.push( inverse );
  17152. }
  17153. }
  17154. pose() {
  17155. // recover the bind-time world matrices
  17156. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17157. const bone = this.bones[ i ];
  17158. if ( bone ) {
  17159. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17160. }
  17161. }
  17162. // compute the local matrices, positions, rotations and scales
  17163. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17164. const bone = this.bones[ i ];
  17165. if ( bone ) {
  17166. if ( bone.parent && bone.parent.isBone ) {
  17167. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17168. bone.matrix.multiply( bone.matrixWorld );
  17169. } else {
  17170. bone.matrix.copy( bone.matrixWorld );
  17171. }
  17172. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17173. }
  17174. }
  17175. }
  17176. update() {
  17177. const bones = this.bones;
  17178. const boneInverses = this.boneInverses;
  17179. const boneMatrices = this.boneMatrices;
  17180. const boneTexture = this.boneTexture;
  17181. // flatten bone matrices to array
  17182. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17183. // compute the offset between the current and the original transform
  17184. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17185. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17186. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17187. }
  17188. if ( boneTexture !== null ) {
  17189. boneTexture.needsUpdate = true;
  17190. }
  17191. }
  17192. clone() {
  17193. return new Skeleton( this.bones, this.boneInverses );
  17194. }
  17195. computeBoneTexture() {
  17196. // layout (1 matrix = 4 pixels)
  17197. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17198. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17199. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17200. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17201. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17202. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17203. size = ceilPowerOfTwo( size );
  17204. size = Math.max( size, 4 );
  17205. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17206. boneMatrices.set( this.boneMatrices ); // copy current values
  17207. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17208. this.boneMatrices = boneMatrices;
  17209. this.boneTexture = boneTexture;
  17210. this.boneTextureSize = size;
  17211. return this;
  17212. }
  17213. getBoneByName( name ) {
  17214. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17215. const bone = this.bones[ i ];
  17216. if ( bone.name === name ) {
  17217. return bone;
  17218. }
  17219. }
  17220. return undefined;
  17221. }
  17222. dispose( ) {
  17223. if ( this.boneTexture !== null ) {
  17224. this.boneTexture.dispose();
  17225. this.boneTexture = null;
  17226. }
  17227. }
  17228. fromJSON( json, bones ) {
  17229. this.uuid = json.uuid;
  17230. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17231. const uuid = json.bones[ i ];
  17232. let bone = bones[ uuid ];
  17233. if ( bone === undefined ) {
  17234. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  17235. bone = new Bone();
  17236. }
  17237. this.bones.push( bone );
  17238. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17239. }
  17240. this.init();
  17241. return this;
  17242. }
  17243. toJSON() {
  17244. const data = {
  17245. metadata: {
  17246. version: 4.5,
  17247. type: 'Skeleton',
  17248. generator: 'Skeleton.toJSON'
  17249. },
  17250. bones: [],
  17251. boneInverses: []
  17252. };
  17253. data.uuid = this.uuid;
  17254. const bones = this.bones;
  17255. const boneInverses = this.boneInverses;
  17256. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17257. const bone = bones[ i ];
  17258. data.bones.push( bone.uuid );
  17259. const boneInverse = boneInverses[ i ];
  17260. data.boneInverses.push( boneInverse.toArray() );
  17261. }
  17262. return data;
  17263. }
  17264. }
  17265. class InstancedBufferAttribute extends BufferAttribute {
  17266. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17267. if ( typeof normalized === 'number' ) {
  17268. meshPerAttribute = normalized;
  17269. normalized = false;
  17270. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  17271. }
  17272. super( array, itemSize, normalized );
  17273. this.meshPerAttribute = meshPerAttribute;
  17274. }
  17275. copy( source ) {
  17276. super.copy( source );
  17277. this.meshPerAttribute = source.meshPerAttribute;
  17278. return this;
  17279. }
  17280. toJSON() {
  17281. const data = super.toJSON();
  17282. data.meshPerAttribute = this.meshPerAttribute;
  17283. data.isInstancedBufferAttribute = true;
  17284. return data;
  17285. }
  17286. }
  17287. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17288. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17289. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17290. const _instanceIntersects = [];
  17291. const _mesh = /*@__PURE__*/ new Mesh();
  17292. class InstancedMesh extends Mesh {
  17293. constructor( geometry, material, count ) {
  17294. super( geometry, material );
  17295. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17296. this.instanceColor = null;
  17297. this.count = count;
  17298. this.frustumCulled = false;
  17299. }
  17300. copy( source ) {
  17301. super.copy( source );
  17302. this.instanceMatrix.copy( source.instanceMatrix );
  17303. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17304. this.count = source.count;
  17305. return this;
  17306. }
  17307. getColorAt( index, color ) {
  17308. color.fromArray( this.instanceColor.array, index * 3 );
  17309. }
  17310. getMatrixAt( index, matrix ) {
  17311. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17312. }
  17313. raycast( raycaster, intersects ) {
  17314. const matrixWorld = this.matrixWorld;
  17315. const raycastTimes = this.count;
  17316. _mesh.geometry = this.geometry;
  17317. _mesh.material = this.material;
  17318. if ( _mesh.material === undefined ) return;
  17319. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  17320. // calculate the world matrix for each instance
  17321. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  17322. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  17323. // the mesh represents this single instance
  17324. _mesh.matrixWorld = _instanceWorldMatrix;
  17325. _mesh.raycast( raycaster, _instanceIntersects );
  17326. // process the result of raycast
  17327. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  17328. const intersect = _instanceIntersects[ i ];
  17329. intersect.instanceId = instanceId;
  17330. intersect.object = this;
  17331. intersects.push( intersect );
  17332. }
  17333. _instanceIntersects.length = 0;
  17334. }
  17335. }
  17336. setColorAt( index, color ) {
  17337. if ( this.instanceColor === null ) {
  17338. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  17339. }
  17340. color.toArray( this.instanceColor.array, index * 3 );
  17341. }
  17342. setMatrixAt( index, matrix ) {
  17343. matrix.toArray( this.instanceMatrix.array, index * 16 );
  17344. }
  17345. updateMorphTargets() {
  17346. }
  17347. dispose() {
  17348. this.dispatchEvent( { type: 'dispose' } );
  17349. }
  17350. }
  17351. InstancedMesh.prototype.isInstancedMesh = true;
  17352. /**
  17353. * parameters = {
  17354. * color: <hex>,
  17355. * opacity: <float>,
  17356. *
  17357. * linewidth: <float>,
  17358. * linecap: "round",
  17359. * linejoin: "round"
  17360. * }
  17361. */
  17362. class LineBasicMaterial extends Material {
  17363. constructor( parameters ) {
  17364. super();
  17365. this.type = 'LineBasicMaterial';
  17366. this.color = new Color( 0xffffff );
  17367. this.linewidth = 1;
  17368. this.linecap = 'round';
  17369. this.linejoin = 'round';
  17370. this.setValues( parameters );
  17371. }
  17372. copy( source ) {
  17373. super.copy( source );
  17374. this.color.copy( source.color );
  17375. this.linewidth = source.linewidth;
  17376. this.linecap = source.linecap;
  17377. this.linejoin = source.linejoin;
  17378. return this;
  17379. }
  17380. }
  17381. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17382. const _start$1 = /*@__PURE__*/ new Vector3();
  17383. const _end$1 = /*@__PURE__*/ new Vector3();
  17384. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  17385. const _ray$1 = /*@__PURE__*/ new Ray();
  17386. const _sphere$1 = /*@__PURE__*/ new Sphere();
  17387. class Line extends Object3D {
  17388. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  17389. super();
  17390. this.type = 'Line';
  17391. this.geometry = geometry;
  17392. this.material = material;
  17393. this.updateMorphTargets();
  17394. }
  17395. copy( source ) {
  17396. super.copy( source );
  17397. this.material = source.material;
  17398. this.geometry = source.geometry;
  17399. return this;
  17400. }
  17401. computeLineDistances() {
  17402. const geometry = this.geometry;
  17403. if ( geometry.isBufferGeometry ) {
  17404. // we assume non-indexed geometry
  17405. if ( geometry.index === null ) {
  17406. const positionAttribute = geometry.attributes.position;
  17407. const lineDistances = [ 0 ];
  17408. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  17409. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  17410. _end$1.fromBufferAttribute( positionAttribute, i );
  17411. lineDistances[ i ] = lineDistances[ i - 1 ];
  17412. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  17413. }
  17414. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17415. } else {
  17416. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17417. }
  17418. } else if ( geometry.isGeometry ) {
  17419. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17420. }
  17421. return this;
  17422. }
  17423. raycast( raycaster, intersects ) {
  17424. const geometry = this.geometry;
  17425. const matrixWorld = this.matrixWorld;
  17426. const threshold = raycaster.params.Line.threshold;
  17427. const drawRange = geometry.drawRange;
  17428. // Checking boundingSphere distance to ray
  17429. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17430. _sphere$1.copy( geometry.boundingSphere );
  17431. _sphere$1.applyMatrix4( matrixWorld );
  17432. _sphere$1.radius += threshold;
  17433. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  17434. //
  17435. _inverseMatrix$1.copy( matrixWorld ).invert();
  17436. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  17437. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17438. const localThresholdSq = localThreshold * localThreshold;
  17439. const vStart = new Vector3();
  17440. const vEnd = new Vector3();
  17441. const interSegment = new Vector3();
  17442. const interRay = new Vector3();
  17443. const step = this.isLineSegments ? 2 : 1;
  17444. if ( geometry.isBufferGeometry ) {
  17445. const index = geometry.index;
  17446. const attributes = geometry.attributes;
  17447. const positionAttribute = attributes.position;
  17448. if ( index !== null ) {
  17449. const start = Math.max( 0, drawRange.start );
  17450. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17451. for ( let i = start, l = end - 1; i < l; i += step ) {
  17452. const a = index.getX( i );
  17453. const b = index.getX( i + 1 );
  17454. vStart.fromBufferAttribute( positionAttribute, a );
  17455. vEnd.fromBufferAttribute( positionAttribute, b );
  17456. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17457. if ( distSq > localThresholdSq ) continue;
  17458. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17459. const distance = raycaster.ray.origin.distanceTo( interRay );
  17460. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17461. intersects.push( {
  17462. distance: distance,
  17463. // What do we want? intersection point on the ray or on the segment??
  17464. // point: raycaster.ray.at( distance ),
  17465. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17466. index: i,
  17467. face: null,
  17468. faceIndex: null,
  17469. object: this
  17470. } );
  17471. }
  17472. } else {
  17473. const start = Math.max( 0, drawRange.start );
  17474. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17475. for ( let i = start, l = end - 1; i < l; i += step ) {
  17476. vStart.fromBufferAttribute( positionAttribute, i );
  17477. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  17478. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17479. if ( distSq > localThresholdSq ) continue;
  17480. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17481. const distance = raycaster.ray.origin.distanceTo( interRay );
  17482. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17483. intersects.push( {
  17484. distance: distance,
  17485. // What do we want? intersection point on the ray or on the segment??
  17486. // point: raycaster.ray.at( distance ),
  17487. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17488. index: i,
  17489. face: null,
  17490. faceIndex: null,
  17491. object: this
  17492. } );
  17493. }
  17494. }
  17495. } else if ( geometry.isGeometry ) {
  17496. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17497. }
  17498. }
  17499. updateMorphTargets() {
  17500. const geometry = this.geometry;
  17501. if ( geometry.isBufferGeometry ) {
  17502. const morphAttributes = geometry.morphAttributes;
  17503. const keys = Object.keys( morphAttributes );
  17504. if ( keys.length > 0 ) {
  17505. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17506. if ( morphAttribute !== undefined ) {
  17507. this.morphTargetInfluences = [];
  17508. this.morphTargetDictionary = {};
  17509. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17510. const name = morphAttribute[ m ].name || String( m );
  17511. this.morphTargetInfluences.push( 0 );
  17512. this.morphTargetDictionary[ name ] = m;
  17513. }
  17514. }
  17515. }
  17516. } else {
  17517. const morphTargets = geometry.morphTargets;
  17518. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17519. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17520. }
  17521. }
  17522. }
  17523. }
  17524. Line.prototype.isLine = true;
  17525. const _start = /*@__PURE__*/ new Vector3();
  17526. const _end = /*@__PURE__*/ new Vector3();
  17527. class LineSegments extends Line {
  17528. constructor( geometry, material ) {
  17529. super( geometry, material );
  17530. this.type = 'LineSegments';
  17531. }
  17532. computeLineDistances() {
  17533. const geometry = this.geometry;
  17534. if ( geometry.isBufferGeometry ) {
  17535. // we assume non-indexed geometry
  17536. if ( geometry.index === null ) {
  17537. const positionAttribute = geometry.attributes.position;
  17538. const lineDistances = [];
  17539. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17540. _start.fromBufferAttribute( positionAttribute, i );
  17541. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17542. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17543. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17544. }
  17545. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17546. } else {
  17547. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17548. }
  17549. } else if ( geometry.isGeometry ) {
  17550. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17551. }
  17552. return this;
  17553. }
  17554. }
  17555. LineSegments.prototype.isLineSegments = true;
  17556. class LineLoop extends Line {
  17557. constructor( geometry, material ) {
  17558. super( geometry, material );
  17559. this.type = 'LineLoop';
  17560. }
  17561. }
  17562. LineLoop.prototype.isLineLoop = true;
  17563. /**
  17564. * parameters = {
  17565. * color: <hex>,
  17566. * opacity: <float>,
  17567. * map: new THREE.Texture( <Image> ),
  17568. * alphaMap: new THREE.Texture( <Image> ),
  17569. *
  17570. * size: <float>,
  17571. * sizeAttenuation: <bool>
  17572. *
  17573. * }
  17574. */
  17575. class PointsMaterial extends Material {
  17576. constructor( parameters ) {
  17577. super();
  17578. this.type = 'PointsMaterial';
  17579. this.color = new Color( 0xffffff );
  17580. this.map = null;
  17581. this.alphaMap = null;
  17582. this.size = 1;
  17583. this.sizeAttenuation = true;
  17584. this.setValues( parameters );
  17585. }
  17586. copy( source ) {
  17587. super.copy( source );
  17588. this.color.copy( source.color );
  17589. this.map = source.map;
  17590. this.alphaMap = source.alphaMap;
  17591. this.size = source.size;
  17592. this.sizeAttenuation = source.sizeAttenuation;
  17593. return this;
  17594. }
  17595. }
  17596. PointsMaterial.prototype.isPointsMaterial = true;
  17597. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17598. const _ray = /*@__PURE__*/ new Ray();
  17599. const _sphere = /*@__PURE__*/ new Sphere();
  17600. const _position$2 = /*@__PURE__*/ new Vector3();
  17601. class Points extends Object3D {
  17602. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17603. super();
  17604. this.type = 'Points';
  17605. this.geometry = geometry;
  17606. this.material = material;
  17607. this.updateMorphTargets();
  17608. }
  17609. copy( source ) {
  17610. super.copy( source );
  17611. this.material = source.material;
  17612. this.geometry = source.geometry;
  17613. return this;
  17614. }
  17615. raycast( raycaster, intersects ) {
  17616. const geometry = this.geometry;
  17617. const matrixWorld = this.matrixWorld;
  17618. const threshold = raycaster.params.Points.threshold;
  17619. const drawRange = geometry.drawRange;
  17620. // Checking boundingSphere distance to ray
  17621. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17622. _sphere.copy( geometry.boundingSphere );
  17623. _sphere.applyMatrix4( matrixWorld );
  17624. _sphere.radius += threshold;
  17625. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17626. //
  17627. _inverseMatrix.copy( matrixWorld ).invert();
  17628. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17629. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17630. const localThresholdSq = localThreshold * localThreshold;
  17631. if ( geometry.isBufferGeometry ) {
  17632. const index = geometry.index;
  17633. const attributes = geometry.attributes;
  17634. const positionAttribute = attributes.position;
  17635. if ( index !== null ) {
  17636. const start = Math.max( 0, drawRange.start );
  17637. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17638. for ( let i = start, il = end; i < il; i ++ ) {
  17639. const a = index.getX( i );
  17640. _position$2.fromBufferAttribute( positionAttribute, a );
  17641. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17642. }
  17643. } else {
  17644. const start = Math.max( 0, drawRange.start );
  17645. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17646. for ( let i = start, l = end; i < l; i ++ ) {
  17647. _position$2.fromBufferAttribute( positionAttribute, i );
  17648. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17649. }
  17650. }
  17651. } else {
  17652. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17653. }
  17654. }
  17655. updateMorphTargets() {
  17656. const geometry = this.geometry;
  17657. if ( geometry.isBufferGeometry ) {
  17658. const morphAttributes = geometry.morphAttributes;
  17659. const keys = Object.keys( morphAttributes );
  17660. if ( keys.length > 0 ) {
  17661. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17662. if ( morphAttribute !== undefined ) {
  17663. this.morphTargetInfluences = [];
  17664. this.morphTargetDictionary = {};
  17665. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17666. const name = morphAttribute[ m ].name || String( m );
  17667. this.morphTargetInfluences.push( 0 );
  17668. this.morphTargetDictionary[ name ] = m;
  17669. }
  17670. }
  17671. }
  17672. } else {
  17673. const morphTargets = geometry.morphTargets;
  17674. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17675. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17676. }
  17677. }
  17678. }
  17679. }
  17680. Points.prototype.isPoints = true;
  17681. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17682. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17683. if ( rayPointDistanceSq < localThresholdSq ) {
  17684. const intersectPoint = new Vector3();
  17685. _ray.closestPointToPoint( point, intersectPoint );
  17686. intersectPoint.applyMatrix4( matrixWorld );
  17687. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17688. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17689. intersects.push( {
  17690. distance: distance,
  17691. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17692. point: intersectPoint,
  17693. index: index,
  17694. face: null,
  17695. object: object
  17696. } );
  17697. }
  17698. }
  17699. class VideoTexture extends Texture {
  17700. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17701. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17702. this.format = format !== undefined ? format : RGBFormat;
  17703. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17704. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17705. this.generateMipmaps = false;
  17706. const scope = this;
  17707. function updateVideo() {
  17708. scope.needsUpdate = true;
  17709. video.requestVideoFrameCallback( updateVideo );
  17710. }
  17711. if ( 'requestVideoFrameCallback' in video ) {
  17712. video.requestVideoFrameCallback( updateVideo );
  17713. }
  17714. }
  17715. clone() {
  17716. return new this.constructor( this.image ).copy( this );
  17717. }
  17718. update() {
  17719. const video = this.image;
  17720. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  17721. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  17722. this.needsUpdate = true;
  17723. }
  17724. }
  17725. }
  17726. VideoTexture.prototype.isVideoTexture = true;
  17727. class CompressedTexture extends Texture {
  17728. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  17729. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17730. this.image = { width: width, height: height };
  17731. this.mipmaps = mipmaps;
  17732. // no flipping for cube textures
  17733. // (also flipping doesn't work for compressed textures )
  17734. this.flipY = false;
  17735. // can't generate mipmaps for compressed textures
  17736. // mips must be embedded in DDS files
  17737. this.generateMipmaps = false;
  17738. }
  17739. }
  17740. CompressedTexture.prototype.isCompressedTexture = true;
  17741. class CanvasTexture extends Texture {
  17742. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17743. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17744. this.needsUpdate = true;
  17745. }
  17746. }
  17747. CanvasTexture.prototype.isCanvasTexture = true;
  17748. class CircleGeometry extends BufferGeometry {
  17749. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17750. super();
  17751. this.type = 'CircleGeometry';
  17752. this.parameters = {
  17753. radius: radius,
  17754. segments: segments,
  17755. thetaStart: thetaStart,
  17756. thetaLength: thetaLength
  17757. };
  17758. segments = Math.max( 3, segments );
  17759. // buffers
  17760. const indices = [];
  17761. const vertices = [];
  17762. const normals = [];
  17763. const uvs = [];
  17764. // helper variables
  17765. const vertex = new Vector3();
  17766. const uv = new Vector2();
  17767. // center point
  17768. vertices.push( 0, 0, 0 );
  17769. normals.push( 0, 0, 1 );
  17770. uvs.push( 0.5, 0.5 );
  17771. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17772. const segment = thetaStart + s / segments * thetaLength;
  17773. // vertex
  17774. vertex.x = radius * Math.cos( segment );
  17775. vertex.y = radius * Math.sin( segment );
  17776. vertices.push( vertex.x, vertex.y, vertex.z );
  17777. // normal
  17778. normals.push( 0, 0, 1 );
  17779. // uvs
  17780. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17781. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17782. uvs.push( uv.x, uv.y );
  17783. }
  17784. // indices
  17785. for ( let i = 1; i <= segments; i ++ ) {
  17786. indices.push( i, i + 1, 0 );
  17787. }
  17788. // build geometry
  17789. this.setIndex( indices );
  17790. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17791. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17792. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17793. }
  17794. static fromJSON( data ) {
  17795. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  17796. }
  17797. }
  17798. class CylinderGeometry extends BufferGeometry {
  17799. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17800. super();
  17801. this.type = 'CylinderGeometry';
  17802. this.parameters = {
  17803. radiusTop: radiusTop,
  17804. radiusBottom: radiusBottom,
  17805. height: height,
  17806. radialSegments: radialSegments,
  17807. heightSegments: heightSegments,
  17808. openEnded: openEnded,
  17809. thetaStart: thetaStart,
  17810. thetaLength: thetaLength
  17811. };
  17812. const scope = this;
  17813. radialSegments = Math.floor( radialSegments );
  17814. heightSegments = Math.floor( heightSegments );
  17815. // buffers
  17816. const indices = [];
  17817. const vertices = [];
  17818. const normals = [];
  17819. const uvs = [];
  17820. // helper variables
  17821. let index = 0;
  17822. const indexArray = [];
  17823. const halfHeight = height / 2;
  17824. let groupStart = 0;
  17825. // generate geometry
  17826. generateTorso();
  17827. if ( openEnded === false ) {
  17828. if ( radiusTop > 0 ) generateCap( true );
  17829. if ( radiusBottom > 0 ) generateCap( false );
  17830. }
  17831. // build geometry
  17832. this.setIndex( indices );
  17833. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17834. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17835. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17836. function generateTorso() {
  17837. const normal = new Vector3();
  17838. const vertex = new Vector3();
  17839. let groupCount = 0;
  17840. // this will be used to calculate the normal
  17841. const slope = ( radiusBottom - radiusTop ) / height;
  17842. // generate vertices, normals and uvs
  17843. for ( let y = 0; y <= heightSegments; y ++ ) {
  17844. const indexRow = [];
  17845. const v = y / heightSegments;
  17846. // calculate the radius of the current row
  17847. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17848. for ( let x = 0; x <= radialSegments; x ++ ) {
  17849. const u = x / radialSegments;
  17850. const theta = u * thetaLength + thetaStart;
  17851. const sinTheta = Math.sin( theta );
  17852. const cosTheta = Math.cos( theta );
  17853. // vertex
  17854. vertex.x = radius * sinTheta;
  17855. vertex.y = - v * height + halfHeight;
  17856. vertex.z = radius * cosTheta;
  17857. vertices.push( vertex.x, vertex.y, vertex.z );
  17858. // normal
  17859. normal.set( sinTheta, slope, cosTheta ).normalize();
  17860. normals.push( normal.x, normal.y, normal.z );
  17861. // uv
  17862. uvs.push( u, 1 - v );
  17863. // save index of vertex in respective row
  17864. indexRow.push( index ++ );
  17865. }
  17866. // now save vertices of the row in our index array
  17867. indexArray.push( indexRow );
  17868. }
  17869. // generate indices
  17870. for ( let x = 0; x < radialSegments; x ++ ) {
  17871. for ( let y = 0; y < heightSegments; y ++ ) {
  17872. // we use the index array to access the correct indices
  17873. const a = indexArray[ y ][ x ];
  17874. const b = indexArray[ y + 1 ][ x ];
  17875. const c = indexArray[ y + 1 ][ x + 1 ];
  17876. const d = indexArray[ y ][ x + 1 ];
  17877. // faces
  17878. indices.push( a, b, d );
  17879. indices.push( b, c, d );
  17880. // update group counter
  17881. groupCount += 6;
  17882. }
  17883. }
  17884. // add a group to the geometry. this will ensure multi material support
  17885. scope.addGroup( groupStart, groupCount, 0 );
  17886. // calculate new start value for groups
  17887. groupStart += groupCount;
  17888. }
  17889. function generateCap( top ) {
  17890. // save the index of the first center vertex
  17891. const centerIndexStart = index;
  17892. const uv = new Vector2();
  17893. const vertex = new Vector3();
  17894. let groupCount = 0;
  17895. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17896. const sign = ( top === true ) ? 1 : - 1;
  17897. // first we generate the center vertex data of the cap.
  17898. // because the geometry needs one set of uvs per face,
  17899. // we must generate a center vertex per face/segment
  17900. for ( let x = 1; x <= radialSegments; x ++ ) {
  17901. // vertex
  17902. vertices.push( 0, halfHeight * sign, 0 );
  17903. // normal
  17904. normals.push( 0, sign, 0 );
  17905. // uv
  17906. uvs.push( 0.5, 0.5 );
  17907. // increase index
  17908. index ++;
  17909. }
  17910. // save the index of the last center vertex
  17911. const centerIndexEnd = index;
  17912. // now we generate the surrounding vertices, normals and uvs
  17913. for ( let x = 0; x <= radialSegments; x ++ ) {
  17914. const u = x / radialSegments;
  17915. const theta = u * thetaLength + thetaStart;
  17916. const cosTheta = Math.cos( theta );
  17917. const sinTheta = Math.sin( theta );
  17918. // vertex
  17919. vertex.x = radius * sinTheta;
  17920. vertex.y = halfHeight * sign;
  17921. vertex.z = radius * cosTheta;
  17922. vertices.push( vertex.x, vertex.y, vertex.z );
  17923. // normal
  17924. normals.push( 0, sign, 0 );
  17925. // uv
  17926. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17927. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17928. uvs.push( uv.x, uv.y );
  17929. // increase index
  17930. index ++;
  17931. }
  17932. // generate indices
  17933. for ( let x = 0; x < radialSegments; x ++ ) {
  17934. const c = centerIndexStart + x;
  17935. const i = centerIndexEnd + x;
  17936. if ( top === true ) {
  17937. // face top
  17938. indices.push( i, i + 1, c );
  17939. } else {
  17940. // face bottom
  17941. indices.push( i + 1, i, c );
  17942. }
  17943. groupCount += 3;
  17944. }
  17945. // add a group to the geometry. this will ensure multi material support
  17946. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17947. // calculate new start value for groups
  17948. groupStart += groupCount;
  17949. }
  17950. }
  17951. static fromJSON( data ) {
  17952. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  17953. }
  17954. }
  17955. class ConeGeometry extends CylinderGeometry {
  17956. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17957. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17958. this.type = 'ConeGeometry';
  17959. this.parameters = {
  17960. radius: radius,
  17961. height: height,
  17962. radialSegments: radialSegments,
  17963. heightSegments: heightSegments,
  17964. openEnded: openEnded,
  17965. thetaStart: thetaStart,
  17966. thetaLength: thetaLength
  17967. };
  17968. }
  17969. static fromJSON( data ) {
  17970. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  17971. }
  17972. }
  17973. class PolyhedronGeometry extends BufferGeometry {
  17974. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  17975. super();
  17976. this.type = 'PolyhedronGeometry';
  17977. this.parameters = {
  17978. vertices: vertices,
  17979. indices: indices,
  17980. radius: radius,
  17981. detail: detail
  17982. };
  17983. // default buffer data
  17984. const vertexBuffer = [];
  17985. const uvBuffer = [];
  17986. // the subdivision creates the vertex buffer data
  17987. subdivide( detail );
  17988. // all vertices should lie on a conceptual sphere with a given radius
  17989. applyRadius( radius );
  17990. // finally, create the uv data
  17991. generateUVs();
  17992. // build non-indexed geometry
  17993. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  17994. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  17995. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  17996. if ( detail === 0 ) {
  17997. this.computeVertexNormals(); // flat normals
  17998. } else {
  17999. this.normalizeNormals(); // smooth normals
  18000. }
  18001. // helper functions
  18002. function subdivide( detail ) {
  18003. const a = new Vector3();
  18004. const b = new Vector3();
  18005. const c = new Vector3();
  18006. // iterate over all faces and apply a subdivison with the given detail value
  18007. for ( let i = 0; i < indices.length; i += 3 ) {
  18008. // get the vertices of the face
  18009. getVertexByIndex( indices[ i + 0 ], a );
  18010. getVertexByIndex( indices[ i + 1 ], b );
  18011. getVertexByIndex( indices[ i + 2 ], c );
  18012. // perform subdivision
  18013. subdivideFace( a, b, c, detail );
  18014. }
  18015. }
  18016. function subdivideFace( a, b, c, detail ) {
  18017. const cols = detail + 1;
  18018. // we use this multidimensional array as a data structure for creating the subdivision
  18019. const v = [];
  18020. // construct all of the vertices for this subdivision
  18021. for ( let i = 0; i <= cols; i ++ ) {
  18022. v[ i ] = [];
  18023. const aj = a.clone().lerp( c, i / cols );
  18024. const bj = b.clone().lerp( c, i / cols );
  18025. const rows = cols - i;
  18026. for ( let j = 0; j <= rows; j ++ ) {
  18027. if ( j === 0 && i === cols ) {
  18028. v[ i ][ j ] = aj;
  18029. } else {
  18030. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18031. }
  18032. }
  18033. }
  18034. // construct all of the faces
  18035. for ( let i = 0; i < cols; i ++ ) {
  18036. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18037. const k = Math.floor( j / 2 );
  18038. if ( j % 2 === 0 ) {
  18039. pushVertex( v[ i ][ k + 1 ] );
  18040. pushVertex( v[ i + 1 ][ k ] );
  18041. pushVertex( v[ i ][ k ] );
  18042. } else {
  18043. pushVertex( v[ i ][ k + 1 ] );
  18044. pushVertex( v[ i + 1 ][ k + 1 ] );
  18045. pushVertex( v[ i + 1 ][ k ] );
  18046. }
  18047. }
  18048. }
  18049. }
  18050. function applyRadius( radius ) {
  18051. const vertex = new Vector3();
  18052. // iterate over the entire buffer and apply the radius to each vertex
  18053. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18054. vertex.x = vertexBuffer[ i + 0 ];
  18055. vertex.y = vertexBuffer[ i + 1 ];
  18056. vertex.z = vertexBuffer[ i + 2 ];
  18057. vertex.normalize().multiplyScalar( radius );
  18058. vertexBuffer[ i + 0 ] = vertex.x;
  18059. vertexBuffer[ i + 1 ] = vertex.y;
  18060. vertexBuffer[ i + 2 ] = vertex.z;
  18061. }
  18062. }
  18063. function generateUVs() {
  18064. const vertex = new Vector3();
  18065. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18066. vertex.x = vertexBuffer[ i + 0 ];
  18067. vertex.y = vertexBuffer[ i + 1 ];
  18068. vertex.z = vertexBuffer[ i + 2 ];
  18069. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18070. const v = inclination( vertex ) / Math.PI + 0.5;
  18071. uvBuffer.push( u, 1 - v );
  18072. }
  18073. correctUVs();
  18074. correctSeam();
  18075. }
  18076. function correctSeam() {
  18077. // handle case when face straddles the seam, see #3269
  18078. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18079. // uv data of a single face
  18080. const x0 = uvBuffer[ i + 0 ];
  18081. const x1 = uvBuffer[ i + 2 ];
  18082. const x2 = uvBuffer[ i + 4 ];
  18083. const max = Math.max( x0, x1, x2 );
  18084. const min = Math.min( x0, x1, x2 );
  18085. // 0.9 is somewhat arbitrary
  18086. if ( max > 0.9 && min < 0.1 ) {
  18087. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18088. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18089. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18090. }
  18091. }
  18092. }
  18093. function pushVertex( vertex ) {
  18094. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18095. }
  18096. function getVertexByIndex( index, vertex ) {
  18097. const stride = index * 3;
  18098. vertex.x = vertices[ stride + 0 ];
  18099. vertex.y = vertices[ stride + 1 ];
  18100. vertex.z = vertices[ stride + 2 ];
  18101. }
  18102. function correctUVs() {
  18103. const a = new Vector3();
  18104. const b = new Vector3();
  18105. const c = new Vector3();
  18106. const centroid = new Vector3();
  18107. const uvA = new Vector2();
  18108. const uvB = new Vector2();
  18109. const uvC = new Vector2();
  18110. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18111. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18112. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18113. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18114. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18115. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18116. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18117. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18118. const azi = azimuth( centroid );
  18119. correctUV( uvA, j + 0, a, azi );
  18120. correctUV( uvB, j + 2, b, azi );
  18121. correctUV( uvC, j + 4, c, azi );
  18122. }
  18123. }
  18124. function correctUV( uv, stride, vector, azimuth ) {
  18125. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18126. uvBuffer[ stride ] = uv.x - 1;
  18127. }
  18128. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18129. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18130. }
  18131. }
  18132. // Angle around the Y axis, counter-clockwise when looking from above.
  18133. function azimuth( vector ) {
  18134. return Math.atan2( vector.z, - vector.x );
  18135. }
  18136. // Angle above the XZ plane.
  18137. function inclination( vector ) {
  18138. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18139. }
  18140. }
  18141. static fromJSON( data ) {
  18142. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  18143. }
  18144. }
  18145. class DodecahedronGeometry extends PolyhedronGeometry {
  18146. constructor( radius = 1, detail = 0 ) {
  18147. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18148. const r = 1 / t;
  18149. const vertices = [
  18150. // (±1, ±1, ±1)
  18151. - 1, - 1, - 1, - 1, - 1, 1,
  18152. - 1, 1, - 1, - 1, 1, 1,
  18153. 1, - 1, - 1, 1, - 1, 1,
  18154. 1, 1, - 1, 1, 1, 1,
  18155. // (0, ±1/φ, ±φ)
  18156. 0, - r, - t, 0, - r, t,
  18157. 0, r, - t, 0, r, t,
  18158. // (±1/φ, ±φ, 0)
  18159. - r, - t, 0, - r, t, 0,
  18160. r, - t, 0, r, t, 0,
  18161. // (±φ, 0, ±1/φ)
  18162. - t, 0, - r, t, 0, - r,
  18163. - t, 0, r, t, 0, r
  18164. ];
  18165. const indices = [
  18166. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18167. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18168. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18169. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18170. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18171. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18172. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18173. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18174. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18175. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18176. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18177. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18178. ];
  18179. super( vertices, indices, radius, detail );
  18180. this.type = 'DodecahedronGeometry';
  18181. this.parameters = {
  18182. radius: radius,
  18183. detail: detail
  18184. };
  18185. }
  18186. static fromJSON( data ) {
  18187. return new DodecahedronGeometry( data.radius, data.detail );
  18188. }
  18189. }
  18190. const _v0 = new Vector3();
  18191. const _v1$1 = new Vector3();
  18192. const _normal = new Vector3();
  18193. const _triangle = new Triangle();
  18194. class EdgesGeometry extends BufferGeometry {
  18195. constructor( geometry = null, thresholdAngle = 1 ) {
  18196. super();
  18197. this.type = 'EdgesGeometry';
  18198. this.parameters = {
  18199. geometry: geometry,
  18200. thresholdAngle: thresholdAngle
  18201. };
  18202. if ( geometry !== null ) {
  18203. const precisionPoints = 4;
  18204. const precision = Math.pow( 10, precisionPoints );
  18205. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  18206. const indexAttr = geometry.getIndex();
  18207. const positionAttr = geometry.getAttribute( 'position' );
  18208. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18209. const indexArr = [ 0, 0, 0 ];
  18210. const vertKeys = [ 'a', 'b', 'c' ];
  18211. const hashes = new Array( 3 );
  18212. const edgeData = {};
  18213. const vertices = [];
  18214. for ( let i = 0; i < indexCount; i += 3 ) {
  18215. if ( indexAttr ) {
  18216. indexArr[ 0 ] = indexAttr.getX( i );
  18217. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18218. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18219. } else {
  18220. indexArr[ 0 ] = i;
  18221. indexArr[ 1 ] = i + 1;
  18222. indexArr[ 2 ] = i + 2;
  18223. }
  18224. const { a, b, c } = _triangle;
  18225. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18226. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18227. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18228. _triangle.getNormal( _normal );
  18229. // create hashes for the edge from the vertices
  18230. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18231. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18232. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18233. // skip degenerate triangles
  18234. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18235. continue;
  18236. }
  18237. // iterate over every edge
  18238. for ( let j = 0; j < 3; j ++ ) {
  18239. // get the first and next vertex making up the edge
  18240. const jNext = ( j + 1 ) % 3;
  18241. const vecHash0 = hashes[ j ];
  18242. const vecHash1 = hashes[ jNext ];
  18243. const v0 = _triangle[ vertKeys[ j ] ];
  18244. const v1 = _triangle[ vertKeys[ jNext ] ];
  18245. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18246. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18247. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18248. // if we found a sibling edge add it into the vertex array if
  18249. // it meets the angle threshold and delete the edge from the map.
  18250. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18251. vertices.push( v0.x, v0.y, v0.z );
  18252. vertices.push( v1.x, v1.y, v1.z );
  18253. }
  18254. edgeData[ reverseHash ] = null;
  18255. } else if ( ! ( hash in edgeData ) ) {
  18256. // if we've already got an edge here then skip adding a new one
  18257. edgeData[ hash ] = {
  18258. index0: indexArr[ j ],
  18259. index1: indexArr[ jNext ],
  18260. normal: _normal.clone(),
  18261. };
  18262. }
  18263. }
  18264. }
  18265. // iterate over all remaining, unmatched edges and add them to the vertex array
  18266. for ( const key in edgeData ) {
  18267. if ( edgeData[ key ] ) {
  18268. const { index0, index1 } = edgeData[ key ];
  18269. _v0.fromBufferAttribute( positionAttr, index0 );
  18270. _v1$1.fromBufferAttribute( positionAttr, index1 );
  18271. vertices.push( _v0.x, _v0.y, _v0.z );
  18272. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  18273. }
  18274. }
  18275. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18276. }
  18277. }
  18278. }
  18279. /**
  18280. * Extensible curve object.
  18281. *
  18282. * Some common of curve methods:
  18283. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18284. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18285. * .getPoints(), .getSpacedPoints()
  18286. * .getLength()
  18287. * .updateArcLengths()
  18288. *
  18289. * This following curves inherit from THREE.Curve:
  18290. *
  18291. * -- 2D curves --
  18292. * THREE.ArcCurve
  18293. * THREE.CubicBezierCurve
  18294. * THREE.EllipseCurve
  18295. * THREE.LineCurve
  18296. * THREE.QuadraticBezierCurve
  18297. * THREE.SplineCurve
  18298. *
  18299. * -- 3D curves --
  18300. * THREE.CatmullRomCurve3
  18301. * THREE.CubicBezierCurve3
  18302. * THREE.LineCurve3
  18303. * THREE.QuadraticBezierCurve3
  18304. *
  18305. * A series of curves can be represented as a THREE.CurvePath.
  18306. *
  18307. **/
  18308. class Curve {
  18309. constructor() {
  18310. this.type = 'Curve';
  18311. this.arcLengthDivisions = 200;
  18312. }
  18313. // Virtual base class method to overwrite and implement in subclasses
  18314. // - t [0 .. 1]
  18315. getPoint( /* t, optionalTarget */ ) {
  18316. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18317. return null;
  18318. }
  18319. // Get point at relative position in curve according to arc length
  18320. // - u [0 .. 1]
  18321. getPointAt( u, optionalTarget ) {
  18322. const t = this.getUtoTmapping( u );
  18323. return this.getPoint( t, optionalTarget );
  18324. }
  18325. // Get sequence of points using getPoint( t )
  18326. getPoints( divisions = 5 ) {
  18327. const points = [];
  18328. for ( let d = 0; d <= divisions; d ++ ) {
  18329. points.push( this.getPoint( d / divisions ) );
  18330. }
  18331. return points;
  18332. }
  18333. // Get sequence of points using getPointAt( u )
  18334. getSpacedPoints( divisions = 5 ) {
  18335. const points = [];
  18336. for ( let d = 0; d <= divisions; d ++ ) {
  18337. points.push( this.getPointAt( d / divisions ) );
  18338. }
  18339. return points;
  18340. }
  18341. // Get total curve arc length
  18342. getLength() {
  18343. const lengths = this.getLengths();
  18344. return lengths[ lengths.length - 1 ];
  18345. }
  18346. // Get list of cumulative segment lengths
  18347. getLengths( divisions = this.arcLengthDivisions ) {
  18348. if ( this.cacheArcLengths &&
  18349. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18350. ! this.needsUpdate ) {
  18351. return this.cacheArcLengths;
  18352. }
  18353. this.needsUpdate = false;
  18354. const cache = [];
  18355. let current, last = this.getPoint( 0 );
  18356. let sum = 0;
  18357. cache.push( 0 );
  18358. for ( let p = 1; p <= divisions; p ++ ) {
  18359. current = this.getPoint( p / divisions );
  18360. sum += current.distanceTo( last );
  18361. cache.push( sum );
  18362. last = current;
  18363. }
  18364. this.cacheArcLengths = cache;
  18365. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18366. }
  18367. updateArcLengths() {
  18368. this.needsUpdate = true;
  18369. this.getLengths();
  18370. }
  18371. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18372. getUtoTmapping( u, distance ) {
  18373. const arcLengths = this.getLengths();
  18374. let i = 0;
  18375. const il = arcLengths.length;
  18376. let targetArcLength; // The targeted u distance value to get
  18377. if ( distance ) {
  18378. targetArcLength = distance;
  18379. } else {
  18380. targetArcLength = u * arcLengths[ il - 1 ];
  18381. }
  18382. // binary search for the index with largest value smaller than target u distance
  18383. let low = 0, high = il - 1, comparison;
  18384. while ( low <= high ) {
  18385. 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
  18386. comparison = arcLengths[ i ] - targetArcLength;
  18387. if ( comparison < 0 ) {
  18388. low = i + 1;
  18389. } else if ( comparison > 0 ) {
  18390. high = i - 1;
  18391. } else {
  18392. high = i;
  18393. break;
  18394. // DONE
  18395. }
  18396. }
  18397. i = high;
  18398. if ( arcLengths[ i ] === targetArcLength ) {
  18399. return i / ( il - 1 );
  18400. }
  18401. // we could get finer grain at lengths, or use simple interpolation between two points
  18402. const lengthBefore = arcLengths[ i ];
  18403. const lengthAfter = arcLengths[ i + 1 ];
  18404. const segmentLength = lengthAfter - lengthBefore;
  18405. // determine where we are between the 'before' and 'after' points
  18406. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18407. // add that fractional amount to t
  18408. const t = ( i + segmentFraction ) / ( il - 1 );
  18409. return t;
  18410. }
  18411. // Returns a unit vector tangent at t
  18412. // In case any sub curve does not implement its tangent derivation,
  18413. // 2 points a small delta apart will be used to find its gradient
  18414. // which seems to give a reasonable approximation
  18415. getTangent( t, optionalTarget ) {
  18416. const delta = 0.0001;
  18417. let t1 = t - delta;
  18418. let t2 = t + delta;
  18419. // Capping in case of danger
  18420. if ( t1 < 0 ) t1 = 0;
  18421. if ( t2 > 1 ) t2 = 1;
  18422. const pt1 = this.getPoint( t1 );
  18423. const pt2 = this.getPoint( t2 );
  18424. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18425. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18426. return tangent;
  18427. }
  18428. getTangentAt( u, optionalTarget ) {
  18429. const t = this.getUtoTmapping( u );
  18430. return this.getTangent( t, optionalTarget );
  18431. }
  18432. computeFrenetFrames( segments, closed ) {
  18433. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18434. const normal = new Vector3();
  18435. const tangents = [];
  18436. const normals = [];
  18437. const binormals = [];
  18438. const vec = new Vector3();
  18439. const mat = new Matrix4();
  18440. // compute the tangent vectors for each segment on the curve
  18441. for ( let i = 0; i <= segments; i ++ ) {
  18442. const u = i / segments;
  18443. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18444. }
  18445. // select an initial normal vector perpendicular to the first tangent vector,
  18446. // and in the direction of the minimum tangent xyz component
  18447. normals[ 0 ] = new Vector3();
  18448. binormals[ 0 ] = new Vector3();
  18449. let min = Number.MAX_VALUE;
  18450. const tx = Math.abs( tangents[ 0 ].x );
  18451. const ty = Math.abs( tangents[ 0 ].y );
  18452. const tz = Math.abs( tangents[ 0 ].z );
  18453. if ( tx <= min ) {
  18454. min = tx;
  18455. normal.set( 1, 0, 0 );
  18456. }
  18457. if ( ty <= min ) {
  18458. min = ty;
  18459. normal.set( 0, 1, 0 );
  18460. }
  18461. if ( tz <= min ) {
  18462. normal.set( 0, 0, 1 );
  18463. }
  18464. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18465. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18466. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18467. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18468. for ( let i = 1; i <= segments; i ++ ) {
  18469. normals[ i ] = normals[ i - 1 ].clone();
  18470. binormals[ i ] = binormals[ i - 1 ].clone();
  18471. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18472. if ( vec.length() > Number.EPSILON ) {
  18473. vec.normalize();
  18474. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18475. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18476. }
  18477. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18478. }
  18479. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18480. if ( closed === true ) {
  18481. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18482. theta /= segments;
  18483. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18484. theta = - theta;
  18485. }
  18486. for ( let i = 1; i <= segments; i ++ ) {
  18487. // twist a little...
  18488. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18489. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18490. }
  18491. }
  18492. return {
  18493. tangents: tangents,
  18494. normals: normals,
  18495. binormals: binormals
  18496. };
  18497. }
  18498. clone() {
  18499. return new this.constructor().copy( this );
  18500. }
  18501. copy( source ) {
  18502. this.arcLengthDivisions = source.arcLengthDivisions;
  18503. return this;
  18504. }
  18505. toJSON() {
  18506. const data = {
  18507. metadata: {
  18508. version: 4.5,
  18509. type: 'Curve',
  18510. generator: 'Curve.toJSON'
  18511. }
  18512. };
  18513. data.arcLengthDivisions = this.arcLengthDivisions;
  18514. data.type = this.type;
  18515. return data;
  18516. }
  18517. fromJSON( json ) {
  18518. this.arcLengthDivisions = json.arcLengthDivisions;
  18519. return this;
  18520. }
  18521. }
  18522. class EllipseCurve extends Curve {
  18523. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18524. super();
  18525. this.type = 'EllipseCurve';
  18526. this.aX = aX;
  18527. this.aY = aY;
  18528. this.xRadius = xRadius;
  18529. this.yRadius = yRadius;
  18530. this.aStartAngle = aStartAngle;
  18531. this.aEndAngle = aEndAngle;
  18532. this.aClockwise = aClockwise;
  18533. this.aRotation = aRotation;
  18534. }
  18535. getPoint( t, optionalTarget ) {
  18536. const point = optionalTarget || new Vector2();
  18537. const twoPi = Math.PI * 2;
  18538. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18539. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18540. // ensures that deltaAngle is 0 .. 2 PI
  18541. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18542. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18543. if ( deltaAngle < Number.EPSILON ) {
  18544. if ( samePoints ) {
  18545. deltaAngle = 0;
  18546. } else {
  18547. deltaAngle = twoPi;
  18548. }
  18549. }
  18550. if ( this.aClockwise === true && ! samePoints ) {
  18551. if ( deltaAngle === twoPi ) {
  18552. deltaAngle = - twoPi;
  18553. } else {
  18554. deltaAngle = deltaAngle - twoPi;
  18555. }
  18556. }
  18557. const angle = this.aStartAngle + t * deltaAngle;
  18558. let x = this.aX + this.xRadius * Math.cos( angle );
  18559. let y = this.aY + this.yRadius * Math.sin( angle );
  18560. if ( this.aRotation !== 0 ) {
  18561. const cos = Math.cos( this.aRotation );
  18562. const sin = Math.sin( this.aRotation );
  18563. const tx = x - this.aX;
  18564. const ty = y - this.aY;
  18565. // Rotate the point about the center of the ellipse.
  18566. x = tx * cos - ty * sin + this.aX;
  18567. y = tx * sin + ty * cos + this.aY;
  18568. }
  18569. return point.set( x, y );
  18570. }
  18571. copy( source ) {
  18572. super.copy( source );
  18573. this.aX = source.aX;
  18574. this.aY = source.aY;
  18575. this.xRadius = source.xRadius;
  18576. this.yRadius = source.yRadius;
  18577. this.aStartAngle = source.aStartAngle;
  18578. this.aEndAngle = source.aEndAngle;
  18579. this.aClockwise = source.aClockwise;
  18580. this.aRotation = source.aRotation;
  18581. return this;
  18582. }
  18583. toJSON() {
  18584. const data = super.toJSON();
  18585. data.aX = this.aX;
  18586. data.aY = this.aY;
  18587. data.xRadius = this.xRadius;
  18588. data.yRadius = this.yRadius;
  18589. data.aStartAngle = this.aStartAngle;
  18590. data.aEndAngle = this.aEndAngle;
  18591. data.aClockwise = this.aClockwise;
  18592. data.aRotation = this.aRotation;
  18593. return data;
  18594. }
  18595. fromJSON( json ) {
  18596. super.fromJSON( json );
  18597. this.aX = json.aX;
  18598. this.aY = json.aY;
  18599. this.xRadius = json.xRadius;
  18600. this.yRadius = json.yRadius;
  18601. this.aStartAngle = json.aStartAngle;
  18602. this.aEndAngle = json.aEndAngle;
  18603. this.aClockwise = json.aClockwise;
  18604. this.aRotation = json.aRotation;
  18605. return this;
  18606. }
  18607. }
  18608. EllipseCurve.prototype.isEllipseCurve = true;
  18609. class ArcCurve extends EllipseCurve {
  18610. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18611. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18612. this.type = 'ArcCurve';
  18613. }
  18614. }
  18615. ArcCurve.prototype.isArcCurve = true;
  18616. /**
  18617. * Centripetal CatmullRom Curve - which is useful for avoiding
  18618. * cusps and self-intersections in non-uniform catmull rom curves.
  18619. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18620. *
  18621. * curve.type accepts centripetal(default), chordal and catmullrom
  18622. * curve.tension is used for catmullrom which defaults to 0.5
  18623. */
  18624. /*
  18625. Based on an optimized c++ solution in
  18626. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18627. - http://ideone.com/NoEbVM
  18628. This CubicPoly class could be used for reusing some variables and calculations,
  18629. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18630. which can be placed in CurveUtils.
  18631. */
  18632. function CubicPoly() {
  18633. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18634. /*
  18635. * Compute coefficients for a cubic polynomial
  18636. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18637. * such that
  18638. * p(0) = x0, p(1) = x1
  18639. * and
  18640. * p'(0) = t0, p'(1) = t1.
  18641. */
  18642. function init( x0, x1, t0, t1 ) {
  18643. c0 = x0;
  18644. c1 = t0;
  18645. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18646. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18647. }
  18648. return {
  18649. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18650. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18651. },
  18652. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18653. // compute tangents when parameterized in [t1,t2]
  18654. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18655. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18656. // rescale tangents for parametrization in [0,1]
  18657. t1 *= dt1;
  18658. t2 *= dt1;
  18659. init( x1, x2, t1, t2 );
  18660. },
  18661. calc: function ( t ) {
  18662. const t2 = t * t;
  18663. const t3 = t2 * t;
  18664. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18665. }
  18666. };
  18667. }
  18668. //
  18669. const tmp = new Vector3();
  18670. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  18671. class CatmullRomCurve3 extends Curve {
  18672. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18673. super();
  18674. this.type = 'CatmullRomCurve3';
  18675. this.points = points;
  18676. this.closed = closed;
  18677. this.curveType = curveType;
  18678. this.tension = tension;
  18679. }
  18680. getPoint( t, optionalTarget = new Vector3() ) {
  18681. const point = optionalTarget;
  18682. const points = this.points;
  18683. const l = points.length;
  18684. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18685. let intPoint = Math.floor( p );
  18686. let weight = p - intPoint;
  18687. if ( this.closed ) {
  18688. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18689. } else if ( weight === 0 && intPoint === l - 1 ) {
  18690. intPoint = l - 2;
  18691. weight = 1;
  18692. }
  18693. let p0, p3; // 4 points (p1 & p2 defined below)
  18694. if ( this.closed || intPoint > 0 ) {
  18695. p0 = points[ ( intPoint - 1 ) % l ];
  18696. } else {
  18697. // extrapolate first point
  18698. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18699. p0 = tmp;
  18700. }
  18701. const p1 = points[ intPoint % l ];
  18702. const p2 = points[ ( intPoint + 1 ) % l ];
  18703. if ( this.closed || intPoint + 2 < l ) {
  18704. p3 = points[ ( intPoint + 2 ) % l ];
  18705. } else {
  18706. // extrapolate last point
  18707. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18708. p3 = tmp;
  18709. }
  18710. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18711. // init Centripetal / Chordal Catmull-Rom
  18712. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18713. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18714. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18715. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18716. // safety check for repeated points
  18717. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18718. if ( dt0 < 1e-4 ) dt0 = dt1;
  18719. if ( dt2 < 1e-4 ) dt2 = dt1;
  18720. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18721. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18722. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18723. } else if ( this.curveType === 'catmullrom' ) {
  18724. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18725. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18726. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18727. }
  18728. point.set(
  18729. px.calc( weight ),
  18730. py.calc( weight ),
  18731. pz.calc( weight )
  18732. );
  18733. return point;
  18734. }
  18735. copy( source ) {
  18736. super.copy( source );
  18737. this.points = [];
  18738. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18739. const point = source.points[ i ];
  18740. this.points.push( point.clone() );
  18741. }
  18742. this.closed = source.closed;
  18743. this.curveType = source.curveType;
  18744. this.tension = source.tension;
  18745. return this;
  18746. }
  18747. toJSON() {
  18748. const data = super.toJSON();
  18749. data.points = [];
  18750. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18751. const point = this.points[ i ];
  18752. data.points.push( point.toArray() );
  18753. }
  18754. data.closed = this.closed;
  18755. data.curveType = this.curveType;
  18756. data.tension = this.tension;
  18757. return data;
  18758. }
  18759. fromJSON( json ) {
  18760. super.fromJSON( json );
  18761. this.points = [];
  18762. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18763. const point = json.points[ i ];
  18764. this.points.push( new Vector3().fromArray( point ) );
  18765. }
  18766. this.closed = json.closed;
  18767. this.curveType = json.curveType;
  18768. this.tension = json.tension;
  18769. return this;
  18770. }
  18771. }
  18772. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18773. /**
  18774. * Bezier Curves formulas obtained from
  18775. * http://en.wikipedia.org/wiki/Bézier_curve
  18776. */
  18777. function CatmullRom( t, p0, p1, p2, p3 ) {
  18778. const v0 = ( p2 - p0 ) * 0.5;
  18779. const v1 = ( p3 - p1 ) * 0.5;
  18780. const t2 = t * t;
  18781. const t3 = t * t2;
  18782. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18783. }
  18784. //
  18785. function QuadraticBezierP0( t, p ) {
  18786. const k = 1 - t;
  18787. return k * k * p;
  18788. }
  18789. function QuadraticBezierP1( t, p ) {
  18790. return 2 * ( 1 - t ) * t * p;
  18791. }
  18792. function QuadraticBezierP2( t, p ) {
  18793. return t * t * p;
  18794. }
  18795. function QuadraticBezier( t, p0, p1, p2 ) {
  18796. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18797. QuadraticBezierP2( t, p2 );
  18798. }
  18799. //
  18800. function CubicBezierP0( t, p ) {
  18801. const k = 1 - t;
  18802. return k * k * k * p;
  18803. }
  18804. function CubicBezierP1( t, p ) {
  18805. const k = 1 - t;
  18806. return 3 * k * k * t * p;
  18807. }
  18808. function CubicBezierP2( t, p ) {
  18809. return 3 * ( 1 - t ) * t * t * p;
  18810. }
  18811. function CubicBezierP3( t, p ) {
  18812. return t * t * t * p;
  18813. }
  18814. function CubicBezier( t, p0, p1, p2, p3 ) {
  18815. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18816. CubicBezierP3( t, p3 );
  18817. }
  18818. class CubicBezierCurve extends Curve {
  18819. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18820. super();
  18821. this.type = 'CubicBezierCurve';
  18822. this.v0 = v0;
  18823. this.v1 = v1;
  18824. this.v2 = v2;
  18825. this.v3 = v3;
  18826. }
  18827. getPoint( t, optionalTarget = new Vector2() ) {
  18828. const point = optionalTarget;
  18829. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18830. point.set(
  18831. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18832. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18833. );
  18834. return point;
  18835. }
  18836. copy( source ) {
  18837. super.copy( source );
  18838. this.v0.copy( source.v0 );
  18839. this.v1.copy( source.v1 );
  18840. this.v2.copy( source.v2 );
  18841. this.v3.copy( source.v3 );
  18842. return this;
  18843. }
  18844. toJSON() {
  18845. const data = super.toJSON();
  18846. data.v0 = this.v0.toArray();
  18847. data.v1 = this.v1.toArray();
  18848. data.v2 = this.v2.toArray();
  18849. data.v3 = this.v3.toArray();
  18850. return data;
  18851. }
  18852. fromJSON( json ) {
  18853. super.fromJSON( json );
  18854. this.v0.fromArray( json.v0 );
  18855. this.v1.fromArray( json.v1 );
  18856. this.v2.fromArray( json.v2 );
  18857. this.v3.fromArray( json.v3 );
  18858. return this;
  18859. }
  18860. }
  18861. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18862. class CubicBezierCurve3 extends Curve {
  18863. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18864. super();
  18865. this.type = 'CubicBezierCurve3';
  18866. this.v0 = v0;
  18867. this.v1 = v1;
  18868. this.v2 = v2;
  18869. this.v3 = v3;
  18870. }
  18871. getPoint( t, optionalTarget = new Vector3() ) {
  18872. const point = optionalTarget;
  18873. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18874. point.set(
  18875. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18876. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18877. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18878. );
  18879. return point;
  18880. }
  18881. copy( source ) {
  18882. super.copy( source );
  18883. this.v0.copy( source.v0 );
  18884. this.v1.copy( source.v1 );
  18885. this.v2.copy( source.v2 );
  18886. this.v3.copy( source.v3 );
  18887. return this;
  18888. }
  18889. toJSON() {
  18890. const data = super.toJSON();
  18891. data.v0 = this.v0.toArray();
  18892. data.v1 = this.v1.toArray();
  18893. data.v2 = this.v2.toArray();
  18894. data.v3 = this.v3.toArray();
  18895. return data;
  18896. }
  18897. fromJSON( json ) {
  18898. super.fromJSON( json );
  18899. this.v0.fromArray( json.v0 );
  18900. this.v1.fromArray( json.v1 );
  18901. this.v2.fromArray( json.v2 );
  18902. this.v3.fromArray( json.v3 );
  18903. return this;
  18904. }
  18905. }
  18906. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18907. class LineCurve extends Curve {
  18908. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18909. super();
  18910. this.type = 'LineCurve';
  18911. this.v1 = v1;
  18912. this.v2 = v2;
  18913. }
  18914. getPoint( t, optionalTarget = new Vector2() ) {
  18915. const point = optionalTarget;
  18916. if ( t === 1 ) {
  18917. point.copy( this.v2 );
  18918. } else {
  18919. point.copy( this.v2 ).sub( this.v1 );
  18920. point.multiplyScalar( t ).add( this.v1 );
  18921. }
  18922. return point;
  18923. }
  18924. // Line curve is linear, so we can overwrite default getPointAt
  18925. getPointAt( u, optionalTarget ) {
  18926. return this.getPoint( u, optionalTarget );
  18927. }
  18928. getTangent( t, optionalTarget ) {
  18929. const tangent = optionalTarget || new Vector2();
  18930. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  18931. return tangent;
  18932. }
  18933. copy( source ) {
  18934. super.copy( source );
  18935. this.v1.copy( source.v1 );
  18936. this.v2.copy( source.v2 );
  18937. return this;
  18938. }
  18939. toJSON() {
  18940. const data = super.toJSON();
  18941. data.v1 = this.v1.toArray();
  18942. data.v2 = this.v2.toArray();
  18943. return data;
  18944. }
  18945. fromJSON( json ) {
  18946. super.fromJSON( json );
  18947. this.v1.fromArray( json.v1 );
  18948. this.v2.fromArray( json.v2 );
  18949. return this;
  18950. }
  18951. }
  18952. LineCurve.prototype.isLineCurve = true;
  18953. class LineCurve3 extends Curve {
  18954. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18955. super();
  18956. this.type = 'LineCurve3';
  18957. this.isLineCurve3 = true;
  18958. this.v1 = v1;
  18959. this.v2 = v2;
  18960. }
  18961. getPoint( t, optionalTarget = new Vector3() ) {
  18962. const point = optionalTarget;
  18963. if ( t === 1 ) {
  18964. point.copy( this.v2 );
  18965. } else {
  18966. point.copy( this.v2 ).sub( this.v1 );
  18967. point.multiplyScalar( t ).add( this.v1 );
  18968. }
  18969. return point;
  18970. }
  18971. // Line curve is linear, so we can overwrite default getPointAt
  18972. getPointAt( u, optionalTarget ) {
  18973. return this.getPoint( u, optionalTarget );
  18974. }
  18975. copy( source ) {
  18976. super.copy( source );
  18977. this.v1.copy( source.v1 );
  18978. this.v2.copy( source.v2 );
  18979. return this;
  18980. }
  18981. toJSON() {
  18982. const data = super.toJSON();
  18983. data.v1 = this.v1.toArray();
  18984. data.v2 = this.v2.toArray();
  18985. return data;
  18986. }
  18987. fromJSON( json ) {
  18988. super.fromJSON( json );
  18989. this.v1.fromArray( json.v1 );
  18990. this.v2.fromArray( json.v2 );
  18991. return this;
  18992. }
  18993. }
  18994. class QuadraticBezierCurve extends Curve {
  18995. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  18996. super();
  18997. this.type = 'QuadraticBezierCurve';
  18998. this.v0 = v0;
  18999. this.v1 = v1;
  19000. this.v2 = v2;
  19001. }
  19002. getPoint( t, optionalTarget = new Vector2() ) {
  19003. const point = optionalTarget;
  19004. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19005. point.set(
  19006. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19007. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19008. );
  19009. return point;
  19010. }
  19011. copy( source ) {
  19012. super.copy( source );
  19013. this.v0.copy( source.v0 );
  19014. this.v1.copy( source.v1 );
  19015. this.v2.copy( source.v2 );
  19016. return this;
  19017. }
  19018. toJSON() {
  19019. const data = super.toJSON();
  19020. data.v0 = this.v0.toArray();
  19021. data.v1 = this.v1.toArray();
  19022. data.v2 = this.v2.toArray();
  19023. return data;
  19024. }
  19025. fromJSON( json ) {
  19026. super.fromJSON( json );
  19027. this.v0.fromArray( json.v0 );
  19028. this.v1.fromArray( json.v1 );
  19029. this.v2.fromArray( json.v2 );
  19030. return this;
  19031. }
  19032. }
  19033. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  19034. class QuadraticBezierCurve3 extends Curve {
  19035. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19036. super();
  19037. this.type = 'QuadraticBezierCurve3';
  19038. this.v0 = v0;
  19039. this.v1 = v1;
  19040. this.v2 = v2;
  19041. }
  19042. getPoint( t, optionalTarget = new Vector3() ) {
  19043. const point = optionalTarget;
  19044. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19045. point.set(
  19046. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19047. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19048. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19049. );
  19050. return point;
  19051. }
  19052. copy( source ) {
  19053. super.copy( source );
  19054. this.v0.copy( source.v0 );
  19055. this.v1.copy( source.v1 );
  19056. this.v2.copy( source.v2 );
  19057. return this;
  19058. }
  19059. toJSON() {
  19060. const data = super.toJSON();
  19061. data.v0 = this.v0.toArray();
  19062. data.v1 = this.v1.toArray();
  19063. data.v2 = this.v2.toArray();
  19064. return data;
  19065. }
  19066. fromJSON( json ) {
  19067. super.fromJSON( json );
  19068. this.v0.fromArray( json.v0 );
  19069. this.v1.fromArray( json.v1 );
  19070. this.v2.fromArray( json.v2 );
  19071. return this;
  19072. }
  19073. }
  19074. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  19075. class SplineCurve extends Curve {
  19076. constructor( points = [] ) {
  19077. super();
  19078. this.type = 'SplineCurve';
  19079. this.points = points;
  19080. }
  19081. getPoint( t, optionalTarget = new Vector2() ) {
  19082. const point = optionalTarget;
  19083. const points = this.points;
  19084. const p = ( points.length - 1 ) * t;
  19085. const intPoint = Math.floor( p );
  19086. const weight = p - intPoint;
  19087. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19088. const p1 = points[ intPoint ];
  19089. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19090. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19091. point.set(
  19092. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19093. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19094. );
  19095. return point;
  19096. }
  19097. copy( source ) {
  19098. super.copy( source );
  19099. this.points = [];
  19100. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19101. const point = source.points[ i ];
  19102. this.points.push( point.clone() );
  19103. }
  19104. return this;
  19105. }
  19106. toJSON() {
  19107. const data = super.toJSON();
  19108. data.points = [];
  19109. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19110. const point = this.points[ i ];
  19111. data.points.push( point.toArray() );
  19112. }
  19113. return data;
  19114. }
  19115. fromJSON( json ) {
  19116. super.fromJSON( json );
  19117. this.points = [];
  19118. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19119. const point = json.points[ i ];
  19120. this.points.push( new Vector2().fromArray( point ) );
  19121. }
  19122. return this;
  19123. }
  19124. }
  19125. SplineCurve.prototype.isSplineCurve = true;
  19126. var Curves = /*#__PURE__*/Object.freeze({
  19127. __proto__: null,
  19128. ArcCurve: ArcCurve,
  19129. CatmullRomCurve3: CatmullRomCurve3,
  19130. CubicBezierCurve: CubicBezierCurve,
  19131. CubicBezierCurve3: CubicBezierCurve3,
  19132. EllipseCurve: EllipseCurve,
  19133. LineCurve: LineCurve,
  19134. LineCurve3: LineCurve3,
  19135. QuadraticBezierCurve: QuadraticBezierCurve,
  19136. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19137. SplineCurve: SplineCurve
  19138. });
  19139. /**************************************************************
  19140. * Curved Path - a curve path is simply a array of connected
  19141. * curves, but retains the api of a curve
  19142. **************************************************************/
  19143. class CurvePath extends Curve {
  19144. constructor() {
  19145. super();
  19146. this.type = 'CurvePath';
  19147. this.curves = [];
  19148. this.autoClose = false; // Automatically closes the path
  19149. }
  19150. add( curve ) {
  19151. this.curves.push( curve );
  19152. }
  19153. closePath() {
  19154. // Add a line curve if start and end of lines are not connected
  19155. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19156. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19157. if ( ! startPoint.equals( endPoint ) ) {
  19158. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19159. }
  19160. }
  19161. // To get accurate point with reference to
  19162. // entire path distance at time t,
  19163. // following has to be done:
  19164. // 1. Length of each sub path have to be known
  19165. // 2. Locate and identify type of curve
  19166. // 3. Get t for the curve
  19167. // 4. Return curve.getPointAt(t')
  19168. getPoint( t, optionalTarget ) {
  19169. const d = t * this.getLength();
  19170. const curveLengths = this.getCurveLengths();
  19171. let i = 0;
  19172. // To think about boundaries points.
  19173. while ( i < curveLengths.length ) {
  19174. if ( curveLengths[ i ] >= d ) {
  19175. const diff = curveLengths[ i ] - d;
  19176. const curve = this.curves[ i ];
  19177. const segmentLength = curve.getLength();
  19178. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19179. return curve.getPointAt( u, optionalTarget );
  19180. }
  19181. i ++;
  19182. }
  19183. return null;
  19184. // loop where sum != 0, sum > d , sum+1 <d
  19185. }
  19186. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19187. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19188. // getPoint() depends on getLength
  19189. getLength() {
  19190. const lens = this.getCurveLengths();
  19191. return lens[ lens.length - 1 ];
  19192. }
  19193. // cacheLengths must be recalculated.
  19194. updateArcLengths() {
  19195. this.needsUpdate = true;
  19196. this.cacheLengths = null;
  19197. this.getCurveLengths();
  19198. }
  19199. // Compute lengths and cache them
  19200. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19201. getCurveLengths() {
  19202. // We use cache values if curves and cache array are same length
  19203. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19204. return this.cacheLengths;
  19205. }
  19206. // Get length of sub-curve
  19207. // Push sums into cached array
  19208. const lengths = [];
  19209. let sums = 0;
  19210. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19211. sums += this.curves[ i ].getLength();
  19212. lengths.push( sums );
  19213. }
  19214. this.cacheLengths = lengths;
  19215. return lengths;
  19216. }
  19217. getSpacedPoints( divisions = 40 ) {
  19218. const points = [];
  19219. for ( let i = 0; i <= divisions; i ++ ) {
  19220. points.push( this.getPoint( i / divisions ) );
  19221. }
  19222. if ( this.autoClose ) {
  19223. points.push( points[ 0 ] );
  19224. }
  19225. return points;
  19226. }
  19227. getPoints( divisions = 12 ) {
  19228. const points = [];
  19229. let last;
  19230. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19231. const curve = curves[ i ];
  19232. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  19233. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  19234. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  19235. : divisions;
  19236. const pts = curve.getPoints( resolution );
  19237. for ( let j = 0; j < pts.length; j ++ ) {
  19238. const point = pts[ j ];
  19239. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19240. points.push( point );
  19241. last = point;
  19242. }
  19243. }
  19244. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19245. points.push( points[ 0 ] );
  19246. }
  19247. return points;
  19248. }
  19249. copy( source ) {
  19250. super.copy( source );
  19251. this.curves = [];
  19252. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19253. const curve = source.curves[ i ];
  19254. this.curves.push( curve.clone() );
  19255. }
  19256. this.autoClose = source.autoClose;
  19257. return this;
  19258. }
  19259. toJSON() {
  19260. const data = super.toJSON();
  19261. data.autoClose = this.autoClose;
  19262. data.curves = [];
  19263. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19264. const curve = this.curves[ i ];
  19265. data.curves.push( curve.toJSON() );
  19266. }
  19267. return data;
  19268. }
  19269. fromJSON( json ) {
  19270. super.fromJSON( json );
  19271. this.autoClose = json.autoClose;
  19272. this.curves = [];
  19273. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19274. const curve = json.curves[ i ];
  19275. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19276. }
  19277. return this;
  19278. }
  19279. }
  19280. class Path extends CurvePath {
  19281. constructor( points ) {
  19282. super();
  19283. this.type = 'Path';
  19284. this.currentPoint = new Vector2();
  19285. if ( points ) {
  19286. this.setFromPoints( points );
  19287. }
  19288. }
  19289. setFromPoints( points ) {
  19290. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19291. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19292. this.lineTo( points[ i ].x, points[ i ].y );
  19293. }
  19294. return this;
  19295. }
  19296. moveTo( x, y ) {
  19297. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19298. return this;
  19299. }
  19300. lineTo( x, y ) {
  19301. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19302. this.curves.push( curve );
  19303. this.currentPoint.set( x, y );
  19304. return this;
  19305. }
  19306. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19307. const curve = new QuadraticBezierCurve(
  19308. this.currentPoint.clone(),
  19309. new Vector2( aCPx, aCPy ),
  19310. new Vector2( aX, aY )
  19311. );
  19312. this.curves.push( curve );
  19313. this.currentPoint.set( aX, aY );
  19314. return this;
  19315. }
  19316. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19317. const curve = new CubicBezierCurve(
  19318. this.currentPoint.clone(),
  19319. new Vector2( aCP1x, aCP1y ),
  19320. new Vector2( aCP2x, aCP2y ),
  19321. new Vector2( aX, aY )
  19322. );
  19323. this.curves.push( curve );
  19324. this.currentPoint.set( aX, aY );
  19325. return this;
  19326. }
  19327. splineThru( pts /*Array of Vector*/ ) {
  19328. const npts = [ this.currentPoint.clone() ].concat( pts );
  19329. const curve = new SplineCurve( npts );
  19330. this.curves.push( curve );
  19331. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19332. return this;
  19333. }
  19334. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19335. const x0 = this.currentPoint.x;
  19336. const y0 = this.currentPoint.y;
  19337. this.absarc( aX + x0, aY + y0, aRadius,
  19338. aStartAngle, aEndAngle, aClockwise );
  19339. return this;
  19340. }
  19341. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19342. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19343. return this;
  19344. }
  19345. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19346. const x0 = this.currentPoint.x;
  19347. const y0 = this.currentPoint.y;
  19348. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19349. return this;
  19350. }
  19351. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19352. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19353. if ( this.curves.length > 0 ) {
  19354. // if a previous curve is present, attempt to join
  19355. const firstPoint = curve.getPoint( 0 );
  19356. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19357. this.lineTo( firstPoint.x, firstPoint.y );
  19358. }
  19359. }
  19360. this.curves.push( curve );
  19361. const lastPoint = curve.getPoint( 1 );
  19362. this.currentPoint.copy( lastPoint );
  19363. return this;
  19364. }
  19365. copy( source ) {
  19366. super.copy( source );
  19367. this.currentPoint.copy( source.currentPoint );
  19368. return this;
  19369. }
  19370. toJSON() {
  19371. const data = super.toJSON();
  19372. data.currentPoint = this.currentPoint.toArray();
  19373. return data;
  19374. }
  19375. fromJSON( json ) {
  19376. super.fromJSON( json );
  19377. this.currentPoint.fromArray( json.currentPoint );
  19378. return this;
  19379. }
  19380. }
  19381. class Shape extends Path {
  19382. constructor( points ) {
  19383. super( points );
  19384. this.uuid = generateUUID();
  19385. this.type = 'Shape';
  19386. this.holes = [];
  19387. }
  19388. getPointsHoles( divisions ) {
  19389. const holesPts = [];
  19390. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19391. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  19392. }
  19393. return holesPts;
  19394. }
  19395. // get points of shape and holes (keypoints based on segments parameter)
  19396. extractPoints( divisions ) {
  19397. return {
  19398. shape: this.getPoints( divisions ),
  19399. holes: this.getPointsHoles( divisions )
  19400. };
  19401. }
  19402. copy( source ) {
  19403. super.copy( source );
  19404. this.holes = [];
  19405. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  19406. const hole = source.holes[ i ];
  19407. this.holes.push( hole.clone() );
  19408. }
  19409. return this;
  19410. }
  19411. toJSON() {
  19412. const data = super.toJSON();
  19413. data.uuid = this.uuid;
  19414. data.holes = [];
  19415. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19416. const hole = this.holes[ i ];
  19417. data.holes.push( hole.toJSON() );
  19418. }
  19419. return data;
  19420. }
  19421. fromJSON( json ) {
  19422. super.fromJSON( json );
  19423. this.uuid = json.uuid;
  19424. this.holes = [];
  19425. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  19426. const hole = json.holes[ i ];
  19427. this.holes.push( new Path().fromJSON( hole ) );
  19428. }
  19429. return this;
  19430. }
  19431. }
  19432. /**
  19433. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19434. */
  19435. const Earcut = {
  19436. triangulate: function ( data, holeIndices, dim = 2 ) {
  19437. const hasHoles = holeIndices && holeIndices.length;
  19438. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  19439. let outerNode = linkedList( data, 0, outerLen, dim, true );
  19440. const triangles = [];
  19441. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  19442. let minX, minY, maxX, maxY, x, y, invSize;
  19443. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  19444. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19445. if ( data.length > 80 * dim ) {
  19446. minX = maxX = data[ 0 ];
  19447. minY = maxY = data[ 1 ];
  19448. for ( let i = dim; i < outerLen; i += dim ) {
  19449. x = data[ i ];
  19450. y = data[ i + 1 ];
  19451. if ( x < minX ) minX = x;
  19452. if ( y < minY ) minY = y;
  19453. if ( x > maxX ) maxX = x;
  19454. if ( y > maxY ) maxY = y;
  19455. }
  19456. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19457. invSize = Math.max( maxX - minX, maxY - minY );
  19458. invSize = invSize !== 0 ? 1 / invSize : 0;
  19459. }
  19460. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  19461. return triangles;
  19462. }
  19463. };
  19464. // create a circular doubly linked list from polygon points in the specified winding order
  19465. function linkedList( data, start, end, dim, clockwise ) {
  19466. let i, last;
  19467. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  19468. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19469. } else {
  19470. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19471. }
  19472. if ( last && equals( last, last.next ) ) {
  19473. removeNode( last );
  19474. last = last.next;
  19475. }
  19476. return last;
  19477. }
  19478. // eliminate colinear or duplicate points
  19479. function filterPoints( start, end ) {
  19480. if ( ! start ) return start;
  19481. if ( ! end ) end = start;
  19482. let p = start,
  19483. again;
  19484. do {
  19485. again = false;
  19486. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  19487. removeNode( p );
  19488. p = end = p.prev;
  19489. if ( p === p.next ) break;
  19490. again = true;
  19491. } else {
  19492. p = p.next;
  19493. }
  19494. } while ( again || p !== end );
  19495. return end;
  19496. }
  19497. // main ear slicing loop which triangulates a polygon (given as a linked list)
  19498. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  19499. if ( ! ear ) return;
  19500. // interlink polygon nodes in z-order
  19501. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  19502. let stop = ear,
  19503. prev, next;
  19504. // iterate through ears, slicing them one by one
  19505. while ( ear.prev !== ear.next ) {
  19506. prev = ear.prev;
  19507. next = ear.next;
  19508. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  19509. // cut off the triangle
  19510. triangles.push( prev.i / dim );
  19511. triangles.push( ear.i / dim );
  19512. triangles.push( next.i / dim );
  19513. removeNode( ear );
  19514. // skipping the next vertex leads to less sliver triangles
  19515. ear = next.next;
  19516. stop = next.next;
  19517. continue;
  19518. }
  19519. ear = next;
  19520. // if we looped through the whole remaining polygon and can't find any more ears
  19521. if ( ear === stop ) {
  19522. // try filtering points and slicing again
  19523. if ( ! pass ) {
  19524. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  19525. // if this didn't work, try curing all small self-intersections locally
  19526. } else if ( pass === 1 ) {
  19527. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  19528. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  19529. // as a last resort, try splitting the remaining polygon into two
  19530. } else if ( pass === 2 ) {
  19531. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  19532. }
  19533. break;
  19534. }
  19535. }
  19536. }
  19537. // check whether a polygon node forms a valid ear with adjacent nodes
  19538. function isEar( ear ) {
  19539. const a = ear.prev,
  19540. b = ear,
  19541. c = ear.next;
  19542. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19543. // now make sure we don't have other points inside the potential ear
  19544. let p = ear.next.next;
  19545. while ( p !== ear.prev ) {
  19546. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19547. area( p.prev, p, p.next ) >= 0 ) return false;
  19548. p = p.next;
  19549. }
  19550. return true;
  19551. }
  19552. function isEarHashed( ear, minX, minY, invSize ) {
  19553. const a = ear.prev,
  19554. b = ear,
  19555. c = ear.next;
  19556. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19557. // triangle bbox; min & max are calculated like this for speed
  19558. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  19559. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  19560. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  19561. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  19562. // z-order range for the current triangle bbox;
  19563. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  19564. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  19565. let p = ear.prevZ,
  19566. n = ear.nextZ;
  19567. // look for points inside the triangle in both directions
  19568. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19569. if ( p !== ear.prev && p !== ear.next &&
  19570. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19571. area( p.prev, p, p.next ) >= 0 ) return false;
  19572. p = p.prevZ;
  19573. if ( n !== ear.prev && n !== ear.next &&
  19574. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19575. area( n.prev, n, n.next ) >= 0 ) return false;
  19576. n = n.nextZ;
  19577. }
  19578. // look for remaining points in decreasing z-order
  19579. while ( p && p.z >= minZ ) {
  19580. if ( p !== ear.prev && p !== ear.next &&
  19581. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19582. area( p.prev, p, p.next ) >= 0 ) return false;
  19583. p = p.prevZ;
  19584. }
  19585. // look for remaining points in increasing z-order
  19586. while ( n && n.z <= maxZ ) {
  19587. if ( n !== ear.prev && n !== ear.next &&
  19588. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19589. area( n.prev, n, n.next ) >= 0 ) return false;
  19590. n = n.nextZ;
  19591. }
  19592. return true;
  19593. }
  19594. // go through all polygon nodes and cure small local self-intersections
  19595. function cureLocalIntersections( start, triangles, dim ) {
  19596. let p = start;
  19597. do {
  19598. const a = p.prev,
  19599. b = p.next.next;
  19600. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  19601. triangles.push( a.i / dim );
  19602. triangles.push( p.i / dim );
  19603. triangles.push( b.i / dim );
  19604. // remove two nodes involved
  19605. removeNode( p );
  19606. removeNode( p.next );
  19607. p = start = b;
  19608. }
  19609. p = p.next;
  19610. } while ( p !== start );
  19611. return filterPoints( p );
  19612. }
  19613. // try splitting polygon into two and triangulate them independently
  19614. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  19615. // look for a valid diagonal that divides the polygon into two
  19616. let a = start;
  19617. do {
  19618. let b = a.next.next;
  19619. while ( b !== a.prev ) {
  19620. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  19621. // split the polygon in two by the diagonal
  19622. let c = splitPolygon( a, b );
  19623. // filter colinear points around the cuts
  19624. a = filterPoints( a, a.next );
  19625. c = filterPoints( c, c.next );
  19626. // run earcut on each half
  19627. earcutLinked( a, triangles, dim, minX, minY, invSize );
  19628. earcutLinked( c, triangles, dim, minX, minY, invSize );
  19629. return;
  19630. }
  19631. b = b.next;
  19632. }
  19633. a = a.next;
  19634. } while ( a !== start );
  19635. }
  19636. // link every hole into the outer loop, producing a single-ring polygon without holes
  19637. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  19638. const queue = [];
  19639. let i, len, start, end, list;
  19640. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  19641. start = holeIndices[ i ] * dim;
  19642. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  19643. list = linkedList( data, start, end, dim, false );
  19644. if ( list === list.next ) list.steiner = true;
  19645. queue.push( getLeftmost( list ) );
  19646. }
  19647. queue.sort( compareX );
  19648. // process holes from left to right
  19649. for ( i = 0; i < queue.length; i ++ ) {
  19650. eliminateHole( queue[ i ], outerNode );
  19651. outerNode = filterPoints( outerNode, outerNode.next );
  19652. }
  19653. return outerNode;
  19654. }
  19655. function compareX( a, b ) {
  19656. return a.x - b.x;
  19657. }
  19658. // find a bridge between vertices that connects hole with an outer ring and and link it
  19659. function eliminateHole( hole, outerNode ) {
  19660. outerNode = findHoleBridge( hole, outerNode );
  19661. if ( outerNode ) {
  19662. const b = splitPolygon( outerNode, hole );
  19663. // filter collinear points around the cuts
  19664. filterPoints( outerNode, outerNode.next );
  19665. filterPoints( b, b.next );
  19666. }
  19667. }
  19668. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19669. function findHoleBridge( hole, outerNode ) {
  19670. let p = outerNode;
  19671. const hx = hole.x;
  19672. const hy = hole.y;
  19673. let qx = - Infinity, m;
  19674. // find a segment intersected by a ray from the hole's leftmost point to the left;
  19675. // segment's endpoint with lesser x will be potential connection point
  19676. do {
  19677. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  19678. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  19679. if ( x <= hx && x > qx ) {
  19680. qx = x;
  19681. if ( x === hx ) {
  19682. if ( hy === p.y ) return p;
  19683. if ( hy === p.next.y ) return p.next;
  19684. }
  19685. m = p.x < p.next.x ? p : p.next;
  19686. }
  19687. }
  19688. p = p.next;
  19689. } while ( p !== outerNode );
  19690. if ( ! m ) return null;
  19691. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  19692. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19693. // if there are no points found, we have a valid connection;
  19694. // otherwise choose the point of the minimum angle with the ray as connection point
  19695. const stop = m,
  19696. mx = m.x,
  19697. my = m.y;
  19698. let tanMin = Infinity, tan;
  19699. p = m;
  19700. do {
  19701. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  19702. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  19703. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  19704. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  19705. m = p;
  19706. tanMin = tan;
  19707. }
  19708. }
  19709. p = p.next;
  19710. } while ( p !== stop );
  19711. return m;
  19712. }
  19713. // whether sector in vertex m contains sector in vertex p in the same coordinates
  19714. function sectorContainsSector( m, p ) {
  19715. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  19716. }
  19717. // interlink polygon nodes in z-order
  19718. function indexCurve( start, minX, minY, invSize ) {
  19719. let p = start;
  19720. do {
  19721. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  19722. p.prevZ = p.prev;
  19723. p.nextZ = p.next;
  19724. p = p.next;
  19725. } while ( p !== start );
  19726. p.prevZ.nextZ = null;
  19727. p.prevZ = null;
  19728. sortLinked( p );
  19729. }
  19730. // Simon Tatham's linked list merge sort algorithm
  19731. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19732. function sortLinked( list ) {
  19733. let i, p, q, e, tail, numMerges, pSize, qSize,
  19734. inSize = 1;
  19735. do {
  19736. p = list;
  19737. list = null;
  19738. tail = null;
  19739. numMerges = 0;
  19740. while ( p ) {
  19741. numMerges ++;
  19742. q = p;
  19743. pSize = 0;
  19744. for ( i = 0; i < inSize; i ++ ) {
  19745. pSize ++;
  19746. q = q.nextZ;
  19747. if ( ! q ) break;
  19748. }
  19749. qSize = inSize;
  19750. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  19751. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  19752. e = p;
  19753. p = p.nextZ;
  19754. pSize --;
  19755. } else {
  19756. e = q;
  19757. q = q.nextZ;
  19758. qSize --;
  19759. }
  19760. if ( tail ) tail.nextZ = e;
  19761. else list = e;
  19762. e.prevZ = tail;
  19763. tail = e;
  19764. }
  19765. p = q;
  19766. }
  19767. tail.nextZ = null;
  19768. inSize *= 2;
  19769. } while ( numMerges > 1 );
  19770. return list;
  19771. }
  19772. // z-order of a point given coords and inverse of the longer side of data bbox
  19773. function zOrder( x, y, minX, minY, invSize ) {
  19774. // coords are transformed into non-negative 15-bit integer range
  19775. x = 32767 * ( x - minX ) * invSize;
  19776. y = 32767 * ( y - minY ) * invSize;
  19777. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  19778. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  19779. x = ( x | ( x << 2 ) ) & 0x33333333;
  19780. x = ( x | ( x << 1 ) ) & 0x55555555;
  19781. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  19782. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  19783. y = ( y | ( y << 2 ) ) & 0x33333333;
  19784. y = ( y | ( y << 1 ) ) & 0x55555555;
  19785. return x | ( y << 1 );
  19786. }
  19787. // find the leftmost node of a polygon ring
  19788. function getLeftmost( start ) {
  19789. let p = start,
  19790. leftmost = start;
  19791. do {
  19792. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  19793. p = p.next;
  19794. } while ( p !== start );
  19795. return leftmost;
  19796. }
  19797. // check if a point lies within a convex triangle
  19798. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  19799. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  19800. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  19801. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  19802. }
  19803. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19804. function isValidDiagonal( a, b ) {
  19805. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  19806. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  19807. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  19808. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  19809. }
  19810. // signed area of a triangle
  19811. function area( p, q, r ) {
  19812. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  19813. }
  19814. // check if two points are equal
  19815. function equals( p1, p2 ) {
  19816. return p1.x === p2.x && p1.y === p2.y;
  19817. }
  19818. // check if two segments intersect
  19819. function intersects( p1, q1, p2, q2 ) {
  19820. const o1 = sign( area( p1, q1, p2 ) );
  19821. const o2 = sign( area( p1, q1, q2 ) );
  19822. const o3 = sign( area( p2, q2, p1 ) );
  19823. const o4 = sign( area( p2, q2, q1 ) );
  19824. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  19825. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19826. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19827. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19828. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19829. return false;
  19830. }
  19831. // for collinear points p, q, r, check if point q lies on segment pr
  19832. function onSegment( p, q, r ) {
  19833. 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 );
  19834. }
  19835. function sign( num ) {
  19836. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  19837. }
  19838. // check if a polygon diagonal intersects any polygon segments
  19839. function intersectsPolygon( a, b ) {
  19840. let p = a;
  19841. do {
  19842. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  19843. intersects( p, p.next, a, b ) ) return true;
  19844. p = p.next;
  19845. } while ( p !== a );
  19846. return false;
  19847. }
  19848. // check if a polygon diagonal is locally inside the polygon
  19849. function locallyInside( a, b ) {
  19850. return area( a.prev, a, a.next ) < 0 ?
  19851. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  19852. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  19853. }
  19854. // check if the middle point of a polygon diagonal is inside the polygon
  19855. function middleInside( a, b ) {
  19856. let p = a,
  19857. inside = false;
  19858. const px = ( a.x + b.x ) / 2,
  19859. py = ( a.y + b.y ) / 2;
  19860. do {
  19861. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  19862. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  19863. inside = ! inside;
  19864. p = p.next;
  19865. } while ( p !== a );
  19866. return inside;
  19867. }
  19868. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19869. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19870. function splitPolygon( a, b ) {
  19871. const a2 = new Node( a.i, a.x, a.y ),
  19872. b2 = new Node( b.i, b.x, b.y ),
  19873. an = a.next,
  19874. bp = b.prev;
  19875. a.next = b;
  19876. b.prev = a;
  19877. a2.next = an;
  19878. an.prev = a2;
  19879. b2.next = a2;
  19880. a2.prev = b2;
  19881. bp.next = b2;
  19882. b2.prev = bp;
  19883. return b2;
  19884. }
  19885. // create a node and optionally link it with previous one (in a circular doubly linked list)
  19886. function insertNode( i, x, y, last ) {
  19887. const p = new Node( i, x, y );
  19888. if ( ! last ) {
  19889. p.prev = p;
  19890. p.next = p;
  19891. } else {
  19892. p.next = last.next;
  19893. p.prev = last;
  19894. last.next.prev = p;
  19895. last.next = p;
  19896. }
  19897. return p;
  19898. }
  19899. function removeNode( p ) {
  19900. p.next.prev = p.prev;
  19901. p.prev.next = p.next;
  19902. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  19903. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  19904. }
  19905. function Node( i, x, y ) {
  19906. // vertex index in coordinates array
  19907. this.i = i;
  19908. // vertex coordinates
  19909. this.x = x;
  19910. this.y = y;
  19911. // previous and next vertex nodes in a polygon ring
  19912. this.prev = null;
  19913. this.next = null;
  19914. // z-order curve value
  19915. this.z = null;
  19916. // previous and next nodes in z-order
  19917. this.prevZ = null;
  19918. this.nextZ = null;
  19919. // indicates whether this is a steiner point
  19920. this.steiner = false;
  19921. }
  19922. function signedArea( data, start, end, dim ) {
  19923. let sum = 0;
  19924. for ( let i = start, j = end - dim; i < end; i += dim ) {
  19925. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  19926. j = i;
  19927. }
  19928. return sum;
  19929. }
  19930. class ShapeUtils {
  19931. // calculate area of the contour polygon
  19932. static area( contour ) {
  19933. const n = contour.length;
  19934. let a = 0.0;
  19935. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  19936. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19937. }
  19938. return a * 0.5;
  19939. }
  19940. static isClockWise( pts ) {
  19941. return ShapeUtils.area( pts ) < 0;
  19942. }
  19943. static triangulateShape( contour, holes ) {
  19944. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19945. const holeIndices = []; // array of hole indices
  19946. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19947. removeDupEndPts( contour );
  19948. addContour( vertices, contour );
  19949. //
  19950. let holeIndex = contour.length;
  19951. holes.forEach( removeDupEndPts );
  19952. for ( let i = 0; i < holes.length; i ++ ) {
  19953. holeIndices.push( holeIndex );
  19954. holeIndex += holes[ i ].length;
  19955. addContour( vertices, holes[ i ] );
  19956. }
  19957. //
  19958. const triangles = Earcut.triangulate( vertices, holeIndices );
  19959. //
  19960. for ( let i = 0; i < triangles.length; i += 3 ) {
  19961. faces.push( triangles.slice( i, i + 3 ) );
  19962. }
  19963. return faces;
  19964. }
  19965. }
  19966. function removeDupEndPts( points ) {
  19967. const l = points.length;
  19968. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19969. points.pop();
  19970. }
  19971. }
  19972. function addContour( vertices, contour ) {
  19973. for ( let i = 0; i < contour.length; i ++ ) {
  19974. vertices.push( contour[ i ].x );
  19975. vertices.push( contour[ i ].y );
  19976. }
  19977. }
  19978. /**
  19979. * Creates extruded geometry from a path shape.
  19980. *
  19981. * parameters = {
  19982. *
  19983. * curveSegments: <int>, // number of points on the curves
  19984. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19985. * depth: <float>, // Depth to extrude the shape
  19986. *
  19987. * bevelEnabled: <bool>, // turn on bevel
  19988. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19989. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19990. * bevelOffset: <float>, // how far from shape outline does bevel start
  19991. * bevelSegments: <int>, // number of bevel layers
  19992. *
  19993. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19994. *
  19995. * UVGenerator: <Object> // object that provides UV generator functions
  19996. *
  19997. * }
  19998. */
  19999. class ExtrudeGeometry extends BufferGeometry {
  20000. 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 = {} ) {
  20001. super();
  20002. this.type = 'ExtrudeGeometry';
  20003. this.parameters = {
  20004. shapes: shapes,
  20005. options: options
  20006. };
  20007. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20008. const scope = this;
  20009. const verticesArray = [];
  20010. const uvArray = [];
  20011. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20012. const shape = shapes[ i ];
  20013. addShape( shape );
  20014. }
  20015. // build geometry
  20016. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20017. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20018. this.computeVertexNormals();
  20019. // functions
  20020. function addShape( shape ) {
  20021. const placeholder = [];
  20022. // options
  20023. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20024. const steps = options.steps !== undefined ? options.steps : 1;
  20025. let depth = options.depth !== undefined ? options.depth : 1;
  20026. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20027. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20028. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20029. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20030. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20031. const extrudePath = options.extrudePath;
  20032. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20033. // deprecated options
  20034. if ( options.amount !== undefined ) {
  20035. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  20036. depth = options.amount;
  20037. }
  20038. //
  20039. let extrudePts, extrudeByPath = false;
  20040. let splineTube, binormal, normal, position2;
  20041. if ( extrudePath ) {
  20042. extrudePts = extrudePath.getSpacedPoints( steps );
  20043. extrudeByPath = true;
  20044. bevelEnabled = false; // bevels not supported for path extrusion
  20045. // SETUP TNB variables
  20046. // TODO1 - have a .isClosed in spline?
  20047. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20048. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20049. binormal = new Vector3();
  20050. normal = new Vector3();
  20051. position2 = new Vector3();
  20052. }
  20053. // Safeguards if bevels are not enabled
  20054. if ( ! bevelEnabled ) {
  20055. bevelSegments = 0;
  20056. bevelThickness = 0;
  20057. bevelSize = 0;
  20058. bevelOffset = 0;
  20059. }
  20060. // Variables initialization
  20061. const shapePoints = shape.extractPoints( curveSegments );
  20062. let vertices = shapePoints.shape;
  20063. const holes = shapePoints.holes;
  20064. const reverse = ! ShapeUtils.isClockWise( vertices );
  20065. if ( reverse ) {
  20066. vertices = vertices.reverse();
  20067. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20068. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20069. const ahole = holes[ h ];
  20070. if ( ShapeUtils.isClockWise( ahole ) ) {
  20071. holes[ h ] = ahole.reverse();
  20072. }
  20073. }
  20074. }
  20075. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20076. /* Vertices */
  20077. const contour = vertices; // vertices has all points but contour has only points of circumference
  20078. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20079. const ahole = holes[ h ];
  20080. vertices = vertices.concat( ahole );
  20081. }
  20082. function scalePt2( pt, vec, size ) {
  20083. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20084. return vec.clone().multiplyScalar( size ).add( pt );
  20085. }
  20086. const vlen = vertices.length, flen = faces.length;
  20087. // Find directions for point movement
  20088. function getBevelVec( inPt, inPrev, inNext ) {
  20089. // computes for inPt the corresponding point inPt' on a new contour
  20090. // shifted by 1 unit (length of normalized vector) to the left
  20091. // if we walk along contour clockwise, this new contour is outside the old one
  20092. //
  20093. // inPt' is the intersection of the two lines parallel to the two
  20094. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20095. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20096. // good reading for geometry algorithms (here: line-line intersection)
  20097. // http://geomalgorithms.com/a05-_intersect-1.html
  20098. const v_prev_x = inPt.x - inPrev.x,
  20099. v_prev_y = inPt.y - inPrev.y;
  20100. const v_next_x = inNext.x - inPt.x,
  20101. v_next_y = inNext.y - inPt.y;
  20102. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20103. // check for collinear edges
  20104. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20105. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20106. // not collinear
  20107. // length of vectors for normalizing
  20108. const v_prev_len = Math.sqrt( v_prev_lensq );
  20109. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20110. // shift adjacent points by unit vectors to the left
  20111. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20112. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20113. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20114. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20115. // scaling factor for v_prev to intersection point
  20116. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20117. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20118. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20119. // vector from inPt to intersection point
  20120. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20121. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20122. // Don't normalize!, otherwise sharp corners become ugly
  20123. // but prevent crazy spikes
  20124. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20125. if ( v_trans_lensq <= 2 ) {
  20126. return new Vector2( v_trans_x, v_trans_y );
  20127. } else {
  20128. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20129. }
  20130. } else {
  20131. // handle special case of collinear edges
  20132. let direction_eq = false; // assumes: opposite
  20133. if ( v_prev_x > Number.EPSILON ) {
  20134. if ( v_next_x > Number.EPSILON ) {
  20135. direction_eq = true;
  20136. }
  20137. } else {
  20138. if ( v_prev_x < - Number.EPSILON ) {
  20139. if ( v_next_x < - Number.EPSILON ) {
  20140. direction_eq = true;
  20141. }
  20142. } else {
  20143. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20144. direction_eq = true;
  20145. }
  20146. }
  20147. }
  20148. if ( direction_eq ) {
  20149. // console.log("Warning: lines are a straight sequence");
  20150. v_trans_x = - v_prev_y;
  20151. v_trans_y = v_prev_x;
  20152. shrink_by = Math.sqrt( v_prev_lensq );
  20153. } else {
  20154. // console.log("Warning: lines are a straight spike");
  20155. v_trans_x = v_prev_x;
  20156. v_trans_y = v_prev_y;
  20157. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20158. }
  20159. }
  20160. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20161. }
  20162. const contourMovements = [];
  20163. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20164. if ( j === il ) j = 0;
  20165. if ( k === il ) k = 0;
  20166. // (j)---(i)---(k)
  20167. // console.log('i,j,k', i, j , k)
  20168. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20169. }
  20170. const holesMovements = [];
  20171. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20172. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20173. const ahole = holes[ h ];
  20174. oneHoleMovements = [];
  20175. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20176. if ( j === il ) j = 0;
  20177. if ( k === il ) k = 0;
  20178. // (j)---(i)---(k)
  20179. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20180. }
  20181. holesMovements.push( oneHoleMovements );
  20182. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20183. }
  20184. // Loop bevelSegments, 1 for the front, 1 for the back
  20185. for ( let b = 0; b < bevelSegments; b ++ ) {
  20186. //for ( b = bevelSegments; b > 0; b -- ) {
  20187. const t = b / bevelSegments;
  20188. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20189. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20190. // contract shape
  20191. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20192. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20193. v( vert.x, vert.y, - z );
  20194. }
  20195. // expand holes
  20196. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20197. const ahole = holes[ h ];
  20198. oneHoleMovements = holesMovements[ h ];
  20199. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20200. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20201. v( vert.x, vert.y, - z );
  20202. }
  20203. }
  20204. }
  20205. const bs = bevelSize + bevelOffset;
  20206. // Back facing vertices
  20207. for ( let i = 0; i < vlen; i ++ ) {
  20208. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20209. if ( ! extrudeByPath ) {
  20210. v( vert.x, vert.y, 0 );
  20211. } else {
  20212. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20213. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20214. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20215. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20216. v( position2.x, position2.y, position2.z );
  20217. }
  20218. }
  20219. // Add stepped vertices...
  20220. // Including front facing vertices
  20221. for ( let s = 1; s <= steps; s ++ ) {
  20222. for ( let i = 0; i < vlen; i ++ ) {
  20223. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20224. if ( ! extrudeByPath ) {
  20225. v( vert.x, vert.y, depth / steps * s );
  20226. } else {
  20227. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20228. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20229. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20230. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20231. v( position2.x, position2.y, position2.z );
  20232. }
  20233. }
  20234. }
  20235. // Add bevel segments planes
  20236. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20237. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  20238. const t = b / bevelSegments;
  20239. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20240. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20241. // contract shape
  20242. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20243. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20244. v( vert.x, vert.y, depth + z );
  20245. }
  20246. // expand holes
  20247. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20248. const ahole = holes[ h ];
  20249. oneHoleMovements = holesMovements[ h ];
  20250. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20251. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20252. if ( ! extrudeByPath ) {
  20253. v( vert.x, vert.y, depth + z );
  20254. } else {
  20255. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20256. }
  20257. }
  20258. }
  20259. }
  20260. /* Faces */
  20261. // Top and bottom faces
  20262. buildLidFaces();
  20263. // Sides faces
  20264. buildSideFaces();
  20265. ///// Internal functions
  20266. function buildLidFaces() {
  20267. const start = verticesArray.length / 3;
  20268. if ( bevelEnabled ) {
  20269. let layer = 0; // steps + 1
  20270. let offset = vlen * layer;
  20271. // Bottom faces
  20272. for ( let i = 0; i < flen; i ++ ) {
  20273. const face = faces[ i ];
  20274. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20275. }
  20276. layer = steps + bevelSegments * 2;
  20277. offset = vlen * layer;
  20278. // Top faces
  20279. for ( let i = 0; i < flen; i ++ ) {
  20280. const face = faces[ i ];
  20281. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20282. }
  20283. } else {
  20284. // Bottom faces
  20285. for ( let i = 0; i < flen; i ++ ) {
  20286. const face = faces[ i ];
  20287. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20288. }
  20289. // Top faces
  20290. for ( let i = 0; i < flen; i ++ ) {
  20291. const face = faces[ i ];
  20292. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20293. }
  20294. }
  20295. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  20296. }
  20297. // Create faces for the z-sides of the shape
  20298. function buildSideFaces() {
  20299. const start = verticesArray.length / 3;
  20300. let layeroffset = 0;
  20301. sidewalls( contour, layeroffset );
  20302. layeroffset += contour.length;
  20303. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20304. const ahole = holes[ h ];
  20305. sidewalls( ahole, layeroffset );
  20306. //, true
  20307. layeroffset += ahole.length;
  20308. }
  20309. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  20310. }
  20311. function sidewalls( contour, layeroffset ) {
  20312. let i = contour.length;
  20313. while ( -- i >= 0 ) {
  20314. const j = i;
  20315. let k = i - 1;
  20316. if ( k < 0 ) k = contour.length - 1;
  20317. //console.log('b', i,j, i-1, k,vertices.length);
  20318. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  20319. const slen1 = vlen * s;
  20320. const slen2 = vlen * ( s + 1 );
  20321. const a = layeroffset + j + slen1,
  20322. b = layeroffset + k + slen1,
  20323. c = layeroffset + k + slen2,
  20324. d = layeroffset + j + slen2;
  20325. f4( a, b, c, d );
  20326. }
  20327. }
  20328. }
  20329. function v( x, y, z ) {
  20330. placeholder.push( x );
  20331. placeholder.push( y );
  20332. placeholder.push( z );
  20333. }
  20334. function f3( a, b, c ) {
  20335. addVertex( a );
  20336. addVertex( b );
  20337. addVertex( c );
  20338. const nextIndex = verticesArray.length / 3;
  20339. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20340. addUV( uvs[ 0 ] );
  20341. addUV( uvs[ 1 ] );
  20342. addUV( uvs[ 2 ] );
  20343. }
  20344. function f4( a, b, c, d ) {
  20345. addVertex( a );
  20346. addVertex( b );
  20347. addVertex( d );
  20348. addVertex( b );
  20349. addVertex( c );
  20350. addVertex( d );
  20351. const nextIndex = verticesArray.length / 3;
  20352. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20353. addUV( uvs[ 0 ] );
  20354. addUV( uvs[ 1 ] );
  20355. addUV( uvs[ 3 ] );
  20356. addUV( uvs[ 1 ] );
  20357. addUV( uvs[ 2 ] );
  20358. addUV( uvs[ 3 ] );
  20359. }
  20360. function addVertex( index ) {
  20361. verticesArray.push( placeholder[ index * 3 + 0 ] );
  20362. verticesArray.push( placeholder[ index * 3 + 1 ] );
  20363. verticesArray.push( placeholder[ index * 3 + 2 ] );
  20364. }
  20365. function addUV( vector2 ) {
  20366. uvArray.push( vector2.x );
  20367. uvArray.push( vector2.y );
  20368. }
  20369. }
  20370. }
  20371. toJSON() {
  20372. const data = super.toJSON();
  20373. const shapes = this.parameters.shapes;
  20374. const options = this.parameters.options;
  20375. return toJSON$1( shapes, options, data );
  20376. }
  20377. static fromJSON( data, shapes ) {
  20378. const geometryShapes = [];
  20379. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20380. const shape = shapes[ data.shapes[ j ] ];
  20381. geometryShapes.push( shape );
  20382. }
  20383. const extrudePath = data.options.extrudePath;
  20384. if ( extrudePath !== undefined ) {
  20385. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20386. }
  20387. return new ExtrudeGeometry( geometryShapes, data.options );
  20388. }
  20389. }
  20390. const WorldUVGenerator = {
  20391. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20392. const a_x = vertices[ indexA * 3 ];
  20393. const a_y = vertices[ indexA * 3 + 1 ];
  20394. const b_x = vertices[ indexB * 3 ];
  20395. const b_y = vertices[ indexB * 3 + 1 ];
  20396. const c_x = vertices[ indexC * 3 ];
  20397. const c_y = vertices[ indexC * 3 + 1 ];
  20398. return [
  20399. new Vector2( a_x, a_y ),
  20400. new Vector2( b_x, b_y ),
  20401. new Vector2( c_x, c_y )
  20402. ];
  20403. },
  20404. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20405. const a_x = vertices[ indexA * 3 ];
  20406. const a_y = vertices[ indexA * 3 + 1 ];
  20407. const a_z = vertices[ indexA * 3 + 2 ];
  20408. const b_x = vertices[ indexB * 3 ];
  20409. const b_y = vertices[ indexB * 3 + 1 ];
  20410. const b_z = vertices[ indexB * 3 + 2 ];
  20411. const c_x = vertices[ indexC * 3 ];
  20412. const c_y = vertices[ indexC * 3 + 1 ];
  20413. const c_z = vertices[ indexC * 3 + 2 ];
  20414. const d_x = vertices[ indexD * 3 ];
  20415. const d_y = vertices[ indexD * 3 + 1 ];
  20416. const d_z = vertices[ indexD * 3 + 2 ];
  20417. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  20418. return [
  20419. new Vector2( a_x, 1 - a_z ),
  20420. new Vector2( b_x, 1 - b_z ),
  20421. new Vector2( c_x, 1 - c_z ),
  20422. new Vector2( d_x, 1 - d_z )
  20423. ];
  20424. } else {
  20425. return [
  20426. new Vector2( a_y, 1 - a_z ),
  20427. new Vector2( b_y, 1 - b_z ),
  20428. new Vector2( c_y, 1 - c_z ),
  20429. new Vector2( d_y, 1 - d_z )
  20430. ];
  20431. }
  20432. }
  20433. };
  20434. function toJSON$1( shapes, options, data ) {
  20435. data.shapes = [];
  20436. if ( Array.isArray( shapes ) ) {
  20437. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20438. const shape = shapes[ i ];
  20439. data.shapes.push( shape.uuid );
  20440. }
  20441. } else {
  20442. data.shapes.push( shapes.uuid );
  20443. }
  20444. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  20445. return data;
  20446. }
  20447. class IcosahedronGeometry extends PolyhedronGeometry {
  20448. constructor( radius = 1, detail = 0 ) {
  20449. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20450. const vertices = [
  20451. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20452. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20453. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20454. ];
  20455. const indices = [
  20456. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20457. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20458. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20459. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20460. ];
  20461. super( vertices, indices, radius, detail );
  20462. this.type = 'IcosahedronGeometry';
  20463. this.parameters = {
  20464. radius: radius,
  20465. detail: detail
  20466. };
  20467. }
  20468. static fromJSON( data ) {
  20469. return new IcosahedronGeometry( data.radius, data.detail );
  20470. }
  20471. }
  20472. class LatheGeometry extends BufferGeometry {
  20473. 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 ) {
  20474. super();
  20475. this.type = 'LatheGeometry';
  20476. this.parameters = {
  20477. points: points,
  20478. segments: segments,
  20479. phiStart: phiStart,
  20480. phiLength: phiLength
  20481. };
  20482. segments = Math.floor( segments );
  20483. // clamp phiLength so it's in range of [ 0, 2PI ]
  20484. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20485. // buffers
  20486. const indices = [];
  20487. const vertices = [];
  20488. const uvs = [];
  20489. // helper variables
  20490. const inverseSegments = 1.0 / segments;
  20491. const vertex = new Vector3();
  20492. const uv = new Vector2();
  20493. // generate vertices and uvs
  20494. for ( let i = 0; i <= segments; i ++ ) {
  20495. const phi = phiStart + i * inverseSegments * phiLength;
  20496. const sin = Math.sin( phi );
  20497. const cos = Math.cos( phi );
  20498. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20499. // vertex
  20500. vertex.x = points[ j ].x * sin;
  20501. vertex.y = points[ j ].y;
  20502. vertex.z = points[ j ].x * cos;
  20503. vertices.push( vertex.x, vertex.y, vertex.z );
  20504. // uv
  20505. uv.x = i / segments;
  20506. uv.y = j / ( points.length - 1 );
  20507. uvs.push( uv.x, uv.y );
  20508. }
  20509. }
  20510. // indices
  20511. for ( let i = 0; i < segments; i ++ ) {
  20512. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20513. const base = j + i * points.length;
  20514. const a = base;
  20515. const b = base + points.length;
  20516. const c = base + points.length + 1;
  20517. const d = base + 1;
  20518. // faces
  20519. indices.push( a, b, d );
  20520. indices.push( b, c, d );
  20521. }
  20522. }
  20523. // build geometry
  20524. this.setIndex( indices );
  20525. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20526. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20527. // generate normals
  20528. this.computeVertexNormals();
  20529. // if the geometry is closed, we need to average the normals along the seam.
  20530. // because the corresponding vertices are identical (but still have different UVs).
  20531. if ( phiLength === Math.PI * 2 ) {
  20532. const normals = this.attributes.normal.array;
  20533. const n1 = new Vector3();
  20534. const n2 = new Vector3();
  20535. const n = new Vector3();
  20536. // this is the buffer offset for the last line of vertices
  20537. const base = segments * points.length * 3;
  20538. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  20539. // select the normal of the vertex in the first line
  20540. n1.x = normals[ j + 0 ];
  20541. n1.y = normals[ j + 1 ];
  20542. n1.z = normals[ j + 2 ];
  20543. // select the normal of the vertex in the last line
  20544. n2.x = normals[ base + j + 0 ];
  20545. n2.y = normals[ base + j + 1 ];
  20546. n2.z = normals[ base + j + 2 ];
  20547. // average normals
  20548. n.addVectors( n1, n2 ).normalize();
  20549. // assign the new values to both normals
  20550. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  20551. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  20552. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  20553. }
  20554. }
  20555. }
  20556. static fromJSON( data ) {
  20557. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20558. }
  20559. }
  20560. class OctahedronGeometry extends PolyhedronGeometry {
  20561. constructor( radius = 1, detail = 0 ) {
  20562. const vertices = [
  20563. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  20564. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20565. ];
  20566. const indices = [
  20567. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20568. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20569. 1, 3, 4, 1, 4, 2
  20570. ];
  20571. super( vertices, indices, radius, detail );
  20572. this.type = 'OctahedronGeometry';
  20573. this.parameters = {
  20574. radius: radius,
  20575. detail: detail
  20576. };
  20577. }
  20578. static fromJSON( data ) {
  20579. return new OctahedronGeometry( data.radius, data.detail );
  20580. }
  20581. }
  20582. class RingGeometry extends BufferGeometry {
  20583. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20584. super();
  20585. this.type = 'RingGeometry';
  20586. this.parameters = {
  20587. innerRadius: innerRadius,
  20588. outerRadius: outerRadius,
  20589. thetaSegments: thetaSegments,
  20590. phiSegments: phiSegments,
  20591. thetaStart: thetaStart,
  20592. thetaLength: thetaLength
  20593. };
  20594. thetaSegments = Math.max( 3, thetaSegments );
  20595. phiSegments = Math.max( 1, phiSegments );
  20596. // buffers
  20597. const indices = [];
  20598. const vertices = [];
  20599. const normals = [];
  20600. const uvs = [];
  20601. // some helper variables
  20602. let radius = innerRadius;
  20603. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20604. const vertex = new Vector3();
  20605. const uv = new Vector2();
  20606. // generate vertices, normals and uvs
  20607. for ( let j = 0; j <= phiSegments; j ++ ) {
  20608. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20609. // values are generate from the inside of the ring to the outside
  20610. const segment = thetaStart + i / thetaSegments * thetaLength;
  20611. // vertex
  20612. vertex.x = radius * Math.cos( segment );
  20613. vertex.y = radius * Math.sin( segment );
  20614. vertices.push( vertex.x, vertex.y, vertex.z );
  20615. // normal
  20616. normals.push( 0, 0, 1 );
  20617. // uv
  20618. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20619. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20620. uvs.push( uv.x, uv.y );
  20621. }
  20622. // increase the radius for next row of vertices
  20623. radius += radiusStep;
  20624. }
  20625. // indices
  20626. for ( let j = 0; j < phiSegments; j ++ ) {
  20627. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20628. for ( let i = 0; i < thetaSegments; i ++ ) {
  20629. const segment = i + thetaSegmentLevel;
  20630. const a = segment;
  20631. const b = segment + thetaSegments + 1;
  20632. const c = segment + thetaSegments + 2;
  20633. const d = segment + 1;
  20634. // faces
  20635. indices.push( a, b, d );
  20636. indices.push( b, c, d );
  20637. }
  20638. }
  20639. // build geometry
  20640. this.setIndex( indices );
  20641. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20642. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20643. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20644. }
  20645. static fromJSON( data ) {
  20646. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20647. }
  20648. }
  20649. class ShapeGeometry extends BufferGeometry {
  20650. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  20651. super();
  20652. this.type = 'ShapeGeometry';
  20653. this.parameters = {
  20654. shapes: shapes,
  20655. curveSegments: curveSegments
  20656. };
  20657. // buffers
  20658. const indices = [];
  20659. const vertices = [];
  20660. const normals = [];
  20661. const uvs = [];
  20662. // helper variables
  20663. let groupStart = 0;
  20664. let groupCount = 0;
  20665. // allow single and array values for "shapes" parameter
  20666. if ( Array.isArray( shapes ) === false ) {
  20667. addShape( shapes );
  20668. } else {
  20669. for ( let i = 0; i < shapes.length; i ++ ) {
  20670. addShape( shapes[ i ] );
  20671. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20672. groupStart += groupCount;
  20673. groupCount = 0;
  20674. }
  20675. }
  20676. // build geometry
  20677. this.setIndex( indices );
  20678. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20679. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20680. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20681. // helper functions
  20682. function addShape( shape ) {
  20683. const indexOffset = vertices.length / 3;
  20684. const points = shape.extractPoints( curveSegments );
  20685. let shapeVertices = points.shape;
  20686. const shapeHoles = points.holes;
  20687. // check direction of vertices
  20688. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20689. shapeVertices = shapeVertices.reverse();
  20690. }
  20691. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20692. const shapeHole = shapeHoles[ i ];
  20693. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20694. shapeHoles[ i ] = shapeHole.reverse();
  20695. }
  20696. }
  20697. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20698. // join vertices of inner and outer paths to a single array
  20699. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20700. const shapeHole = shapeHoles[ i ];
  20701. shapeVertices = shapeVertices.concat( shapeHole );
  20702. }
  20703. // vertices, normals, uvs
  20704. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20705. const vertex = shapeVertices[ i ];
  20706. vertices.push( vertex.x, vertex.y, 0 );
  20707. normals.push( 0, 0, 1 );
  20708. uvs.push( vertex.x, vertex.y ); // world uvs
  20709. }
  20710. // incides
  20711. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20712. const face = faces[ i ];
  20713. const a = face[ 0 ] + indexOffset;
  20714. const b = face[ 1 ] + indexOffset;
  20715. const c = face[ 2 ] + indexOffset;
  20716. indices.push( a, b, c );
  20717. groupCount += 3;
  20718. }
  20719. }
  20720. }
  20721. toJSON() {
  20722. const data = super.toJSON();
  20723. const shapes = this.parameters.shapes;
  20724. return toJSON( shapes, data );
  20725. }
  20726. static fromJSON( data, shapes ) {
  20727. const geometryShapes = [];
  20728. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20729. const shape = shapes[ data.shapes[ j ] ];
  20730. geometryShapes.push( shape );
  20731. }
  20732. return new ShapeGeometry( geometryShapes, data.curveSegments );
  20733. }
  20734. }
  20735. function toJSON( shapes, data ) {
  20736. data.shapes = [];
  20737. if ( Array.isArray( shapes ) ) {
  20738. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20739. const shape = shapes[ i ];
  20740. data.shapes.push( shape.uuid );
  20741. }
  20742. } else {
  20743. data.shapes.push( shapes.uuid );
  20744. }
  20745. return data;
  20746. }
  20747. class SphereGeometry extends BufferGeometry {
  20748. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  20749. super();
  20750. this.type = 'SphereGeometry';
  20751. this.parameters = {
  20752. radius: radius,
  20753. widthSegments: widthSegments,
  20754. heightSegments: heightSegments,
  20755. phiStart: phiStart,
  20756. phiLength: phiLength,
  20757. thetaStart: thetaStart,
  20758. thetaLength: thetaLength
  20759. };
  20760. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  20761. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  20762. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  20763. let index = 0;
  20764. const grid = [];
  20765. const vertex = new Vector3();
  20766. const normal = new Vector3();
  20767. // buffers
  20768. const indices = [];
  20769. const vertices = [];
  20770. const normals = [];
  20771. const uvs = [];
  20772. // generate vertices, normals and uvs
  20773. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  20774. const verticesRow = [];
  20775. const v = iy / heightSegments;
  20776. // special case for the poles
  20777. let uOffset = 0;
  20778. if ( iy == 0 && thetaStart == 0 ) {
  20779. uOffset = 0.5 / widthSegments;
  20780. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  20781. uOffset = - 0.5 / widthSegments;
  20782. }
  20783. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  20784. const u = ix / widthSegments;
  20785. // vertex
  20786. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20787. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20788. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20789. vertices.push( vertex.x, vertex.y, vertex.z );
  20790. // normal
  20791. normal.copy( vertex ).normalize();
  20792. normals.push( normal.x, normal.y, normal.z );
  20793. // uv
  20794. uvs.push( u + uOffset, 1 - v );
  20795. verticesRow.push( index ++ );
  20796. }
  20797. grid.push( verticesRow );
  20798. }
  20799. // indices
  20800. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20801. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20802. const a = grid[ iy ][ ix + 1 ];
  20803. const b = grid[ iy ][ ix ];
  20804. const c = grid[ iy + 1 ][ ix ];
  20805. const d = grid[ iy + 1 ][ ix + 1 ];
  20806. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20807. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20808. }
  20809. }
  20810. // build geometry
  20811. this.setIndex( indices );
  20812. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20813. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20814. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20815. }
  20816. static fromJSON( data ) {
  20817. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  20818. }
  20819. }
  20820. class TetrahedronGeometry extends PolyhedronGeometry {
  20821. constructor( radius = 1, detail = 0 ) {
  20822. const vertices = [
  20823. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20824. ];
  20825. const indices = [
  20826. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20827. ];
  20828. super( vertices, indices, radius, detail );
  20829. this.type = 'TetrahedronGeometry';
  20830. this.parameters = {
  20831. radius: radius,
  20832. detail: detail
  20833. };
  20834. }
  20835. static fromJSON( data ) {
  20836. return new TetrahedronGeometry( data.radius, data.detail );
  20837. }
  20838. }
  20839. class TorusGeometry extends BufferGeometry {
  20840. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  20841. super();
  20842. this.type = 'TorusGeometry';
  20843. this.parameters = {
  20844. radius: radius,
  20845. tube: tube,
  20846. radialSegments: radialSegments,
  20847. tubularSegments: tubularSegments,
  20848. arc: arc
  20849. };
  20850. radialSegments = Math.floor( radialSegments );
  20851. tubularSegments = Math.floor( tubularSegments );
  20852. // buffers
  20853. const indices = [];
  20854. const vertices = [];
  20855. const normals = [];
  20856. const uvs = [];
  20857. // helper variables
  20858. const center = new Vector3();
  20859. const vertex = new Vector3();
  20860. const normal = new Vector3();
  20861. // generate vertices, normals and uvs
  20862. for ( let j = 0; j <= radialSegments; j ++ ) {
  20863. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20864. const u = i / tubularSegments * arc;
  20865. const v = j / radialSegments * Math.PI * 2;
  20866. // vertex
  20867. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20868. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20869. vertex.z = tube * Math.sin( v );
  20870. vertices.push( vertex.x, vertex.y, vertex.z );
  20871. // normal
  20872. center.x = radius * Math.cos( u );
  20873. center.y = radius * Math.sin( u );
  20874. normal.subVectors( vertex, center ).normalize();
  20875. normals.push( normal.x, normal.y, normal.z );
  20876. // uv
  20877. uvs.push( i / tubularSegments );
  20878. uvs.push( j / radialSegments );
  20879. }
  20880. }
  20881. // generate indices
  20882. for ( let j = 1; j <= radialSegments; j ++ ) {
  20883. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20884. // indices
  20885. const a = ( tubularSegments + 1 ) * j + i - 1;
  20886. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20887. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20888. const d = ( tubularSegments + 1 ) * j + i;
  20889. // faces
  20890. indices.push( a, b, d );
  20891. indices.push( b, c, d );
  20892. }
  20893. }
  20894. // build geometry
  20895. this.setIndex( indices );
  20896. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20897. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20898. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20899. }
  20900. static fromJSON( data ) {
  20901. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  20902. }
  20903. }
  20904. class TorusKnotGeometry extends BufferGeometry {
  20905. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20906. super();
  20907. this.type = 'TorusKnotGeometry';
  20908. this.parameters = {
  20909. radius: radius,
  20910. tube: tube,
  20911. tubularSegments: tubularSegments,
  20912. radialSegments: radialSegments,
  20913. p: p,
  20914. q: q
  20915. };
  20916. tubularSegments = Math.floor( tubularSegments );
  20917. radialSegments = Math.floor( radialSegments );
  20918. // buffers
  20919. const indices = [];
  20920. const vertices = [];
  20921. const normals = [];
  20922. const uvs = [];
  20923. // helper variables
  20924. const vertex = new Vector3();
  20925. const normal = new Vector3();
  20926. const P1 = new Vector3();
  20927. const P2 = new Vector3();
  20928. const B = new Vector3();
  20929. const T = new Vector3();
  20930. const N = new Vector3();
  20931. // generate vertices, normals and uvs
  20932. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20933. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20934. const u = i / tubularSegments * p * Math.PI * 2;
  20935. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20936. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20937. calculatePositionOnCurve( u, p, q, radius, P1 );
  20938. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20939. // calculate orthonormal basis
  20940. T.subVectors( P2, P1 );
  20941. N.addVectors( P2, P1 );
  20942. B.crossVectors( T, N );
  20943. N.crossVectors( B, T );
  20944. // normalize B, N. T can be ignored, we don't use it
  20945. B.normalize();
  20946. N.normalize();
  20947. for ( let j = 0; j <= radialSegments; ++ j ) {
  20948. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20949. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20950. const v = j / radialSegments * Math.PI * 2;
  20951. const cx = - tube * Math.cos( v );
  20952. const cy = tube * Math.sin( v );
  20953. // now calculate the final vertex position.
  20954. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20955. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20956. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20957. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20958. vertices.push( vertex.x, vertex.y, vertex.z );
  20959. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20960. normal.subVectors( vertex, P1 ).normalize();
  20961. normals.push( normal.x, normal.y, normal.z );
  20962. // uv
  20963. uvs.push( i / tubularSegments );
  20964. uvs.push( j / radialSegments );
  20965. }
  20966. }
  20967. // generate indices
  20968. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20969. for ( let i = 1; i <= radialSegments; i ++ ) {
  20970. // indices
  20971. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20972. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20973. const c = ( radialSegments + 1 ) * j + i;
  20974. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20975. // faces
  20976. indices.push( a, b, d );
  20977. indices.push( b, c, d );
  20978. }
  20979. }
  20980. // build geometry
  20981. this.setIndex( indices );
  20982. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20983. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20984. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20985. // this function calculates the current position on the torus curve
  20986. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20987. const cu = Math.cos( u );
  20988. const su = Math.sin( u );
  20989. const quOverP = q / p * u;
  20990. const cs = Math.cos( quOverP );
  20991. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20992. position.y = radius * ( 2 + cs ) * su * 0.5;
  20993. position.z = radius * Math.sin( quOverP ) * 0.5;
  20994. }
  20995. }
  20996. static fromJSON( data ) {
  20997. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  20998. }
  20999. }
  21000. class TubeGeometry extends BufferGeometry {
  21001. 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 ) {
  21002. super();
  21003. this.type = 'TubeGeometry';
  21004. this.parameters = {
  21005. path: path,
  21006. tubularSegments: tubularSegments,
  21007. radius: radius,
  21008. radialSegments: radialSegments,
  21009. closed: closed
  21010. };
  21011. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21012. // expose internals
  21013. this.tangents = frames.tangents;
  21014. this.normals = frames.normals;
  21015. this.binormals = frames.binormals;
  21016. // helper variables
  21017. const vertex = new Vector3();
  21018. const normal = new Vector3();
  21019. const uv = new Vector2();
  21020. let P = new Vector3();
  21021. // buffer
  21022. const vertices = [];
  21023. const normals = [];
  21024. const uvs = [];
  21025. const indices = [];
  21026. // create buffer data
  21027. generateBufferData();
  21028. // build geometry
  21029. this.setIndex( indices );
  21030. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21031. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21032. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21033. // functions
  21034. function generateBufferData() {
  21035. for ( let i = 0; i < tubularSegments; i ++ ) {
  21036. generateSegment( i );
  21037. }
  21038. // if the geometry is not closed, generate the last row of vertices and normals
  21039. // at the regular position on the given path
  21040. //
  21041. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21042. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21043. // uvs are generated in a separate function.
  21044. // this makes it easy compute correct values for closed geometries
  21045. generateUVs();
  21046. // finally create faces
  21047. generateIndices();
  21048. }
  21049. function generateSegment( i ) {
  21050. // we use getPointAt to sample evenly distributed points from the given path
  21051. P = path.getPointAt( i / tubularSegments, P );
  21052. // retrieve corresponding normal and binormal
  21053. const N = frames.normals[ i ];
  21054. const B = frames.binormals[ i ];
  21055. // generate normals and vertices for the current segment
  21056. for ( let j = 0; j <= radialSegments; j ++ ) {
  21057. const v = j / radialSegments * Math.PI * 2;
  21058. const sin = Math.sin( v );
  21059. const cos = - Math.cos( v );
  21060. // normal
  21061. normal.x = ( cos * N.x + sin * B.x );
  21062. normal.y = ( cos * N.y + sin * B.y );
  21063. normal.z = ( cos * N.z + sin * B.z );
  21064. normal.normalize();
  21065. normals.push( normal.x, normal.y, normal.z );
  21066. // vertex
  21067. vertex.x = P.x + radius * normal.x;
  21068. vertex.y = P.y + radius * normal.y;
  21069. vertex.z = P.z + radius * normal.z;
  21070. vertices.push( vertex.x, vertex.y, vertex.z );
  21071. }
  21072. }
  21073. function generateIndices() {
  21074. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21075. for ( let i = 1; i <= radialSegments; i ++ ) {
  21076. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21077. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21078. const c = ( radialSegments + 1 ) * j + i;
  21079. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21080. // faces
  21081. indices.push( a, b, d );
  21082. indices.push( b, c, d );
  21083. }
  21084. }
  21085. }
  21086. function generateUVs() {
  21087. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21088. for ( let j = 0; j <= radialSegments; j ++ ) {
  21089. uv.x = i / tubularSegments;
  21090. uv.y = j / radialSegments;
  21091. uvs.push( uv.x, uv.y );
  21092. }
  21093. }
  21094. }
  21095. }
  21096. toJSON() {
  21097. const data = super.toJSON();
  21098. data.path = this.parameters.path.toJSON();
  21099. return data;
  21100. }
  21101. static fromJSON( data ) {
  21102. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21103. // User defined curves or instances of CurvePath will not be deserialized.
  21104. return new TubeGeometry(
  21105. new Curves[ data.path.type ]().fromJSON( data.path ),
  21106. data.tubularSegments,
  21107. data.radius,
  21108. data.radialSegments,
  21109. data.closed
  21110. );
  21111. }
  21112. }
  21113. class WireframeGeometry extends BufferGeometry {
  21114. constructor( geometry = null ) {
  21115. super();
  21116. this.type = 'WireframeGeometry';
  21117. this.parameters = {
  21118. geometry: geometry
  21119. };
  21120. if ( geometry !== null ) {
  21121. // buffer
  21122. const vertices = [];
  21123. const edges = new Set();
  21124. // helper variables
  21125. const start = new Vector3();
  21126. const end = new Vector3();
  21127. if ( geometry.index !== null ) {
  21128. // indexed BufferGeometry
  21129. const position = geometry.attributes.position;
  21130. const indices = geometry.index;
  21131. let groups = geometry.groups;
  21132. if ( groups.length === 0 ) {
  21133. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  21134. }
  21135. // create a data structure that contains all eges without duplicates
  21136. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21137. const group = groups[ o ];
  21138. const groupStart = group.start;
  21139. const groupCount = group.count;
  21140. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21141. for ( let j = 0; j < 3; j ++ ) {
  21142. const index1 = indices.getX( i + j );
  21143. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21144. start.fromBufferAttribute( position, index1 );
  21145. end.fromBufferAttribute( position, index2 );
  21146. if ( isUniqueEdge( start, end, edges ) === true ) {
  21147. vertices.push( start.x, start.y, start.z );
  21148. vertices.push( end.x, end.y, end.z );
  21149. }
  21150. }
  21151. }
  21152. }
  21153. } else {
  21154. // non-indexed BufferGeometry
  21155. const position = geometry.attributes.position;
  21156. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21157. for ( let j = 0; j < 3; j ++ ) {
  21158. // three edges per triangle, an edge is represented as (index1, index2)
  21159. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21160. const index1 = 3 * i + j;
  21161. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21162. start.fromBufferAttribute( position, index1 );
  21163. end.fromBufferAttribute( position, index2 );
  21164. if ( isUniqueEdge( start, end, edges ) === true ) {
  21165. vertices.push( start.x, start.y, start.z );
  21166. vertices.push( end.x, end.y, end.z );
  21167. }
  21168. }
  21169. }
  21170. }
  21171. // build geometry
  21172. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21173. }
  21174. }
  21175. }
  21176. function isUniqueEdge( start, end, edges ) {
  21177. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21178. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21179. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21180. return false;
  21181. } else {
  21182. edges.add( hash1, hash2 );
  21183. return true;
  21184. }
  21185. }
  21186. var Geometries = /*#__PURE__*/Object.freeze({
  21187. __proto__: null,
  21188. BoxGeometry: BoxGeometry,
  21189. BoxBufferGeometry: BoxGeometry,
  21190. CircleGeometry: CircleGeometry,
  21191. CircleBufferGeometry: CircleGeometry,
  21192. ConeGeometry: ConeGeometry,
  21193. ConeBufferGeometry: ConeGeometry,
  21194. CylinderGeometry: CylinderGeometry,
  21195. CylinderBufferGeometry: CylinderGeometry,
  21196. DodecahedronGeometry: DodecahedronGeometry,
  21197. DodecahedronBufferGeometry: DodecahedronGeometry,
  21198. EdgesGeometry: EdgesGeometry,
  21199. ExtrudeGeometry: ExtrudeGeometry,
  21200. ExtrudeBufferGeometry: ExtrudeGeometry,
  21201. IcosahedronGeometry: IcosahedronGeometry,
  21202. IcosahedronBufferGeometry: IcosahedronGeometry,
  21203. LatheGeometry: LatheGeometry,
  21204. LatheBufferGeometry: LatheGeometry,
  21205. OctahedronGeometry: OctahedronGeometry,
  21206. OctahedronBufferGeometry: OctahedronGeometry,
  21207. PlaneGeometry: PlaneGeometry,
  21208. PlaneBufferGeometry: PlaneGeometry,
  21209. PolyhedronGeometry: PolyhedronGeometry,
  21210. PolyhedronBufferGeometry: PolyhedronGeometry,
  21211. RingGeometry: RingGeometry,
  21212. RingBufferGeometry: RingGeometry,
  21213. ShapeGeometry: ShapeGeometry,
  21214. ShapeBufferGeometry: ShapeGeometry,
  21215. SphereGeometry: SphereGeometry,
  21216. SphereBufferGeometry: SphereGeometry,
  21217. TetrahedronGeometry: TetrahedronGeometry,
  21218. TetrahedronBufferGeometry: TetrahedronGeometry,
  21219. TorusGeometry: TorusGeometry,
  21220. TorusBufferGeometry: TorusGeometry,
  21221. TorusKnotGeometry: TorusKnotGeometry,
  21222. TorusKnotBufferGeometry: TorusKnotGeometry,
  21223. TubeGeometry: TubeGeometry,
  21224. TubeBufferGeometry: TubeGeometry,
  21225. WireframeGeometry: WireframeGeometry
  21226. });
  21227. /**
  21228. * parameters = {
  21229. * color: <THREE.Color>
  21230. * }
  21231. */
  21232. class ShadowMaterial extends Material {
  21233. constructor( parameters ) {
  21234. super();
  21235. this.type = 'ShadowMaterial';
  21236. this.color = new Color( 0x000000 );
  21237. this.transparent = true;
  21238. this.setValues( parameters );
  21239. }
  21240. copy( source ) {
  21241. super.copy( source );
  21242. this.color.copy( source.color );
  21243. return this;
  21244. }
  21245. }
  21246. ShadowMaterial.prototype.isShadowMaterial = true;
  21247. /**
  21248. * parameters = {
  21249. * color: <hex>,
  21250. * roughness: <float>,
  21251. * metalness: <float>,
  21252. * opacity: <float>,
  21253. *
  21254. * map: new THREE.Texture( <Image> ),
  21255. *
  21256. * lightMap: new THREE.Texture( <Image> ),
  21257. * lightMapIntensity: <float>
  21258. *
  21259. * aoMap: new THREE.Texture( <Image> ),
  21260. * aoMapIntensity: <float>
  21261. *
  21262. * emissive: <hex>,
  21263. * emissiveIntensity: <float>
  21264. * emissiveMap: new THREE.Texture( <Image> ),
  21265. *
  21266. * bumpMap: new THREE.Texture( <Image> ),
  21267. * bumpScale: <float>,
  21268. *
  21269. * normalMap: new THREE.Texture( <Image> ),
  21270. * normalMapType: THREE.TangentSpaceNormalMap,
  21271. * normalScale: <Vector2>,
  21272. *
  21273. * displacementMap: new THREE.Texture( <Image> ),
  21274. * displacementScale: <float>,
  21275. * displacementBias: <float>,
  21276. *
  21277. * roughnessMap: new THREE.Texture( <Image> ),
  21278. *
  21279. * metalnessMap: new THREE.Texture( <Image> ),
  21280. *
  21281. * alphaMap: new THREE.Texture( <Image> ),
  21282. *
  21283. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21284. * envMapIntensity: <float>
  21285. *
  21286. * refractionRatio: <float>,
  21287. *
  21288. * wireframe: <boolean>,
  21289. * wireframeLinewidth: <float>,
  21290. *
  21291. * flatShading: <bool>
  21292. * }
  21293. */
  21294. class MeshStandardMaterial extends Material {
  21295. constructor( parameters ) {
  21296. super();
  21297. this.defines = { 'STANDARD': '' };
  21298. this.type = 'MeshStandardMaterial';
  21299. this.color = new Color( 0xffffff ); // diffuse
  21300. this.roughness = 1.0;
  21301. this.metalness = 0.0;
  21302. this.map = null;
  21303. this.lightMap = null;
  21304. this.lightMapIntensity = 1.0;
  21305. this.aoMap = null;
  21306. this.aoMapIntensity = 1.0;
  21307. this.emissive = new Color( 0x000000 );
  21308. this.emissiveIntensity = 1.0;
  21309. this.emissiveMap = null;
  21310. this.bumpMap = null;
  21311. this.bumpScale = 1;
  21312. this.normalMap = null;
  21313. this.normalMapType = TangentSpaceNormalMap;
  21314. this.normalScale = new Vector2( 1, 1 );
  21315. this.displacementMap = null;
  21316. this.displacementScale = 1;
  21317. this.displacementBias = 0;
  21318. this.roughnessMap = null;
  21319. this.metalnessMap = null;
  21320. this.alphaMap = null;
  21321. this.envMap = null;
  21322. this.envMapIntensity = 1.0;
  21323. this.refractionRatio = 0.98;
  21324. this.wireframe = false;
  21325. this.wireframeLinewidth = 1;
  21326. this.wireframeLinecap = 'round';
  21327. this.wireframeLinejoin = 'round';
  21328. this.flatShading = false;
  21329. this.setValues( parameters );
  21330. }
  21331. copy( source ) {
  21332. super.copy( source );
  21333. this.defines = { 'STANDARD': '' };
  21334. this.color.copy( source.color );
  21335. this.roughness = source.roughness;
  21336. this.metalness = source.metalness;
  21337. this.map = source.map;
  21338. this.lightMap = source.lightMap;
  21339. this.lightMapIntensity = source.lightMapIntensity;
  21340. this.aoMap = source.aoMap;
  21341. this.aoMapIntensity = source.aoMapIntensity;
  21342. this.emissive.copy( source.emissive );
  21343. this.emissiveMap = source.emissiveMap;
  21344. this.emissiveIntensity = source.emissiveIntensity;
  21345. this.bumpMap = source.bumpMap;
  21346. this.bumpScale = source.bumpScale;
  21347. this.normalMap = source.normalMap;
  21348. this.normalMapType = source.normalMapType;
  21349. this.normalScale.copy( source.normalScale );
  21350. this.displacementMap = source.displacementMap;
  21351. this.displacementScale = source.displacementScale;
  21352. this.displacementBias = source.displacementBias;
  21353. this.roughnessMap = source.roughnessMap;
  21354. this.metalnessMap = source.metalnessMap;
  21355. this.alphaMap = source.alphaMap;
  21356. this.envMap = source.envMap;
  21357. this.envMapIntensity = source.envMapIntensity;
  21358. this.refractionRatio = source.refractionRatio;
  21359. this.wireframe = source.wireframe;
  21360. this.wireframeLinewidth = source.wireframeLinewidth;
  21361. this.wireframeLinecap = source.wireframeLinecap;
  21362. this.wireframeLinejoin = source.wireframeLinejoin;
  21363. this.flatShading = source.flatShading;
  21364. return this;
  21365. }
  21366. }
  21367. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21368. /**
  21369. * parameters = {
  21370. * clearcoat: <float>,
  21371. * clearcoatMap: new THREE.Texture( <Image> ),
  21372. * clearcoatRoughness: <float>,
  21373. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  21374. * clearcoatNormalScale: <Vector2>,
  21375. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  21376. *
  21377. * ior: <float>,
  21378. * reflectivity: <float>,
  21379. *
  21380. * sheen: <float>,
  21381. * sheenColor: <Color>,
  21382. * sheenColorMap: new THREE.Texture( <Image> ),
  21383. * sheenRoughness: <float>,
  21384. * sheenRoughnessMap: new THREE.Texture( <Image> ),
  21385. *
  21386. * transmission: <float>,
  21387. * transmissionMap: new THREE.Texture( <Image> ),
  21388. *
  21389. * thickness: <float>,
  21390. * thicknessMap: new THREE.Texture( <Image> ),
  21391. * attenuationDistance: <float>,
  21392. * attenuationColor: <Color>,
  21393. *
  21394. * specularIntensity: <float>,
  21395. * specularIntensityMap: new THREE.Texture( <Image> ),
  21396. * specularColor: <Color>,
  21397. * specularColorMap: new THREE.Texture( <Image> )
  21398. * }
  21399. */
  21400. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21401. constructor( parameters ) {
  21402. super();
  21403. this.defines = {
  21404. 'STANDARD': '',
  21405. 'PHYSICAL': ''
  21406. };
  21407. this.type = 'MeshPhysicalMaterial';
  21408. this.clearcoatMap = null;
  21409. this.clearcoatRoughness = 0.0;
  21410. this.clearcoatRoughnessMap = null;
  21411. this.clearcoatNormalScale = new Vector2( 1, 1 );
  21412. this.clearcoatNormalMap = null;
  21413. this.ior = 1.5;
  21414. Object.defineProperty( this, 'reflectivity', {
  21415. get: function () {
  21416. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  21417. },
  21418. set: function ( reflectivity ) {
  21419. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  21420. }
  21421. } );
  21422. this.sheenColor = new Color( 0x000000 );
  21423. this.sheenColorMap = null;
  21424. this.sheenRoughness = 1.0;
  21425. this.sheenRoughnessMap = null;
  21426. this.transmissionMap = null;
  21427. this.thickness = 0;
  21428. this.thicknessMap = null;
  21429. this.attenuationDistance = 0.0;
  21430. this.attenuationColor = new Color( 1, 1, 1 );
  21431. this.specularIntensity = 1.0;
  21432. this.specularIntensityMap = null;
  21433. this.specularColor = new Color( 1, 1, 1 );
  21434. this.specularColorMap = null;
  21435. this._sheen = 0.0;
  21436. this._clearcoat = 0;
  21437. this._transmission = 0;
  21438. this.setValues( parameters );
  21439. }
  21440. get sheen() {
  21441. return this._sheen;
  21442. }
  21443. set sheen( value ) {
  21444. if ( this._sheen > 0 !== value > 0 ) {
  21445. this.version ++;
  21446. }
  21447. this._sheen = value;
  21448. }
  21449. get clearcoat() {
  21450. return this._clearcoat;
  21451. }
  21452. set clearcoat( value ) {
  21453. if ( this._clearcoat > 0 !== value > 0 ) {
  21454. this.version ++;
  21455. }
  21456. this._clearcoat = value;
  21457. }
  21458. get transmission() {
  21459. return this._transmission;
  21460. }
  21461. set transmission( value ) {
  21462. if ( this._transmission > 0 !== value > 0 ) {
  21463. this.version ++;
  21464. }
  21465. this._transmission = value;
  21466. }
  21467. copy( source ) {
  21468. super.copy( source );
  21469. this.defines = {
  21470. 'STANDARD': '',
  21471. 'PHYSICAL': ''
  21472. };
  21473. this.clearcoat = source.clearcoat;
  21474. this.clearcoatMap = source.clearcoatMap;
  21475. this.clearcoatRoughness = source.clearcoatRoughness;
  21476. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21477. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21478. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21479. this.ior = source.ior;
  21480. this.sheen = source.sheen;
  21481. this.sheenColor.copy( source.sheenColor );
  21482. this.sheenColorMap = source.sheenColorMap;
  21483. this.sheenRoughness = source.sheenRoughness;
  21484. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21485. this.transmission = source.transmission;
  21486. this.transmissionMap = source.transmissionMap;
  21487. this.thickness = source.thickness;
  21488. this.thicknessMap = source.thicknessMap;
  21489. this.attenuationDistance = source.attenuationDistance;
  21490. this.attenuationColor.copy( source.attenuationColor );
  21491. this.specularIntensity = source.specularIntensity;
  21492. this.specularIntensityMap = source.specularIntensityMap;
  21493. this.specularColor.copy( source.specularColor );
  21494. this.specularColorMap = source.specularColorMap;
  21495. return this;
  21496. }
  21497. }
  21498. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21499. /**
  21500. * parameters = {
  21501. * color: <hex>,
  21502. * specular: <hex>,
  21503. * shininess: <float>,
  21504. * opacity: <float>,
  21505. *
  21506. * map: new THREE.Texture( <Image> ),
  21507. *
  21508. * lightMap: new THREE.Texture( <Image> ),
  21509. * lightMapIntensity: <float>
  21510. *
  21511. * aoMap: new THREE.Texture( <Image> ),
  21512. * aoMapIntensity: <float>
  21513. *
  21514. * emissive: <hex>,
  21515. * emissiveIntensity: <float>
  21516. * emissiveMap: new THREE.Texture( <Image> ),
  21517. *
  21518. * bumpMap: new THREE.Texture( <Image> ),
  21519. * bumpScale: <float>,
  21520. *
  21521. * normalMap: new THREE.Texture( <Image> ),
  21522. * normalMapType: THREE.TangentSpaceNormalMap,
  21523. * normalScale: <Vector2>,
  21524. *
  21525. * displacementMap: new THREE.Texture( <Image> ),
  21526. * displacementScale: <float>,
  21527. * displacementBias: <float>,
  21528. *
  21529. * specularMap: new THREE.Texture( <Image> ),
  21530. *
  21531. * alphaMap: new THREE.Texture( <Image> ),
  21532. *
  21533. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21534. * combine: THREE.MultiplyOperation,
  21535. * reflectivity: <float>,
  21536. * refractionRatio: <float>,
  21537. *
  21538. * wireframe: <boolean>,
  21539. * wireframeLinewidth: <float>,
  21540. *
  21541. * flatShading: <bool>
  21542. * }
  21543. */
  21544. class MeshPhongMaterial extends Material {
  21545. constructor( parameters ) {
  21546. super();
  21547. this.type = 'MeshPhongMaterial';
  21548. this.color = new Color( 0xffffff ); // diffuse
  21549. this.specular = new Color( 0x111111 );
  21550. this.shininess = 30;
  21551. this.map = null;
  21552. this.lightMap = null;
  21553. this.lightMapIntensity = 1.0;
  21554. this.aoMap = null;
  21555. this.aoMapIntensity = 1.0;
  21556. this.emissive = new Color( 0x000000 );
  21557. this.emissiveIntensity = 1.0;
  21558. this.emissiveMap = null;
  21559. this.bumpMap = null;
  21560. this.bumpScale = 1;
  21561. this.normalMap = null;
  21562. this.normalMapType = TangentSpaceNormalMap;
  21563. this.normalScale = new Vector2( 1, 1 );
  21564. this.displacementMap = null;
  21565. this.displacementScale = 1;
  21566. this.displacementBias = 0;
  21567. this.specularMap = null;
  21568. this.alphaMap = null;
  21569. this.envMap = null;
  21570. this.combine = MultiplyOperation;
  21571. this.reflectivity = 1;
  21572. this.refractionRatio = 0.98;
  21573. this.wireframe = false;
  21574. this.wireframeLinewidth = 1;
  21575. this.wireframeLinecap = 'round';
  21576. this.wireframeLinejoin = 'round';
  21577. this.flatShading = false;
  21578. this.setValues( parameters );
  21579. }
  21580. copy( source ) {
  21581. super.copy( source );
  21582. this.color.copy( source.color );
  21583. this.specular.copy( source.specular );
  21584. this.shininess = source.shininess;
  21585. this.map = source.map;
  21586. this.lightMap = source.lightMap;
  21587. this.lightMapIntensity = source.lightMapIntensity;
  21588. this.aoMap = source.aoMap;
  21589. this.aoMapIntensity = source.aoMapIntensity;
  21590. this.emissive.copy( source.emissive );
  21591. this.emissiveMap = source.emissiveMap;
  21592. this.emissiveIntensity = source.emissiveIntensity;
  21593. this.bumpMap = source.bumpMap;
  21594. this.bumpScale = source.bumpScale;
  21595. this.normalMap = source.normalMap;
  21596. this.normalMapType = source.normalMapType;
  21597. this.normalScale.copy( source.normalScale );
  21598. this.displacementMap = source.displacementMap;
  21599. this.displacementScale = source.displacementScale;
  21600. this.displacementBias = source.displacementBias;
  21601. this.specularMap = source.specularMap;
  21602. this.alphaMap = source.alphaMap;
  21603. this.envMap = source.envMap;
  21604. this.combine = source.combine;
  21605. this.reflectivity = source.reflectivity;
  21606. this.refractionRatio = source.refractionRatio;
  21607. this.wireframe = source.wireframe;
  21608. this.wireframeLinewidth = source.wireframeLinewidth;
  21609. this.wireframeLinecap = source.wireframeLinecap;
  21610. this.wireframeLinejoin = source.wireframeLinejoin;
  21611. this.flatShading = source.flatShading;
  21612. return this;
  21613. }
  21614. }
  21615. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21616. /**
  21617. * parameters = {
  21618. * color: <hex>,
  21619. *
  21620. * map: new THREE.Texture( <Image> ),
  21621. * gradientMap: new THREE.Texture( <Image> ),
  21622. *
  21623. * lightMap: new THREE.Texture( <Image> ),
  21624. * lightMapIntensity: <float>
  21625. *
  21626. * aoMap: new THREE.Texture( <Image> ),
  21627. * aoMapIntensity: <float>
  21628. *
  21629. * emissive: <hex>,
  21630. * emissiveIntensity: <float>
  21631. * emissiveMap: new THREE.Texture( <Image> ),
  21632. *
  21633. * bumpMap: new THREE.Texture( <Image> ),
  21634. * bumpScale: <float>,
  21635. *
  21636. * normalMap: new THREE.Texture( <Image> ),
  21637. * normalMapType: THREE.TangentSpaceNormalMap,
  21638. * normalScale: <Vector2>,
  21639. *
  21640. * displacementMap: new THREE.Texture( <Image> ),
  21641. * displacementScale: <float>,
  21642. * displacementBias: <float>,
  21643. *
  21644. * alphaMap: new THREE.Texture( <Image> ),
  21645. *
  21646. * wireframe: <boolean>,
  21647. * wireframeLinewidth: <float>,
  21648. *
  21649. * }
  21650. */
  21651. class MeshToonMaterial extends Material {
  21652. constructor( parameters ) {
  21653. super();
  21654. this.defines = { 'TOON': '' };
  21655. this.type = 'MeshToonMaterial';
  21656. this.color = new Color( 0xffffff );
  21657. this.map = null;
  21658. this.gradientMap = null;
  21659. this.lightMap = null;
  21660. this.lightMapIntensity = 1.0;
  21661. this.aoMap = null;
  21662. this.aoMapIntensity = 1.0;
  21663. this.emissive = new Color( 0x000000 );
  21664. this.emissiveIntensity = 1.0;
  21665. this.emissiveMap = null;
  21666. this.bumpMap = null;
  21667. this.bumpScale = 1;
  21668. this.normalMap = null;
  21669. this.normalMapType = TangentSpaceNormalMap;
  21670. this.normalScale = new Vector2( 1, 1 );
  21671. this.displacementMap = null;
  21672. this.displacementScale = 1;
  21673. this.displacementBias = 0;
  21674. this.alphaMap = null;
  21675. this.wireframe = false;
  21676. this.wireframeLinewidth = 1;
  21677. this.wireframeLinecap = 'round';
  21678. this.wireframeLinejoin = 'round';
  21679. this.setValues( parameters );
  21680. }
  21681. copy( source ) {
  21682. super.copy( source );
  21683. this.color.copy( source.color );
  21684. this.map = source.map;
  21685. this.gradientMap = source.gradientMap;
  21686. this.lightMap = source.lightMap;
  21687. this.lightMapIntensity = source.lightMapIntensity;
  21688. this.aoMap = source.aoMap;
  21689. this.aoMapIntensity = source.aoMapIntensity;
  21690. this.emissive.copy( source.emissive );
  21691. this.emissiveMap = source.emissiveMap;
  21692. this.emissiveIntensity = source.emissiveIntensity;
  21693. this.bumpMap = source.bumpMap;
  21694. this.bumpScale = source.bumpScale;
  21695. this.normalMap = source.normalMap;
  21696. this.normalMapType = source.normalMapType;
  21697. this.normalScale.copy( source.normalScale );
  21698. this.displacementMap = source.displacementMap;
  21699. this.displacementScale = source.displacementScale;
  21700. this.displacementBias = source.displacementBias;
  21701. this.alphaMap = source.alphaMap;
  21702. this.wireframe = source.wireframe;
  21703. this.wireframeLinewidth = source.wireframeLinewidth;
  21704. this.wireframeLinecap = source.wireframeLinecap;
  21705. this.wireframeLinejoin = source.wireframeLinejoin;
  21706. return this;
  21707. }
  21708. }
  21709. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21710. /**
  21711. * parameters = {
  21712. * opacity: <float>,
  21713. *
  21714. * bumpMap: new THREE.Texture( <Image> ),
  21715. * bumpScale: <float>,
  21716. *
  21717. * normalMap: new THREE.Texture( <Image> ),
  21718. * normalMapType: THREE.TangentSpaceNormalMap,
  21719. * normalScale: <Vector2>,
  21720. *
  21721. * displacementMap: new THREE.Texture( <Image> ),
  21722. * displacementScale: <float>,
  21723. * displacementBias: <float>,
  21724. *
  21725. * wireframe: <boolean>,
  21726. * wireframeLinewidth: <float>
  21727. *
  21728. * flatShading: <bool>
  21729. * }
  21730. */
  21731. class MeshNormalMaterial extends Material {
  21732. constructor( parameters ) {
  21733. super();
  21734. this.type = 'MeshNormalMaterial';
  21735. this.bumpMap = null;
  21736. this.bumpScale = 1;
  21737. this.normalMap = null;
  21738. this.normalMapType = TangentSpaceNormalMap;
  21739. this.normalScale = new Vector2( 1, 1 );
  21740. this.displacementMap = null;
  21741. this.displacementScale = 1;
  21742. this.displacementBias = 0;
  21743. this.wireframe = false;
  21744. this.wireframeLinewidth = 1;
  21745. this.fog = false;
  21746. this.flatShading = false;
  21747. this.setValues( parameters );
  21748. }
  21749. copy( source ) {
  21750. super.copy( source );
  21751. this.bumpMap = source.bumpMap;
  21752. this.bumpScale = source.bumpScale;
  21753. this.normalMap = source.normalMap;
  21754. this.normalMapType = source.normalMapType;
  21755. this.normalScale.copy( source.normalScale );
  21756. this.displacementMap = source.displacementMap;
  21757. this.displacementScale = source.displacementScale;
  21758. this.displacementBias = source.displacementBias;
  21759. this.wireframe = source.wireframe;
  21760. this.wireframeLinewidth = source.wireframeLinewidth;
  21761. this.flatShading = source.flatShading;
  21762. return this;
  21763. }
  21764. }
  21765. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21766. /**
  21767. * parameters = {
  21768. * color: <hex>,
  21769. * opacity: <float>,
  21770. *
  21771. * map: new THREE.Texture( <Image> ),
  21772. *
  21773. * lightMap: new THREE.Texture( <Image> ),
  21774. * lightMapIntensity: <float>
  21775. *
  21776. * aoMap: new THREE.Texture( <Image> ),
  21777. * aoMapIntensity: <float>
  21778. *
  21779. * emissive: <hex>,
  21780. * emissiveIntensity: <float>
  21781. * emissiveMap: new THREE.Texture( <Image> ),
  21782. *
  21783. * specularMap: new THREE.Texture( <Image> ),
  21784. *
  21785. * alphaMap: new THREE.Texture( <Image> ),
  21786. *
  21787. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21788. * combine: THREE.Multiply,
  21789. * reflectivity: <float>,
  21790. * refractionRatio: <float>,
  21791. *
  21792. * wireframe: <boolean>,
  21793. * wireframeLinewidth: <float>,
  21794. *
  21795. * }
  21796. */
  21797. class MeshLambertMaterial extends Material {
  21798. constructor( parameters ) {
  21799. super();
  21800. this.type = 'MeshLambertMaterial';
  21801. this.color = new Color( 0xffffff ); // diffuse
  21802. this.map = null;
  21803. this.lightMap = null;
  21804. this.lightMapIntensity = 1.0;
  21805. this.aoMap = null;
  21806. this.aoMapIntensity = 1.0;
  21807. this.emissive = new Color( 0x000000 );
  21808. this.emissiveIntensity = 1.0;
  21809. this.emissiveMap = null;
  21810. this.specularMap = null;
  21811. this.alphaMap = null;
  21812. this.envMap = null;
  21813. this.combine = MultiplyOperation;
  21814. this.reflectivity = 1;
  21815. this.refractionRatio = 0.98;
  21816. this.wireframe = false;
  21817. this.wireframeLinewidth = 1;
  21818. this.wireframeLinecap = 'round';
  21819. this.wireframeLinejoin = 'round';
  21820. this.setValues( parameters );
  21821. }
  21822. copy( source ) {
  21823. super.copy( source );
  21824. this.color.copy( source.color );
  21825. this.map = source.map;
  21826. this.lightMap = source.lightMap;
  21827. this.lightMapIntensity = source.lightMapIntensity;
  21828. this.aoMap = source.aoMap;
  21829. this.aoMapIntensity = source.aoMapIntensity;
  21830. this.emissive.copy( source.emissive );
  21831. this.emissiveMap = source.emissiveMap;
  21832. this.emissiveIntensity = source.emissiveIntensity;
  21833. this.specularMap = source.specularMap;
  21834. this.alphaMap = source.alphaMap;
  21835. this.envMap = source.envMap;
  21836. this.combine = source.combine;
  21837. this.reflectivity = source.reflectivity;
  21838. this.refractionRatio = source.refractionRatio;
  21839. this.wireframe = source.wireframe;
  21840. this.wireframeLinewidth = source.wireframeLinewidth;
  21841. this.wireframeLinecap = source.wireframeLinecap;
  21842. this.wireframeLinejoin = source.wireframeLinejoin;
  21843. return this;
  21844. }
  21845. }
  21846. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21847. /**
  21848. * parameters = {
  21849. * color: <hex>,
  21850. * opacity: <float>,
  21851. *
  21852. * matcap: new THREE.Texture( <Image> ),
  21853. *
  21854. * map: new THREE.Texture( <Image> ),
  21855. *
  21856. * bumpMap: new THREE.Texture( <Image> ),
  21857. * bumpScale: <float>,
  21858. *
  21859. * normalMap: new THREE.Texture( <Image> ),
  21860. * normalMapType: THREE.TangentSpaceNormalMap,
  21861. * normalScale: <Vector2>,
  21862. *
  21863. * displacementMap: new THREE.Texture( <Image> ),
  21864. * displacementScale: <float>,
  21865. * displacementBias: <float>,
  21866. *
  21867. * alphaMap: new THREE.Texture( <Image> ),
  21868. *
  21869. * flatShading: <bool>
  21870. * }
  21871. */
  21872. class MeshMatcapMaterial extends Material {
  21873. constructor( parameters ) {
  21874. super();
  21875. this.defines = { 'MATCAP': '' };
  21876. this.type = 'MeshMatcapMaterial';
  21877. this.color = new Color( 0xffffff ); // diffuse
  21878. this.matcap = null;
  21879. this.map = null;
  21880. this.bumpMap = null;
  21881. this.bumpScale = 1;
  21882. this.normalMap = null;
  21883. this.normalMapType = TangentSpaceNormalMap;
  21884. this.normalScale = new Vector2( 1, 1 );
  21885. this.displacementMap = null;
  21886. this.displacementScale = 1;
  21887. this.displacementBias = 0;
  21888. this.alphaMap = null;
  21889. this.flatShading = false;
  21890. this.setValues( parameters );
  21891. }
  21892. copy( source ) {
  21893. super.copy( source );
  21894. this.defines = { 'MATCAP': '' };
  21895. this.color.copy( source.color );
  21896. this.matcap = source.matcap;
  21897. this.map = source.map;
  21898. this.bumpMap = source.bumpMap;
  21899. this.bumpScale = source.bumpScale;
  21900. this.normalMap = source.normalMap;
  21901. this.normalMapType = source.normalMapType;
  21902. this.normalScale.copy( source.normalScale );
  21903. this.displacementMap = source.displacementMap;
  21904. this.displacementScale = source.displacementScale;
  21905. this.displacementBias = source.displacementBias;
  21906. this.alphaMap = source.alphaMap;
  21907. this.flatShading = source.flatShading;
  21908. return this;
  21909. }
  21910. }
  21911. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21912. /**
  21913. * parameters = {
  21914. * color: <hex>,
  21915. * opacity: <float>,
  21916. *
  21917. * linewidth: <float>,
  21918. *
  21919. * scale: <float>,
  21920. * dashSize: <float>,
  21921. * gapSize: <float>
  21922. * }
  21923. */
  21924. class LineDashedMaterial extends LineBasicMaterial {
  21925. constructor( parameters ) {
  21926. super();
  21927. this.type = 'LineDashedMaterial';
  21928. this.scale = 1;
  21929. this.dashSize = 3;
  21930. this.gapSize = 1;
  21931. this.setValues( parameters );
  21932. }
  21933. copy( source ) {
  21934. super.copy( source );
  21935. this.scale = source.scale;
  21936. this.dashSize = source.dashSize;
  21937. this.gapSize = source.gapSize;
  21938. return this;
  21939. }
  21940. }
  21941. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21942. var Materials = /*#__PURE__*/Object.freeze({
  21943. __proto__: null,
  21944. ShadowMaterial: ShadowMaterial,
  21945. SpriteMaterial: SpriteMaterial,
  21946. RawShaderMaterial: RawShaderMaterial,
  21947. ShaderMaterial: ShaderMaterial,
  21948. PointsMaterial: PointsMaterial,
  21949. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21950. MeshStandardMaterial: MeshStandardMaterial,
  21951. MeshPhongMaterial: MeshPhongMaterial,
  21952. MeshToonMaterial: MeshToonMaterial,
  21953. MeshNormalMaterial: MeshNormalMaterial,
  21954. MeshLambertMaterial: MeshLambertMaterial,
  21955. MeshDepthMaterial: MeshDepthMaterial,
  21956. MeshDistanceMaterial: MeshDistanceMaterial,
  21957. MeshBasicMaterial: MeshBasicMaterial,
  21958. MeshMatcapMaterial: MeshMatcapMaterial,
  21959. LineDashedMaterial: LineDashedMaterial,
  21960. LineBasicMaterial: LineBasicMaterial,
  21961. Material: Material
  21962. });
  21963. const AnimationUtils = {
  21964. // same as Array.prototype.slice, but also works on typed arrays
  21965. arraySlice: function ( array, from, to ) {
  21966. if ( AnimationUtils.isTypedArray( array ) ) {
  21967. // in ios9 array.subarray(from, undefined) will return empty array
  21968. // but array.subarray(from) or array.subarray(from, len) is correct
  21969. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  21970. }
  21971. return array.slice( from, to );
  21972. },
  21973. // converts an array to a specific type
  21974. convertArray: function ( array, type, forceClone ) {
  21975. if ( ! array || // let 'undefined' and 'null' pass
  21976. ! forceClone && array.constructor === type ) return array;
  21977. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21978. return new type( array ); // create typed array
  21979. }
  21980. return Array.prototype.slice.call( array ); // create Array
  21981. },
  21982. isTypedArray: function ( object ) {
  21983. return ArrayBuffer.isView( object ) &&
  21984. ! ( object instanceof DataView );
  21985. },
  21986. // returns an array by which times and values can be sorted
  21987. getKeyframeOrder: function ( times ) {
  21988. function compareTime( i, j ) {
  21989. return times[ i ] - times[ j ];
  21990. }
  21991. const n = times.length;
  21992. const result = new Array( n );
  21993. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21994. result.sort( compareTime );
  21995. return result;
  21996. },
  21997. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21998. sortedArray: function ( values, stride, order ) {
  21999. const nValues = values.length;
  22000. const result = new values.constructor( nValues );
  22001. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22002. const srcOffset = order[ i ] * stride;
  22003. for ( let j = 0; j !== stride; ++ j ) {
  22004. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22005. }
  22006. }
  22007. return result;
  22008. },
  22009. // function for parsing AOS keyframe formats
  22010. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  22011. let i = 1, key = jsonKeys[ 0 ];
  22012. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22013. key = jsonKeys[ i ++ ];
  22014. }
  22015. if ( key === undefined ) return; // no data
  22016. let value = key[ valuePropertyName ];
  22017. if ( value === undefined ) return; // no data
  22018. if ( Array.isArray( value ) ) {
  22019. do {
  22020. value = key[ valuePropertyName ];
  22021. if ( value !== undefined ) {
  22022. times.push( key.time );
  22023. values.push.apply( values, value ); // push all elements
  22024. }
  22025. key = jsonKeys[ i ++ ];
  22026. } while ( key !== undefined );
  22027. } else if ( value.toArray !== undefined ) {
  22028. // ...assume THREE.Math-ish
  22029. do {
  22030. value = key[ valuePropertyName ];
  22031. if ( value !== undefined ) {
  22032. times.push( key.time );
  22033. value.toArray( values, values.length );
  22034. }
  22035. key = jsonKeys[ i ++ ];
  22036. } while ( key !== undefined );
  22037. } else {
  22038. // otherwise push as-is
  22039. do {
  22040. value = key[ valuePropertyName ];
  22041. if ( value !== undefined ) {
  22042. times.push( key.time );
  22043. values.push( value );
  22044. }
  22045. key = jsonKeys[ i ++ ];
  22046. } while ( key !== undefined );
  22047. }
  22048. },
  22049. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22050. const clip = sourceClip.clone();
  22051. clip.name = name;
  22052. const tracks = [];
  22053. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22054. const track = clip.tracks[ i ];
  22055. const valueSize = track.getValueSize();
  22056. const times = [];
  22057. const values = [];
  22058. for ( let j = 0; j < track.times.length; ++ j ) {
  22059. const frame = track.times[ j ] * fps;
  22060. if ( frame < startFrame || frame >= endFrame ) continue;
  22061. times.push( track.times[ j ] );
  22062. for ( let k = 0; k < valueSize; ++ k ) {
  22063. values.push( track.values[ j * valueSize + k ] );
  22064. }
  22065. }
  22066. if ( times.length === 0 ) continue;
  22067. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  22068. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  22069. tracks.push( track );
  22070. }
  22071. clip.tracks = tracks;
  22072. // find minimum .times value across all tracks in the trimmed clip
  22073. let minStartTime = Infinity;
  22074. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22075. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22076. minStartTime = clip.tracks[ i ].times[ 0 ];
  22077. }
  22078. }
  22079. // shift all tracks such that clip begins at t=0
  22080. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22081. clip.tracks[ i ].shift( - 1 * minStartTime );
  22082. }
  22083. clip.resetDuration();
  22084. return clip;
  22085. },
  22086. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22087. if ( fps <= 0 ) fps = 30;
  22088. const numTracks = referenceClip.tracks.length;
  22089. const referenceTime = referenceFrame / fps;
  22090. // Make each track's values relative to the values at the reference frame
  22091. for ( let i = 0; i < numTracks; ++ i ) {
  22092. const referenceTrack = referenceClip.tracks[ i ];
  22093. const referenceTrackType = referenceTrack.ValueTypeName;
  22094. // Skip this track if it's non-numeric
  22095. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22096. // Find the track in the target clip whose name and type matches the reference track
  22097. const targetTrack = targetClip.tracks.find( function ( track ) {
  22098. return track.name === referenceTrack.name
  22099. && track.ValueTypeName === referenceTrackType;
  22100. } );
  22101. if ( targetTrack === undefined ) continue;
  22102. let referenceOffset = 0;
  22103. const referenceValueSize = referenceTrack.getValueSize();
  22104. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22105. referenceOffset = referenceValueSize / 3;
  22106. }
  22107. let targetOffset = 0;
  22108. const targetValueSize = targetTrack.getValueSize();
  22109. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22110. targetOffset = targetValueSize / 3;
  22111. }
  22112. const lastIndex = referenceTrack.times.length - 1;
  22113. let referenceValue;
  22114. // Find the value to subtract out of the track
  22115. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22116. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22117. const startIndex = referenceOffset;
  22118. const endIndex = referenceValueSize - referenceOffset;
  22119. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22120. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22121. // Reference frame is after the last keyframe, so just use the last keyframe
  22122. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22123. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22124. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22125. } else {
  22126. // Interpolate to the reference value
  22127. const interpolant = referenceTrack.createInterpolant();
  22128. const startIndex = referenceOffset;
  22129. const endIndex = referenceValueSize - referenceOffset;
  22130. interpolant.evaluate( referenceTime );
  22131. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22132. }
  22133. // Conjugate the quaternion
  22134. if ( referenceTrackType === 'quaternion' ) {
  22135. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22136. referenceQuat.toArray( referenceValue );
  22137. }
  22138. // Subtract the reference value from all of the track values
  22139. const numTimes = targetTrack.times.length;
  22140. for ( let j = 0; j < numTimes; ++ j ) {
  22141. const valueStart = j * targetValueSize + targetOffset;
  22142. if ( referenceTrackType === 'quaternion' ) {
  22143. // Multiply the conjugate for quaternion track types
  22144. Quaternion.multiplyQuaternionsFlat(
  22145. targetTrack.values,
  22146. valueStart,
  22147. referenceValue,
  22148. 0,
  22149. targetTrack.values,
  22150. valueStart
  22151. );
  22152. } else {
  22153. const valueEnd = targetValueSize - targetOffset * 2;
  22154. // Subtract each value for all other numeric track types
  22155. for ( let k = 0; k < valueEnd; ++ k ) {
  22156. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22157. }
  22158. }
  22159. }
  22160. }
  22161. targetClip.blendMode = AdditiveAnimationBlendMode;
  22162. return targetClip;
  22163. }
  22164. };
  22165. /**
  22166. * Abstract base class of interpolants over parametric samples.
  22167. *
  22168. * The parameter domain is one dimensional, typically the time or a path
  22169. * along a curve defined by the data.
  22170. *
  22171. * The sample values can have any dimensionality and derived classes may
  22172. * apply special interpretations to the data.
  22173. *
  22174. * This class provides the interval seek in a Template Method, deferring
  22175. * the actual interpolation to derived classes.
  22176. *
  22177. * Time complexity is O(1) for linear access crossing at most two points
  22178. * and O(log N) for random access, where N is the number of positions.
  22179. *
  22180. * References:
  22181. *
  22182. * http://www.oodesign.com/template-method-pattern.html
  22183. *
  22184. */
  22185. class Interpolant {
  22186. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22187. this.parameterPositions = parameterPositions;
  22188. this._cachedIndex = 0;
  22189. this.resultBuffer = resultBuffer !== undefined ?
  22190. resultBuffer : new sampleValues.constructor( sampleSize );
  22191. this.sampleValues = sampleValues;
  22192. this.valueSize = sampleSize;
  22193. this.settings = null;
  22194. this.DefaultSettings_ = {};
  22195. }
  22196. evaluate( t ) {
  22197. const pp = this.parameterPositions;
  22198. let i1 = this._cachedIndex,
  22199. t1 = pp[ i1 ],
  22200. t0 = pp[ i1 - 1 ];
  22201. validate_interval: {
  22202. seek: {
  22203. let right;
  22204. linear_scan: {
  22205. //- See http://jsperf.com/comparison-to-undefined/3
  22206. //- slower code:
  22207. //-
  22208. //- if ( t >= t1 || t1 === undefined ) {
  22209. forward_scan: if ( ! ( t < t1 ) ) {
  22210. for ( let giveUpAt = i1 + 2; ; ) {
  22211. if ( t1 === undefined ) {
  22212. if ( t < t0 ) break forward_scan;
  22213. // after end
  22214. i1 = pp.length;
  22215. this._cachedIndex = i1;
  22216. return this.afterEnd_( i1 - 1, t, t0 );
  22217. }
  22218. if ( i1 === giveUpAt ) break; // this loop
  22219. t0 = t1;
  22220. t1 = pp[ ++ i1 ];
  22221. if ( t < t1 ) {
  22222. // we have arrived at the sought interval
  22223. break seek;
  22224. }
  22225. }
  22226. // prepare binary search on the right side of the index
  22227. right = pp.length;
  22228. break linear_scan;
  22229. }
  22230. //- slower code:
  22231. //- if ( t < t0 || t0 === undefined ) {
  22232. if ( ! ( t >= t0 ) ) {
  22233. // looping?
  22234. const t1global = pp[ 1 ];
  22235. if ( t < t1global ) {
  22236. i1 = 2; // + 1, using the scan for the details
  22237. t0 = t1global;
  22238. }
  22239. // linear reverse scan
  22240. for ( let giveUpAt = i1 - 2; ; ) {
  22241. if ( t0 === undefined ) {
  22242. // before start
  22243. this._cachedIndex = 0;
  22244. return this.beforeStart_( 0, t, t1 );
  22245. }
  22246. if ( i1 === giveUpAt ) break; // this loop
  22247. t1 = t0;
  22248. t0 = pp[ -- i1 - 1 ];
  22249. if ( t >= t0 ) {
  22250. // we have arrived at the sought interval
  22251. break seek;
  22252. }
  22253. }
  22254. // prepare binary search on the left side of the index
  22255. right = i1;
  22256. i1 = 0;
  22257. break linear_scan;
  22258. }
  22259. // the interval is valid
  22260. break validate_interval;
  22261. } // linear scan
  22262. // binary search
  22263. while ( i1 < right ) {
  22264. const mid = ( i1 + right ) >>> 1;
  22265. if ( t < pp[ mid ] ) {
  22266. right = mid;
  22267. } else {
  22268. i1 = mid + 1;
  22269. }
  22270. }
  22271. t1 = pp[ i1 ];
  22272. t0 = pp[ i1 - 1 ];
  22273. // check boundary cases, again
  22274. if ( t0 === undefined ) {
  22275. this._cachedIndex = 0;
  22276. return this.beforeStart_( 0, t, t1 );
  22277. }
  22278. if ( t1 === undefined ) {
  22279. i1 = pp.length;
  22280. this._cachedIndex = i1;
  22281. return this.afterEnd_( i1 - 1, t0, t );
  22282. }
  22283. } // seek
  22284. this._cachedIndex = i1;
  22285. this.intervalChanged_( i1, t0, t1 );
  22286. } // validate_interval
  22287. return this.interpolate_( i1, t0, t, t1 );
  22288. }
  22289. getSettings_() {
  22290. return this.settings || this.DefaultSettings_;
  22291. }
  22292. copySampleValue_( index ) {
  22293. // copies a sample value to the result buffer
  22294. const result = this.resultBuffer,
  22295. values = this.sampleValues,
  22296. stride = this.valueSize,
  22297. offset = index * stride;
  22298. for ( let i = 0; i !== stride; ++ i ) {
  22299. result[ i ] = values[ offset + i ];
  22300. }
  22301. return result;
  22302. }
  22303. // Template methods for derived classes:
  22304. interpolate_( /* i1, t0, t, t1 */ ) {
  22305. throw new Error( 'call to abstract method' );
  22306. // implementations shall return this.resultBuffer
  22307. }
  22308. intervalChanged_( /* i1, t0, t1 */ ) {
  22309. // empty
  22310. }
  22311. }
  22312. // ALIAS DEFINITIONS
  22313. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22314. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22315. /**
  22316. * Fast and simple cubic spline interpolant.
  22317. *
  22318. * It was derived from a Hermitian construction setting the first derivative
  22319. * at each sample position to the linear slope between neighboring positions
  22320. * over their parameter interval.
  22321. */
  22322. class CubicInterpolant extends Interpolant {
  22323. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22324. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22325. this._weightPrev = - 0;
  22326. this._offsetPrev = - 0;
  22327. this._weightNext = - 0;
  22328. this._offsetNext = - 0;
  22329. this.DefaultSettings_ = {
  22330. endingStart: ZeroCurvatureEnding,
  22331. endingEnd: ZeroCurvatureEnding
  22332. };
  22333. }
  22334. intervalChanged_( i1, t0, t1 ) {
  22335. const pp = this.parameterPositions;
  22336. let iPrev = i1 - 2,
  22337. iNext = i1 + 1,
  22338. tPrev = pp[ iPrev ],
  22339. tNext = pp[ iNext ];
  22340. if ( tPrev === undefined ) {
  22341. switch ( this.getSettings_().endingStart ) {
  22342. case ZeroSlopeEnding:
  22343. // f'(t0) = 0
  22344. iPrev = i1;
  22345. tPrev = 2 * t0 - t1;
  22346. break;
  22347. case WrapAroundEnding:
  22348. // use the other end of the curve
  22349. iPrev = pp.length - 2;
  22350. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22351. break;
  22352. default: // ZeroCurvatureEnding
  22353. // f''(t0) = 0 a.k.a. Natural Spline
  22354. iPrev = i1;
  22355. tPrev = t1;
  22356. }
  22357. }
  22358. if ( tNext === undefined ) {
  22359. switch ( this.getSettings_().endingEnd ) {
  22360. case ZeroSlopeEnding:
  22361. // f'(tN) = 0
  22362. iNext = i1;
  22363. tNext = 2 * t1 - t0;
  22364. break;
  22365. case WrapAroundEnding:
  22366. // use the other end of the curve
  22367. iNext = 1;
  22368. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22369. break;
  22370. default: // ZeroCurvatureEnding
  22371. // f''(tN) = 0, a.k.a. Natural Spline
  22372. iNext = i1 - 1;
  22373. tNext = t0;
  22374. }
  22375. }
  22376. const halfDt = ( t1 - t0 ) * 0.5,
  22377. stride = this.valueSize;
  22378. this._weightPrev = halfDt / ( t0 - tPrev );
  22379. this._weightNext = halfDt / ( tNext - t1 );
  22380. this._offsetPrev = iPrev * stride;
  22381. this._offsetNext = iNext * stride;
  22382. }
  22383. interpolate_( i1, t0, t, t1 ) {
  22384. const result = this.resultBuffer,
  22385. values = this.sampleValues,
  22386. stride = this.valueSize,
  22387. o1 = i1 * stride, o0 = o1 - stride,
  22388. oP = this._offsetPrev, oN = this._offsetNext,
  22389. wP = this._weightPrev, wN = this._weightNext,
  22390. p = ( t - t0 ) / ( t1 - t0 ),
  22391. pp = p * p,
  22392. ppp = pp * p;
  22393. // evaluate polynomials
  22394. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  22395. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  22396. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22397. const sN = wN * ppp - wN * pp;
  22398. // combine data linearly
  22399. for ( let i = 0; i !== stride; ++ i ) {
  22400. result[ i ] =
  22401. sP * values[ oP + i ] +
  22402. s0 * values[ o0 + i ] +
  22403. s1 * values[ o1 + i ] +
  22404. sN * values[ oN + i ];
  22405. }
  22406. return result;
  22407. }
  22408. }
  22409. class LinearInterpolant extends Interpolant {
  22410. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22411. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22412. }
  22413. interpolate_( i1, t0, t, t1 ) {
  22414. const result = this.resultBuffer,
  22415. values = this.sampleValues,
  22416. stride = this.valueSize,
  22417. offset1 = i1 * stride,
  22418. offset0 = offset1 - stride,
  22419. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22420. weight0 = 1 - weight1;
  22421. for ( let i = 0; i !== stride; ++ i ) {
  22422. result[ i ] =
  22423. values[ offset0 + i ] * weight0 +
  22424. values[ offset1 + i ] * weight1;
  22425. }
  22426. return result;
  22427. }
  22428. }
  22429. /**
  22430. *
  22431. * Interpolant that evaluates to the sample value at the position preceeding
  22432. * the parameter.
  22433. */
  22434. class DiscreteInterpolant extends Interpolant {
  22435. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22436. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22437. }
  22438. interpolate_( i1 /*, t0, t, t1 */ ) {
  22439. return this.copySampleValue_( i1 - 1 );
  22440. }
  22441. }
  22442. class KeyframeTrack {
  22443. constructor( name, times, values, interpolation ) {
  22444. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22445. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22446. this.name = name;
  22447. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  22448. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  22449. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22450. }
  22451. // Serialization (in static context, because of constructor invocation
  22452. // and automatic invocation of .toJSON):
  22453. static toJSON( track ) {
  22454. const trackType = track.constructor;
  22455. let json;
  22456. // derived classes can define a static toJSON method
  22457. if ( trackType.toJSON !== this.toJSON ) {
  22458. json = trackType.toJSON( track );
  22459. } else {
  22460. // by default, we assume the data can be serialized as-is
  22461. json = {
  22462. 'name': track.name,
  22463. 'times': AnimationUtils.convertArray( track.times, Array ),
  22464. 'values': AnimationUtils.convertArray( track.values, Array )
  22465. };
  22466. const interpolation = track.getInterpolation();
  22467. if ( interpolation !== track.DefaultInterpolation ) {
  22468. json.interpolation = interpolation;
  22469. }
  22470. }
  22471. json.type = track.ValueTypeName; // mandatory
  22472. return json;
  22473. }
  22474. InterpolantFactoryMethodDiscrete( result ) {
  22475. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22476. }
  22477. InterpolantFactoryMethodLinear( result ) {
  22478. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22479. }
  22480. InterpolantFactoryMethodSmooth( result ) {
  22481. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22482. }
  22483. setInterpolation( interpolation ) {
  22484. let factoryMethod;
  22485. switch ( interpolation ) {
  22486. case InterpolateDiscrete:
  22487. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22488. break;
  22489. case InterpolateLinear:
  22490. factoryMethod = this.InterpolantFactoryMethodLinear;
  22491. break;
  22492. case InterpolateSmooth:
  22493. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22494. break;
  22495. }
  22496. if ( factoryMethod === undefined ) {
  22497. const message = 'unsupported interpolation for ' +
  22498. this.ValueTypeName + ' keyframe track named ' + this.name;
  22499. if ( this.createInterpolant === undefined ) {
  22500. // fall back to default, unless the default itself is messed up
  22501. if ( interpolation !== this.DefaultInterpolation ) {
  22502. this.setInterpolation( this.DefaultInterpolation );
  22503. } else {
  22504. throw new Error( message ); // fatal, in this case
  22505. }
  22506. }
  22507. console.warn( 'THREE.KeyframeTrack:', message );
  22508. return this;
  22509. }
  22510. this.createInterpolant = factoryMethod;
  22511. return this;
  22512. }
  22513. getInterpolation() {
  22514. switch ( this.createInterpolant ) {
  22515. case this.InterpolantFactoryMethodDiscrete:
  22516. return InterpolateDiscrete;
  22517. case this.InterpolantFactoryMethodLinear:
  22518. return InterpolateLinear;
  22519. case this.InterpolantFactoryMethodSmooth:
  22520. return InterpolateSmooth;
  22521. }
  22522. }
  22523. getValueSize() {
  22524. return this.values.length / this.times.length;
  22525. }
  22526. // move all keyframes either forwards or backwards in time
  22527. shift( timeOffset ) {
  22528. if ( timeOffset !== 0.0 ) {
  22529. const times = this.times;
  22530. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22531. times[ i ] += timeOffset;
  22532. }
  22533. }
  22534. return this;
  22535. }
  22536. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22537. scale( timeScale ) {
  22538. if ( timeScale !== 1.0 ) {
  22539. const times = this.times;
  22540. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22541. times[ i ] *= timeScale;
  22542. }
  22543. }
  22544. return this;
  22545. }
  22546. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22547. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22548. trim( startTime, endTime ) {
  22549. const times = this.times,
  22550. nKeys = times.length;
  22551. let from = 0,
  22552. to = nKeys - 1;
  22553. while ( from !== nKeys && times[ from ] < startTime ) {
  22554. ++ from;
  22555. }
  22556. while ( to !== - 1 && times[ to ] > endTime ) {
  22557. -- to;
  22558. }
  22559. ++ to; // inclusive -> exclusive bound
  22560. if ( from !== 0 || to !== nKeys ) {
  22561. // empty tracks are forbidden, so keep at least one keyframe
  22562. if ( from >= to ) {
  22563. to = Math.max( to, 1 );
  22564. from = to - 1;
  22565. }
  22566. const stride = this.getValueSize();
  22567. this.times = AnimationUtils.arraySlice( times, from, to );
  22568. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  22569. }
  22570. return this;
  22571. }
  22572. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22573. validate() {
  22574. let valid = true;
  22575. const valueSize = this.getValueSize();
  22576. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22577. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22578. valid = false;
  22579. }
  22580. const times = this.times,
  22581. values = this.values,
  22582. nKeys = times.length;
  22583. if ( nKeys === 0 ) {
  22584. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22585. valid = false;
  22586. }
  22587. let prevTime = null;
  22588. for ( let i = 0; i !== nKeys; i ++ ) {
  22589. const currTime = times[ i ];
  22590. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22591. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22592. valid = false;
  22593. break;
  22594. }
  22595. if ( prevTime !== null && prevTime > currTime ) {
  22596. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22597. valid = false;
  22598. break;
  22599. }
  22600. prevTime = currTime;
  22601. }
  22602. if ( values !== undefined ) {
  22603. if ( AnimationUtils.isTypedArray( values ) ) {
  22604. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22605. const value = values[ i ];
  22606. if ( isNaN( value ) ) {
  22607. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22608. valid = false;
  22609. break;
  22610. }
  22611. }
  22612. }
  22613. }
  22614. return valid;
  22615. }
  22616. // removes equivalent sequential keys as common in morph target sequences
  22617. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22618. optimize() {
  22619. // times or values may be shared with other tracks, so overwriting is unsafe
  22620. const times = AnimationUtils.arraySlice( this.times ),
  22621. values = AnimationUtils.arraySlice( this.values ),
  22622. stride = this.getValueSize(),
  22623. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22624. lastIndex = times.length - 1;
  22625. let writeIndex = 1;
  22626. for ( let i = 1; i < lastIndex; ++ i ) {
  22627. let keep = false;
  22628. const time = times[ i ];
  22629. const timeNext = times[ i + 1 ];
  22630. // remove adjacent keyframes scheduled at the same time
  22631. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22632. if ( ! smoothInterpolation ) {
  22633. // remove unnecessary keyframes same as their neighbors
  22634. const offset = i * stride,
  22635. offsetP = offset - stride,
  22636. offsetN = offset + stride;
  22637. for ( let j = 0; j !== stride; ++ j ) {
  22638. const value = values[ offset + j ];
  22639. if ( value !== values[ offsetP + j ] ||
  22640. value !== values[ offsetN + j ] ) {
  22641. keep = true;
  22642. break;
  22643. }
  22644. }
  22645. } else {
  22646. keep = true;
  22647. }
  22648. }
  22649. // in-place compaction
  22650. if ( keep ) {
  22651. if ( i !== writeIndex ) {
  22652. times[ writeIndex ] = times[ i ];
  22653. const readOffset = i * stride,
  22654. writeOffset = writeIndex * stride;
  22655. for ( let j = 0; j !== stride; ++ j ) {
  22656. values[ writeOffset + j ] = values[ readOffset + j ];
  22657. }
  22658. }
  22659. ++ writeIndex;
  22660. }
  22661. }
  22662. // flush last keyframe (compaction looks ahead)
  22663. if ( lastIndex > 0 ) {
  22664. times[ writeIndex ] = times[ lastIndex ];
  22665. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22666. values[ writeOffset + j ] = values[ readOffset + j ];
  22667. }
  22668. ++ writeIndex;
  22669. }
  22670. if ( writeIndex !== times.length ) {
  22671. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22672. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22673. } else {
  22674. this.times = times;
  22675. this.values = values;
  22676. }
  22677. return this;
  22678. }
  22679. clone() {
  22680. const times = AnimationUtils.arraySlice( this.times, 0 );
  22681. const values = AnimationUtils.arraySlice( this.values, 0 );
  22682. const TypedKeyframeTrack = this.constructor;
  22683. const track = new TypedKeyframeTrack( this.name, times, values );
  22684. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22685. track.createInterpolant = this.createInterpolant;
  22686. return track;
  22687. }
  22688. }
  22689. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22690. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22691. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22692. /**
  22693. * A Track of Boolean keyframe values.
  22694. */
  22695. class BooleanKeyframeTrack extends KeyframeTrack {}
  22696. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22697. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22698. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22699. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22700. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22701. /**
  22702. * A Track of keyframe values that represent color.
  22703. */
  22704. class ColorKeyframeTrack extends KeyframeTrack {}
  22705. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22706. /**
  22707. * A Track of numeric keyframe values.
  22708. */
  22709. class NumberKeyframeTrack extends KeyframeTrack {}
  22710. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22711. /**
  22712. * Spherical linear unit quaternion interpolant.
  22713. */
  22714. class QuaternionLinearInterpolant extends Interpolant {
  22715. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22716. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22717. }
  22718. interpolate_( i1, t0, t, t1 ) {
  22719. const result = this.resultBuffer,
  22720. values = this.sampleValues,
  22721. stride = this.valueSize,
  22722. alpha = ( t - t0 ) / ( t1 - t0 );
  22723. let offset = i1 * stride;
  22724. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22725. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22726. }
  22727. return result;
  22728. }
  22729. }
  22730. /**
  22731. * A Track of quaternion keyframe values.
  22732. */
  22733. class QuaternionKeyframeTrack extends KeyframeTrack {
  22734. InterpolantFactoryMethodLinear( result ) {
  22735. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22736. }
  22737. }
  22738. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  22739. // ValueBufferType is inherited
  22740. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22741. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22742. /**
  22743. * A Track that interpolates Strings
  22744. */
  22745. class StringKeyframeTrack extends KeyframeTrack {}
  22746. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22747. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22748. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22749. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22750. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22751. /**
  22752. * A Track of vectored keyframe values.
  22753. */
  22754. class VectorKeyframeTrack extends KeyframeTrack {}
  22755. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  22756. class AnimationClip {
  22757. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22758. this.name = name;
  22759. this.tracks = tracks;
  22760. this.duration = duration;
  22761. this.blendMode = blendMode;
  22762. this.uuid = generateUUID();
  22763. // this means it should figure out its duration by scanning the tracks
  22764. if ( this.duration < 0 ) {
  22765. this.resetDuration();
  22766. }
  22767. }
  22768. static parse( json ) {
  22769. const tracks = [],
  22770. jsonTracks = json.tracks,
  22771. frameTime = 1.0 / ( json.fps || 1.0 );
  22772. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22773. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22774. }
  22775. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  22776. clip.uuid = json.uuid;
  22777. return clip;
  22778. }
  22779. static toJSON( clip ) {
  22780. const tracks = [],
  22781. clipTracks = clip.tracks;
  22782. const json = {
  22783. 'name': clip.name,
  22784. 'duration': clip.duration,
  22785. 'tracks': tracks,
  22786. 'uuid': clip.uuid,
  22787. 'blendMode': clip.blendMode
  22788. };
  22789. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22790. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22791. }
  22792. return json;
  22793. }
  22794. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  22795. const numMorphTargets = morphTargetSequence.length;
  22796. const tracks = [];
  22797. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22798. let times = [];
  22799. let values = [];
  22800. times.push(
  22801. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22802. i,
  22803. ( i + 1 ) % numMorphTargets );
  22804. values.push( 0, 1, 0 );
  22805. const order = AnimationUtils.getKeyframeOrder( times );
  22806. times = AnimationUtils.sortedArray( times, 1, order );
  22807. values = AnimationUtils.sortedArray( values, 1, order );
  22808. // if there is a key at the first frame, duplicate it as the
  22809. // last frame as well for perfect loop.
  22810. if ( ! noLoop && times[ 0 ] === 0 ) {
  22811. times.push( numMorphTargets );
  22812. values.push( values[ 0 ] );
  22813. }
  22814. tracks.push(
  22815. new NumberKeyframeTrack(
  22816. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22817. times, values
  22818. ).scale( 1.0 / fps ) );
  22819. }
  22820. return new this( name, - 1, tracks );
  22821. }
  22822. static findByName( objectOrClipArray, name ) {
  22823. let clipArray = objectOrClipArray;
  22824. if ( ! Array.isArray( objectOrClipArray ) ) {
  22825. const o = objectOrClipArray;
  22826. clipArray = o.geometry && o.geometry.animations || o.animations;
  22827. }
  22828. for ( let i = 0; i < clipArray.length; i ++ ) {
  22829. if ( clipArray[ i ].name === name ) {
  22830. return clipArray[ i ];
  22831. }
  22832. }
  22833. return null;
  22834. }
  22835. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  22836. const animationToMorphTargets = {};
  22837. // tested with https://regex101.com/ on trick sequences
  22838. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22839. const pattern = /^([\w-]*?)([\d]+)$/;
  22840. // sort morph target names into animation groups based
  22841. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22842. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22843. const morphTarget = morphTargets[ i ];
  22844. const parts = morphTarget.name.match( pattern );
  22845. if ( parts && parts.length > 1 ) {
  22846. const name = parts[ 1 ];
  22847. let animationMorphTargets = animationToMorphTargets[ name ];
  22848. if ( ! animationMorphTargets ) {
  22849. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22850. }
  22851. animationMorphTargets.push( morphTarget );
  22852. }
  22853. }
  22854. const clips = [];
  22855. for ( const name in animationToMorphTargets ) {
  22856. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22857. }
  22858. return clips;
  22859. }
  22860. // parse the animation.hierarchy format
  22861. static parseAnimation( animation, bones ) {
  22862. if ( ! animation ) {
  22863. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22864. return null;
  22865. }
  22866. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22867. // only return track if there are actually keys.
  22868. if ( animationKeys.length !== 0 ) {
  22869. const times = [];
  22870. const values = [];
  22871. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22872. // empty keys are filtered out, so check again
  22873. if ( times.length !== 0 ) {
  22874. destTracks.push( new trackType( trackName, times, values ) );
  22875. }
  22876. }
  22877. };
  22878. const tracks = [];
  22879. const clipName = animation.name || 'default';
  22880. const fps = animation.fps || 30;
  22881. const blendMode = animation.blendMode;
  22882. // automatic length determination in AnimationClip.
  22883. let duration = animation.length || - 1;
  22884. const hierarchyTracks = animation.hierarchy || [];
  22885. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22886. const animationKeys = hierarchyTracks[ h ].keys;
  22887. // skip empty tracks
  22888. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22889. // process morph targets
  22890. if ( animationKeys[ 0 ].morphTargets ) {
  22891. // figure out all morph targets used in this track
  22892. const morphTargetNames = {};
  22893. let k;
  22894. for ( k = 0; k < animationKeys.length; k ++ ) {
  22895. if ( animationKeys[ k ].morphTargets ) {
  22896. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22897. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  22898. }
  22899. }
  22900. }
  22901. // create a track for each morph target with all zero
  22902. // morphTargetInfluences except for the keys in which
  22903. // the morphTarget is named.
  22904. for ( const morphTargetName in morphTargetNames ) {
  22905. const times = [];
  22906. const values = [];
  22907. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22908. const animationKey = animationKeys[ k ];
  22909. times.push( animationKey.time );
  22910. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22911. }
  22912. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22913. }
  22914. duration = morphTargetNames.length * ( fps || 1.0 );
  22915. } else {
  22916. // ...assume skeletal animation
  22917. const boneName = '.bones[' + bones[ h ].name + ']';
  22918. addNonemptyTrack(
  22919. VectorKeyframeTrack, boneName + '.position',
  22920. animationKeys, 'pos', tracks );
  22921. addNonemptyTrack(
  22922. QuaternionKeyframeTrack, boneName + '.quaternion',
  22923. animationKeys, 'rot', tracks );
  22924. addNonemptyTrack(
  22925. VectorKeyframeTrack, boneName + '.scale',
  22926. animationKeys, 'scl', tracks );
  22927. }
  22928. }
  22929. if ( tracks.length === 0 ) {
  22930. return null;
  22931. }
  22932. const clip = new this( clipName, duration, tracks, blendMode );
  22933. return clip;
  22934. }
  22935. resetDuration() {
  22936. const tracks = this.tracks;
  22937. let duration = 0;
  22938. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22939. const track = this.tracks[ i ];
  22940. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22941. }
  22942. this.duration = duration;
  22943. return this;
  22944. }
  22945. trim() {
  22946. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22947. this.tracks[ i ].trim( 0, this.duration );
  22948. }
  22949. return this;
  22950. }
  22951. validate() {
  22952. let valid = true;
  22953. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22954. valid = valid && this.tracks[ i ].validate();
  22955. }
  22956. return valid;
  22957. }
  22958. optimize() {
  22959. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22960. this.tracks[ i ].optimize();
  22961. }
  22962. return this;
  22963. }
  22964. clone() {
  22965. const tracks = [];
  22966. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22967. tracks.push( this.tracks[ i ].clone() );
  22968. }
  22969. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  22970. }
  22971. toJSON() {
  22972. return this.constructor.toJSON( this );
  22973. }
  22974. }
  22975. function getTrackTypeForValueTypeName( typeName ) {
  22976. switch ( typeName.toLowerCase() ) {
  22977. case 'scalar':
  22978. case 'double':
  22979. case 'float':
  22980. case 'number':
  22981. case 'integer':
  22982. return NumberKeyframeTrack;
  22983. case 'vector':
  22984. case 'vector2':
  22985. case 'vector3':
  22986. case 'vector4':
  22987. return VectorKeyframeTrack;
  22988. case 'color':
  22989. return ColorKeyframeTrack;
  22990. case 'quaternion':
  22991. return QuaternionKeyframeTrack;
  22992. case 'bool':
  22993. case 'boolean':
  22994. return BooleanKeyframeTrack;
  22995. case 'string':
  22996. return StringKeyframeTrack;
  22997. }
  22998. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22999. }
  23000. function parseKeyframeTrack( json ) {
  23001. if ( json.type === undefined ) {
  23002. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23003. }
  23004. const trackType = getTrackTypeForValueTypeName( json.type );
  23005. if ( json.times === undefined ) {
  23006. const times = [], values = [];
  23007. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23008. json.times = times;
  23009. json.values = values;
  23010. }
  23011. // derived classes can define a static parse method
  23012. if ( trackType.parse !== undefined ) {
  23013. return trackType.parse( json );
  23014. } else {
  23015. // by default, we assume a constructor compatible with the base
  23016. return new trackType( json.name, json.times, json.values, json.interpolation );
  23017. }
  23018. }
  23019. const Cache = {
  23020. enabled: false,
  23021. files: {},
  23022. add: function ( key, file ) {
  23023. if ( this.enabled === false ) return;
  23024. // console.log( 'THREE.Cache', 'Adding key:', key );
  23025. this.files[ key ] = file;
  23026. },
  23027. get: function ( key ) {
  23028. if ( this.enabled === false ) return;
  23029. // console.log( 'THREE.Cache', 'Checking key:', key );
  23030. return this.files[ key ];
  23031. },
  23032. remove: function ( key ) {
  23033. delete this.files[ key ];
  23034. },
  23035. clear: function () {
  23036. this.files = {};
  23037. }
  23038. };
  23039. class LoadingManager {
  23040. constructor( onLoad, onProgress, onError ) {
  23041. const scope = this;
  23042. let isLoading = false;
  23043. let itemsLoaded = 0;
  23044. let itemsTotal = 0;
  23045. let urlModifier = undefined;
  23046. const handlers = [];
  23047. // Refer to #5689 for the reason why we don't set .onStart
  23048. // in the constructor
  23049. this.onStart = undefined;
  23050. this.onLoad = onLoad;
  23051. this.onProgress = onProgress;
  23052. this.onError = onError;
  23053. this.itemStart = function ( url ) {
  23054. itemsTotal ++;
  23055. if ( isLoading === false ) {
  23056. if ( scope.onStart !== undefined ) {
  23057. scope.onStart( url, itemsLoaded, itemsTotal );
  23058. }
  23059. }
  23060. isLoading = true;
  23061. };
  23062. this.itemEnd = function ( url ) {
  23063. itemsLoaded ++;
  23064. if ( scope.onProgress !== undefined ) {
  23065. scope.onProgress( url, itemsLoaded, itemsTotal );
  23066. }
  23067. if ( itemsLoaded === itemsTotal ) {
  23068. isLoading = false;
  23069. if ( scope.onLoad !== undefined ) {
  23070. scope.onLoad();
  23071. }
  23072. }
  23073. };
  23074. this.itemError = function ( url ) {
  23075. if ( scope.onError !== undefined ) {
  23076. scope.onError( url );
  23077. }
  23078. };
  23079. this.resolveURL = function ( url ) {
  23080. if ( urlModifier ) {
  23081. return urlModifier( url );
  23082. }
  23083. return url;
  23084. };
  23085. this.setURLModifier = function ( transform ) {
  23086. urlModifier = transform;
  23087. return this;
  23088. };
  23089. this.addHandler = function ( regex, loader ) {
  23090. handlers.push( regex, loader );
  23091. return this;
  23092. };
  23093. this.removeHandler = function ( regex ) {
  23094. const index = handlers.indexOf( regex );
  23095. if ( index !== - 1 ) {
  23096. handlers.splice( index, 2 );
  23097. }
  23098. return this;
  23099. };
  23100. this.getHandler = function ( file ) {
  23101. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23102. const regex = handlers[ i ];
  23103. const loader = handlers[ i + 1 ];
  23104. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23105. if ( regex.test( file ) ) {
  23106. return loader;
  23107. }
  23108. }
  23109. return null;
  23110. };
  23111. }
  23112. }
  23113. const DefaultLoadingManager = new LoadingManager();
  23114. class Loader {
  23115. constructor( manager ) {
  23116. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23117. this.crossOrigin = 'anonymous';
  23118. this.withCredentials = false;
  23119. this.path = '';
  23120. this.resourcePath = '';
  23121. this.requestHeader = {};
  23122. }
  23123. load( /* url, onLoad, onProgress, onError */ ) {}
  23124. loadAsync( url, onProgress ) {
  23125. const scope = this;
  23126. return new Promise( function ( resolve, reject ) {
  23127. scope.load( url, resolve, onProgress, reject );
  23128. } );
  23129. }
  23130. parse( /* data */ ) {}
  23131. setCrossOrigin( crossOrigin ) {
  23132. this.crossOrigin = crossOrigin;
  23133. return this;
  23134. }
  23135. setWithCredentials( value ) {
  23136. this.withCredentials = value;
  23137. return this;
  23138. }
  23139. setPath( path ) {
  23140. this.path = path;
  23141. return this;
  23142. }
  23143. setResourcePath( resourcePath ) {
  23144. this.resourcePath = resourcePath;
  23145. return this;
  23146. }
  23147. setRequestHeader( requestHeader ) {
  23148. this.requestHeader = requestHeader;
  23149. return this;
  23150. }
  23151. }
  23152. const loading = {};
  23153. class FileLoader extends Loader {
  23154. constructor( manager ) {
  23155. super( manager );
  23156. }
  23157. load( url, onLoad, onProgress, onError ) {
  23158. if ( url === undefined ) url = '';
  23159. if ( this.path !== undefined ) url = this.path + url;
  23160. url = this.manager.resolveURL( url );
  23161. const cached = Cache.get( url );
  23162. if ( cached !== undefined ) {
  23163. this.manager.itemStart( url );
  23164. setTimeout( () => {
  23165. if ( onLoad ) onLoad( cached );
  23166. this.manager.itemEnd( url );
  23167. }, 0 );
  23168. return cached;
  23169. }
  23170. // Check if request is duplicate
  23171. if ( loading[ url ] !== undefined ) {
  23172. loading[ url ].push( {
  23173. onLoad: onLoad,
  23174. onProgress: onProgress,
  23175. onError: onError
  23176. } );
  23177. return;
  23178. }
  23179. // Initialise array for duplicate requests
  23180. loading[ url ] = [];
  23181. loading[ url ].push( {
  23182. onLoad: onLoad,
  23183. onProgress: onProgress,
  23184. onError: onError,
  23185. } );
  23186. // create request
  23187. const req = new Request( url, {
  23188. headers: new Headers( this.requestHeader ),
  23189. credentials: this.withCredentials ? 'include' : 'same-origin',
  23190. // An abort controller could be added within a future PR
  23191. } );
  23192. // start the fetch
  23193. fetch( req )
  23194. .then( response => {
  23195. if ( response.status === 200 || response.status === 0 ) {
  23196. // Some browsers return HTTP Status 0 when using non-http protocol
  23197. // e.g. 'file://' or 'data://'. Handle as success.
  23198. if ( response.status === 0 ) {
  23199. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23200. }
  23201. const callbacks = loading[ url ];
  23202. const reader = response.body.getReader();
  23203. const contentLength = response.headers.get( 'Content-Length' );
  23204. const total = contentLength ? parseInt( contentLength ) : 0;
  23205. const lengthComputable = total !== 0;
  23206. let loaded = 0;
  23207. // periodically read data into the new stream tracking while download progress
  23208. return new ReadableStream( {
  23209. start( controller ) {
  23210. readData();
  23211. function readData() {
  23212. reader.read().then( ( { done, value } ) => {
  23213. if ( done ) {
  23214. controller.close();
  23215. } else {
  23216. loaded += value.byteLength;
  23217. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23218. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23219. const callback = callbacks[ i ];
  23220. if ( callback.onProgress ) callback.onProgress( event );
  23221. }
  23222. controller.enqueue( value );
  23223. readData();
  23224. }
  23225. } );
  23226. }
  23227. }
  23228. } );
  23229. } else {
  23230. throw Error( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}` );
  23231. }
  23232. } )
  23233. .then( stream => {
  23234. const response = new Response( stream );
  23235. switch ( this.responseType ) {
  23236. case 'arraybuffer':
  23237. return response.arrayBuffer();
  23238. case 'blob':
  23239. return response.blob();
  23240. case 'document':
  23241. return response.text()
  23242. .then( text => {
  23243. const parser = new DOMParser();
  23244. return parser.parseFromString( text, this.mimeType );
  23245. } );
  23246. case 'json':
  23247. return response.json();
  23248. default:
  23249. return response.text();
  23250. }
  23251. } )
  23252. .then( data => {
  23253. // Add to cache only on HTTP success, so that we do not cache
  23254. // error response bodies as proper responses to requests.
  23255. Cache.add( url, data );
  23256. const callbacks = loading[ url ];
  23257. delete loading[ url ];
  23258. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23259. const callback = callbacks[ i ];
  23260. if ( callback.onLoad ) callback.onLoad( data );
  23261. }
  23262. this.manager.itemEnd( url );
  23263. } )
  23264. .catch( err => {
  23265. // Abort errors and other errors are handled the same
  23266. const callbacks = loading[ url ];
  23267. delete loading[ url ];
  23268. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23269. const callback = callbacks[ i ];
  23270. if ( callback.onError ) callback.onError( err );
  23271. }
  23272. this.manager.itemError( url );
  23273. this.manager.itemEnd( url );
  23274. } );
  23275. this.manager.itemStart( url );
  23276. }
  23277. setResponseType( value ) {
  23278. this.responseType = value;
  23279. return this;
  23280. }
  23281. setMimeType( value ) {
  23282. this.mimeType = value;
  23283. return this;
  23284. }
  23285. }
  23286. class AnimationLoader extends Loader {
  23287. constructor( manager ) {
  23288. super( manager );
  23289. }
  23290. load( url, onLoad, onProgress, onError ) {
  23291. const scope = this;
  23292. const loader = new FileLoader( this.manager );
  23293. loader.setPath( this.path );
  23294. loader.setRequestHeader( this.requestHeader );
  23295. loader.setWithCredentials( this.withCredentials );
  23296. loader.load( url, function ( text ) {
  23297. try {
  23298. onLoad( scope.parse( JSON.parse( text ) ) );
  23299. } catch ( e ) {
  23300. if ( onError ) {
  23301. onError( e );
  23302. } else {
  23303. console.error( e );
  23304. }
  23305. scope.manager.itemError( url );
  23306. }
  23307. }, onProgress, onError );
  23308. }
  23309. parse( json ) {
  23310. const animations = [];
  23311. for ( let i = 0; i < json.length; i ++ ) {
  23312. const clip = AnimationClip.parse( json[ i ] );
  23313. animations.push( clip );
  23314. }
  23315. return animations;
  23316. }
  23317. }
  23318. /**
  23319. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23320. *
  23321. * Sub classes have to implement the parse() method which will be used in load().
  23322. */
  23323. class CompressedTextureLoader extends Loader {
  23324. constructor( manager ) {
  23325. super( manager );
  23326. }
  23327. load( url, onLoad, onProgress, onError ) {
  23328. const scope = this;
  23329. const images = [];
  23330. const texture = new CompressedTexture();
  23331. const loader = new FileLoader( this.manager );
  23332. loader.setPath( this.path );
  23333. loader.setResponseType( 'arraybuffer' );
  23334. loader.setRequestHeader( this.requestHeader );
  23335. loader.setWithCredentials( scope.withCredentials );
  23336. let loaded = 0;
  23337. function loadTexture( i ) {
  23338. loader.load( url[ i ], function ( buffer ) {
  23339. const texDatas = scope.parse( buffer, true );
  23340. images[ i ] = {
  23341. width: texDatas.width,
  23342. height: texDatas.height,
  23343. format: texDatas.format,
  23344. mipmaps: texDatas.mipmaps
  23345. };
  23346. loaded += 1;
  23347. if ( loaded === 6 ) {
  23348. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23349. texture.image = images;
  23350. texture.format = texDatas.format;
  23351. texture.needsUpdate = true;
  23352. if ( onLoad ) onLoad( texture );
  23353. }
  23354. }, onProgress, onError );
  23355. }
  23356. if ( Array.isArray( url ) ) {
  23357. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23358. loadTexture( i );
  23359. }
  23360. } else {
  23361. // compressed cubemap texture stored in a single DDS file
  23362. loader.load( url, function ( buffer ) {
  23363. const texDatas = scope.parse( buffer, true );
  23364. if ( texDatas.isCubemap ) {
  23365. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23366. for ( let f = 0; f < faces; f ++ ) {
  23367. images[ f ] = { mipmaps: [] };
  23368. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23369. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23370. images[ f ].format = texDatas.format;
  23371. images[ f ].width = texDatas.width;
  23372. images[ f ].height = texDatas.height;
  23373. }
  23374. }
  23375. texture.image = images;
  23376. } else {
  23377. texture.image.width = texDatas.width;
  23378. texture.image.height = texDatas.height;
  23379. texture.mipmaps = texDatas.mipmaps;
  23380. }
  23381. if ( texDatas.mipmapCount === 1 ) {
  23382. texture.minFilter = LinearFilter;
  23383. }
  23384. texture.format = texDatas.format;
  23385. texture.needsUpdate = true;
  23386. if ( onLoad ) onLoad( texture );
  23387. }, onProgress, onError );
  23388. }
  23389. return texture;
  23390. }
  23391. }
  23392. class ImageLoader extends Loader {
  23393. constructor( manager ) {
  23394. super( manager );
  23395. }
  23396. load( url, onLoad, onProgress, onError ) {
  23397. if ( this.path !== undefined ) url = this.path + url;
  23398. url = this.manager.resolveURL( url );
  23399. const scope = this;
  23400. const cached = Cache.get( url );
  23401. if ( cached !== undefined ) {
  23402. scope.manager.itemStart( url );
  23403. setTimeout( function () {
  23404. if ( onLoad ) onLoad( cached );
  23405. scope.manager.itemEnd( url );
  23406. }, 0 );
  23407. return cached;
  23408. }
  23409. const image = createElementNS( 'img' );
  23410. function onImageLoad() {
  23411. removeEventListeners();
  23412. Cache.add( url, this );
  23413. if ( onLoad ) onLoad( this );
  23414. scope.manager.itemEnd( url );
  23415. }
  23416. function onImageError( event ) {
  23417. removeEventListeners();
  23418. if ( onError ) onError( event );
  23419. scope.manager.itemError( url );
  23420. scope.manager.itemEnd( url );
  23421. }
  23422. function removeEventListeners() {
  23423. image.removeEventListener( 'load', onImageLoad, false );
  23424. image.removeEventListener( 'error', onImageError, false );
  23425. }
  23426. image.addEventListener( 'load', onImageLoad, false );
  23427. image.addEventListener( 'error', onImageError, false );
  23428. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23429. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23430. }
  23431. scope.manager.itemStart( url );
  23432. image.src = url;
  23433. return image;
  23434. }
  23435. }
  23436. class CubeTextureLoader extends Loader {
  23437. constructor( manager ) {
  23438. super( manager );
  23439. }
  23440. load( urls, onLoad, onProgress, onError ) {
  23441. const texture = new CubeTexture();
  23442. const loader = new ImageLoader( this.manager );
  23443. loader.setCrossOrigin( this.crossOrigin );
  23444. loader.setPath( this.path );
  23445. let loaded = 0;
  23446. function loadTexture( i ) {
  23447. loader.load( urls[ i ], function ( image ) {
  23448. texture.images[ i ] = image;
  23449. loaded ++;
  23450. if ( loaded === 6 ) {
  23451. texture.needsUpdate = true;
  23452. if ( onLoad ) onLoad( texture );
  23453. }
  23454. }, undefined, onError );
  23455. }
  23456. for ( let i = 0; i < urls.length; ++ i ) {
  23457. loadTexture( i );
  23458. }
  23459. return texture;
  23460. }
  23461. }
  23462. /**
  23463. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23464. *
  23465. * Sub classes have to implement the parse() method which will be used in load().
  23466. */
  23467. class DataTextureLoader extends Loader {
  23468. constructor( manager ) {
  23469. super( manager );
  23470. }
  23471. load( url, onLoad, onProgress, onError ) {
  23472. const scope = this;
  23473. const texture = new DataTexture();
  23474. const loader = new FileLoader( this.manager );
  23475. loader.setResponseType( 'arraybuffer' );
  23476. loader.setRequestHeader( this.requestHeader );
  23477. loader.setPath( this.path );
  23478. loader.setWithCredentials( scope.withCredentials );
  23479. loader.load( url, function ( buffer ) {
  23480. const texData = scope.parse( buffer );
  23481. if ( ! texData ) return;
  23482. if ( texData.image !== undefined ) {
  23483. texture.image = texData.image;
  23484. } else if ( texData.data !== undefined ) {
  23485. texture.image.width = texData.width;
  23486. texture.image.height = texData.height;
  23487. texture.image.data = texData.data;
  23488. }
  23489. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23490. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23491. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23492. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23493. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23494. if ( texData.encoding !== undefined ) {
  23495. texture.encoding = texData.encoding;
  23496. }
  23497. if ( texData.flipY !== undefined ) {
  23498. texture.flipY = texData.flipY;
  23499. }
  23500. if ( texData.format !== undefined ) {
  23501. texture.format = texData.format;
  23502. }
  23503. if ( texData.type !== undefined ) {
  23504. texture.type = texData.type;
  23505. }
  23506. if ( texData.mipmaps !== undefined ) {
  23507. texture.mipmaps = texData.mipmaps;
  23508. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23509. }
  23510. if ( texData.mipmapCount === 1 ) {
  23511. texture.minFilter = LinearFilter;
  23512. }
  23513. if ( texData.generateMipmaps !== undefined ) {
  23514. texture.generateMipmaps = texData.generateMipmaps;
  23515. }
  23516. texture.needsUpdate = true;
  23517. if ( onLoad ) onLoad( texture, texData );
  23518. }, onProgress, onError );
  23519. return texture;
  23520. }
  23521. }
  23522. class TextureLoader extends Loader {
  23523. constructor( manager ) {
  23524. super( manager );
  23525. }
  23526. load( url, onLoad, onProgress, onError ) {
  23527. const texture = new Texture();
  23528. const loader = new ImageLoader( this.manager );
  23529. loader.setCrossOrigin( this.crossOrigin );
  23530. loader.setPath( this.path );
  23531. loader.load( url, function ( image ) {
  23532. texture.image = image;
  23533. texture.needsUpdate = true;
  23534. if ( onLoad !== undefined ) {
  23535. onLoad( texture );
  23536. }
  23537. }, onProgress, onError );
  23538. return texture;
  23539. }
  23540. }
  23541. class Light extends Object3D {
  23542. constructor( color, intensity = 1 ) {
  23543. super();
  23544. this.type = 'Light';
  23545. this.color = new Color( color );
  23546. this.intensity = intensity;
  23547. }
  23548. dispose() {
  23549. // Empty here in base class; some subclasses override.
  23550. }
  23551. copy( source ) {
  23552. super.copy( source );
  23553. this.color.copy( source.color );
  23554. this.intensity = source.intensity;
  23555. return this;
  23556. }
  23557. toJSON( meta ) {
  23558. const data = super.toJSON( meta );
  23559. data.object.color = this.color.getHex();
  23560. data.object.intensity = this.intensity;
  23561. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23562. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23563. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23564. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23565. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23566. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23567. return data;
  23568. }
  23569. }
  23570. Light.prototype.isLight = true;
  23571. class HemisphereLight extends Light {
  23572. constructor( skyColor, groundColor, intensity ) {
  23573. super( skyColor, intensity );
  23574. this.type = 'HemisphereLight';
  23575. this.position.copy( Object3D.DefaultUp );
  23576. this.updateMatrix();
  23577. this.groundColor = new Color( groundColor );
  23578. }
  23579. copy( source ) {
  23580. Light.prototype.copy.call( this, source );
  23581. this.groundColor.copy( source.groundColor );
  23582. return this;
  23583. }
  23584. }
  23585. HemisphereLight.prototype.isHemisphereLight = true;
  23586. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23587. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23588. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23589. class LightShadow {
  23590. constructor( camera ) {
  23591. this.camera = camera;
  23592. this.bias = 0;
  23593. this.normalBias = 0;
  23594. this.radius = 1;
  23595. this.blurSamples = 8;
  23596. this.mapSize = new Vector2( 512, 512 );
  23597. this.map = null;
  23598. this.mapPass = null;
  23599. this.matrix = new Matrix4();
  23600. this.autoUpdate = true;
  23601. this.needsUpdate = false;
  23602. this._frustum = new Frustum();
  23603. this._frameExtents = new Vector2( 1, 1 );
  23604. this._viewportCount = 1;
  23605. this._viewports = [
  23606. new Vector4( 0, 0, 1, 1 )
  23607. ];
  23608. }
  23609. getViewportCount() {
  23610. return this._viewportCount;
  23611. }
  23612. getFrustum() {
  23613. return this._frustum;
  23614. }
  23615. updateMatrices( light ) {
  23616. const shadowCamera = this.camera;
  23617. const shadowMatrix = this.matrix;
  23618. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23619. shadowCamera.position.copy( _lightPositionWorld$1 );
  23620. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23621. shadowCamera.lookAt( _lookTarget$1 );
  23622. shadowCamera.updateMatrixWorld();
  23623. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23624. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23625. shadowMatrix.set(
  23626. 0.5, 0.0, 0.0, 0.5,
  23627. 0.0, 0.5, 0.0, 0.5,
  23628. 0.0, 0.0, 0.5, 0.5,
  23629. 0.0, 0.0, 0.0, 1.0
  23630. );
  23631. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23632. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23633. }
  23634. getViewport( viewportIndex ) {
  23635. return this._viewports[ viewportIndex ];
  23636. }
  23637. getFrameExtents() {
  23638. return this._frameExtents;
  23639. }
  23640. dispose() {
  23641. if ( this.map ) {
  23642. this.map.dispose();
  23643. }
  23644. if ( this.mapPass ) {
  23645. this.mapPass.dispose();
  23646. }
  23647. }
  23648. copy( source ) {
  23649. this.camera = source.camera.clone();
  23650. this.bias = source.bias;
  23651. this.radius = source.radius;
  23652. this.mapSize.copy( source.mapSize );
  23653. return this;
  23654. }
  23655. clone() {
  23656. return new this.constructor().copy( this );
  23657. }
  23658. toJSON() {
  23659. const object = {};
  23660. if ( this.bias !== 0 ) object.bias = this.bias;
  23661. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23662. if ( this.radius !== 1 ) object.radius = this.radius;
  23663. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23664. object.camera = this.camera.toJSON( false ).object;
  23665. delete object.camera.matrix;
  23666. return object;
  23667. }
  23668. }
  23669. class SpotLightShadow extends LightShadow {
  23670. constructor() {
  23671. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23672. this.focus = 1;
  23673. }
  23674. updateMatrices( light ) {
  23675. const camera = this.camera;
  23676. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23677. const aspect = this.mapSize.width / this.mapSize.height;
  23678. const far = light.distance || camera.far;
  23679. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23680. camera.fov = fov;
  23681. camera.aspect = aspect;
  23682. camera.far = far;
  23683. camera.updateProjectionMatrix();
  23684. }
  23685. super.updateMatrices( light );
  23686. }
  23687. copy( source ) {
  23688. super.copy( source );
  23689. this.focus = source.focus;
  23690. return this;
  23691. }
  23692. }
  23693. SpotLightShadow.prototype.isSpotLightShadow = true;
  23694. class SpotLight extends Light {
  23695. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  23696. super( color, intensity );
  23697. this.type = 'SpotLight';
  23698. this.position.copy( Object3D.DefaultUp );
  23699. this.updateMatrix();
  23700. this.target = new Object3D();
  23701. this.distance = distance;
  23702. this.angle = angle;
  23703. this.penumbra = penumbra;
  23704. this.decay = decay; // for physically correct lights, should be 2.
  23705. this.shadow = new SpotLightShadow();
  23706. }
  23707. get power() {
  23708. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23709. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23710. return this.intensity * Math.PI;
  23711. }
  23712. set power( power ) {
  23713. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23714. this.intensity = power / Math.PI;
  23715. }
  23716. dispose() {
  23717. this.shadow.dispose();
  23718. }
  23719. copy( source ) {
  23720. super.copy( source );
  23721. this.distance = source.distance;
  23722. this.angle = source.angle;
  23723. this.penumbra = source.penumbra;
  23724. this.decay = source.decay;
  23725. this.target = source.target.clone();
  23726. this.shadow = source.shadow.clone();
  23727. return this;
  23728. }
  23729. }
  23730. SpotLight.prototype.isSpotLight = true;
  23731. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  23732. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  23733. const _lookTarget = /*@__PURE__*/ new Vector3();
  23734. class PointLightShadow extends LightShadow {
  23735. constructor() {
  23736. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23737. this._frameExtents = new Vector2( 4, 2 );
  23738. this._viewportCount = 6;
  23739. this._viewports = [
  23740. // These viewports map a cube-map onto a 2D texture with the
  23741. // following orientation:
  23742. //
  23743. // xzXZ
  23744. // y Y
  23745. //
  23746. // X - Positive x direction
  23747. // x - Negative x direction
  23748. // Y - Positive y direction
  23749. // y - Negative y direction
  23750. // Z - Positive z direction
  23751. // z - Negative z direction
  23752. // positive X
  23753. new Vector4( 2, 1, 1, 1 ),
  23754. // negative X
  23755. new Vector4( 0, 1, 1, 1 ),
  23756. // positive Z
  23757. new Vector4( 3, 1, 1, 1 ),
  23758. // negative Z
  23759. new Vector4( 1, 1, 1, 1 ),
  23760. // positive Y
  23761. new Vector4( 3, 0, 1, 1 ),
  23762. // negative Y
  23763. new Vector4( 1, 0, 1, 1 )
  23764. ];
  23765. this._cubeDirections = [
  23766. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23767. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  23768. ];
  23769. this._cubeUps = [
  23770. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23771. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  23772. ];
  23773. }
  23774. updateMatrices( light, viewportIndex = 0 ) {
  23775. const camera = this.camera;
  23776. const shadowMatrix = this.matrix;
  23777. const far = light.distance || camera.far;
  23778. if ( far !== camera.far ) {
  23779. camera.far = far;
  23780. camera.updateProjectionMatrix();
  23781. }
  23782. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23783. camera.position.copy( _lightPositionWorld );
  23784. _lookTarget.copy( camera.position );
  23785. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23786. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23787. camera.lookAt( _lookTarget );
  23788. camera.updateMatrixWorld();
  23789. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  23790. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23791. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  23792. }
  23793. }
  23794. PointLightShadow.prototype.isPointLightShadow = true;
  23795. class PointLight extends Light {
  23796. constructor( color, intensity, distance = 0, decay = 1 ) {
  23797. super( color, intensity );
  23798. this.type = 'PointLight';
  23799. this.distance = distance;
  23800. this.decay = decay; // for physically correct lights, should be 2.
  23801. this.shadow = new PointLightShadow();
  23802. }
  23803. get power() {
  23804. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23805. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23806. return this.intensity * 4 * Math.PI;
  23807. }
  23808. set power( power ) {
  23809. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23810. this.intensity = power / ( 4 * Math.PI );
  23811. }
  23812. dispose() {
  23813. this.shadow.dispose();
  23814. }
  23815. copy( source ) {
  23816. super.copy( source );
  23817. this.distance = source.distance;
  23818. this.decay = source.decay;
  23819. this.shadow = source.shadow.clone();
  23820. return this;
  23821. }
  23822. }
  23823. PointLight.prototype.isPointLight = true;
  23824. class DirectionalLightShadow extends LightShadow {
  23825. constructor() {
  23826. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23827. }
  23828. }
  23829. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23830. class DirectionalLight extends Light {
  23831. constructor( color, intensity ) {
  23832. super( color, intensity );
  23833. this.type = 'DirectionalLight';
  23834. this.position.copy( Object3D.DefaultUp );
  23835. this.updateMatrix();
  23836. this.target = new Object3D();
  23837. this.shadow = new DirectionalLightShadow();
  23838. }
  23839. dispose() {
  23840. this.shadow.dispose();
  23841. }
  23842. copy( source ) {
  23843. super.copy( source );
  23844. this.target = source.target.clone();
  23845. this.shadow = source.shadow.clone();
  23846. return this;
  23847. }
  23848. }
  23849. DirectionalLight.prototype.isDirectionalLight = true;
  23850. class AmbientLight extends Light {
  23851. constructor( color, intensity ) {
  23852. super( color, intensity );
  23853. this.type = 'AmbientLight';
  23854. }
  23855. }
  23856. AmbientLight.prototype.isAmbientLight = true;
  23857. class RectAreaLight extends Light {
  23858. constructor( color, intensity, width = 10, height = 10 ) {
  23859. super( color, intensity );
  23860. this.type = 'RectAreaLight';
  23861. this.width = width;
  23862. this.height = height;
  23863. }
  23864. get power() {
  23865. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23866. return this.intensity * this.width * this.height * Math.PI;
  23867. }
  23868. set power( power ) {
  23869. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23870. this.intensity = power / ( this.width * this.height * Math.PI );
  23871. }
  23872. copy( source ) {
  23873. super.copy( source );
  23874. this.width = source.width;
  23875. this.height = source.height;
  23876. return this;
  23877. }
  23878. toJSON( meta ) {
  23879. const data = super.toJSON( meta );
  23880. data.object.width = this.width;
  23881. data.object.height = this.height;
  23882. return data;
  23883. }
  23884. }
  23885. RectAreaLight.prototype.isRectAreaLight = true;
  23886. /**
  23887. * Primary reference:
  23888. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23889. *
  23890. * Secondary reference:
  23891. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23892. */
  23893. // 3-band SH defined by 9 coefficients
  23894. class SphericalHarmonics3 {
  23895. constructor() {
  23896. this.coefficients = [];
  23897. for ( let i = 0; i < 9; i ++ ) {
  23898. this.coefficients.push( new Vector3() );
  23899. }
  23900. }
  23901. set( coefficients ) {
  23902. for ( let i = 0; i < 9; i ++ ) {
  23903. this.coefficients[ i ].copy( coefficients[ i ] );
  23904. }
  23905. return this;
  23906. }
  23907. zero() {
  23908. for ( let i = 0; i < 9; i ++ ) {
  23909. this.coefficients[ i ].set( 0, 0, 0 );
  23910. }
  23911. return this;
  23912. }
  23913. // get the radiance in the direction of the normal
  23914. // target is a Vector3
  23915. getAt( normal, target ) {
  23916. // normal is assumed to be unit length
  23917. const x = normal.x, y = normal.y, z = normal.z;
  23918. const coeff = this.coefficients;
  23919. // band 0
  23920. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23921. // band 1
  23922. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23923. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23924. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23925. // band 2
  23926. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23927. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23928. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23929. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23930. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23931. return target;
  23932. }
  23933. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23934. // target is a Vector3
  23935. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23936. getIrradianceAt( normal, target ) {
  23937. // normal is assumed to be unit length
  23938. const x = normal.x, y = normal.y, z = normal.z;
  23939. const coeff = this.coefficients;
  23940. // band 0
  23941. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23942. // band 1
  23943. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23944. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23945. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23946. // band 2
  23947. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23948. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23949. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23950. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23951. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23952. return target;
  23953. }
  23954. add( sh ) {
  23955. for ( let i = 0; i < 9; i ++ ) {
  23956. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23957. }
  23958. return this;
  23959. }
  23960. addScaledSH( sh, s ) {
  23961. for ( let i = 0; i < 9; i ++ ) {
  23962. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23963. }
  23964. return this;
  23965. }
  23966. scale( s ) {
  23967. for ( let i = 0; i < 9; i ++ ) {
  23968. this.coefficients[ i ].multiplyScalar( s );
  23969. }
  23970. return this;
  23971. }
  23972. lerp( sh, alpha ) {
  23973. for ( let i = 0; i < 9; i ++ ) {
  23974. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  23975. }
  23976. return this;
  23977. }
  23978. equals( sh ) {
  23979. for ( let i = 0; i < 9; i ++ ) {
  23980. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  23981. return false;
  23982. }
  23983. }
  23984. return true;
  23985. }
  23986. copy( sh ) {
  23987. return this.set( sh.coefficients );
  23988. }
  23989. clone() {
  23990. return new this.constructor().copy( this );
  23991. }
  23992. fromArray( array, offset = 0 ) {
  23993. const coefficients = this.coefficients;
  23994. for ( let i = 0; i < 9; i ++ ) {
  23995. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  23996. }
  23997. return this;
  23998. }
  23999. toArray( array = [], offset = 0 ) {
  24000. const coefficients = this.coefficients;
  24001. for ( let i = 0; i < 9; i ++ ) {
  24002. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24003. }
  24004. return array;
  24005. }
  24006. // evaluate the basis functions
  24007. // shBasis is an Array[ 9 ]
  24008. static getBasisAt( normal, shBasis ) {
  24009. // normal is assumed to be unit length
  24010. const x = normal.x, y = normal.y, z = normal.z;
  24011. // band 0
  24012. shBasis[ 0 ] = 0.282095;
  24013. // band 1
  24014. shBasis[ 1 ] = 0.488603 * y;
  24015. shBasis[ 2 ] = 0.488603 * z;
  24016. shBasis[ 3 ] = 0.488603 * x;
  24017. // band 2
  24018. shBasis[ 4 ] = 1.092548 * x * y;
  24019. shBasis[ 5 ] = 1.092548 * y * z;
  24020. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24021. shBasis[ 7 ] = 1.092548 * x * z;
  24022. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24023. }
  24024. }
  24025. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  24026. class LightProbe extends Light {
  24027. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24028. super( undefined, intensity );
  24029. this.sh = sh;
  24030. }
  24031. copy( source ) {
  24032. super.copy( source );
  24033. this.sh.copy( source.sh );
  24034. return this;
  24035. }
  24036. fromJSON( json ) {
  24037. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24038. this.sh.fromArray( json.sh );
  24039. return this;
  24040. }
  24041. toJSON( meta ) {
  24042. const data = super.toJSON( meta );
  24043. data.object.sh = this.sh.toArray();
  24044. return data;
  24045. }
  24046. }
  24047. LightProbe.prototype.isLightProbe = true;
  24048. class MaterialLoader extends Loader {
  24049. constructor( manager ) {
  24050. super( manager );
  24051. this.textures = {};
  24052. }
  24053. load( url, onLoad, onProgress, onError ) {
  24054. const scope = this;
  24055. const loader = new FileLoader( scope.manager );
  24056. loader.setPath( scope.path );
  24057. loader.setRequestHeader( scope.requestHeader );
  24058. loader.setWithCredentials( scope.withCredentials );
  24059. loader.load( url, function ( text ) {
  24060. try {
  24061. onLoad( scope.parse( JSON.parse( text ) ) );
  24062. } catch ( e ) {
  24063. if ( onError ) {
  24064. onError( e );
  24065. } else {
  24066. console.error( e );
  24067. }
  24068. scope.manager.itemError( url );
  24069. }
  24070. }, onProgress, onError );
  24071. }
  24072. parse( json ) {
  24073. const textures = this.textures;
  24074. function getTexture( name ) {
  24075. if ( textures[ name ] === undefined ) {
  24076. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24077. }
  24078. return textures[ name ];
  24079. }
  24080. const material = new Materials[ json.type ]();
  24081. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24082. if ( json.name !== undefined ) material.name = json.name;
  24083. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24084. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24085. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24086. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24087. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24088. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24089. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24090. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24091. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24092. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24093. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24094. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24095. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24096. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24097. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24098. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24099. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24100. if ( json.fog !== undefined ) material.fog = json.fog;
  24101. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24102. if ( json.blending !== undefined ) material.blending = json.blending;
  24103. if ( json.combine !== undefined ) material.combine = json.combine;
  24104. if ( json.side !== undefined ) material.side = json.side;
  24105. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24106. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24107. if ( json.format !== undefined ) material.format = json.format;
  24108. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24109. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24110. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24111. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24112. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24113. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24114. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24115. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24116. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24117. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24118. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24119. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24120. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24121. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24122. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24123. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24124. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24125. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24126. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24127. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24128. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24129. if ( json.scale !== undefined ) material.scale = json.scale;
  24130. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24131. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24132. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24133. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24134. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24135. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24136. if ( json.visible !== undefined ) material.visible = json.visible;
  24137. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24138. if ( json.userData !== undefined ) material.userData = json.userData;
  24139. if ( json.vertexColors !== undefined ) {
  24140. if ( typeof json.vertexColors === 'number' ) {
  24141. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24142. } else {
  24143. material.vertexColors = json.vertexColors;
  24144. }
  24145. }
  24146. // Shader Material
  24147. if ( json.uniforms !== undefined ) {
  24148. for ( const name in json.uniforms ) {
  24149. const uniform = json.uniforms[ name ];
  24150. material.uniforms[ name ] = {};
  24151. switch ( uniform.type ) {
  24152. case 't':
  24153. material.uniforms[ name ].value = getTexture( uniform.value );
  24154. break;
  24155. case 'c':
  24156. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24157. break;
  24158. case 'v2':
  24159. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24160. break;
  24161. case 'v3':
  24162. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24163. break;
  24164. case 'v4':
  24165. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24166. break;
  24167. case 'm3':
  24168. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24169. break;
  24170. case 'm4':
  24171. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24172. break;
  24173. default:
  24174. material.uniforms[ name ].value = uniform.value;
  24175. }
  24176. }
  24177. }
  24178. if ( json.defines !== undefined ) material.defines = json.defines;
  24179. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24180. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24181. if ( json.extensions !== undefined ) {
  24182. for ( const key in json.extensions ) {
  24183. material.extensions[ key ] = json.extensions[ key ];
  24184. }
  24185. }
  24186. // Deprecated
  24187. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24188. // for PointsMaterial
  24189. if ( json.size !== undefined ) material.size = json.size;
  24190. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24191. // maps
  24192. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24193. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24194. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24195. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24196. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24197. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24198. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24199. if ( json.normalScale !== undefined ) {
  24200. let normalScale = json.normalScale;
  24201. if ( Array.isArray( normalScale ) === false ) {
  24202. // Blender exporter used to export a scalar. See #7459
  24203. normalScale = [ normalScale, normalScale ];
  24204. }
  24205. material.normalScale = new Vector2().fromArray( normalScale );
  24206. }
  24207. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24208. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24209. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24210. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24211. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24212. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24213. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24214. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24215. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24216. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24217. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24218. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24219. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24220. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24221. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24222. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24223. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24224. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24225. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24226. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24227. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24228. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24229. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24230. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24231. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24232. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24233. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24234. return material;
  24235. }
  24236. setTextures( value ) {
  24237. this.textures = value;
  24238. return this;
  24239. }
  24240. }
  24241. class LoaderUtils {
  24242. static decodeText( array ) {
  24243. if ( typeof TextDecoder !== 'undefined' ) {
  24244. return new TextDecoder().decode( array );
  24245. }
  24246. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24247. // throws a "maximum call stack size exceeded" error for large arrays.
  24248. let s = '';
  24249. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24250. // Implicitly assumes little-endian.
  24251. s += String.fromCharCode( array[ i ] );
  24252. }
  24253. try {
  24254. // merges multi-byte utf-8 characters.
  24255. return decodeURIComponent( escape( s ) );
  24256. } catch ( e ) { // see #16358
  24257. return s;
  24258. }
  24259. }
  24260. static extractUrlBase( url ) {
  24261. const index = url.lastIndexOf( '/' );
  24262. if ( index === - 1 ) return './';
  24263. return url.substr( 0, index + 1 );
  24264. }
  24265. static resolveURL( url, path ) {
  24266. // Invalid URL
  24267. if ( typeof url !== 'string' || url === '' ) return '';
  24268. // Host Relative URL
  24269. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24270. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24271. }
  24272. // Absolute URL http://,https://,//
  24273. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24274. // Data URI
  24275. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24276. // Blob URL
  24277. if ( /^blob:.*$/i.test( url ) ) return url;
  24278. // Relative URL
  24279. return path + url;
  24280. }
  24281. }
  24282. class InstancedBufferGeometry extends BufferGeometry {
  24283. constructor() {
  24284. super();
  24285. this.type = 'InstancedBufferGeometry';
  24286. this.instanceCount = Infinity;
  24287. }
  24288. copy( source ) {
  24289. super.copy( source );
  24290. this.instanceCount = source.instanceCount;
  24291. return this;
  24292. }
  24293. clone() {
  24294. return new this.constructor().copy( this );
  24295. }
  24296. toJSON() {
  24297. const data = super.toJSON( this );
  24298. data.instanceCount = this.instanceCount;
  24299. data.isInstancedBufferGeometry = true;
  24300. return data;
  24301. }
  24302. }
  24303. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24304. class BufferGeometryLoader extends Loader {
  24305. constructor( manager ) {
  24306. super( manager );
  24307. }
  24308. load( url, onLoad, onProgress, onError ) {
  24309. const scope = this;
  24310. const loader = new FileLoader( scope.manager );
  24311. loader.setPath( scope.path );
  24312. loader.setRequestHeader( scope.requestHeader );
  24313. loader.setWithCredentials( scope.withCredentials );
  24314. loader.load( url, function ( text ) {
  24315. try {
  24316. onLoad( scope.parse( JSON.parse( text ) ) );
  24317. } catch ( e ) {
  24318. if ( onError ) {
  24319. onError( e );
  24320. } else {
  24321. console.error( e );
  24322. }
  24323. scope.manager.itemError( url );
  24324. }
  24325. }, onProgress, onError );
  24326. }
  24327. parse( json ) {
  24328. const interleavedBufferMap = {};
  24329. const arrayBufferMap = {};
  24330. function getInterleavedBuffer( json, uuid ) {
  24331. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24332. const interleavedBuffers = json.interleavedBuffers;
  24333. const interleavedBuffer = interleavedBuffers[ uuid ];
  24334. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24335. const array = getTypedArray( interleavedBuffer.type, buffer );
  24336. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24337. ib.uuid = interleavedBuffer.uuid;
  24338. interleavedBufferMap[ uuid ] = ib;
  24339. return ib;
  24340. }
  24341. function getArrayBuffer( json, uuid ) {
  24342. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24343. const arrayBuffers = json.arrayBuffers;
  24344. const arrayBuffer = arrayBuffers[ uuid ];
  24345. const ab = new Uint32Array( arrayBuffer ).buffer;
  24346. arrayBufferMap[ uuid ] = ab;
  24347. return ab;
  24348. }
  24349. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24350. const index = json.data.index;
  24351. if ( index !== undefined ) {
  24352. const typedArray = getTypedArray( index.type, index.array );
  24353. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24354. }
  24355. const attributes = json.data.attributes;
  24356. for ( const key in attributes ) {
  24357. const attribute = attributes[ key ];
  24358. let bufferAttribute;
  24359. if ( attribute.isInterleavedBufferAttribute ) {
  24360. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24361. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24362. } else {
  24363. const typedArray = getTypedArray( attribute.type, attribute.array );
  24364. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24365. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24366. }
  24367. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24368. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24369. if ( attribute.updateRange !== undefined ) {
  24370. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24371. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24372. }
  24373. geometry.setAttribute( key, bufferAttribute );
  24374. }
  24375. const morphAttributes = json.data.morphAttributes;
  24376. if ( morphAttributes ) {
  24377. for ( const key in morphAttributes ) {
  24378. const attributeArray = morphAttributes[ key ];
  24379. const array = [];
  24380. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24381. const attribute = attributeArray[ i ];
  24382. let bufferAttribute;
  24383. if ( attribute.isInterleavedBufferAttribute ) {
  24384. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24385. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24386. } else {
  24387. const typedArray = getTypedArray( attribute.type, attribute.array );
  24388. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24389. }
  24390. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24391. array.push( bufferAttribute );
  24392. }
  24393. geometry.morphAttributes[ key ] = array;
  24394. }
  24395. }
  24396. const morphTargetsRelative = json.data.morphTargetsRelative;
  24397. if ( morphTargetsRelative ) {
  24398. geometry.morphTargetsRelative = true;
  24399. }
  24400. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24401. if ( groups !== undefined ) {
  24402. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24403. const group = groups[ i ];
  24404. geometry.addGroup( group.start, group.count, group.materialIndex );
  24405. }
  24406. }
  24407. const boundingSphere = json.data.boundingSphere;
  24408. if ( boundingSphere !== undefined ) {
  24409. const center = new Vector3();
  24410. if ( boundingSphere.center !== undefined ) {
  24411. center.fromArray( boundingSphere.center );
  24412. }
  24413. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24414. }
  24415. if ( json.name ) geometry.name = json.name;
  24416. if ( json.userData ) geometry.userData = json.userData;
  24417. return geometry;
  24418. }
  24419. }
  24420. class ObjectLoader extends Loader {
  24421. constructor( manager ) {
  24422. super( manager );
  24423. }
  24424. load( url, onLoad, onProgress, onError ) {
  24425. const scope = this;
  24426. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24427. this.resourcePath = this.resourcePath || path;
  24428. const loader = new FileLoader( this.manager );
  24429. loader.setPath( this.path );
  24430. loader.setRequestHeader( this.requestHeader );
  24431. loader.setWithCredentials( this.withCredentials );
  24432. loader.load( url, function ( text ) {
  24433. let json = null;
  24434. try {
  24435. json = JSON.parse( text );
  24436. } catch ( error ) {
  24437. if ( onError !== undefined ) onError( error );
  24438. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24439. return;
  24440. }
  24441. const metadata = json.metadata;
  24442. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24443. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24444. return;
  24445. }
  24446. scope.parse( json, onLoad );
  24447. }, onProgress, onError );
  24448. }
  24449. async loadAsync( url, onProgress ) {
  24450. const scope = this;
  24451. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24452. this.resourcePath = this.resourcePath || path;
  24453. const loader = new FileLoader( this.manager );
  24454. loader.setPath( this.path );
  24455. loader.setRequestHeader( this.requestHeader );
  24456. loader.setWithCredentials( this.withCredentials );
  24457. const text = await loader.loadAsync( url, onProgress );
  24458. const json = JSON.parse( text );
  24459. const metadata = json.metadata;
  24460. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24461. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24462. }
  24463. return await scope.parseAsync( json );
  24464. }
  24465. parse( json, onLoad ) {
  24466. const animations = this.parseAnimations( json.animations );
  24467. const shapes = this.parseShapes( json.shapes );
  24468. const geometries = this.parseGeometries( json.geometries, shapes );
  24469. const images = this.parseImages( json.images, function () {
  24470. if ( onLoad !== undefined ) onLoad( object );
  24471. } );
  24472. const textures = this.parseTextures( json.textures, images );
  24473. const materials = this.parseMaterials( json.materials, textures );
  24474. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24475. const skeletons = this.parseSkeletons( json.skeletons, object );
  24476. this.bindSkeletons( object, skeletons );
  24477. //
  24478. if ( onLoad !== undefined ) {
  24479. let hasImages = false;
  24480. for ( const uuid in images ) {
  24481. if ( images[ uuid ] instanceof HTMLImageElement ) {
  24482. hasImages = true;
  24483. break;
  24484. }
  24485. }
  24486. if ( hasImages === false ) onLoad( object );
  24487. }
  24488. return object;
  24489. }
  24490. async parseAsync( json ) {
  24491. const animations = this.parseAnimations( json.animations );
  24492. const shapes = this.parseShapes( json.shapes );
  24493. const geometries = this.parseGeometries( json.geometries, shapes );
  24494. const images = await this.parseImagesAsync( json.images );
  24495. const textures = this.parseTextures( json.textures, images );
  24496. const materials = this.parseMaterials( json.materials, textures );
  24497. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24498. const skeletons = this.parseSkeletons( json.skeletons, object );
  24499. this.bindSkeletons( object, skeletons );
  24500. return object;
  24501. }
  24502. parseShapes( json ) {
  24503. const shapes = {};
  24504. if ( json !== undefined ) {
  24505. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24506. const shape = new Shape().fromJSON( json[ i ] );
  24507. shapes[ shape.uuid ] = shape;
  24508. }
  24509. }
  24510. return shapes;
  24511. }
  24512. parseSkeletons( json, object ) {
  24513. const skeletons = {};
  24514. const bones = {};
  24515. // generate bone lookup table
  24516. object.traverse( function ( child ) {
  24517. if ( child.isBone ) bones[ child.uuid ] = child;
  24518. } );
  24519. // create skeletons
  24520. if ( json !== undefined ) {
  24521. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24522. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24523. skeletons[ skeleton.uuid ] = skeleton;
  24524. }
  24525. }
  24526. return skeletons;
  24527. }
  24528. parseGeometries( json, shapes ) {
  24529. const geometries = {};
  24530. if ( json !== undefined ) {
  24531. const bufferGeometryLoader = new BufferGeometryLoader();
  24532. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24533. let geometry;
  24534. const data = json[ i ];
  24535. switch ( data.type ) {
  24536. case 'BufferGeometry':
  24537. case 'InstancedBufferGeometry':
  24538. geometry = bufferGeometryLoader.parse( data );
  24539. break;
  24540. case 'Geometry':
  24541. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  24542. break;
  24543. default:
  24544. if ( data.type in Geometries ) {
  24545. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24546. } else {
  24547. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24548. }
  24549. }
  24550. geometry.uuid = data.uuid;
  24551. if ( data.name !== undefined ) geometry.name = data.name;
  24552. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24553. geometries[ data.uuid ] = geometry;
  24554. }
  24555. }
  24556. return geometries;
  24557. }
  24558. parseMaterials( json, textures ) {
  24559. const cache = {}; // MultiMaterial
  24560. const materials = {};
  24561. if ( json !== undefined ) {
  24562. const loader = new MaterialLoader();
  24563. loader.setTextures( textures );
  24564. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24565. const data = json[ i ];
  24566. if ( data.type === 'MultiMaterial' ) {
  24567. // Deprecated
  24568. const array = [];
  24569. for ( let j = 0; j < data.materials.length; j ++ ) {
  24570. const material = data.materials[ j ];
  24571. if ( cache[ material.uuid ] === undefined ) {
  24572. cache[ material.uuid ] = loader.parse( material );
  24573. }
  24574. array.push( cache[ material.uuid ] );
  24575. }
  24576. materials[ data.uuid ] = array;
  24577. } else {
  24578. if ( cache[ data.uuid ] === undefined ) {
  24579. cache[ data.uuid ] = loader.parse( data );
  24580. }
  24581. materials[ data.uuid ] = cache[ data.uuid ];
  24582. }
  24583. }
  24584. }
  24585. return materials;
  24586. }
  24587. parseAnimations( json ) {
  24588. const animations = {};
  24589. if ( json !== undefined ) {
  24590. for ( let i = 0; i < json.length; i ++ ) {
  24591. const data = json[ i ];
  24592. const clip = AnimationClip.parse( data );
  24593. animations[ clip.uuid ] = clip;
  24594. }
  24595. }
  24596. return animations;
  24597. }
  24598. parseImages( json, onLoad ) {
  24599. const scope = this;
  24600. const images = {};
  24601. let loader;
  24602. function loadImage( url ) {
  24603. scope.manager.itemStart( url );
  24604. return loader.load( url, function () {
  24605. scope.manager.itemEnd( url );
  24606. }, undefined, function () {
  24607. scope.manager.itemError( url );
  24608. scope.manager.itemEnd( url );
  24609. } );
  24610. }
  24611. function deserializeImage( image ) {
  24612. if ( typeof image === 'string' ) {
  24613. const url = image;
  24614. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24615. return loadImage( path );
  24616. } else {
  24617. if ( image.data ) {
  24618. return {
  24619. data: getTypedArray( image.type, image.data ),
  24620. width: image.width,
  24621. height: image.height
  24622. };
  24623. } else {
  24624. return null;
  24625. }
  24626. }
  24627. }
  24628. if ( json !== undefined && json.length > 0 ) {
  24629. const manager = new LoadingManager( onLoad );
  24630. loader = new ImageLoader( manager );
  24631. loader.setCrossOrigin( this.crossOrigin );
  24632. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24633. const image = json[ i ];
  24634. const url = image.url;
  24635. if ( Array.isArray( url ) ) {
  24636. // load array of images e.g CubeTexture
  24637. images[ image.uuid ] = [];
  24638. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24639. const currentUrl = url[ j ];
  24640. const deserializedImage = deserializeImage( currentUrl );
  24641. if ( deserializedImage !== null ) {
  24642. if ( deserializedImage instanceof HTMLImageElement ) {
  24643. images[ image.uuid ].push( deserializedImage );
  24644. } else {
  24645. // special case: handle array of data textures for cube textures
  24646. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24647. }
  24648. }
  24649. }
  24650. } else {
  24651. // load single image
  24652. const deserializedImage = deserializeImage( image.url );
  24653. if ( deserializedImage !== null ) {
  24654. images[ image.uuid ] = deserializedImage;
  24655. }
  24656. }
  24657. }
  24658. }
  24659. return images;
  24660. }
  24661. async parseImagesAsync( json ) {
  24662. const scope = this;
  24663. const images = {};
  24664. let loader;
  24665. async function deserializeImage( image ) {
  24666. if ( typeof image === 'string' ) {
  24667. const url = image;
  24668. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24669. return await loader.loadAsync( path );
  24670. } else {
  24671. if ( image.data ) {
  24672. return {
  24673. data: getTypedArray( image.type, image.data ),
  24674. width: image.width,
  24675. height: image.height
  24676. };
  24677. } else {
  24678. return null;
  24679. }
  24680. }
  24681. }
  24682. if ( json !== undefined && json.length > 0 ) {
  24683. loader = new ImageLoader( this.manager );
  24684. loader.setCrossOrigin( this.crossOrigin );
  24685. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24686. const image = json[ i ];
  24687. const url = image.url;
  24688. if ( Array.isArray( url ) ) {
  24689. // load array of images e.g CubeTexture
  24690. images[ image.uuid ] = [];
  24691. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24692. const currentUrl = url[ j ];
  24693. const deserializedImage = await deserializeImage( currentUrl );
  24694. if ( deserializedImage !== null ) {
  24695. if ( deserializedImage instanceof HTMLImageElement ) {
  24696. images[ image.uuid ].push( deserializedImage );
  24697. } else {
  24698. // special case: handle array of data textures for cube textures
  24699. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24700. }
  24701. }
  24702. }
  24703. } else {
  24704. // load single image
  24705. const deserializedImage = await deserializeImage( image.url );
  24706. if ( deserializedImage !== null ) {
  24707. images[ image.uuid ] = deserializedImage;
  24708. }
  24709. }
  24710. }
  24711. }
  24712. return images;
  24713. }
  24714. parseTextures( json, images ) {
  24715. function parseConstant( value, type ) {
  24716. if ( typeof value === 'number' ) return value;
  24717. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24718. return type[ value ];
  24719. }
  24720. const textures = {};
  24721. if ( json !== undefined ) {
  24722. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24723. const data = json[ i ];
  24724. if ( data.image === undefined ) {
  24725. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24726. }
  24727. if ( images[ data.image ] === undefined ) {
  24728. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24729. }
  24730. let texture;
  24731. const image = images[ data.image ];
  24732. if ( Array.isArray( image ) ) {
  24733. texture = new CubeTexture( image );
  24734. if ( image.length === 6 ) texture.needsUpdate = true;
  24735. } else {
  24736. if ( image && image.data ) {
  24737. texture = new DataTexture( image.data, image.width, image.height );
  24738. } else {
  24739. texture = new Texture( image );
  24740. }
  24741. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24742. }
  24743. texture.uuid = data.uuid;
  24744. if ( data.name !== undefined ) texture.name = data.name;
  24745. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24746. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24747. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24748. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24749. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24750. if ( data.wrap !== undefined ) {
  24751. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24752. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24753. }
  24754. if ( data.format !== undefined ) texture.format = data.format;
  24755. if ( data.type !== undefined ) texture.type = data.type;
  24756. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  24757. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24758. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24759. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24760. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24761. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24762. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24763. if ( data.userData !== undefined ) texture.userData = data.userData;
  24764. textures[ data.uuid ] = texture;
  24765. }
  24766. }
  24767. return textures;
  24768. }
  24769. parseObject( data, geometries, materials, textures, animations ) {
  24770. let object;
  24771. function getGeometry( name ) {
  24772. if ( geometries[ name ] === undefined ) {
  24773. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24774. }
  24775. return geometries[ name ];
  24776. }
  24777. function getMaterial( name ) {
  24778. if ( name === undefined ) return undefined;
  24779. if ( Array.isArray( name ) ) {
  24780. const array = [];
  24781. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24782. const uuid = name[ i ];
  24783. if ( materials[ uuid ] === undefined ) {
  24784. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24785. }
  24786. array.push( materials[ uuid ] );
  24787. }
  24788. return array;
  24789. }
  24790. if ( materials[ name ] === undefined ) {
  24791. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24792. }
  24793. return materials[ name ];
  24794. }
  24795. function getTexture( uuid ) {
  24796. if ( textures[ uuid ] === undefined ) {
  24797. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  24798. }
  24799. return textures[ uuid ];
  24800. }
  24801. let geometry, material;
  24802. switch ( data.type ) {
  24803. case 'Scene':
  24804. object = new Scene();
  24805. if ( data.background !== undefined ) {
  24806. if ( Number.isInteger( data.background ) ) {
  24807. object.background = new Color( data.background );
  24808. } else {
  24809. object.background = getTexture( data.background );
  24810. }
  24811. }
  24812. if ( data.environment !== undefined ) {
  24813. object.environment = getTexture( data.environment );
  24814. }
  24815. if ( data.fog !== undefined ) {
  24816. if ( data.fog.type === 'Fog' ) {
  24817. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24818. } else if ( data.fog.type === 'FogExp2' ) {
  24819. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24820. }
  24821. }
  24822. break;
  24823. case 'PerspectiveCamera':
  24824. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24825. if ( data.focus !== undefined ) object.focus = data.focus;
  24826. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24827. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24828. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24829. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24830. break;
  24831. case 'OrthographicCamera':
  24832. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24833. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24834. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24835. break;
  24836. case 'AmbientLight':
  24837. object = new AmbientLight( data.color, data.intensity );
  24838. break;
  24839. case 'DirectionalLight':
  24840. object = new DirectionalLight( data.color, data.intensity );
  24841. break;
  24842. case 'PointLight':
  24843. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24844. break;
  24845. case 'RectAreaLight':
  24846. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24847. break;
  24848. case 'SpotLight':
  24849. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24850. break;
  24851. case 'HemisphereLight':
  24852. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24853. break;
  24854. case 'LightProbe':
  24855. object = new LightProbe().fromJSON( data );
  24856. break;
  24857. case 'SkinnedMesh':
  24858. geometry = getGeometry( data.geometry );
  24859. material = getMaterial( data.material );
  24860. object = new SkinnedMesh( geometry, material );
  24861. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24862. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24863. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24864. break;
  24865. case 'Mesh':
  24866. geometry = getGeometry( data.geometry );
  24867. material = getMaterial( data.material );
  24868. object = new Mesh( geometry, material );
  24869. break;
  24870. case 'InstancedMesh':
  24871. geometry = getGeometry( data.geometry );
  24872. material = getMaterial( data.material );
  24873. const count = data.count;
  24874. const instanceMatrix = data.instanceMatrix;
  24875. const instanceColor = data.instanceColor;
  24876. object = new InstancedMesh( geometry, material, count );
  24877. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24878. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  24879. break;
  24880. case 'LOD':
  24881. object = new LOD();
  24882. break;
  24883. case 'Line':
  24884. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  24885. break;
  24886. case 'LineLoop':
  24887. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  24888. break;
  24889. case 'LineSegments':
  24890. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24891. break;
  24892. case 'PointCloud':
  24893. case 'Points':
  24894. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24895. break;
  24896. case 'Sprite':
  24897. object = new Sprite( getMaterial( data.material ) );
  24898. break;
  24899. case 'Group':
  24900. object = new Group();
  24901. break;
  24902. case 'Bone':
  24903. object = new Bone();
  24904. break;
  24905. default:
  24906. object = new Object3D();
  24907. }
  24908. object.uuid = data.uuid;
  24909. if ( data.name !== undefined ) object.name = data.name;
  24910. if ( data.matrix !== undefined ) {
  24911. object.matrix.fromArray( data.matrix );
  24912. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24913. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  24914. } else {
  24915. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24916. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24917. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24918. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24919. }
  24920. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24921. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24922. if ( data.shadow ) {
  24923. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24924. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  24925. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24926. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24927. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24928. }
  24929. if ( data.visible !== undefined ) object.visible = data.visible;
  24930. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  24931. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  24932. if ( data.userData !== undefined ) object.userData = data.userData;
  24933. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  24934. if ( data.children !== undefined ) {
  24935. const children = data.children;
  24936. for ( let i = 0; i < children.length; i ++ ) {
  24937. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  24938. }
  24939. }
  24940. if ( data.animations !== undefined ) {
  24941. const objectAnimations = data.animations;
  24942. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  24943. const uuid = objectAnimations[ i ];
  24944. object.animations.push( animations[ uuid ] );
  24945. }
  24946. }
  24947. if ( data.type === 'LOD' ) {
  24948. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  24949. const levels = data.levels;
  24950. for ( let l = 0; l < levels.length; l ++ ) {
  24951. const level = levels[ l ];
  24952. const child = object.getObjectByProperty( 'uuid', level.object );
  24953. if ( child !== undefined ) {
  24954. object.addLevel( child, level.distance );
  24955. }
  24956. }
  24957. }
  24958. return object;
  24959. }
  24960. bindSkeletons( object, skeletons ) {
  24961. if ( Object.keys( skeletons ).length === 0 ) return;
  24962. object.traverse( function ( child ) {
  24963. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  24964. const skeleton = skeletons[ child.skeleton ];
  24965. if ( skeleton === undefined ) {
  24966. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  24967. } else {
  24968. child.bind( skeleton, child.bindMatrix );
  24969. }
  24970. }
  24971. } );
  24972. }
  24973. /* DEPRECATED */
  24974. setTexturePath( value ) {
  24975. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  24976. return this.setResourcePath( value );
  24977. }
  24978. }
  24979. const TEXTURE_MAPPING = {
  24980. UVMapping: UVMapping,
  24981. CubeReflectionMapping: CubeReflectionMapping,
  24982. CubeRefractionMapping: CubeRefractionMapping,
  24983. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24984. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24985. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24986. CubeUVRefractionMapping: CubeUVRefractionMapping
  24987. };
  24988. const TEXTURE_WRAPPING = {
  24989. RepeatWrapping: RepeatWrapping,
  24990. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24991. MirroredRepeatWrapping: MirroredRepeatWrapping
  24992. };
  24993. const TEXTURE_FILTER = {
  24994. NearestFilter: NearestFilter,
  24995. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24996. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24997. LinearFilter: LinearFilter,
  24998. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24999. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25000. };
  25001. class ImageBitmapLoader extends Loader {
  25002. constructor( manager ) {
  25003. super( manager );
  25004. if ( typeof createImageBitmap === 'undefined' ) {
  25005. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25006. }
  25007. if ( typeof fetch === 'undefined' ) {
  25008. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25009. }
  25010. this.options = { premultiplyAlpha: 'none' };
  25011. }
  25012. setOptions( options ) {
  25013. this.options = options;
  25014. return this;
  25015. }
  25016. load( url, onLoad, onProgress, onError ) {
  25017. if ( url === undefined ) url = '';
  25018. if ( this.path !== undefined ) url = this.path + url;
  25019. url = this.manager.resolveURL( url );
  25020. const scope = this;
  25021. const cached = Cache.get( url );
  25022. if ( cached !== undefined ) {
  25023. scope.manager.itemStart( url );
  25024. setTimeout( function () {
  25025. if ( onLoad ) onLoad( cached );
  25026. scope.manager.itemEnd( url );
  25027. }, 0 );
  25028. return cached;
  25029. }
  25030. const fetchOptions = {};
  25031. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25032. fetchOptions.headers = this.requestHeader;
  25033. fetch( url, fetchOptions ).then( function ( res ) {
  25034. return res.blob();
  25035. } ).then( function ( blob ) {
  25036. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25037. } ).then( function ( imageBitmap ) {
  25038. Cache.add( url, imageBitmap );
  25039. if ( onLoad ) onLoad( imageBitmap );
  25040. scope.manager.itemEnd( url );
  25041. } ).catch( function ( e ) {
  25042. if ( onError ) onError( e );
  25043. scope.manager.itemError( url );
  25044. scope.manager.itemEnd( url );
  25045. } );
  25046. scope.manager.itemStart( url );
  25047. }
  25048. }
  25049. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  25050. let _context;
  25051. const AudioContext = {
  25052. getContext: function () {
  25053. if ( _context === undefined ) {
  25054. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25055. }
  25056. return _context;
  25057. },
  25058. setContext: function ( value ) {
  25059. _context = value;
  25060. }
  25061. };
  25062. class AudioLoader extends Loader {
  25063. constructor( manager ) {
  25064. super( manager );
  25065. }
  25066. load( url, onLoad, onProgress, onError ) {
  25067. const scope = this;
  25068. const loader = new FileLoader( this.manager );
  25069. loader.setResponseType( 'arraybuffer' );
  25070. loader.setPath( this.path );
  25071. loader.setRequestHeader( this.requestHeader );
  25072. loader.setWithCredentials( this.withCredentials );
  25073. loader.load( url, function ( buffer ) {
  25074. try {
  25075. // Create a copy of the buffer. The `decodeAudioData` method
  25076. // detaches the buffer when complete, preventing reuse.
  25077. const bufferCopy = buffer.slice( 0 );
  25078. const context = AudioContext.getContext();
  25079. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25080. onLoad( audioBuffer );
  25081. } );
  25082. } catch ( e ) {
  25083. if ( onError ) {
  25084. onError( e );
  25085. } else {
  25086. console.error( e );
  25087. }
  25088. scope.manager.itemError( url );
  25089. }
  25090. }, onProgress, onError );
  25091. }
  25092. }
  25093. class HemisphereLightProbe extends LightProbe {
  25094. constructor( skyColor, groundColor, intensity = 1 ) {
  25095. super( undefined, intensity );
  25096. const color1 = new Color().set( skyColor );
  25097. const color2 = new Color().set( groundColor );
  25098. const sky = new Vector3( color1.r, color1.g, color1.b );
  25099. const ground = new Vector3( color2.r, color2.g, color2.b );
  25100. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25101. const c0 = Math.sqrt( Math.PI );
  25102. const c1 = c0 * Math.sqrt( 0.75 );
  25103. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25104. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25105. }
  25106. }
  25107. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  25108. class AmbientLightProbe extends LightProbe {
  25109. constructor( color, intensity = 1 ) {
  25110. super( undefined, intensity );
  25111. const color1 = new Color().set( color );
  25112. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25113. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25114. }
  25115. }
  25116. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  25117. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25118. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25119. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25120. class StereoCamera {
  25121. constructor() {
  25122. this.type = 'StereoCamera';
  25123. this.aspect = 1;
  25124. this.eyeSep = 0.064;
  25125. this.cameraL = new PerspectiveCamera();
  25126. this.cameraL.layers.enable( 1 );
  25127. this.cameraL.matrixAutoUpdate = false;
  25128. this.cameraR = new PerspectiveCamera();
  25129. this.cameraR.layers.enable( 2 );
  25130. this.cameraR.matrixAutoUpdate = false;
  25131. this._cache = {
  25132. focus: null,
  25133. fov: null,
  25134. aspect: null,
  25135. near: null,
  25136. far: null,
  25137. zoom: null,
  25138. eyeSep: null
  25139. };
  25140. }
  25141. update( camera ) {
  25142. const cache = this._cache;
  25143. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25144. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25145. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25146. if ( needsUpdate ) {
  25147. cache.focus = camera.focus;
  25148. cache.fov = camera.fov;
  25149. cache.aspect = camera.aspect * this.aspect;
  25150. cache.near = camera.near;
  25151. cache.far = camera.far;
  25152. cache.zoom = camera.zoom;
  25153. cache.eyeSep = this.eyeSep;
  25154. // Off-axis stereoscopic effect based on
  25155. // http://paulbourke.net/stereographics/stereorender/
  25156. _projectionMatrix.copy( camera.projectionMatrix );
  25157. const eyeSepHalf = cache.eyeSep / 2;
  25158. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25159. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25160. let xmin, xmax;
  25161. // translate xOffset
  25162. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25163. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25164. // for left eye
  25165. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25166. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25167. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25168. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25169. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25170. // for right eye
  25171. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25172. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25173. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25174. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25175. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25176. }
  25177. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25178. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25179. }
  25180. }
  25181. class Clock {
  25182. constructor( autoStart = true ) {
  25183. this.autoStart = autoStart;
  25184. this.startTime = 0;
  25185. this.oldTime = 0;
  25186. this.elapsedTime = 0;
  25187. this.running = false;
  25188. }
  25189. start() {
  25190. this.startTime = now();
  25191. this.oldTime = this.startTime;
  25192. this.elapsedTime = 0;
  25193. this.running = true;
  25194. }
  25195. stop() {
  25196. this.getElapsedTime();
  25197. this.running = false;
  25198. this.autoStart = false;
  25199. }
  25200. getElapsedTime() {
  25201. this.getDelta();
  25202. return this.elapsedTime;
  25203. }
  25204. getDelta() {
  25205. let diff = 0;
  25206. if ( this.autoStart && ! this.running ) {
  25207. this.start();
  25208. return 0;
  25209. }
  25210. if ( this.running ) {
  25211. const newTime = now();
  25212. diff = ( newTime - this.oldTime ) / 1000;
  25213. this.oldTime = newTime;
  25214. this.elapsedTime += diff;
  25215. }
  25216. return diff;
  25217. }
  25218. }
  25219. function now() {
  25220. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25221. }
  25222. const _position$1 = /*@__PURE__*/ new Vector3();
  25223. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25224. const _scale$1 = /*@__PURE__*/ new Vector3();
  25225. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25226. class AudioListener extends Object3D {
  25227. constructor() {
  25228. super();
  25229. this.type = 'AudioListener';
  25230. this.context = AudioContext.getContext();
  25231. this.gain = this.context.createGain();
  25232. this.gain.connect( this.context.destination );
  25233. this.filter = null;
  25234. this.timeDelta = 0;
  25235. // private
  25236. this._clock = new Clock();
  25237. }
  25238. getInput() {
  25239. return this.gain;
  25240. }
  25241. removeFilter() {
  25242. if ( this.filter !== null ) {
  25243. this.gain.disconnect( this.filter );
  25244. this.filter.disconnect( this.context.destination );
  25245. this.gain.connect( this.context.destination );
  25246. this.filter = null;
  25247. }
  25248. return this;
  25249. }
  25250. getFilter() {
  25251. return this.filter;
  25252. }
  25253. setFilter( value ) {
  25254. if ( this.filter !== null ) {
  25255. this.gain.disconnect( this.filter );
  25256. this.filter.disconnect( this.context.destination );
  25257. } else {
  25258. this.gain.disconnect( this.context.destination );
  25259. }
  25260. this.filter = value;
  25261. this.gain.connect( this.filter );
  25262. this.filter.connect( this.context.destination );
  25263. return this;
  25264. }
  25265. getMasterVolume() {
  25266. return this.gain.gain.value;
  25267. }
  25268. setMasterVolume( value ) {
  25269. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25270. return this;
  25271. }
  25272. updateMatrixWorld( force ) {
  25273. super.updateMatrixWorld( force );
  25274. const listener = this.context.listener;
  25275. const up = this.up;
  25276. this.timeDelta = this._clock.getDelta();
  25277. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25278. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25279. if ( listener.positionX ) {
  25280. // code path for Chrome (see #14393)
  25281. const endTime = this.context.currentTime + this.timeDelta;
  25282. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25283. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25284. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25285. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25286. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25287. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25288. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25289. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25290. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25291. } else {
  25292. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25293. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25294. }
  25295. }
  25296. }
  25297. class Audio extends Object3D {
  25298. constructor( listener ) {
  25299. super();
  25300. this.type = 'Audio';
  25301. this.listener = listener;
  25302. this.context = listener.context;
  25303. this.gain = this.context.createGain();
  25304. this.gain.connect( listener.getInput() );
  25305. this.autoplay = false;
  25306. this.buffer = null;
  25307. this.detune = 0;
  25308. this.loop = false;
  25309. this.loopStart = 0;
  25310. this.loopEnd = 0;
  25311. this.offset = 0;
  25312. this.duration = undefined;
  25313. this.playbackRate = 1;
  25314. this.isPlaying = false;
  25315. this.hasPlaybackControl = true;
  25316. this.source = null;
  25317. this.sourceType = 'empty';
  25318. this._startedAt = 0;
  25319. this._progress = 0;
  25320. this._connected = false;
  25321. this.filters = [];
  25322. }
  25323. getOutput() {
  25324. return this.gain;
  25325. }
  25326. setNodeSource( audioNode ) {
  25327. this.hasPlaybackControl = false;
  25328. this.sourceType = 'audioNode';
  25329. this.source = audioNode;
  25330. this.connect();
  25331. return this;
  25332. }
  25333. setMediaElementSource( mediaElement ) {
  25334. this.hasPlaybackControl = false;
  25335. this.sourceType = 'mediaNode';
  25336. this.source = this.context.createMediaElementSource( mediaElement );
  25337. this.connect();
  25338. return this;
  25339. }
  25340. setMediaStreamSource( mediaStream ) {
  25341. this.hasPlaybackControl = false;
  25342. this.sourceType = 'mediaStreamNode';
  25343. this.source = this.context.createMediaStreamSource( mediaStream );
  25344. this.connect();
  25345. return this;
  25346. }
  25347. setBuffer( audioBuffer ) {
  25348. this.buffer = audioBuffer;
  25349. this.sourceType = 'buffer';
  25350. if ( this.autoplay ) this.play();
  25351. return this;
  25352. }
  25353. play( delay = 0 ) {
  25354. if ( this.isPlaying === true ) {
  25355. console.warn( 'THREE.Audio: Audio is already playing.' );
  25356. return;
  25357. }
  25358. if ( this.hasPlaybackControl === false ) {
  25359. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25360. return;
  25361. }
  25362. this._startedAt = this.context.currentTime + delay;
  25363. const source = this.context.createBufferSource();
  25364. source.buffer = this.buffer;
  25365. source.loop = this.loop;
  25366. source.loopStart = this.loopStart;
  25367. source.loopEnd = this.loopEnd;
  25368. source.onended = this.onEnded.bind( this );
  25369. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25370. this.isPlaying = true;
  25371. this.source = source;
  25372. this.setDetune( this.detune );
  25373. this.setPlaybackRate( this.playbackRate );
  25374. return this.connect();
  25375. }
  25376. pause() {
  25377. if ( this.hasPlaybackControl === false ) {
  25378. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25379. return;
  25380. }
  25381. if ( this.isPlaying === true ) {
  25382. // update current progress
  25383. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25384. if ( this.loop === true ) {
  25385. // ensure _progress does not exceed duration with looped audios
  25386. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25387. }
  25388. this.source.stop();
  25389. this.source.onended = null;
  25390. this.isPlaying = false;
  25391. }
  25392. return this;
  25393. }
  25394. stop() {
  25395. if ( this.hasPlaybackControl === false ) {
  25396. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25397. return;
  25398. }
  25399. this._progress = 0;
  25400. this.source.stop();
  25401. this.source.onended = null;
  25402. this.isPlaying = false;
  25403. return this;
  25404. }
  25405. connect() {
  25406. if ( this.filters.length > 0 ) {
  25407. this.source.connect( this.filters[ 0 ] );
  25408. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25409. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25410. }
  25411. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25412. } else {
  25413. this.source.connect( this.getOutput() );
  25414. }
  25415. this._connected = true;
  25416. return this;
  25417. }
  25418. disconnect() {
  25419. if ( this.filters.length > 0 ) {
  25420. this.source.disconnect( this.filters[ 0 ] );
  25421. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25422. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25423. }
  25424. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25425. } else {
  25426. this.source.disconnect( this.getOutput() );
  25427. }
  25428. this._connected = false;
  25429. return this;
  25430. }
  25431. getFilters() {
  25432. return this.filters;
  25433. }
  25434. setFilters( value ) {
  25435. if ( ! value ) value = [];
  25436. if ( this._connected === true ) {
  25437. this.disconnect();
  25438. this.filters = value.slice();
  25439. this.connect();
  25440. } else {
  25441. this.filters = value.slice();
  25442. }
  25443. return this;
  25444. }
  25445. setDetune( value ) {
  25446. this.detune = value;
  25447. if ( this.source.detune === undefined ) return; // only set detune when available
  25448. if ( this.isPlaying === true ) {
  25449. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25450. }
  25451. return this;
  25452. }
  25453. getDetune() {
  25454. return this.detune;
  25455. }
  25456. getFilter() {
  25457. return this.getFilters()[ 0 ];
  25458. }
  25459. setFilter( filter ) {
  25460. return this.setFilters( filter ? [ filter ] : [] );
  25461. }
  25462. setPlaybackRate( value ) {
  25463. if ( this.hasPlaybackControl === false ) {
  25464. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25465. return;
  25466. }
  25467. this.playbackRate = value;
  25468. if ( this.isPlaying === true ) {
  25469. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25470. }
  25471. return this;
  25472. }
  25473. getPlaybackRate() {
  25474. return this.playbackRate;
  25475. }
  25476. onEnded() {
  25477. this.isPlaying = false;
  25478. }
  25479. getLoop() {
  25480. if ( this.hasPlaybackControl === false ) {
  25481. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25482. return false;
  25483. }
  25484. return this.loop;
  25485. }
  25486. setLoop( value ) {
  25487. if ( this.hasPlaybackControl === false ) {
  25488. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25489. return;
  25490. }
  25491. this.loop = value;
  25492. if ( this.isPlaying === true ) {
  25493. this.source.loop = this.loop;
  25494. }
  25495. return this;
  25496. }
  25497. setLoopStart( value ) {
  25498. this.loopStart = value;
  25499. return this;
  25500. }
  25501. setLoopEnd( value ) {
  25502. this.loopEnd = value;
  25503. return this;
  25504. }
  25505. getVolume() {
  25506. return this.gain.gain.value;
  25507. }
  25508. setVolume( value ) {
  25509. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25510. return this;
  25511. }
  25512. }
  25513. const _position = /*@__PURE__*/ new Vector3();
  25514. const _quaternion = /*@__PURE__*/ new Quaternion();
  25515. const _scale = /*@__PURE__*/ new Vector3();
  25516. const _orientation = /*@__PURE__*/ new Vector3();
  25517. class PositionalAudio extends Audio {
  25518. constructor( listener ) {
  25519. super( listener );
  25520. this.panner = this.context.createPanner();
  25521. this.panner.panningModel = 'HRTF';
  25522. this.panner.connect( this.gain );
  25523. }
  25524. getOutput() {
  25525. return this.panner;
  25526. }
  25527. getRefDistance() {
  25528. return this.panner.refDistance;
  25529. }
  25530. setRefDistance( value ) {
  25531. this.panner.refDistance = value;
  25532. return this;
  25533. }
  25534. getRolloffFactor() {
  25535. return this.panner.rolloffFactor;
  25536. }
  25537. setRolloffFactor( value ) {
  25538. this.panner.rolloffFactor = value;
  25539. return this;
  25540. }
  25541. getDistanceModel() {
  25542. return this.panner.distanceModel;
  25543. }
  25544. setDistanceModel( value ) {
  25545. this.panner.distanceModel = value;
  25546. return this;
  25547. }
  25548. getMaxDistance() {
  25549. return this.panner.maxDistance;
  25550. }
  25551. setMaxDistance( value ) {
  25552. this.panner.maxDistance = value;
  25553. return this;
  25554. }
  25555. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25556. this.panner.coneInnerAngle = coneInnerAngle;
  25557. this.panner.coneOuterAngle = coneOuterAngle;
  25558. this.panner.coneOuterGain = coneOuterGain;
  25559. return this;
  25560. }
  25561. updateMatrixWorld( force ) {
  25562. super.updateMatrixWorld( force );
  25563. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25564. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25565. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25566. const panner = this.panner;
  25567. if ( panner.positionX ) {
  25568. // code path for Chrome and Firefox (see #14393)
  25569. const endTime = this.context.currentTime + this.listener.timeDelta;
  25570. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25571. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25572. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25573. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25574. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25575. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25576. } else {
  25577. panner.setPosition( _position.x, _position.y, _position.z );
  25578. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25579. }
  25580. }
  25581. }
  25582. class AudioAnalyser {
  25583. constructor( audio, fftSize = 2048 ) {
  25584. this.analyser = audio.context.createAnalyser();
  25585. this.analyser.fftSize = fftSize;
  25586. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25587. audio.getOutput().connect( this.analyser );
  25588. }
  25589. getFrequencyData() {
  25590. this.analyser.getByteFrequencyData( this.data );
  25591. return this.data;
  25592. }
  25593. getAverageFrequency() {
  25594. let value = 0;
  25595. const data = this.getFrequencyData();
  25596. for ( let i = 0; i < data.length; i ++ ) {
  25597. value += data[ i ];
  25598. }
  25599. return value / data.length;
  25600. }
  25601. }
  25602. class PropertyMixer {
  25603. constructor( binding, typeName, valueSize ) {
  25604. this.binding = binding;
  25605. this.valueSize = valueSize;
  25606. let mixFunction,
  25607. mixFunctionAdditive,
  25608. setIdentity;
  25609. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25610. //
  25611. // interpolators can use .buffer as their .result
  25612. // the data then goes to 'incoming'
  25613. //
  25614. // 'accu0' and 'accu1' are used frame-interleaved for
  25615. // the cumulative result and are compared to detect
  25616. // changes
  25617. //
  25618. // 'orig' stores the original state of the property
  25619. //
  25620. // 'add' is used for additive cumulative results
  25621. //
  25622. // 'work' is optional and is only present for quaternion types. It is used
  25623. // to store intermediate quaternion multiplication results
  25624. switch ( typeName ) {
  25625. case 'quaternion':
  25626. mixFunction = this._slerp;
  25627. mixFunctionAdditive = this._slerpAdditive;
  25628. setIdentity = this._setAdditiveIdentityQuaternion;
  25629. this.buffer = new Float64Array( valueSize * 6 );
  25630. this._workIndex = 5;
  25631. break;
  25632. case 'string':
  25633. case 'bool':
  25634. mixFunction = this._select;
  25635. // Use the regular mix function and for additive on these types,
  25636. // additive is not relevant for non-numeric types
  25637. mixFunctionAdditive = this._select;
  25638. setIdentity = this._setAdditiveIdentityOther;
  25639. this.buffer = new Array( valueSize * 5 );
  25640. break;
  25641. default:
  25642. mixFunction = this._lerp;
  25643. mixFunctionAdditive = this._lerpAdditive;
  25644. setIdentity = this._setAdditiveIdentityNumeric;
  25645. this.buffer = new Float64Array( valueSize * 5 );
  25646. }
  25647. this._mixBufferRegion = mixFunction;
  25648. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25649. this._setIdentity = setIdentity;
  25650. this._origIndex = 3;
  25651. this._addIndex = 4;
  25652. this.cumulativeWeight = 0;
  25653. this.cumulativeWeightAdditive = 0;
  25654. this.useCount = 0;
  25655. this.referenceCount = 0;
  25656. }
  25657. // accumulate data in the 'incoming' region into 'accu<i>'
  25658. accumulate( accuIndex, weight ) {
  25659. // note: happily accumulating nothing when weight = 0, the caller knows
  25660. // the weight and shouldn't have made the call in the first place
  25661. const buffer = this.buffer,
  25662. stride = this.valueSize,
  25663. offset = accuIndex * stride + stride;
  25664. let currentWeight = this.cumulativeWeight;
  25665. if ( currentWeight === 0 ) {
  25666. // accuN := incoming * weight
  25667. for ( let i = 0; i !== stride; ++ i ) {
  25668. buffer[ offset + i ] = buffer[ i ];
  25669. }
  25670. currentWeight = weight;
  25671. } else {
  25672. // accuN := accuN + incoming * weight
  25673. currentWeight += weight;
  25674. const mix = weight / currentWeight;
  25675. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25676. }
  25677. this.cumulativeWeight = currentWeight;
  25678. }
  25679. // accumulate data in the 'incoming' region into 'add'
  25680. accumulateAdditive( weight ) {
  25681. const buffer = this.buffer,
  25682. stride = this.valueSize,
  25683. offset = stride * this._addIndex;
  25684. if ( this.cumulativeWeightAdditive === 0 ) {
  25685. // add = identity
  25686. this._setIdentity();
  25687. }
  25688. // add := add + incoming * weight
  25689. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25690. this.cumulativeWeightAdditive += weight;
  25691. }
  25692. // apply the state of 'accu<i>' to the binding when accus differ
  25693. apply( accuIndex ) {
  25694. const stride = this.valueSize,
  25695. buffer = this.buffer,
  25696. offset = accuIndex * stride + stride,
  25697. weight = this.cumulativeWeight,
  25698. weightAdditive = this.cumulativeWeightAdditive,
  25699. binding = this.binding;
  25700. this.cumulativeWeight = 0;
  25701. this.cumulativeWeightAdditive = 0;
  25702. if ( weight < 1 ) {
  25703. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25704. const originalValueOffset = stride * this._origIndex;
  25705. this._mixBufferRegion(
  25706. buffer, offset, originalValueOffset, 1 - weight, stride );
  25707. }
  25708. if ( weightAdditive > 0 ) {
  25709. // accuN := accuN + additive accuN
  25710. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25711. }
  25712. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25713. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25714. // value has changed -> update scene graph
  25715. binding.setValue( buffer, offset );
  25716. break;
  25717. }
  25718. }
  25719. }
  25720. // remember the state of the bound property and copy it to both accus
  25721. saveOriginalState() {
  25722. const binding = this.binding;
  25723. const buffer = this.buffer,
  25724. stride = this.valueSize,
  25725. originalValueOffset = stride * this._origIndex;
  25726. binding.getValue( buffer, originalValueOffset );
  25727. // accu[0..1] := orig -- initially detect changes against the original
  25728. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25729. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25730. }
  25731. // Add to identity for additive
  25732. this._setIdentity();
  25733. this.cumulativeWeight = 0;
  25734. this.cumulativeWeightAdditive = 0;
  25735. }
  25736. // apply the state previously taken via 'saveOriginalState' to the binding
  25737. restoreOriginalState() {
  25738. const originalValueOffset = this.valueSize * 3;
  25739. this.binding.setValue( this.buffer, originalValueOffset );
  25740. }
  25741. _setAdditiveIdentityNumeric() {
  25742. const startIndex = this._addIndex * this.valueSize;
  25743. const endIndex = startIndex + this.valueSize;
  25744. for ( let i = startIndex; i < endIndex; i ++ ) {
  25745. this.buffer[ i ] = 0;
  25746. }
  25747. }
  25748. _setAdditiveIdentityQuaternion() {
  25749. this._setAdditiveIdentityNumeric();
  25750. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  25751. }
  25752. _setAdditiveIdentityOther() {
  25753. const startIndex = this._origIndex * this.valueSize;
  25754. const targetIndex = this._addIndex * this.valueSize;
  25755. for ( let i = 0; i < this.valueSize; i ++ ) {
  25756. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  25757. }
  25758. }
  25759. // mix functions
  25760. _select( buffer, dstOffset, srcOffset, t, stride ) {
  25761. if ( t >= 0.5 ) {
  25762. for ( let i = 0; i !== stride; ++ i ) {
  25763. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  25764. }
  25765. }
  25766. }
  25767. _slerp( buffer, dstOffset, srcOffset, t ) {
  25768. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  25769. }
  25770. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25771. const workOffset = this._workIndex * stride;
  25772. // Store result in intermediate buffer offset
  25773. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  25774. // Slerp to the intermediate result
  25775. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  25776. }
  25777. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  25778. const s = 1 - t;
  25779. for ( let i = 0; i !== stride; ++ i ) {
  25780. const j = dstOffset + i;
  25781. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  25782. }
  25783. }
  25784. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25785. for ( let i = 0; i !== stride; ++ i ) {
  25786. const j = dstOffset + i;
  25787. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  25788. }
  25789. }
  25790. }
  25791. // Characters [].:/ are reserved for track binding syntax.
  25792. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25793. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  25794. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25795. // only latin characters, and the unicode \p{L} is not yet supported. So
  25796. // instead, we exclude reserved characters and match everything else.
  25797. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25798. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  25799. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25800. // be matched to parse the rest of the track name.
  25801. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  25802. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25803. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  25804. // Object on target node, and accessor. May not contain reserved
  25805. // characters. Accessor may contain any character except closing bracket.
  25806. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  25807. // Property and accessor. May not contain reserved characters. Accessor may
  25808. // contain any non-bracket characters.
  25809. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  25810. const _trackRe = new RegExp( ''
  25811. + '^'
  25812. + _directoryRe
  25813. + _nodeRe
  25814. + _objectRe
  25815. + _propertyRe
  25816. + '$'
  25817. );
  25818. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  25819. class Composite {
  25820. constructor( targetGroup, path, optionalParsedPath ) {
  25821. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  25822. this._targetGroup = targetGroup;
  25823. this._bindings = targetGroup.subscribe_( path, parsedPath );
  25824. }
  25825. getValue( array, offset ) {
  25826. this.bind(); // bind all binding
  25827. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25828. binding = this._bindings[ firstValidIndex ];
  25829. // and only call .getValue on the first
  25830. if ( binding !== undefined ) binding.getValue( array, offset );
  25831. }
  25832. setValue( array, offset ) {
  25833. const bindings = this._bindings;
  25834. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25835. bindings[ i ].setValue( array, offset );
  25836. }
  25837. }
  25838. bind() {
  25839. const bindings = this._bindings;
  25840. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25841. bindings[ i ].bind();
  25842. }
  25843. }
  25844. unbind() {
  25845. const bindings = this._bindings;
  25846. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25847. bindings[ i ].unbind();
  25848. }
  25849. }
  25850. }
  25851. // Note: This class uses a State pattern on a per-method basis:
  25852. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25853. // prototype version of these methods with one that represents
  25854. // the bound state. When the property is not found, the methods
  25855. // become no-ops.
  25856. class PropertyBinding {
  25857. constructor( rootNode, path, parsedPath ) {
  25858. this.path = path;
  25859. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  25860. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  25861. this.rootNode = rootNode;
  25862. // initial state of these methods that calls 'bind'
  25863. this.getValue = this._getValue_unbound;
  25864. this.setValue = this._setValue_unbound;
  25865. }
  25866. static create( root, path, parsedPath ) {
  25867. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  25868. return new PropertyBinding( root, path, parsedPath );
  25869. } else {
  25870. return new PropertyBinding.Composite( root, path, parsedPath );
  25871. }
  25872. }
  25873. /**
  25874. * Replaces spaces with underscores and removes unsupported characters from
  25875. * node names, to ensure compatibility with parseTrackName().
  25876. *
  25877. * @param {string} name Node name to be sanitized.
  25878. * @return {string}
  25879. */
  25880. static sanitizeNodeName( name ) {
  25881. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  25882. }
  25883. static parseTrackName( trackName ) {
  25884. const matches = _trackRe.exec( trackName );
  25885. if ( ! matches ) {
  25886. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  25887. }
  25888. const results = {
  25889. // directoryName: matches[ 1 ], // (tschw) currently unused
  25890. nodeName: matches[ 2 ],
  25891. objectName: matches[ 3 ],
  25892. objectIndex: matches[ 4 ],
  25893. propertyName: matches[ 5 ], // required
  25894. propertyIndex: matches[ 6 ]
  25895. };
  25896. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  25897. if ( lastDot !== undefined && lastDot !== - 1 ) {
  25898. const objectName = results.nodeName.substring( lastDot + 1 );
  25899. // Object names must be checked against an allowlist. Otherwise, there
  25900. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25901. // 'bar' could be the objectName, or part of a nodeName (which can
  25902. // include '.' characters).
  25903. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  25904. results.nodeName = results.nodeName.substring( 0, lastDot );
  25905. results.objectName = objectName;
  25906. }
  25907. }
  25908. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  25909. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  25910. }
  25911. return results;
  25912. }
  25913. static findNode( root, nodeName ) {
  25914. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  25915. return root;
  25916. }
  25917. // search into skeleton bones.
  25918. if ( root.skeleton ) {
  25919. const bone = root.skeleton.getBoneByName( nodeName );
  25920. if ( bone !== undefined ) {
  25921. return bone;
  25922. }
  25923. }
  25924. // search into node subtree.
  25925. if ( root.children ) {
  25926. const searchNodeSubtree = function ( children ) {
  25927. for ( let i = 0; i < children.length; i ++ ) {
  25928. const childNode = children[ i ];
  25929. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  25930. return childNode;
  25931. }
  25932. const result = searchNodeSubtree( childNode.children );
  25933. if ( result ) return result;
  25934. }
  25935. return null;
  25936. };
  25937. const subTreeNode = searchNodeSubtree( root.children );
  25938. if ( subTreeNode ) {
  25939. return subTreeNode;
  25940. }
  25941. }
  25942. return null;
  25943. }
  25944. // these are used to "bind" a nonexistent property
  25945. _getValue_unavailable() {}
  25946. _setValue_unavailable() {}
  25947. // Getters
  25948. _getValue_direct( buffer, offset ) {
  25949. buffer[ offset ] = this.targetObject[ this.propertyName ];
  25950. }
  25951. _getValue_array( buffer, offset ) {
  25952. const source = this.resolvedProperty;
  25953. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  25954. buffer[ offset ++ ] = source[ i ];
  25955. }
  25956. }
  25957. _getValue_arrayElement( buffer, offset ) {
  25958. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  25959. }
  25960. _getValue_toArray( buffer, offset ) {
  25961. this.resolvedProperty.toArray( buffer, offset );
  25962. }
  25963. // Direct
  25964. _setValue_direct( buffer, offset ) {
  25965. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25966. }
  25967. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  25968. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25969. this.targetObject.needsUpdate = true;
  25970. }
  25971. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25972. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25973. this.targetObject.matrixWorldNeedsUpdate = true;
  25974. }
  25975. // EntireArray
  25976. _setValue_array( buffer, offset ) {
  25977. const dest = this.resolvedProperty;
  25978. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25979. dest[ i ] = buffer[ offset ++ ];
  25980. }
  25981. }
  25982. _setValue_array_setNeedsUpdate( buffer, offset ) {
  25983. const dest = this.resolvedProperty;
  25984. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25985. dest[ i ] = buffer[ offset ++ ];
  25986. }
  25987. this.targetObject.needsUpdate = true;
  25988. }
  25989. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25990. const dest = this.resolvedProperty;
  25991. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25992. dest[ i ] = buffer[ offset ++ ];
  25993. }
  25994. this.targetObject.matrixWorldNeedsUpdate = true;
  25995. }
  25996. // ArrayElement
  25997. _setValue_arrayElement( buffer, offset ) {
  25998. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25999. }
  26000. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26001. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26002. this.targetObject.needsUpdate = true;
  26003. }
  26004. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26005. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26006. this.targetObject.matrixWorldNeedsUpdate = true;
  26007. }
  26008. // HasToFromArray
  26009. _setValue_fromArray( buffer, offset ) {
  26010. this.resolvedProperty.fromArray( buffer, offset );
  26011. }
  26012. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26013. this.resolvedProperty.fromArray( buffer, offset );
  26014. this.targetObject.needsUpdate = true;
  26015. }
  26016. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26017. this.resolvedProperty.fromArray( buffer, offset );
  26018. this.targetObject.matrixWorldNeedsUpdate = true;
  26019. }
  26020. _getValue_unbound( targetArray, offset ) {
  26021. this.bind();
  26022. this.getValue( targetArray, offset );
  26023. }
  26024. _setValue_unbound( sourceArray, offset ) {
  26025. this.bind();
  26026. this.setValue( sourceArray, offset );
  26027. }
  26028. // create getter / setter pair for a property in the scene graph
  26029. bind() {
  26030. let targetObject = this.node;
  26031. const parsedPath = this.parsedPath;
  26032. const objectName = parsedPath.objectName;
  26033. const propertyName = parsedPath.propertyName;
  26034. let propertyIndex = parsedPath.propertyIndex;
  26035. if ( ! targetObject ) {
  26036. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26037. this.node = targetObject;
  26038. }
  26039. // set fail state so we can just 'return' on error
  26040. this.getValue = this._getValue_unavailable;
  26041. this.setValue = this._setValue_unavailable;
  26042. // ensure there is a value node
  26043. if ( ! targetObject ) {
  26044. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26045. return;
  26046. }
  26047. if ( objectName ) {
  26048. let objectIndex = parsedPath.objectIndex;
  26049. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26050. switch ( objectName ) {
  26051. case 'materials':
  26052. if ( ! targetObject.material ) {
  26053. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26054. return;
  26055. }
  26056. if ( ! targetObject.material.materials ) {
  26057. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26058. return;
  26059. }
  26060. targetObject = targetObject.material.materials;
  26061. break;
  26062. case 'bones':
  26063. if ( ! targetObject.skeleton ) {
  26064. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26065. return;
  26066. }
  26067. // potential future optimization: skip this if propertyIndex is already an integer
  26068. // and convert the integer string to a true integer.
  26069. targetObject = targetObject.skeleton.bones;
  26070. // support resolving morphTarget names into indices.
  26071. for ( let i = 0; i < targetObject.length; i ++ ) {
  26072. if ( targetObject[ i ].name === objectIndex ) {
  26073. objectIndex = i;
  26074. break;
  26075. }
  26076. }
  26077. break;
  26078. default:
  26079. if ( targetObject[ objectName ] === undefined ) {
  26080. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26081. return;
  26082. }
  26083. targetObject = targetObject[ objectName ];
  26084. }
  26085. if ( objectIndex !== undefined ) {
  26086. if ( targetObject[ objectIndex ] === undefined ) {
  26087. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26088. return;
  26089. }
  26090. targetObject = targetObject[ objectIndex ];
  26091. }
  26092. }
  26093. // resolve property
  26094. const nodeProperty = targetObject[ propertyName ];
  26095. if ( nodeProperty === undefined ) {
  26096. const nodeName = parsedPath.nodeName;
  26097. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26098. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26099. return;
  26100. }
  26101. // determine versioning scheme
  26102. let versioning = this.Versioning.None;
  26103. this.targetObject = targetObject;
  26104. if ( targetObject.needsUpdate !== undefined ) { // material
  26105. versioning = this.Versioning.NeedsUpdate;
  26106. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26107. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26108. }
  26109. // determine how the property gets bound
  26110. let bindingType = this.BindingType.Direct;
  26111. if ( propertyIndex !== undefined ) {
  26112. // access a sub element of the property array (only primitives are supported right now)
  26113. if ( propertyName === 'morphTargetInfluences' ) {
  26114. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26115. // support resolving morphTarget names into indices.
  26116. if ( ! targetObject.geometry ) {
  26117. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26118. return;
  26119. }
  26120. if ( targetObject.geometry.isBufferGeometry ) {
  26121. if ( ! targetObject.geometry.morphAttributes ) {
  26122. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26123. return;
  26124. }
  26125. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26126. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26127. }
  26128. } else {
  26129. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  26130. return;
  26131. }
  26132. }
  26133. bindingType = this.BindingType.ArrayElement;
  26134. this.resolvedProperty = nodeProperty;
  26135. this.propertyIndex = propertyIndex;
  26136. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26137. // must use copy for Object3D.Euler/Quaternion
  26138. bindingType = this.BindingType.HasFromToArray;
  26139. this.resolvedProperty = nodeProperty;
  26140. } else if ( Array.isArray( nodeProperty ) ) {
  26141. bindingType = this.BindingType.EntireArray;
  26142. this.resolvedProperty = nodeProperty;
  26143. } else {
  26144. this.propertyName = propertyName;
  26145. }
  26146. // select getter / setter
  26147. this.getValue = this.GetterByBindingType[ bindingType ];
  26148. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26149. }
  26150. unbind() {
  26151. this.node = null;
  26152. // back to the prototype version of getValue / setValue
  26153. // note: avoiding to mutate the shape of 'this' via 'delete'
  26154. this.getValue = this._getValue_unbound;
  26155. this.setValue = this._setValue_unbound;
  26156. }
  26157. }
  26158. PropertyBinding.Composite = Composite;
  26159. PropertyBinding.prototype.BindingType = {
  26160. Direct: 0,
  26161. EntireArray: 1,
  26162. ArrayElement: 2,
  26163. HasFromToArray: 3
  26164. };
  26165. PropertyBinding.prototype.Versioning = {
  26166. None: 0,
  26167. NeedsUpdate: 1,
  26168. MatrixWorldNeedsUpdate: 2
  26169. };
  26170. PropertyBinding.prototype.GetterByBindingType = [
  26171. PropertyBinding.prototype._getValue_direct,
  26172. PropertyBinding.prototype._getValue_array,
  26173. PropertyBinding.prototype._getValue_arrayElement,
  26174. PropertyBinding.prototype._getValue_toArray,
  26175. ];
  26176. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26177. [
  26178. // Direct
  26179. PropertyBinding.prototype._setValue_direct,
  26180. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26181. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26182. ], [
  26183. // EntireArray
  26184. PropertyBinding.prototype._setValue_array,
  26185. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26186. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26187. ], [
  26188. // ArrayElement
  26189. PropertyBinding.prototype._setValue_arrayElement,
  26190. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26191. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26192. ], [
  26193. // HasToFromArray
  26194. PropertyBinding.prototype._setValue_fromArray,
  26195. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26196. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26197. ]
  26198. ];
  26199. /**
  26200. *
  26201. * A group of objects that receives a shared animation state.
  26202. *
  26203. * Usage:
  26204. *
  26205. * - Add objects you would otherwise pass as 'root' to the
  26206. * constructor or the .clipAction method of AnimationMixer.
  26207. *
  26208. * - Instead pass this object as 'root'.
  26209. *
  26210. * - You can also add and remove objects later when the mixer
  26211. * is running.
  26212. *
  26213. * Note:
  26214. *
  26215. * Objects of this class appear as one object to the mixer,
  26216. * so cache control of the individual objects must be done
  26217. * on the group.
  26218. *
  26219. * Limitation:
  26220. *
  26221. * - The animated properties must be compatible among the
  26222. * all objects in the group.
  26223. *
  26224. * - A single property can either be controlled through a
  26225. * target group or directly, but not both.
  26226. */
  26227. class AnimationObjectGroup {
  26228. constructor() {
  26229. this.uuid = generateUUID();
  26230. // cached objects followed by the active ones
  26231. this._objects = Array.prototype.slice.call( arguments );
  26232. this.nCachedObjects_ = 0; // threshold
  26233. // note: read by PropertyBinding.Composite
  26234. const indices = {};
  26235. this._indicesByUUID = indices; // for bookkeeping
  26236. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26237. indices[ arguments[ i ].uuid ] = i;
  26238. }
  26239. this._paths = []; // inside: string
  26240. this._parsedPaths = []; // inside: { we don't care, here }
  26241. this._bindings = []; // inside: Array< PropertyBinding >
  26242. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26243. const scope = this;
  26244. this.stats = {
  26245. objects: {
  26246. get total() {
  26247. return scope._objects.length;
  26248. },
  26249. get inUse() {
  26250. return this.total - scope.nCachedObjects_;
  26251. }
  26252. },
  26253. get bindingsPerObject() {
  26254. return scope._bindings.length;
  26255. }
  26256. };
  26257. }
  26258. add() {
  26259. const objects = this._objects,
  26260. indicesByUUID = this._indicesByUUID,
  26261. paths = this._paths,
  26262. parsedPaths = this._parsedPaths,
  26263. bindings = this._bindings,
  26264. nBindings = bindings.length;
  26265. let knownObject = undefined,
  26266. nObjects = objects.length,
  26267. nCachedObjects = this.nCachedObjects_;
  26268. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26269. const object = arguments[ i ],
  26270. uuid = object.uuid;
  26271. let index = indicesByUUID[ uuid ];
  26272. if ( index === undefined ) {
  26273. // unknown object -> add it to the ACTIVE region
  26274. index = nObjects ++;
  26275. indicesByUUID[ uuid ] = index;
  26276. objects.push( object );
  26277. // accounting is done, now do the same for all bindings
  26278. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26279. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26280. }
  26281. } else if ( index < nCachedObjects ) {
  26282. knownObject = objects[ index ];
  26283. // move existing object to the ACTIVE region
  26284. const firstActiveIndex = -- nCachedObjects,
  26285. lastCachedObject = objects[ firstActiveIndex ];
  26286. indicesByUUID[ lastCachedObject.uuid ] = index;
  26287. objects[ index ] = lastCachedObject;
  26288. indicesByUUID[ uuid ] = firstActiveIndex;
  26289. objects[ firstActiveIndex ] = object;
  26290. // accounting is done, now do the same for all bindings
  26291. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26292. const bindingsForPath = bindings[ j ],
  26293. lastCached = bindingsForPath[ firstActiveIndex ];
  26294. let binding = bindingsForPath[ index ];
  26295. bindingsForPath[ index ] = lastCached;
  26296. if ( binding === undefined ) {
  26297. // since we do not bother to create new bindings
  26298. // for objects that are cached, the binding may
  26299. // or may not exist
  26300. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26301. }
  26302. bindingsForPath[ firstActiveIndex ] = binding;
  26303. }
  26304. } else if ( objects[ index ] !== knownObject ) {
  26305. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26306. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26307. } // else the object is already where we want it to be
  26308. } // for arguments
  26309. this.nCachedObjects_ = nCachedObjects;
  26310. }
  26311. remove() {
  26312. const objects = this._objects,
  26313. indicesByUUID = this._indicesByUUID,
  26314. bindings = this._bindings,
  26315. nBindings = bindings.length;
  26316. let nCachedObjects = this.nCachedObjects_;
  26317. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26318. const object = arguments[ i ],
  26319. uuid = object.uuid,
  26320. index = indicesByUUID[ uuid ];
  26321. if ( index !== undefined && index >= nCachedObjects ) {
  26322. // move existing object into the CACHED region
  26323. const lastCachedIndex = nCachedObjects ++,
  26324. firstActiveObject = objects[ lastCachedIndex ];
  26325. indicesByUUID[ firstActiveObject.uuid ] = index;
  26326. objects[ index ] = firstActiveObject;
  26327. indicesByUUID[ uuid ] = lastCachedIndex;
  26328. objects[ lastCachedIndex ] = object;
  26329. // accounting is done, now do the same for all bindings
  26330. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26331. const bindingsForPath = bindings[ j ],
  26332. firstActive = bindingsForPath[ lastCachedIndex ],
  26333. binding = bindingsForPath[ index ];
  26334. bindingsForPath[ index ] = firstActive;
  26335. bindingsForPath[ lastCachedIndex ] = binding;
  26336. }
  26337. }
  26338. } // for arguments
  26339. this.nCachedObjects_ = nCachedObjects;
  26340. }
  26341. // remove & forget
  26342. uncache() {
  26343. const objects = this._objects,
  26344. indicesByUUID = this._indicesByUUID,
  26345. bindings = this._bindings,
  26346. nBindings = bindings.length;
  26347. let nCachedObjects = this.nCachedObjects_,
  26348. nObjects = objects.length;
  26349. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26350. const object = arguments[ i ],
  26351. uuid = object.uuid,
  26352. index = indicesByUUID[ uuid ];
  26353. if ( index !== undefined ) {
  26354. delete indicesByUUID[ uuid ];
  26355. if ( index < nCachedObjects ) {
  26356. // object is cached, shrink the CACHED region
  26357. const firstActiveIndex = -- nCachedObjects,
  26358. lastCachedObject = objects[ firstActiveIndex ],
  26359. lastIndex = -- nObjects,
  26360. lastObject = objects[ lastIndex ];
  26361. // last cached object takes this object's place
  26362. indicesByUUID[ lastCachedObject.uuid ] = index;
  26363. objects[ index ] = lastCachedObject;
  26364. // last object goes to the activated slot and pop
  26365. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26366. objects[ firstActiveIndex ] = lastObject;
  26367. objects.pop();
  26368. // accounting is done, now do the same for all bindings
  26369. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26370. const bindingsForPath = bindings[ j ],
  26371. lastCached = bindingsForPath[ firstActiveIndex ],
  26372. last = bindingsForPath[ lastIndex ];
  26373. bindingsForPath[ index ] = lastCached;
  26374. bindingsForPath[ firstActiveIndex ] = last;
  26375. bindingsForPath.pop();
  26376. }
  26377. } else {
  26378. // object is active, just swap with the last and pop
  26379. const lastIndex = -- nObjects,
  26380. lastObject = objects[ lastIndex ];
  26381. if ( lastIndex > 0 ) {
  26382. indicesByUUID[ lastObject.uuid ] = index;
  26383. }
  26384. objects[ index ] = lastObject;
  26385. objects.pop();
  26386. // accounting is done, now do the same for all bindings
  26387. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26388. const bindingsForPath = bindings[ j ];
  26389. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26390. bindingsForPath.pop();
  26391. }
  26392. } // cached or active
  26393. } // if object is known
  26394. } // for arguments
  26395. this.nCachedObjects_ = nCachedObjects;
  26396. }
  26397. // Internal interface used by befriended PropertyBinding.Composite:
  26398. subscribe_( path, parsedPath ) {
  26399. // returns an array of bindings for the given path that is changed
  26400. // according to the contained objects in the group
  26401. const indicesByPath = this._bindingsIndicesByPath;
  26402. let index = indicesByPath[ path ];
  26403. const bindings = this._bindings;
  26404. if ( index !== undefined ) return bindings[ index ];
  26405. const paths = this._paths,
  26406. parsedPaths = this._parsedPaths,
  26407. objects = this._objects,
  26408. nObjects = objects.length,
  26409. nCachedObjects = this.nCachedObjects_,
  26410. bindingsForPath = new Array( nObjects );
  26411. index = bindings.length;
  26412. indicesByPath[ path ] = index;
  26413. paths.push( path );
  26414. parsedPaths.push( parsedPath );
  26415. bindings.push( bindingsForPath );
  26416. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26417. const object = objects[ i ];
  26418. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26419. }
  26420. return bindingsForPath;
  26421. }
  26422. unsubscribe_( path ) {
  26423. // tells the group to forget about a property path and no longer
  26424. // update the array previously obtained with 'subscribe_'
  26425. const indicesByPath = this._bindingsIndicesByPath,
  26426. index = indicesByPath[ path ];
  26427. if ( index !== undefined ) {
  26428. const paths = this._paths,
  26429. parsedPaths = this._parsedPaths,
  26430. bindings = this._bindings,
  26431. lastBindingsIndex = bindings.length - 1,
  26432. lastBindings = bindings[ lastBindingsIndex ],
  26433. lastBindingsPath = path[ lastBindingsIndex ];
  26434. indicesByPath[ lastBindingsPath ] = index;
  26435. bindings[ index ] = lastBindings;
  26436. bindings.pop();
  26437. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26438. parsedPaths.pop();
  26439. paths[ index ] = paths[ lastBindingsIndex ];
  26440. paths.pop();
  26441. }
  26442. }
  26443. }
  26444. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26445. class AnimationAction {
  26446. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26447. this._mixer = mixer;
  26448. this._clip = clip;
  26449. this._localRoot = localRoot;
  26450. this.blendMode = blendMode;
  26451. const tracks = clip.tracks,
  26452. nTracks = tracks.length,
  26453. interpolants = new Array( nTracks );
  26454. const interpolantSettings = {
  26455. endingStart: ZeroCurvatureEnding,
  26456. endingEnd: ZeroCurvatureEnding
  26457. };
  26458. for ( let i = 0; i !== nTracks; ++ i ) {
  26459. const interpolant = tracks[ i ].createInterpolant( null );
  26460. interpolants[ i ] = interpolant;
  26461. interpolant.settings = interpolantSettings;
  26462. }
  26463. this._interpolantSettings = interpolantSettings;
  26464. this._interpolants = interpolants; // bound by the mixer
  26465. // inside: PropertyMixer (managed by the mixer)
  26466. this._propertyBindings = new Array( nTracks );
  26467. this._cacheIndex = null; // for the memory manager
  26468. this._byClipCacheIndex = null; // for the memory manager
  26469. this._timeScaleInterpolant = null;
  26470. this._weightInterpolant = null;
  26471. this.loop = LoopRepeat;
  26472. this._loopCount = - 1;
  26473. // global mixer time when the action is to be started
  26474. // it's set back to 'null' upon start of the action
  26475. this._startTime = null;
  26476. // scaled local time of the action
  26477. // gets clamped or wrapped to 0..clip.duration according to loop
  26478. this.time = 0;
  26479. this.timeScale = 1;
  26480. this._effectiveTimeScale = 1;
  26481. this.weight = 1;
  26482. this._effectiveWeight = 1;
  26483. this.repetitions = Infinity; // no. of repetitions when looping
  26484. this.paused = false; // true -> zero effective time scale
  26485. this.enabled = true; // false -> zero effective weight
  26486. this.clampWhenFinished = false;// keep feeding the last frame?
  26487. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26488. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26489. }
  26490. // State & Scheduling
  26491. play() {
  26492. this._mixer._activateAction( this );
  26493. return this;
  26494. }
  26495. stop() {
  26496. this._mixer._deactivateAction( this );
  26497. return this.reset();
  26498. }
  26499. reset() {
  26500. this.paused = false;
  26501. this.enabled = true;
  26502. this.time = 0; // restart clip
  26503. this._loopCount = - 1;// forget previous loops
  26504. this._startTime = null;// forget scheduling
  26505. return this.stopFading().stopWarping();
  26506. }
  26507. isRunning() {
  26508. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26509. this._startTime === null && this._mixer._isActiveAction( this );
  26510. }
  26511. // return true when play has been called
  26512. isScheduled() {
  26513. return this._mixer._isActiveAction( this );
  26514. }
  26515. startAt( time ) {
  26516. this._startTime = time;
  26517. return this;
  26518. }
  26519. setLoop( mode, repetitions ) {
  26520. this.loop = mode;
  26521. this.repetitions = repetitions;
  26522. return this;
  26523. }
  26524. // Weight
  26525. // set the weight stopping any scheduled fading
  26526. // although .enabled = false yields an effective weight of zero, this
  26527. // method does *not* change .enabled, because it would be confusing
  26528. setEffectiveWeight( weight ) {
  26529. this.weight = weight;
  26530. // note: same logic as when updated at runtime
  26531. this._effectiveWeight = this.enabled ? weight : 0;
  26532. return this.stopFading();
  26533. }
  26534. // return the weight considering fading and .enabled
  26535. getEffectiveWeight() {
  26536. return this._effectiveWeight;
  26537. }
  26538. fadeIn( duration ) {
  26539. return this._scheduleFading( duration, 0, 1 );
  26540. }
  26541. fadeOut( duration ) {
  26542. return this._scheduleFading( duration, 1, 0 );
  26543. }
  26544. crossFadeFrom( fadeOutAction, duration, warp ) {
  26545. fadeOutAction.fadeOut( duration );
  26546. this.fadeIn( duration );
  26547. if ( warp ) {
  26548. const fadeInDuration = this._clip.duration,
  26549. fadeOutDuration = fadeOutAction._clip.duration,
  26550. startEndRatio = fadeOutDuration / fadeInDuration,
  26551. endStartRatio = fadeInDuration / fadeOutDuration;
  26552. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26553. this.warp( endStartRatio, 1.0, duration );
  26554. }
  26555. return this;
  26556. }
  26557. crossFadeTo( fadeInAction, duration, warp ) {
  26558. return fadeInAction.crossFadeFrom( this, duration, warp );
  26559. }
  26560. stopFading() {
  26561. const weightInterpolant = this._weightInterpolant;
  26562. if ( weightInterpolant !== null ) {
  26563. this._weightInterpolant = null;
  26564. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26565. }
  26566. return this;
  26567. }
  26568. // Time Scale Control
  26569. // set the time scale stopping any scheduled warping
  26570. // although .paused = true yields an effective time scale of zero, this
  26571. // method does *not* change .paused, because it would be confusing
  26572. setEffectiveTimeScale( timeScale ) {
  26573. this.timeScale = timeScale;
  26574. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26575. return this.stopWarping();
  26576. }
  26577. // return the time scale considering warping and .paused
  26578. getEffectiveTimeScale() {
  26579. return this._effectiveTimeScale;
  26580. }
  26581. setDuration( duration ) {
  26582. this.timeScale = this._clip.duration / duration;
  26583. return this.stopWarping();
  26584. }
  26585. syncWith( action ) {
  26586. this.time = action.time;
  26587. this.timeScale = action.timeScale;
  26588. return this.stopWarping();
  26589. }
  26590. halt( duration ) {
  26591. return this.warp( this._effectiveTimeScale, 0, duration );
  26592. }
  26593. warp( startTimeScale, endTimeScale, duration ) {
  26594. const mixer = this._mixer,
  26595. now = mixer.time,
  26596. timeScale = this.timeScale;
  26597. let interpolant = this._timeScaleInterpolant;
  26598. if ( interpolant === null ) {
  26599. interpolant = mixer._lendControlInterpolant();
  26600. this._timeScaleInterpolant = interpolant;
  26601. }
  26602. const times = interpolant.parameterPositions,
  26603. values = interpolant.sampleValues;
  26604. times[ 0 ] = now;
  26605. times[ 1 ] = now + duration;
  26606. values[ 0 ] = startTimeScale / timeScale;
  26607. values[ 1 ] = endTimeScale / timeScale;
  26608. return this;
  26609. }
  26610. stopWarping() {
  26611. const timeScaleInterpolant = this._timeScaleInterpolant;
  26612. if ( timeScaleInterpolant !== null ) {
  26613. this._timeScaleInterpolant = null;
  26614. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26615. }
  26616. return this;
  26617. }
  26618. // Object Accessors
  26619. getMixer() {
  26620. return this._mixer;
  26621. }
  26622. getClip() {
  26623. return this._clip;
  26624. }
  26625. getRoot() {
  26626. return this._localRoot || this._mixer._root;
  26627. }
  26628. // Interna
  26629. _update( time, deltaTime, timeDirection, accuIndex ) {
  26630. // called by the mixer
  26631. if ( ! this.enabled ) {
  26632. // call ._updateWeight() to update ._effectiveWeight
  26633. this._updateWeight( time );
  26634. return;
  26635. }
  26636. const startTime = this._startTime;
  26637. if ( startTime !== null ) {
  26638. // check for scheduled start of action
  26639. const timeRunning = ( time - startTime ) * timeDirection;
  26640. if ( timeRunning < 0 || timeDirection === 0 ) {
  26641. return; // yet to come / don't decide when delta = 0
  26642. }
  26643. // start
  26644. this._startTime = null; // unschedule
  26645. deltaTime = timeDirection * timeRunning;
  26646. }
  26647. // apply time scale and advance time
  26648. deltaTime *= this._updateTimeScale( time );
  26649. const clipTime = this._updateTime( deltaTime );
  26650. // note: _updateTime may disable the action resulting in
  26651. // an effective weight of 0
  26652. const weight = this._updateWeight( time );
  26653. if ( weight > 0 ) {
  26654. const interpolants = this._interpolants;
  26655. const propertyMixers = this._propertyBindings;
  26656. switch ( this.blendMode ) {
  26657. case AdditiveAnimationBlendMode:
  26658. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26659. interpolants[ j ].evaluate( clipTime );
  26660. propertyMixers[ j ].accumulateAdditive( weight );
  26661. }
  26662. break;
  26663. case NormalAnimationBlendMode:
  26664. default:
  26665. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26666. interpolants[ j ].evaluate( clipTime );
  26667. propertyMixers[ j ].accumulate( accuIndex, weight );
  26668. }
  26669. }
  26670. }
  26671. }
  26672. _updateWeight( time ) {
  26673. let weight = 0;
  26674. if ( this.enabled ) {
  26675. weight = this.weight;
  26676. const interpolant = this._weightInterpolant;
  26677. if ( interpolant !== null ) {
  26678. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26679. weight *= interpolantValue;
  26680. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26681. this.stopFading();
  26682. if ( interpolantValue === 0 ) {
  26683. // faded out, disable
  26684. this.enabled = false;
  26685. }
  26686. }
  26687. }
  26688. }
  26689. this._effectiveWeight = weight;
  26690. return weight;
  26691. }
  26692. _updateTimeScale( time ) {
  26693. let timeScale = 0;
  26694. if ( ! this.paused ) {
  26695. timeScale = this.timeScale;
  26696. const interpolant = this._timeScaleInterpolant;
  26697. if ( interpolant !== null ) {
  26698. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26699. timeScale *= interpolantValue;
  26700. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26701. this.stopWarping();
  26702. if ( timeScale === 0 ) {
  26703. // motion has halted, pause
  26704. this.paused = true;
  26705. } else {
  26706. // warp done - apply final time scale
  26707. this.timeScale = timeScale;
  26708. }
  26709. }
  26710. }
  26711. }
  26712. this._effectiveTimeScale = timeScale;
  26713. return timeScale;
  26714. }
  26715. _updateTime( deltaTime ) {
  26716. const duration = this._clip.duration;
  26717. const loop = this.loop;
  26718. let time = this.time + deltaTime;
  26719. let loopCount = this._loopCount;
  26720. const pingPong = ( loop === LoopPingPong );
  26721. if ( deltaTime === 0 ) {
  26722. if ( loopCount === - 1 ) return time;
  26723. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26724. }
  26725. if ( loop === LoopOnce ) {
  26726. if ( loopCount === - 1 ) {
  26727. // just started
  26728. this._loopCount = 0;
  26729. this._setEndings( true, true, false );
  26730. }
  26731. handle_stop: {
  26732. if ( time >= duration ) {
  26733. time = duration;
  26734. } else if ( time < 0 ) {
  26735. time = 0;
  26736. } else {
  26737. this.time = time;
  26738. break handle_stop;
  26739. }
  26740. if ( this.clampWhenFinished ) this.paused = true;
  26741. else this.enabled = false;
  26742. this.time = time;
  26743. this._mixer.dispatchEvent( {
  26744. type: 'finished', action: this,
  26745. direction: deltaTime < 0 ? - 1 : 1
  26746. } );
  26747. }
  26748. } else { // repetitive Repeat or PingPong
  26749. if ( loopCount === - 1 ) {
  26750. // just started
  26751. if ( deltaTime >= 0 ) {
  26752. loopCount = 0;
  26753. this._setEndings( true, this.repetitions === 0, pingPong );
  26754. } else {
  26755. // when looping in reverse direction, the initial
  26756. // transition through zero counts as a repetition,
  26757. // so leave loopCount at -1
  26758. this._setEndings( this.repetitions === 0, true, pingPong );
  26759. }
  26760. }
  26761. if ( time >= duration || time < 0 ) {
  26762. // wrap around
  26763. const loopDelta = Math.floor( time / duration ); // signed
  26764. time -= duration * loopDelta;
  26765. loopCount += Math.abs( loopDelta );
  26766. const pending = this.repetitions - loopCount;
  26767. if ( pending <= 0 ) {
  26768. // have to stop (switch state, clamp time, fire event)
  26769. if ( this.clampWhenFinished ) this.paused = true;
  26770. else this.enabled = false;
  26771. time = deltaTime > 0 ? duration : 0;
  26772. this.time = time;
  26773. this._mixer.dispatchEvent( {
  26774. type: 'finished', action: this,
  26775. direction: deltaTime > 0 ? 1 : - 1
  26776. } );
  26777. } else {
  26778. // keep running
  26779. if ( pending === 1 ) {
  26780. // entering the last round
  26781. const atStart = deltaTime < 0;
  26782. this._setEndings( atStart, ! atStart, pingPong );
  26783. } else {
  26784. this._setEndings( false, false, pingPong );
  26785. }
  26786. this._loopCount = loopCount;
  26787. this.time = time;
  26788. this._mixer.dispatchEvent( {
  26789. type: 'loop', action: this, loopDelta: loopDelta
  26790. } );
  26791. }
  26792. } else {
  26793. this.time = time;
  26794. }
  26795. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  26796. // invert time for the "pong round"
  26797. return duration - time;
  26798. }
  26799. }
  26800. return time;
  26801. }
  26802. _setEndings( atStart, atEnd, pingPong ) {
  26803. const settings = this._interpolantSettings;
  26804. if ( pingPong ) {
  26805. settings.endingStart = ZeroSlopeEnding;
  26806. settings.endingEnd = ZeroSlopeEnding;
  26807. } else {
  26808. // assuming for LoopOnce atStart == atEnd == true
  26809. if ( atStart ) {
  26810. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26811. } else {
  26812. settings.endingStart = WrapAroundEnding;
  26813. }
  26814. if ( atEnd ) {
  26815. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26816. } else {
  26817. settings.endingEnd = WrapAroundEnding;
  26818. }
  26819. }
  26820. }
  26821. _scheduleFading( duration, weightNow, weightThen ) {
  26822. const mixer = this._mixer, now = mixer.time;
  26823. let interpolant = this._weightInterpolant;
  26824. if ( interpolant === null ) {
  26825. interpolant = mixer._lendControlInterpolant();
  26826. this._weightInterpolant = interpolant;
  26827. }
  26828. const times = interpolant.parameterPositions,
  26829. values = interpolant.sampleValues;
  26830. times[ 0 ] = now;
  26831. values[ 0 ] = weightNow;
  26832. times[ 1 ] = now + duration;
  26833. values[ 1 ] = weightThen;
  26834. return this;
  26835. }
  26836. }
  26837. class AnimationMixer extends EventDispatcher {
  26838. constructor( root ) {
  26839. super();
  26840. this._root = root;
  26841. this._initMemoryManager();
  26842. this._accuIndex = 0;
  26843. this.time = 0;
  26844. this.timeScale = 1.0;
  26845. }
  26846. _bindAction( action, prototypeAction ) {
  26847. const root = action._localRoot || this._root,
  26848. tracks = action._clip.tracks,
  26849. nTracks = tracks.length,
  26850. bindings = action._propertyBindings,
  26851. interpolants = action._interpolants,
  26852. rootUuid = root.uuid,
  26853. bindingsByRoot = this._bindingsByRootAndName;
  26854. let bindingsByName = bindingsByRoot[ rootUuid ];
  26855. if ( bindingsByName === undefined ) {
  26856. bindingsByName = {};
  26857. bindingsByRoot[ rootUuid ] = bindingsByName;
  26858. }
  26859. for ( let i = 0; i !== nTracks; ++ i ) {
  26860. const track = tracks[ i ],
  26861. trackName = track.name;
  26862. let binding = bindingsByName[ trackName ];
  26863. if ( binding !== undefined ) {
  26864. bindings[ i ] = binding;
  26865. } else {
  26866. binding = bindings[ i ];
  26867. if ( binding !== undefined ) {
  26868. // existing binding, make sure the cache knows
  26869. if ( binding._cacheIndex === null ) {
  26870. ++ binding.referenceCount;
  26871. this._addInactiveBinding( binding, rootUuid, trackName );
  26872. }
  26873. continue;
  26874. }
  26875. const path = prototypeAction && prototypeAction.
  26876. _propertyBindings[ i ].binding.parsedPath;
  26877. binding = new PropertyMixer(
  26878. PropertyBinding.create( root, trackName, path ),
  26879. track.ValueTypeName, track.getValueSize() );
  26880. ++ binding.referenceCount;
  26881. this._addInactiveBinding( binding, rootUuid, trackName );
  26882. bindings[ i ] = binding;
  26883. }
  26884. interpolants[ i ].resultBuffer = binding.buffer;
  26885. }
  26886. }
  26887. _activateAction( action ) {
  26888. if ( ! this._isActiveAction( action ) ) {
  26889. if ( action._cacheIndex === null ) {
  26890. // this action has been forgotten by the cache, but the user
  26891. // appears to be still using it -> rebind
  26892. const rootUuid = ( action._localRoot || this._root ).uuid,
  26893. clipUuid = action._clip.uuid,
  26894. actionsForClip = this._actionsByClip[ clipUuid ];
  26895. this._bindAction( action,
  26896. actionsForClip && actionsForClip.knownActions[ 0 ] );
  26897. this._addInactiveAction( action, clipUuid, rootUuid );
  26898. }
  26899. const bindings = action._propertyBindings;
  26900. // increment reference counts / sort out state
  26901. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26902. const binding = bindings[ i ];
  26903. if ( binding.useCount ++ === 0 ) {
  26904. this._lendBinding( binding );
  26905. binding.saveOriginalState();
  26906. }
  26907. }
  26908. this._lendAction( action );
  26909. }
  26910. }
  26911. _deactivateAction( action ) {
  26912. if ( this._isActiveAction( action ) ) {
  26913. const bindings = action._propertyBindings;
  26914. // decrement reference counts / sort out state
  26915. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26916. const binding = bindings[ i ];
  26917. if ( -- binding.useCount === 0 ) {
  26918. binding.restoreOriginalState();
  26919. this._takeBackBinding( binding );
  26920. }
  26921. }
  26922. this._takeBackAction( action );
  26923. }
  26924. }
  26925. // Memory manager
  26926. _initMemoryManager() {
  26927. this._actions = []; // 'nActiveActions' followed by inactive ones
  26928. this._nActiveActions = 0;
  26929. this._actionsByClip = {};
  26930. // inside:
  26931. // {
  26932. // knownActions: Array< AnimationAction > - used as prototypes
  26933. // actionByRoot: AnimationAction - lookup
  26934. // }
  26935. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26936. this._nActiveBindings = 0;
  26937. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26938. this._controlInterpolants = []; // same game as above
  26939. this._nActiveControlInterpolants = 0;
  26940. const scope = this;
  26941. this.stats = {
  26942. actions: {
  26943. get total() {
  26944. return scope._actions.length;
  26945. },
  26946. get inUse() {
  26947. return scope._nActiveActions;
  26948. }
  26949. },
  26950. bindings: {
  26951. get total() {
  26952. return scope._bindings.length;
  26953. },
  26954. get inUse() {
  26955. return scope._nActiveBindings;
  26956. }
  26957. },
  26958. controlInterpolants: {
  26959. get total() {
  26960. return scope._controlInterpolants.length;
  26961. },
  26962. get inUse() {
  26963. return scope._nActiveControlInterpolants;
  26964. }
  26965. }
  26966. };
  26967. }
  26968. // Memory management for AnimationAction objects
  26969. _isActiveAction( action ) {
  26970. const index = action._cacheIndex;
  26971. return index !== null && index < this._nActiveActions;
  26972. }
  26973. _addInactiveAction( action, clipUuid, rootUuid ) {
  26974. const actions = this._actions,
  26975. actionsByClip = this._actionsByClip;
  26976. let actionsForClip = actionsByClip[ clipUuid ];
  26977. if ( actionsForClip === undefined ) {
  26978. actionsForClip = {
  26979. knownActions: [ action ],
  26980. actionByRoot: {}
  26981. };
  26982. action._byClipCacheIndex = 0;
  26983. actionsByClip[ clipUuid ] = actionsForClip;
  26984. } else {
  26985. const knownActions = actionsForClip.knownActions;
  26986. action._byClipCacheIndex = knownActions.length;
  26987. knownActions.push( action );
  26988. }
  26989. action._cacheIndex = actions.length;
  26990. actions.push( action );
  26991. actionsForClip.actionByRoot[ rootUuid ] = action;
  26992. }
  26993. _removeInactiveAction( action ) {
  26994. const actions = this._actions,
  26995. lastInactiveAction = actions[ actions.length - 1 ],
  26996. cacheIndex = action._cacheIndex;
  26997. lastInactiveAction._cacheIndex = cacheIndex;
  26998. actions[ cacheIndex ] = lastInactiveAction;
  26999. actions.pop();
  27000. action._cacheIndex = null;
  27001. const clipUuid = action._clip.uuid,
  27002. actionsByClip = this._actionsByClip,
  27003. actionsForClip = actionsByClip[ clipUuid ],
  27004. knownActionsForClip = actionsForClip.knownActions,
  27005. lastKnownAction =
  27006. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27007. byClipCacheIndex = action._byClipCacheIndex;
  27008. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27009. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27010. knownActionsForClip.pop();
  27011. action._byClipCacheIndex = null;
  27012. const actionByRoot = actionsForClip.actionByRoot,
  27013. rootUuid = ( action._localRoot || this._root ).uuid;
  27014. delete actionByRoot[ rootUuid ];
  27015. if ( knownActionsForClip.length === 0 ) {
  27016. delete actionsByClip[ clipUuid ];
  27017. }
  27018. this._removeInactiveBindingsForAction( action );
  27019. }
  27020. _removeInactiveBindingsForAction( action ) {
  27021. const bindings = action._propertyBindings;
  27022. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27023. const binding = bindings[ i ];
  27024. if ( -- binding.referenceCount === 0 ) {
  27025. this._removeInactiveBinding( binding );
  27026. }
  27027. }
  27028. }
  27029. _lendAction( action ) {
  27030. // [ active actions | inactive actions ]
  27031. // [ active actions >| inactive actions ]
  27032. // s a
  27033. // <-swap->
  27034. // a s
  27035. const actions = this._actions,
  27036. prevIndex = action._cacheIndex,
  27037. lastActiveIndex = this._nActiveActions ++,
  27038. firstInactiveAction = actions[ lastActiveIndex ];
  27039. action._cacheIndex = lastActiveIndex;
  27040. actions[ lastActiveIndex ] = action;
  27041. firstInactiveAction._cacheIndex = prevIndex;
  27042. actions[ prevIndex ] = firstInactiveAction;
  27043. }
  27044. _takeBackAction( action ) {
  27045. // [ active actions | inactive actions ]
  27046. // [ active actions |< inactive actions ]
  27047. // a s
  27048. // <-swap->
  27049. // s a
  27050. const actions = this._actions,
  27051. prevIndex = action._cacheIndex,
  27052. firstInactiveIndex = -- this._nActiveActions,
  27053. lastActiveAction = actions[ firstInactiveIndex ];
  27054. action._cacheIndex = firstInactiveIndex;
  27055. actions[ firstInactiveIndex ] = action;
  27056. lastActiveAction._cacheIndex = prevIndex;
  27057. actions[ prevIndex ] = lastActiveAction;
  27058. }
  27059. // Memory management for PropertyMixer objects
  27060. _addInactiveBinding( binding, rootUuid, trackName ) {
  27061. const bindingsByRoot = this._bindingsByRootAndName,
  27062. bindings = this._bindings;
  27063. let bindingByName = bindingsByRoot[ rootUuid ];
  27064. if ( bindingByName === undefined ) {
  27065. bindingByName = {};
  27066. bindingsByRoot[ rootUuid ] = bindingByName;
  27067. }
  27068. bindingByName[ trackName ] = binding;
  27069. binding._cacheIndex = bindings.length;
  27070. bindings.push( binding );
  27071. }
  27072. _removeInactiveBinding( binding ) {
  27073. const bindings = this._bindings,
  27074. propBinding = binding.binding,
  27075. rootUuid = propBinding.rootNode.uuid,
  27076. trackName = propBinding.path,
  27077. bindingsByRoot = this._bindingsByRootAndName,
  27078. bindingByName = bindingsByRoot[ rootUuid ],
  27079. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27080. cacheIndex = binding._cacheIndex;
  27081. lastInactiveBinding._cacheIndex = cacheIndex;
  27082. bindings[ cacheIndex ] = lastInactiveBinding;
  27083. bindings.pop();
  27084. delete bindingByName[ trackName ];
  27085. if ( Object.keys( bindingByName ).length === 0 ) {
  27086. delete bindingsByRoot[ rootUuid ];
  27087. }
  27088. }
  27089. _lendBinding( binding ) {
  27090. const bindings = this._bindings,
  27091. prevIndex = binding._cacheIndex,
  27092. lastActiveIndex = this._nActiveBindings ++,
  27093. firstInactiveBinding = bindings[ lastActiveIndex ];
  27094. binding._cacheIndex = lastActiveIndex;
  27095. bindings[ lastActiveIndex ] = binding;
  27096. firstInactiveBinding._cacheIndex = prevIndex;
  27097. bindings[ prevIndex ] = firstInactiveBinding;
  27098. }
  27099. _takeBackBinding( binding ) {
  27100. const bindings = this._bindings,
  27101. prevIndex = binding._cacheIndex,
  27102. firstInactiveIndex = -- this._nActiveBindings,
  27103. lastActiveBinding = bindings[ firstInactiveIndex ];
  27104. binding._cacheIndex = firstInactiveIndex;
  27105. bindings[ firstInactiveIndex ] = binding;
  27106. lastActiveBinding._cacheIndex = prevIndex;
  27107. bindings[ prevIndex ] = lastActiveBinding;
  27108. }
  27109. // Memory management of Interpolants for weight and time scale
  27110. _lendControlInterpolant() {
  27111. const interpolants = this._controlInterpolants,
  27112. lastActiveIndex = this._nActiveControlInterpolants ++;
  27113. let interpolant = interpolants[ lastActiveIndex ];
  27114. if ( interpolant === undefined ) {
  27115. interpolant = new LinearInterpolant(
  27116. new Float32Array( 2 ), new Float32Array( 2 ),
  27117. 1, this._controlInterpolantsResultBuffer );
  27118. interpolant.__cacheIndex = lastActiveIndex;
  27119. interpolants[ lastActiveIndex ] = interpolant;
  27120. }
  27121. return interpolant;
  27122. }
  27123. _takeBackControlInterpolant( interpolant ) {
  27124. const interpolants = this._controlInterpolants,
  27125. prevIndex = interpolant.__cacheIndex,
  27126. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27127. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27128. interpolant.__cacheIndex = firstInactiveIndex;
  27129. interpolants[ firstInactiveIndex ] = interpolant;
  27130. lastActiveInterpolant.__cacheIndex = prevIndex;
  27131. interpolants[ prevIndex ] = lastActiveInterpolant;
  27132. }
  27133. // return an action for a clip optionally using a custom root target
  27134. // object (this method allocates a lot of dynamic memory in case a
  27135. // previously unknown clip/root combination is specified)
  27136. clipAction( clip, optionalRoot, blendMode ) {
  27137. const root = optionalRoot || this._root,
  27138. rootUuid = root.uuid;
  27139. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27140. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27141. const actionsForClip = this._actionsByClip[ clipUuid ];
  27142. let prototypeAction = null;
  27143. if ( blendMode === undefined ) {
  27144. if ( clipObject !== null ) {
  27145. blendMode = clipObject.blendMode;
  27146. } else {
  27147. blendMode = NormalAnimationBlendMode;
  27148. }
  27149. }
  27150. if ( actionsForClip !== undefined ) {
  27151. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27152. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27153. return existingAction;
  27154. }
  27155. // we know the clip, so we don't have to parse all
  27156. // the bindings again but can just copy
  27157. prototypeAction = actionsForClip.knownActions[ 0 ];
  27158. // also, take the clip from the prototype action
  27159. if ( clipObject === null )
  27160. clipObject = prototypeAction._clip;
  27161. }
  27162. // clip must be known when specified via string
  27163. if ( clipObject === null ) return null;
  27164. // allocate all resources required to run it
  27165. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27166. this._bindAction( newAction, prototypeAction );
  27167. // and make the action known to the memory manager
  27168. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27169. return newAction;
  27170. }
  27171. // get an existing action
  27172. existingAction( clip, optionalRoot ) {
  27173. const root = optionalRoot || this._root,
  27174. rootUuid = root.uuid,
  27175. clipObject = typeof clip === 'string' ?
  27176. AnimationClip.findByName( root, clip ) : clip,
  27177. clipUuid = clipObject ? clipObject.uuid : clip,
  27178. actionsForClip = this._actionsByClip[ clipUuid ];
  27179. if ( actionsForClip !== undefined ) {
  27180. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27181. }
  27182. return null;
  27183. }
  27184. // deactivates all previously scheduled actions
  27185. stopAllAction() {
  27186. const actions = this._actions,
  27187. nActions = this._nActiveActions;
  27188. for ( let i = nActions - 1; i >= 0; -- i ) {
  27189. actions[ i ].stop();
  27190. }
  27191. return this;
  27192. }
  27193. // advance the time and update apply the animation
  27194. update( deltaTime ) {
  27195. deltaTime *= this.timeScale;
  27196. const actions = this._actions,
  27197. nActions = this._nActiveActions,
  27198. time = this.time += deltaTime,
  27199. timeDirection = Math.sign( deltaTime ),
  27200. accuIndex = this._accuIndex ^= 1;
  27201. // run active actions
  27202. for ( let i = 0; i !== nActions; ++ i ) {
  27203. const action = actions[ i ];
  27204. action._update( time, deltaTime, timeDirection, accuIndex );
  27205. }
  27206. // update scene graph
  27207. const bindings = this._bindings,
  27208. nBindings = this._nActiveBindings;
  27209. for ( let i = 0; i !== nBindings; ++ i ) {
  27210. bindings[ i ].apply( accuIndex );
  27211. }
  27212. return this;
  27213. }
  27214. // Allows you to seek to a specific time in an animation.
  27215. setTime( timeInSeconds ) {
  27216. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27217. for ( let i = 0; i < this._actions.length; i ++ ) {
  27218. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27219. }
  27220. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27221. }
  27222. // return this mixer's root target object
  27223. getRoot() {
  27224. return this._root;
  27225. }
  27226. // free all resources specific to a particular clip
  27227. uncacheClip( clip ) {
  27228. const actions = this._actions,
  27229. clipUuid = clip.uuid,
  27230. actionsByClip = this._actionsByClip,
  27231. actionsForClip = actionsByClip[ clipUuid ];
  27232. if ( actionsForClip !== undefined ) {
  27233. // note: just calling _removeInactiveAction would mess up the
  27234. // iteration state and also require updating the state we can
  27235. // just throw away
  27236. const actionsToRemove = actionsForClip.knownActions;
  27237. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27238. const action = actionsToRemove[ i ];
  27239. this._deactivateAction( action );
  27240. const cacheIndex = action._cacheIndex,
  27241. lastInactiveAction = actions[ actions.length - 1 ];
  27242. action._cacheIndex = null;
  27243. action._byClipCacheIndex = null;
  27244. lastInactiveAction._cacheIndex = cacheIndex;
  27245. actions[ cacheIndex ] = lastInactiveAction;
  27246. actions.pop();
  27247. this._removeInactiveBindingsForAction( action );
  27248. }
  27249. delete actionsByClip[ clipUuid ];
  27250. }
  27251. }
  27252. // free all resources specific to a particular root target object
  27253. uncacheRoot( root ) {
  27254. const rootUuid = root.uuid,
  27255. actionsByClip = this._actionsByClip;
  27256. for ( const clipUuid in actionsByClip ) {
  27257. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27258. action = actionByRoot[ rootUuid ];
  27259. if ( action !== undefined ) {
  27260. this._deactivateAction( action );
  27261. this._removeInactiveAction( action );
  27262. }
  27263. }
  27264. const bindingsByRoot = this._bindingsByRootAndName,
  27265. bindingByName = bindingsByRoot[ rootUuid ];
  27266. if ( bindingByName !== undefined ) {
  27267. for ( const trackName in bindingByName ) {
  27268. const binding = bindingByName[ trackName ];
  27269. binding.restoreOriginalState();
  27270. this._removeInactiveBinding( binding );
  27271. }
  27272. }
  27273. }
  27274. // remove a targeted clip from the cache
  27275. uncacheAction( clip, optionalRoot ) {
  27276. const action = this.existingAction( clip, optionalRoot );
  27277. if ( action !== null ) {
  27278. this._deactivateAction( action );
  27279. this._removeInactiveAction( action );
  27280. }
  27281. }
  27282. }
  27283. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  27284. class Uniform {
  27285. constructor( value ) {
  27286. if ( typeof value === 'string' ) {
  27287. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27288. value = arguments[ 1 ];
  27289. }
  27290. this.value = value;
  27291. }
  27292. clone() {
  27293. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27294. }
  27295. }
  27296. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27297. constructor( array, stride, meshPerAttribute = 1 ) {
  27298. super( array, stride );
  27299. this.meshPerAttribute = meshPerAttribute;
  27300. }
  27301. copy( source ) {
  27302. super.copy( source );
  27303. this.meshPerAttribute = source.meshPerAttribute;
  27304. return this;
  27305. }
  27306. clone( data ) {
  27307. const ib = super.clone( data );
  27308. ib.meshPerAttribute = this.meshPerAttribute;
  27309. return ib;
  27310. }
  27311. toJSON( data ) {
  27312. const json = super.toJSON( data );
  27313. json.isInstancedInterleavedBuffer = true;
  27314. json.meshPerAttribute = this.meshPerAttribute;
  27315. return json;
  27316. }
  27317. }
  27318. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27319. class GLBufferAttribute {
  27320. constructor( buffer, type, itemSize, elementSize, count ) {
  27321. this.buffer = buffer;
  27322. this.type = type;
  27323. this.itemSize = itemSize;
  27324. this.elementSize = elementSize;
  27325. this.count = count;
  27326. this.version = 0;
  27327. }
  27328. set needsUpdate( value ) {
  27329. if ( value === true ) this.version ++;
  27330. }
  27331. setBuffer( buffer ) {
  27332. this.buffer = buffer;
  27333. return this;
  27334. }
  27335. setType( type, elementSize ) {
  27336. this.type = type;
  27337. this.elementSize = elementSize;
  27338. return this;
  27339. }
  27340. setItemSize( itemSize ) {
  27341. this.itemSize = itemSize;
  27342. return this;
  27343. }
  27344. setCount( count ) {
  27345. this.count = count;
  27346. return this;
  27347. }
  27348. }
  27349. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27350. class Raycaster {
  27351. constructor( origin, direction, near = 0, far = Infinity ) {
  27352. this.ray = new Ray( origin, direction );
  27353. // direction is assumed to be normalized (for accurate distance calculations)
  27354. this.near = near;
  27355. this.far = far;
  27356. this.camera = null;
  27357. this.layers = new Layers();
  27358. this.params = {
  27359. Mesh: {},
  27360. Line: { threshold: 1 },
  27361. LOD: {},
  27362. Points: { threshold: 1 },
  27363. Sprite: {}
  27364. };
  27365. }
  27366. set( origin, direction ) {
  27367. // direction is assumed to be normalized (for accurate distance calculations)
  27368. this.ray.set( origin, direction );
  27369. }
  27370. setFromCamera( coords, camera ) {
  27371. if ( camera && camera.isPerspectiveCamera ) {
  27372. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27373. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27374. this.camera = camera;
  27375. } else if ( camera && camera.isOrthographicCamera ) {
  27376. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27377. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27378. this.camera = camera;
  27379. } else {
  27380. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27381. }
  27382. }
  27383. intersectObject( object, recursive = true, intersects = [] ) {
  27384. intersectObject( object, this, intersects, recursive );
  27385. intersects.sort( ascSort );
  27386. return intersects;
  27387. }
  27388. intersectObjects( objects, recursive = true, intersects = [] ) {
  27389. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27390. intersectObject( objects[ i ], this, intersects, recursive );
  27391. }
  27392. intersects.sort( ascSort );
  27393. return intersects;
  27394. }
  27395. }
  27396. function ascSort( a, b ) {
  27397. return a.distance - b.distance;
  27398. }
  27399. function intersectObject( object, raycaster, intersects, recursive ) {
  27400. if ( object.layers.test( raycaster.layers ) ) {
  27401. object.raycast( raycaster, intersects );
  27402. }
  27403. if ( recursive === true ) {
  27404. const children = object.children;
  27405. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27406. intersectObject( children[ i ], raycaster, intersects, true );
  27407. }
  27408. }
  27409. }
  27410. /**
  27411. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27412. *
  27413. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27414. * The azimuthal angle (theta) is measured from the positive z-axis.
  27415. */
  27416. class Spherical {
  27417. constructor( radius = 1, phi = 0, theta = 0 ) {
  27418. this.radius = radius;
  27419. this.phi = phi; // polar angle
  27420. this.theta = theta; // azimuthal angle
  27421. return this;
  27422. }
  27423. set( radius, phi, theta ) {
  27424. this.radius = radius;
  27425. this.phi = phi;
  27426. this.theta = theta;
  27427. return this;
  27428. }
  27429. copy( other ) {
  27430. this.radius = other.radius;
  27431. this.phi = other.phi;
  27432. this.theta = other.theta;
  27433. return this;
  27434. }
  27435. // restrict phi to be betwee EPS and PI-EPS
  27436. makeSafe() {
  27437. const EPS = 0.000001;
  27438. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27439. return this;
  27440. }
  27441. setFromVector3( v ) {
  27442. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27443. }
  27444. setFromCartesianCoords( x, y, z ) {
  27445. this.radius = Math.sqrt( x * x + y * y + z * z );
  27446. if ( this.radius === 0 ) {
  27447. this.theta = 0;
  27448. this.phi = 0;
  27449. } else {
  27450. this.theta = Math.atan2( x, z );
  27451. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27452. }
  27453. return this;
  27454. }
  27455. clone() {
  27456. return new this.constructor().copy( this );
  27457. }
  27458. }
  27459. /**
  27460. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27461. */
  27462. class Cylindrical {
  27463. constructor( radius = 1, theta = 0, y = 0 ) {
  27464. this.radius = radius; // distance from the origin to a point in the x-z plane
  27465. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27466. this.y = y; // height above the x-z plane
  27467. return this;
  27468. }
  27469. set( radius, theta, y ) {
  27470. this.radius = radius;
  27471. this.theta = theta;
  27472. this.y = y;
  27473. return this;
  27474. }
  27475. copy( other ) {
  27476. this.radius = other.radius;
  27477. this.theta = other.theta;
  27478. this.y = other.y;
  27479. return this;
  27480. }
  27481. setFromVector3( v ) {
  27482. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27483. }
  27484. setFromCartesianCoords( x, y, z ) {
  27485. this.radius = Math.sqrt( x * x + z * z );
  27486. this.theta = Math.atan2( x, z );
  27487. this.y = y;
  27488. return this;
  27489. }
  27490. clone() {
  27491. return new this.constructor().copy( this );
  27492. }
  27493. }
  27494. const _vector$4 = /*@__PURE__*/ new Vector2();
  27495. class Box2 {
  27496. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  27497. this.min = min;
  27498. this.max = max;
  27499. }
  27500. set( min, max ) {
  27501. this.min.copy( min );
  27502. this.max.copy( max );
  27503. return this;
  27504. }
  27505. setFromPoints( points ) {
  27506. this.makeEmpty();
  27507. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27508. this.expandByPoint( points[ i ] );
  27509. }
  27510. return this;
  27511. }
  27512. setFromCenterAndSize( center, size ) {
  27513. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  27514. this.min.copy( center ).sub( halfSize );
  27515. this.max.copy( center ).add( halfSize );
  27516. return this;
  27517. }
  27518. clone() {
  27519. return new this.constructor().copy( this );
  27520. }
  27521. copy( box ) {
  27522. this.min.copy( box.min );
  27523. this.max.copy( box.max );
  27524. return this;
  27525. }
  27526. makeEmpty() {
  27527. this.min.x = this.min.y = + Infinity;
  27528. this.max.x = this.max.y = - Infinity;
  27529. return this;
  27530. }
  27531. isEmpty() {
  27532. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27533. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27534. }
  27535. getCenter( target ) {
  27536. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27537. }
  27538. getSize( target ) {
  27539. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27540. }
  27541. expandByPoint( point ) {
  27542. this.min.min( point );
  27543. this.max.max( point );
  27544. return this;
  27545. }
  27546. expandByVector( vector ) {
  27547. this.min.sub( vector );
  27548. this.max.add( vector );
  27549. return this;
  27550. }
  27551. expandByScalar( scalar ) {
  27552. this.min.addScalar( - scalar );
  27553. this.max.addScalar( scalar );
  27554. return this;
  27555. }
  27556. containsPoint( point ) {
  27557. return point.x < this.min.x || point.x > this.max.x ||
  27558. point.y < this.min.y || point.y > this.max.y ? false : true;
  27559. }
  27560. containsBox( box ) {
  27561. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27562. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27563. }
  27564. getParameter( point, target ) {
  27565. // This can potentially have a divide by zero if the box
  27566. // has a size dimension of 0.
  27567. return target.set(
  27568. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27569. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27570. );
  27571. }
  27572. intersectsBox( box ) {
  27573. // using 4 splitting planes to rule out intersections
  27574. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27575. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27576. }
  27577. clampPoint( point, target ) {
  27578. return target.copy( point ).clamp( this.min, this.max );
  27579. }
  27580. distanceToPoint( point ) {
  27581. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  27582. return clampedPoint.sub( point ).length();
  27583. }
  27584. intersect( box ) {
  27585. this.min.max( box.min );
  27586. this.max.min( box.max );
  27587. return this;
  27588. }
  27589. union( box ) {
  27590. this.min.min( box.min );
  27591. this.max.max( box.max );
  27592. return this;
  27593. }
  27594. translate( offset ) {
  27595. this.min.add( offset );
  27596. this.max.add( offset );
  27597. return this;
  27598. }
  27599. equals( box ) {
  27600. return box.min.equals( this.min ) && box.max.equals( this.max );
  27601. }
  27602. }
  27603. Box2.prototype.isBox2 = true;
  27604. const _startP = /*@__PURE__*/ new Vector3();
  27605. const _startEnd = /*@__PURE__*/ new Vector3();
  27606. class Line3 {
  27607. constructor( start = new Vector3(), end = new Vector3() ) {
  27608. this.start = start;
  27609. this.end = end;
  27610. }
  27611. set( start, end ) {
  27612. this.start.copy( start );
  27613. this.end.copy( end );
  27614. return this;
  27615. }
  27616. copy( line ) {
  27617. this.start.copy( line.start );
  27618. this.end.copy( line.end );
  27619. return this;
  27620. }
  27621. getCenter( target ) {
  27622. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27623. }
  27624. delta( target ) {
  27625. return target.subVectors( this.end, this.start );
  27626. }
  27627. distanceSq() {
  27628. return this.start.distanceToSquared( this.end );
  27629. }
  27630. distance() {
  27631. return this.start.distanceTo( this.end );
  27632. }
  27633. at( t, target ) {
  27634. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27635. }
  27636. closestPointToPointParameter( point, clampToLine ) {
  27637. _startP.subVectors( point, this.start );
  27638. _startEnd.subVectors( this.end, this.start );
  27639. const startEnd2 = _startEnd.dot( _startEnd );
  27640. const startEnd_startP = _startEnd.dot( _startP );
  27641. let t = startEnd_startP / startEnd2;
  27642. if ( clampToLine ) {
  27643. t = clamp( t, 0, 1 );
  27644. }
  27645. return t;
  27646. }
  27647. closestPointToPoint( point, clampToLine, target ) {
  27648. const t = this.closestPointToPointParameter( point, clampToLine );
  27649. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27650. }
  27651. applyMatrix4( matrix ) {
  27652. this.start.applyMatrix4( matrix );
  27653. this.end.applyMatrix4( matrix );
  27654. return this;
  27655. }
  27656. equals( line ) {
  27657. return line.start.equals( this.start ) && line.end.equals( this.end );
  27658. }
  27659. clone() {
  27660. return new this.constructor().copy( this );
  27661. }
  27662. }
  27663. const _vector$3 = /*@__PURE__*/ new Vector3();
  27664. class SpotLightHelper extends Object3D {
  27665. constructor( light, color ) {
  27666. super();
  27667. this.light = light;
  27668. this.light.updateMatrixWorld();
  27669. this.matrix = light.matrixWorld;
  27670. this.matrixAutoUpdate = false;
  27671. this.color = color;
  27672. const geometry = new BufferGeometry();
  27673. const positions = [
  27674. 0, 0, 0, 0, 0, 1,
  27675. 0, 0, 0, 1, 0, 1,
  27676. 0, 0, 0, - 1, 0, 1,
  27677. 0, 0, 0, 0, 1, 1,
  27678. 0, 0, 0, 0, - 1, 1
  27679. ];
  27680. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27681. const p1 = ( i / l ) * Math.PI * 2;
  27682. const p2 = ( j / l ) * Math.PI * 2;
  27683. positions.push(
  27684. Math.cos( p1 ), Math.sin( p1 ), 1,
  27685. Math.cos( p2 ), Math.sin( p2 ), 1
  27686. );
  27687. }
  27688. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27689. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27690. this.cone = new LineSegments( geometry, material );
  27691. this.add( this.cone );
  27692. this.update();
  27693. }
  27694. dispose() {
  27695. this.cone.geometry.dispose();
  27696. this.cone.material.dispose();
  27697. }
  27698. update() {
  27699. this.light.updateMatrixWorld();
  27700. const coneLength = this.light.distance ? this.light.distance : 1000;
  27701. const coneWidth = coneLength * Math.tan( this.light.angle );
  27702. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  27703. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  27704. this.cone.lookAt( _vector$3 );
  27705. if ( this.color !== undefined ) {
  27706. this.cone.material.color.set( this.color );
  27707. } else {
  27708. this.cone.material.color.copy( this.light.color );
  27709. }
  27710. }
  27711. }
  27712. const _vector$2 = /*@__PURE__*/ new Vector3();
  27713. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  27714. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  27715. class SkeletonHelper extends LineSegments {
  27716. constructor( object ) {
  27717. const bones = getBoneList( object );
  27718. const geometry = new BufferGeometry();
  27719. const vertices = [];
  27720. const colors = [];
  27721. const color1 = new Color( 0, 0, 1 );
  27722. const color2 = new Color( 0, 1, 0 );
  27723. for ( let i = 0; i < bones.length; i ++ ) {
  27724. const bone = bones[ i ];
  27725. if ( bone.parent && bone.parent.isBone ) {
  27726. vertices.push( 0, 0, 0 );
  27727. vertices.push( 0, 0, 0 );
  27728. colors.push( color1.r, color1.g, color1.b );
  27729. colors.push( color2.r, color2.g, color2.b );
  27730. }
  27731. }
  27732. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27733. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27734. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  27735. super( geometry, material );
  27736. this.type = 'SkeletonHelper';
  27737. this.isSkeletonHelper = true;
  27738. this.root = object;
  27739. this.bones = bones;
  27740. this.matrix = object.matrixWorld;
  27741. this.matrixAutoUpdate = false;
  27742. }
  27743. updateMatrixWorld( force ) {
  27744. const bones = this.bones;
  27745. const geometry = this.geometry;
  27746. const position = geometry.getAttribute( 'position' );
  27747. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  27748. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  27749. const bone = bones[ i ];
  27750. if ( bone.parent && bone.parent.isBone ) {
  27751. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  27752. _vector$2.setFromMatrixPosition( _boneMatrix );
  27753. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  27754. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  27755. _vector$2.setFromMatrixPosition( _boneMatrix );
  27756. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  27757. j += 2;
  27758. }
  27759. }
  27760. geometry.getAttribute( 'position' ).needsUpdate = true;
  27761. super.updateMatrixWorld( force );
  27762. }
  27763. }
  27764. function getBoneList( object ) {
  27765. const boneList = [];
  27766. if ( object && object.isBone ) {
  27767. boneList.push( object );
  27768. }
  27769. for ( let i = 0; i < object.children.length; i ++ ) {
  27770. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  27771. }
  27772. return boneList;
  27773. }
  27774. class PointLightHelper extends Mesh {
  27775. constructor( light, sphereSize, color ) {
  27776. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  27777. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27778. super( geometry, material );
  27779. this.light = light;
  27780. this.light.updateMatrixWorld();
  27781. this.color = color;
  27782. this.type = 'PointLightHelper';
  27783. this.matrix = this.light.matrixWorld;
  27784. this.matrixAutoUpdate = false;
  27785. this.update();
  27786. /*
  27787. // TODO: delete this comment?
  27788. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27789. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27790. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27791. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27792. const d = light.distance;
  27793. if ( d === 0.0 ) {
  27794. this.lightDistance.visible = false;
  27795. } else {
  27796. this.lightDistance.scale.set( d, d, d );
  27797. }
  27798. this.add( this.lightDistance );
  27799. */
  27800. }
  27801. dispose() {
  27802. this.geometry.dispose();
  27803. this.material.dispose();
  27804. }
  27805. update() {
  27806. if ( this.color !== undefined ) {
  27807. this.material.color.set( this.color );
  27808. } else {
  27809. this.material.color.copy( this.light.color );
  27810. }
  27811. /*
  27812. const d = this.light.distance;
  27813. if ( d === 0.0 ) {
  27814. this.lightDistance.visible = false;
  27815. } else {
  27816. this.lightDistance.visible = true;
  27817. this.lightDistance.scale.set( d, d, d );
  27818. }
  27819. */
  27820. }
  27821. }
  27822. const _vector$1 = /*@__PURE__*/ new Vector3();
  27823. const _color1 = /*@__PURE__*/ new Color();
  27824. const _color2 = /*@__PURE__*/ new Color();
  27825. class HemisphereLightHelper extends Object3D {
  27826. constructor( light, size, color ) {
  27827. super();
  27828. this.light = light;
  27829. this.light.updateMatrixWorld();
  27830. this.matrix = light.matrixWorld;
  27831. this.matrixAutoUpdate = false;
  27832. this.color = color;
  27833. const geometry = new OctahedronGeometry( size );
  27834. geometry.rotateY( Math.PI * 0.5 );
  27835. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27836. if ( this.color === undefined ) this.material.vertexColors = true;
  27837. const position = geometry.getAttribute( 'position' );
  27838. const colors = new Float32Array( position.count * 3 );
  27839. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  27840. this.add( new Mesh( geometry, this.material ) );
  27841. this.update();
  27842. }
  27843. dispose() {
  27844. this.children[ 0 ].geometry.dispose();
  27845. this.children[ 0 ].material.dispose();
  27846. }
  27847. update() {
  27848. const mesh = this.children[ 0 ];
  27849. if ( this.color !== undefined ) {
  27850. this.material.color.set( this.color );
  27851. } else {
  27852. const colors = mesh.geometry.getAttribute( 'color' );
  27853. _color1.copy( this.light.color );
  27854. _color2.copy( this.light.groundColor );
  27855. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  27856. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  27857. colors.setXYZ( i, color.r, color.g, color.b );
  27858. }
  27859. colors.needsUpdate = true;
  27860. }
  27861. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  27862. }
  27863. }
  27864. class GridHelper extends LineSegments {
  27865. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  27866. color1 = new Color( color1 );
  27867. color2 = new Color( color2 );
  27868. const center = divisions / 2;
  27869. const step = size / divisions;
  27870. const halfSize = size / 2;
  27871. const vertices = [], colors = [];
  27872. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  27873. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  27874. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  27875. const color = i === center ? color1 : color2;
  27876. color.toArray( colors, j ); j += 3;
  27877. color.toArray( colors, j ); j += 3;
  27878. color.toArray( colors, j ); j += 3;
  27879. color.toArray( colors, j ); j += 3;
  27880. }
  27881. const geometry = new BufferGeometry();
  27882. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27883. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27884. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27885. super( geometry, material );
  27886. this.type = 'GridHelper';
  27887. }
  27888. }
  27889. class PolarGridHelper extends LineSegments {
  27890. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  27891. color1 = new Color( color1 );
  27892. color2 = new Color( color2 );
  27893. const vertices = [];
  27894. const colors = [];
  27895. // create the radials
  27896. for ( let i = 0; i <= radials; i ++ ) {
  27897. const v = ( i / radials ) * ( Math.PI * 2 );
  27898. const x = Math.sin( v ) * radius;
  27899. const z = Math.cos( v ) * radius;
  27900. vertices.push( 0, 0, 0 );
  27901. vertices.push( x, 0, z );
  27902. const color = ( i & 1 ) ? color1 : color2;
  27903. colors.push( color.r, color.g, color.b );
  27904. colors.push( color.r, color.g, color.b );
  27905. }
  27906. // create the circles
  27907. for ( let i = 0; i <= circles; i ++ ) {
  27908. const color = ( i & 1 ) ? color1 : color2;
  27909. const r = radius - ( radius / circles * i );
  27910. for ( let j = 0; j < divisions; j ++ ) {
  27911. // first vertex
  27912. let v = ( j / divisions ) * ( Math.PI * 2 );
  27913. let x = Math.sin( v ) * r;
  27914. let z = Math.cos( v ) * r;
  27915. vertices.push( x, 0, z );
  27916. colors.push( color.r, color.g, color.b );
  27917. // second vertex
  27918. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  27919. x = Math.sin( v ) * r;
  27920. z = Math.cos( v ) * r;
  27921. vertices.push( x, 0, z );
  27922. colors.push( color.r, color.g, color.b );
  27923. }
  27924. }
  27925. const geometry = new BufferGeometry();
  27926. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27927. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27928. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27929. super( geometry, material );
  27930. this.type = 'PolarGridHelper';
  27931. }
  27932. }
  27933. const _v1 = /*@__PURE__*/ new Vector3();
  27934. const _v2 = /*@__PURE__*/ new Vector3();
  27935. const _v3 = /*@__PURE__*/ new Vector3();
  27936. class DirectionalLightHelper extends Object3D {
  27937. constructor( light, size, color ) {
  27938. super();
  27939. this.light = light;
  27940. this.light.updateMatrixWorld();
  27941. this.matrix = light.matrixWorld;
  27942. this.matrixAutoUpdate = false;
  27943. this.color = color;
  27944. if ( size === undefined ) size = 1;
  27945. let geometry = new BufferGeometry();
  27946. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  27947. - size, size, 0,
  27948. size, size, 0,
  27949. size, - size, 0,
  27950. - size, - size, 0,
  27951. - size, size, 0
  27952. ], 3 ) );
  27953. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27954. this.lightPlane = new Line( geometry, material );
  27955. this.add( this.lightPlane );
  27956. geometry = new BufferGeometry();
  27957. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  27958. this.targetLine = new Line( geometry, material );
  27959. this.add( this.targetLine );
  27960. this.update();
  27961. }
  27962. dispose() {
  27963. this.lightPlane.geometry.dispose();
  27964. this.lightPlane.material.dispose();
  27965. this.targetLine.geometry.dispose();
  27966. this.targetLine.material.dispose();
  27967. }
  27968. update() {
  27969. _v1.setFromMatrixPosition( this.light.matrixWorld );
  27970. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  27971. _v3.subVectors( _v2, _v1 );
  27972. this.lightPlane.lookAt( _v2 );
  27973. if ( this.color !== undefined ) {
  27974. this.lightPlane.material.color.set( this.color );
  27975. this.targetLine.material.color.set( this.color );
  27976. } else {
  27977. this.lightPlane.material.color.copy( this.light.color );
  27978. this.targetLine.material.color.copy( this.light.color );
  27979. }
  27980. this.targetLine.lookAt( _v2 );
  27981. this.targetLine.scale.z = _v3.length();
  27982. }
  27983. }
  27984. const _vector = /*@__PURE__*/ new Vector3();
  27985. const _camera = /*@__PURE__*/ new Camera();
  27986. /**
  27987. * - shows frustum, line of sight and up of the camera
  27988. * - suitable for fast updates
  27989. * - based on frustum visualization in lightgl.js shadowmap example
  27990. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27991. */
  27992. class CameraHelper extends LineSegments {
  27993. constructor( camera ) {
  27994. const geometry = new BufferGeometry();
  27995. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  27996. const vertices = [];
  27997. const colors = [];
  27998. const pointMap = {};
  27999. // colors
  28000. const colorFrustum = new Color( 0xffaa00 );
  28001. const colorCone = new Color( 0xff0000 );
  28002. const colorUp = new Color( 0x00aaff );
  28003. const colorTarget = new Color( 0xffffff );
  28004. const colorCross = new Color( 0x333333 );
  28005. // near
  28006. addLine( 'n1', 'n2', colorFrustum );
  28007. addLine( 'n2', 'n4', colorFrustum );
  28008. addLine( 'n4', 'n3', colorFrustum );
  28009. addLine( 'n3', 'n1', colorFrustum );
  28010. // far
  28011. addLine( 'f1', 'f2', colorFrustum );
  28012. addLine( 'f2', 'f4', colorFrustum );
  28013. addLine( 'f4', 'f3', colorFrustum );
  28014. addLine( 'f3', 'f1', colorFrustum );
  28015. // sides
  28016. addLine( 'n1', 'f1', colorFrustum );
  28017. addLine( 'n2', 'f2', colorFrustum );
  28018. addLine( 'n3', 'f3', colorFrustum );
  28019. addLine( 'n4', 'f4', colorFrustum );
  28020. // cone
  28021. addLine( 'p', 'n1', colorCone );
  28022. addLine( 'p', 'n2', colorCone );
  28023. addLine( 'p', 'n3', colorCone );
  28024. addLine( 'p', 'n4', colorCone );
  28025. // up
  28026. addLine( 'u1', 'u2', colorUp );
  28027. addLine( 'u2', 'u3', colorUp );
  28028. addLine( 'u3', 'u1', colorUp );
  28029. // target
  28030. addLine( 'c', 't', colorTarget );
  28031. addLine( 'p', 'c', colorCross );
  28032. // cross
  28033. addLine( 'cn1', 'cn2', colorCross );
  28034. addLine( 'cn3', 'cn4', colorCross );
  28035. addLine( 'cf1', 'cf2', colorCross );
  28036. addLine( 'cf3', 'cf4', colorCross );
  28037. function addLine( a, b, color ) {
  28038. addPoint( a, color );
  28039. addPoint( b, color );
  28040. }
  28041. function addPoint( id, color ) {
  28042. vertices.push( 0, 0, 0 );
  28043. colors.push( color.r, color.g, color.b );
  28044. if ( pointMap[ id ] === undefined ) {
  28045. pointMap[ id ] = [];
  28046. }
  28047. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28048. }
  28049. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28050. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28051. super( geometry, material );
  28052. this.type = 'CameraHelper';
  28053. this.camera = camera;
  28054. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28055. this.matrix = camera.matrixWorld;
  28056. this.matrixAutoUpdate = false;
  28057. this.pointMap = pointMap;
  28058. this.update();
  28059. }
  28060. update() {
  28061. const geometry = this.geometry;
  28062. const pointMap = this.pointMap;
  28063. const w = 1, h = 1;
  28064. // we need just camera projection matrix inverse
  28065. // world matrix must be identity
  28066. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28067. // center / target
  28068. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28069. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28070. // near
  28071. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28072. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28073. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28074. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28075. // far
  28076. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28077. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28078. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28079. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28080. // up
  28081. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28082. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28083. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28084. // cross
  28085. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28086. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28087. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28088. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28089. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28090. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28091. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28092. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28093. geometry.getAttribute( 'position' ).needsUpdate = true;
  28094. }
  28095. dispose() {
  28096. this.geometry.dispose();
  28097. this.material.dispose();
  28098. }
  28099. }
  28100. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28101. _vector.set( x, y, z ).unproject( camera );
  28102. const points = pointMap[ point ];
  28103. if ( points !== undefined ) {
  28104. const position = geometry.getAttribute( 'position' );
  28105. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28106. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28107. }
  28108. }
  28109. }
  28110. const _box = /*@__PURE__*/ new Box3();
  28111. class BoxHelper extends LineSegments {
  28112. constructor( object, color = 0xffff00 ) {
  28113. 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 ] );
  28114. const positions = new Float32Array( 8 * 3 );
  28115. const geometry = new BufferGeometry();
  28116. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28117. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28118. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28119. this.object = object;
  28120. this.type = 'BoxHelper';
  28121. this.matrixAutoUpdate = false;
  28122. this.update();
  28123. }
  28124. update( object ) {
  28125. if ( object !== undefined ) {
  28126. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28127. }
  28128. if ( this.object !== undefined ) {
  28129. _box.setFromObject( this.object );
  28130. }
  28131. if ( _box.isEmpty() ) return;
  28132. const min = _box.min;
  28133. const max = _box.max;
  28134. /*
  28135. 5____4
  28136. 1/___0/|
  28137. | 6__|_7
  28138. 2/___3/
  28139. 0: max.x, max.y, max.z
  28140. 1: min.x, max.y, max.z
  28141. 2: min.x, min.y, max.z
  28142. 3: max.x, min.y, max.z
  28143. 4: max.x, max.y, min.z
  28144. 5: min.x, max.y, min.z
  28145. 6: min.x, min.y, min.z
  28146. 7: max.x, min.y, min.z
  28147. */
  28148. const position = this.geometry.attributes.position;
  28149. const array = position.array;
  28150. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28151. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28152. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28153. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28154. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28155. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28156. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28157. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28158. position.needsUpdate = true;
  28159. this.geometry.computeBoundingSphere();
  28160. }
  28161. setFromObject( object ) {
  28162. this.object = object;
  28163. this.update();
  28164. return this;
  28165. }
  28166. copy( source ) {
  28167. LineSegments.prototype.copy.call( this, source );
  28168. this.object = source.object;
  28169. return this;
  28170. }
  28171. }
  28172. class Box3Helper extends LineSegments {
  28173. constructor( box, color = 0xffff00 ) {
  28174. 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 ] );
  28175. 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 ];
  28176. const geometry = new BufferGeometry();
  28177. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28178. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28179. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28180. this.box = box;
  28181. this.type = 'Box3Helper';
  28182. this.geometry.computeBoundingSphere();
  28183. }
  28184. updateMatrixWorld( force ) {
  28185. const box = this.box;
  28186. if ( box.isEmpty() ) return;
  28187. box.getCenter( this.position );
  28188. box.getSize( this.scale );
  28189. this.scale.multiplyScalar( 0.5 );
  28190. super.updateMatrixWorld( force );
  28191. }
  28192. }
  28193. class PlaneHelper extends Line {
  28194. constructor( plane, size = 1, hex = 0xffff00 ) {
  28195. const color = hex;
  28196. 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 ];
  28197. const geometry = new BufferGeometry();
  28198. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28199. geometry.computeBoundingSphere();
  28200. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28201. this.type = 'PlaneHelper';
  28202. this.plane = plane;
  28203. this.size = size;
  28204. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28205. const geometry2 = new BufferGeometry();
  28206. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28207. geometry2.computeBoundingSphere();
  28208. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28209. }
  28210. updateMatrixWorld( force ) {
  28211. let scale = - this.plane.constant;
  28212. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28213. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28214. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28215. this.lookAt( this.plane.normal );
  28216. super.updateMatrixWorld( force );
  28217. }
  28218. }
  28219. const _axis = /*@__PURE__*/ new Vector3();
  28220. let _lineGeometry, _coneGeometry;
  28221. class ArrowHelper extends Object3D {
  28222. // dir is assumed to be normalized
  28223. 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 ) {
  28224. super();
  28225. this.type = 'ArrowHelper';
  28226. if ( _lineGeometry === undefined ) {
  28227. _lineGeometry = new BufferGeometry();
  28228. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28229. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28230. _coneGeometry.translate( 0, - 0.5, 0 );
  28231. }
  28232. this.position.copy( origin );
  28233. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28234. this.line.matrixAutoUpdate = false;
  28235. this.add( this.line );
  28236. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28237. this.cone.matrixAutoUpdate = false;
  28238. this.add( this.cone );
  28239. this.setDirection( dir );
  28240. this.setLength( length, headLength, headWidth );
  28241. }
  28242. setDirection( dir ) {
  28243. // dir is assumed to be normalized
  28244. if ( dir.y > 0.99999 ) {
  28245. this.quaternion.set( 0, 0, 0, 1 );
  28246. } else if ( dir.y < - 0.99999 ) {
  28247. this.quaternion.set( 1, 0, 0, 0 );
  28248. } else {
  28249. _axis.set( dir.z, 0, - dir.x ).normalize();
  28250. const radians = Math.acos( dir.y );
  28251. this.quaternion.setFromAxisAngle( _axis, radians );
  28252. }
  28253. }
  28254. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28255. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28256. this.line.updateMatrix();
  28257. this.cone.scale.set( headWidth, headLength, headWidth );
  28258. this.cone.position.y = length;
  28259. this.cone.updateMatrix();
  28260. }
  28261. setColor( color ) {
  28262. this.line.material.color.set( color );
  28263. this.cone.material.color.set( color );
  28264. }
  28265. copy( source ) {
  28266. super.copy( source, false );
  28267. this.line.copy( source.line );
  28268. this.cone.copy( source.cone );
  28269. return this;
  28270. }
  28271. }
  28272. class AxesHelper extends LineSegments {
  28273. constructor( size = 1 ) {
  28274. const vertices = [
  28275. 0, 0, 0, size, 0, 0,
  28276. 0, 0, 0, 0, size, 0,
  28277. 0, 0, 0, 0, 0, size
  28278. ];
  28279. const colors = [
  28280. 1, 0, 0, 1, 0.6, 0,
  28281. 0, 1, 0, 0.6, 1, 0,
  28282. 0, 0, 1, 0, 0.6, 1
  28283. ];
  28284. const geometry = new BufferGeometry();
  28285. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28286. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28287. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28288. super( geometry, material );
  28289. this.type = 'AxesHelper';
  28290. }
  28291. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28292. const color = new Color();
  28293. const array = this.geometry.attributes.color.array;
  28294. color.set( xAxisColor );
  28295. color.toArray( array, 0 );
  28296. color.toArray( array, 3 );
  28297. color.set( yAxisColor );
  28298. color.toArray( array, 6 );
  28299. color.toArray( array, 9 );
  28300. color.set( zAxisColor );
  28301. color.toArray( array, 12 );
  28302. color.toArray( array, 15 );
  28303. this.geometry.attributes.color.needsUpdate = true;
  28304. return this;
  28305. }
  28306. dispose() {
  28307. this.geometry.dispose();
  28308. this.material.dispose();
  28309. }
  28310. }
  28311. class ShapePath {
  28312. constructor() {
  28313. this.type = 'ShapePath';
  28314. this.color = new Color();
  28315. this.subPaths = [];
  28316. this.currentPath = null;
  28317. }
  28318. moveTo( x, y ) {
  28319. this.currentPath = new Path();
  28320. this.subPaths.push( this.currentPath );
  28321. this.currentPath.moveTo( x, y );
  28322. return this;
  28323. }
  28324. lineTo( x, y ) {
  28325. this.currentPath.lineTo( x, y );
  28326. return this;
  28327. }
  28328. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  28329. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28330. return this;
  28331. }
  28332. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28333. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28334. return this;
  28335. }
  28336. splineThru( pts ) {
  28337. this.currentPath.splineThru( pts );
  28338. return this;
  28339. }
  28340. toShapes( isCCW, noHoles ) {
  28341. function toShapesNoHoles( inSubpaths ) {
  28342. const shapes = [];
  28343. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28344. const tmpPath = inSubpaths[ i ];
  28345. const tmpShape = new Shape();
  28346. tmpShape.curves = tmpPath.curves;
  28347. shapes.push( tmpShape );
  28348. }
  28349. return shapes;
  28350. }
  28351. function isPointInsidePolygon( inPt, inPolygon ) {
  28352. const polyLen = inPolygon.length;
  28353. // inPt on polygon contour => immediate success or
  28354. // toggling of inside/outside at every single! intersection point of an edge
  28355. // with the horizontal line through inPt, left of inPt
  28356. // not counting lowerY endpoints of edges and whole edges on that line
  28357. let inside = false;
  28358. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28359. let edgeLowPt = inPolygon[ p ];
  28360. let edgeHighPt = inPolygon[ q ];
  28361. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28362. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28363. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28364. // not parallel
  28365. if ( edgeDy < 0 ) {
  28366. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28367. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28368. }
  28369. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28370. if ( inPt.y === edgeLowPt.y ) {
  28371. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28372. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28373. } else {
  28374. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28375. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28376. if ( perpEdge < 0 ) continue;
  28377. inside = ! inside; // true intersection left of inPt
  28378. }
  28379. } else {
  28380. // parallel or collinear
  28381. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28382. // edge lies on the same horizontal line as inPt
  28383. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28384. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28385. // continue;
  28386. }
  28387. }
  28388. return inside;
  28389. }
  28390. const isClockWise = ShapeUtils.isClockWise;
  28391. const subPaths = this.subPaths;
  28392. if ( subPaths.length === 0 ) return [];
  28393. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28394. let solid, tmpPath, tmpShape;
  28395. const shapes = [];
  28396. if ( subPaths.length === 1 ) {
  28397. tmpPath = subPaths[ 0 ];
  28398. tmpShape = new Shape();
  28399. tmpShape.curves = tmpPath.curves;
  28400. shapes.push( tmpShape );
  28401. return shapes;
  28402. }
  28403. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28404. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28405. // console.log("Holes first", holesFirst);
  28406. const betterShapeHoles = [];
  28407. const newShapes = [];
  28408. let newShapeHoles = [];
  28409. let mainIdx = 0;
  28410. let tmpPoints;
  28411. newShapes[ mainIdx ] = undefined;
  28412. newShapeHoles[ mainIdx ] = [];
  28413. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  28414. tmpPath = subPaths[ i ];
  28415. tmpPoints = tmpPath.getPoints();
  28416. solid = isClockWise( tmpPoints );
  28417. solid = isCCW ? ! solid : solid;
  28418. if ( solid ) {
  28419. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28420. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28421. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28422. if ( holesFirst ) mainIdx ++;
  28423. newShapeHoles[ mainIdx ] = [];
  28424. //console.log('cw', i);
  28425. } else {
  28426. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28427. //console.log('ccw', i);
  28428. }
  28429. }
  28430. // only Holes? -> probably all Shapes with wrong orientation
  28431. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28432. if ( newShapes.length > 1 ) {
  28433. let ambiguous = false;
  28434. const toChange = [];
  28435. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28436. betterShapeHoles[ sIdx ] = [];
  28437. }
  28438. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28439. const sho = newShapeHoles[ sIdx ];
  28440. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28441. const ho = sho[ hIdx ];
  28442. let hole_unassigned = true;
  28443. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28444. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28445. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  28446. if ( hole_unassigned ) {
  28447. hole_unassigned = false;
  28448. betterShapeHoles[ s2Idx ].push( ho );
  28449. } else {
  28450. ambiguous = true;
  28451. }
  28452. }
  28453. }
  28454. if ( hole_unassigned ) {
  28455. betterShapeHoles[ sIdx ].push( ho );
  28456. }
  28457. }
  28458. }
  28459. // console.log("ambiguous: ", ambiguous);
  28460. if ( toChange.length > 0 ) {
  28461. // console.log("to change: ", toChange);
  28462. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  28463. }
  28464. }
  28465. let tmpHoles;
  28466. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  28467. tmpShape = newShapes[ i ].s;
  28468. shapes.push( tmpShape );
  28469. tmpHoles = newShapeHoles[ i ];
  28470. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28471. tmpShape.holes.push( tmpHoles[ j ].h );
  28472. }
  28473. }
  28474. //console.log("shape", shapes);
  28475. return shapes;
  28476. }
  28477. }
  28478. const _floatView = new Float32Array( 1 );
  28479. const _int32View = new Int32Array( _floatView.buffer );
  28480. class DataUtils {
  28481. // Converts float32 to float16 (stored as uint16 value).
  28482. static toHalfFloat( val ) {
  28483. if ( val > 65504 ) {
  28484. console.warn( 'THREE.DataUtils.toHalfFloat(): value exceeds 65504.' );
  28485. val = 65504; // maximum representable value in float16
  28486. }
  28487. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28488. /* This method is faster than the OpenEXR implementation (very often
  28489. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28490. * by James Tursa?s half-precision code. */
  28491. _floatView[ 0 ] = val;
  28492. const x = _int32View[ 0 ];
  28493. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  28494. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  28495. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  28496. /* If zero, or denormal, or exponent underflows too much for a denormal
  28497. * half, return signed zero. */
  28498. if ( e < 103 ) return bits;
  28499. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28500. if ( e > 142 ) {
  28501. bits |= 0x7c00;
  28502. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28503. * not Inf, so make sure we set one mantissa bit too. */
  28504. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  28505. return bits;
  28506. }
  28507. /* If exponent underflows but not too much, return a denormal */
  28508. if ( e < 113 ) {
  28509. m |= 0x0800;
  28510. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28511. * to 1, which is OK. */
  28512. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  28513. return bits;
  28514. }
  28515. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  28516. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28517. * the exponent, which is OK. */
  28518. bits += m & 1;
  28519. return bits;
  28520. }
  28521. }
  28522. const LineStrip = 0;
  28523. const LinePieces = 1;
  28524. const NoColors = 0;
  28525. const FaceColors = 1;
  28526. const VertexColors = 2;
  28527. function MeshFaceMaterial( materials ) {
  28528. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  28529. return materials;
  28530. }
  28531. function MultiMaterial( materials = [] ) {
  28532. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  28533. materials.isMultiMaterial = true;
  28534. materials.materials = materials;
  28535. materials.clone = function () {
  28536. return materials.slice();
  28537. };
  28538. return materials;
  28539. }
  28540. function PointCloud( geometry, material ) {
  28541. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28542. return new Points( geometry, material );
  28543. }
  28544. function Particle( material ) {
  28545. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28546. return new Sprite( material );
  28547. }
  28548. function ParticleSystem( geometry, material ) {
  28549. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28550. return new Points( geometry, material );
  28551. }
  28552. function PointCloudMaterial( parameters ) {
  28553. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28554. return new PointsMaterial( parameters );
  28555. }
  28556. function ParticleBasicMaterial( parameters ) {
  28557. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28558. return new PointsMaterial( parameters );
  28559. }
  28560. function ParticleSystemMaterial( parameters ) {
  28561. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28562. return new PointsMaterial( parameters );
  28563. }
  28564. function Vertex( x, y, z ) {
  28565. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28566. return new Vector3( x, y, z );
  28567. }
  28568. //
  28569. function DynamicBufferAttribute( array, itemSize ) {
  28570. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  28571. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  28572. }
  28573. function Int8Attribute( array, itemSize ) {
  28574. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28575. return new Int8BufferAttribute( array, itemSize );
  28576. }
  28577. function Uint8Attribute( array, itemSize ) {
  28578. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28579. return new Uint8BufferAttribute( array, itemSize );
  28580. }
  28581. function Uint8ClampedAttribute( array, itemSize ) {
  28582. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28583. return new Uint8ClampedBufferAttribute( array, itemSize );
  28584. }
  28585. function Int16Attribute( array, itemSize ) {
  28586. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28587. return new Int16BufferAttribute( array, itemSize );
  28588. }
  28589. function Uint16Attribute( array, itemSize ) {
  28590. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28591. return new Uint16BufferAttribute( array, itemSize );
  28592. }
  28593. function Int32Attribute( array, itemSize ) {
  28594. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28595. return new Int32BufferAttribute( array, itemSize );
  28596. }
  28597. function Uint32Attribute( array, itemSize ) {
  28598. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28599. return new Uint32BufferAttribute( array, itemSize );
  28600. }
  28601. function Float32Attribute( array, itemSize ) {
  28602. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28603. return new Float32BufferAttribute( array, itemSize );
  28604. }
  28605. function Float64Attribute( array, itemSize ) {
  28606. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  28607. return new Float64BufferAttribute( array, itemSize );
  28608. }
  28609. //
  28610. Curve.create = function ( construct, getPoint ) {
  28611. console.log( 'THREE.Curve.create() has been deprecated' );
  28612. construct.prototype = Object.create( Curve.prototype );
  28613. construct.prototype.constructor = construct;
  28614. construct.prototype.getPoint = getPoint;
  28615. return construct;
  28616. };
  28617. //
  28618. Path.prototype.fromPoints = function ( points ) {
  28619. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28620. return this.setFromPoints( points );
  28621. };
  28622. //
  28623. function AxisHelper( size ) {
  28624. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28625. return new AxesHelper( size );
  28626. }
  28627. function BoundingBoxHelper( object, color ) {
  28628. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28629. return new BoxHelper( object, color );
  28630. }
  28631. function EdgesHelper( object, hex ) {
  28632. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28633. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28634. }
  28635. GridHelper.prototype.setColors = function () {
  28636. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28637. };
  28638. SkeletonHelper.prototype.update = function () {
  28639. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28640. };
  28641. function WireframeHelper( object, hex ) {
  28642. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28643. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28644. }
  28645. //
  28646. Loader.prototype.extractUrlBase = function ( url ) {
  28647. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28648. return LoaderUtils.extractUrlBase( url );
  28649. };
  28650. Loader.Handlers = {
  28651. add: function ( /* regex, loader */ ) {
  28652. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28653. },
  28654. get: function ( /* file */ ) {
  28655. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28656. }
  28657. };
  28658. function XHRLoader( manager ) {
  28659. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28660. return new FileLoader( manager );
  28661. }
  28662. function BinaryTextureLoader( manager ) {
  28663. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28664. return new DataTextureLoader( manager );
  28665. }
  28666. //
  28667. Box2.prototype.center = function ( optionalTarget ) {
  28668. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28669. return this.getCenter( optionalTarget );
  28670. };
  28671. Box2.prototype.empty = function () {
  28672. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28673. return this.isEmpty();
  28674. };
  28675. Box2.prototype.isIntersectionBox = function ( box ) {
  28676. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28677. return this.intersectsBox( box );
  28678. };
  28679. Box2.prototype.size = function ( optionalTarget ) {
  28680. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28681. return this.getSize( optionalTarget );
  28682. };
  28683. //
  28684. Box3.prototype.center = function ( optionalTarget ) {
  28685. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28686. return this.getCenter( optionalTarget );
  28687. };
  28688. Box3.prototype.empty = function () {
  28689. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28690. return this.isEmpty();
  28691. };
  28692. Box3.prototype.isIntersectionBox = function ( box ) {
  28693. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28694. return this.intersectsBox( box );
  28695. };
  28696. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28697. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28698. return this.intersectsSphere( sphere );
  28699. };
  28700. Box3.prototype.size = function ( optionalTarget ) {
  28701. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  28702. return this.getSize( optionalTarget );
  28703. };
  28704. //
  28705. Sphere.prototype.empty = function () {
  28706. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  28707. return this.isEmpty();
  28708. };
  28709. //
  28710. Frustum.prototype.setFromMatrix = function ( m ) {
  28711. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  28712. return this.setFromProjectionMatrix( m );
  28713. };
  28714. //
  28715. Line3.prototype.center = function ( optionalTarget ) {
  28716. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  28717. return this.getCenter( optionalTarget );
  28718. };
  28719. //
  28720. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  28721. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28722. return this.toArray( array, offset );
  28723. };
  28724. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  28725. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  28726. return vector.applyMatrix3( this );
  28727. };
  28728. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  28729. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  28730. };
  28731. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  28732. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  28733. return attribute.applyMatrix3( this );
  28734. };
  28735. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28736. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  28737. };
  28738. Matrix3.prototype.getInverse = function ( matrix ) {
  28739. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28740. return this.copy( matrix ).invert();
  28741. };
  28742. //
  28743. Matrix4.prototype.extractPosition = function ( m ) {
  28744. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  28745. return this.copyPosition( m );
  28746. };
  28747. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  28748. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28749. return this.toArray( array, offset );
  28750. };
  28751. Matrix4.prototype.getPosition = function () {
  28752. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  28753. return new Vector3().setFromMatrixColumn( this, 3 );
  28754. };
  28755. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  28756. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  28757. return this.makeRotationFromQuaternion( q );
  28758. };
  28759. Matrix4.prototype.multiplyToArray = function () {
  28760. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  28761. };
  28762. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  28763. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28764. return vector.applyMatrix4( this );
  28765. };
  28766. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  28767. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28768. return vector.applyMatrix4( this );
  28769. };
  28770. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  28771. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  28772. };
  28773. Matrix4.prototype.rotateAxis = function ( v ) {
  28774. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  28775. v.transformDirection( this );
  28776. };
  28777. Matrix4.prototype.crossVector = function ( vector ) {
  28778. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28779. return vector.applyMatrix4( this );
  28780. };
  28781. Matrix4.prototype.translate = function () {
  28782. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  28783. };
  28784. Matrix4.prototype.rotateX = function () {
  28785. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  28786. };
  28787. Matrix4.prototype.rotateY = function () {
  28788. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  28789. };
  28790. Matrix4.prototype.rotateZ = function () {
  28791. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  28792. };
  28793. Matrix4.prototype.rotateByAxis = function () {
  28794. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  28795. };
  28796. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  28797. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  28798. return attribute.applyMatrix4( this );
  28799. };
  28800. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28801. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  28802. };
  28803. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  28804. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  28805. return this.makePerspective( left, right, top, bottom, near, far );
  28806. };
  28807. Matrix4.prototype.getInverse = function ( matrix ) {
  28808. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28809. return this.copy( matrix ).invert();
  28810. };
  28811. //
  28812. Plane.prototype.isIntersectionLine = function ( line ) {
  28813. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  28814. return this.intersectsLine( line );
  28815. };
  28816. //
  28817. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  28818. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  28819. return vector.applyQuaternion( this );
  28820. };
  28821. Quaternion.prototype.inverse = function ( ) {
  28822. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  28823. return this.invert();
  28824. };
  28825. //
  28826. Ray.prototype.isIntersectionBox = function ( box ) {
  28827. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28828. return this.intersectsBox( box );
  28829. };
  28830. Ray.prototype.isIntersectionPlane = function ( plane ) {
  28831. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  28832. return this.intersectsPlane( plane );
  28833. };
  28834. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  28835. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28836. return this.intersectsSphere( sphere );
  28837. };
  28838. //
  28839. Triangle.prototype.area = function () {
  28840. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  28841. return this.getArea();
  28842. };
  28843. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  28844. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28845. return this.getBarycoord( point, target );
  28846. };
  28847. Triangle.prototype.midpoint = function ( target ) {
  28848. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  28849. return this.getMidpoint( target );
  28850. };
  28851. Triangle.prototypenormal = function ( target ) {
  28852. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28853. return this.getNormal( target );
  28854. };
  28855. Triangle.prototype.plane = function ( target ) {
  28856. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  28857. return this.getPlane( target );
  28858. };
  28859. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  28860. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28861. return Triangle.getBarycoord( point, a, b, c, target );
  28862. };
  28863. Triangle.normal = function ( a, b, c, target ) {
  28864. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28865. return Triangle.getNormal( a, b, c, target );
  28866. };
  28867. //
  28868. Shape.prototype.extractAllPoints = function ( divisions ) {
  28869. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  28870. return this.extractPoints( divisions );
  28871. };
  28872. Shape.prototype.extrude = function ( options ) {
  28873. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  28874. return new ExtrudeGeometry( this, options );
  28875. };
  28876. Shape.prototype.makeGeometry = function ( options ) {
  28877. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  28878. return new ShapeGeometry( this, options );
  28879. };
  28880. //
  28881. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  28882. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28883. return this.fromBufferAttribute( attribute, index, offset );
  28884. };
  28885. Vector2.prototype.distanceToManhattan = function ( v ) {
  28886. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28887. return this.manhattanDistanceTo( v );
  28888. };
  28889. Vector2.prototype.lengthManhattan = function () {
  28890. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  28891. return this.manhattanLength();
  28892. };
  28893. //
  28894. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28895. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  28896. };
  28897. Vector3.prototype.setEulerFromQuaternion = function () {
  28898. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  28899. };
  28900. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  28901. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  28902. return this.setFromMatrixPosition( m );
  28903. };
  28904. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  28905. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  28906. return this.setFromMatrixScale( m );
  28907. };
  28908. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  28909. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  28910. return this.setFromMatrixColumn( matrix, index );
  28911. };
  28912. Vector3.prototype.applyProjection = function ( m ) {
  28913. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  28914. return this.applyMatrix4( m );
  28915. };
  28916. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  28917. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28918. return this.fromBufferAttribute( attribute, index, offset );
  28919. };
  28920. Vector3.prototype.distanceToManhattan = function ( v ) {
  28921. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28922. return this.manhattanDistanceTo( v );
  28923. };
  28924. Vector3.prototype.lengthManhattan = function () {
  28925. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  28926. return this.manhattanLength();
  28927. };
  28928. //
  28929. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  28930. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28931. return this.fromBufferAttribute( attribute, index, offset );
  28932. };
  28933. Vector4.prototype.lengthManhattan = function () {
  28934. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  28935. return this.manhattanLength();
  28936. };
  28937. //
  28938. Object3D.prototype.getChildByName = function ( name ) {
  28939. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  28940. return this.getObjectByName( name );
  28941. };
  28942. Object3D.prototype.renderDepth = function () {
  28943. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  28944. };
  28945. Object3D.prototype.translate = function ( distance, axis ) {
  28946. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  28947. return this.translateOnAxis( axis, distance );
  28948. };
  28949. Object3D.prototype.getWorldRotation = function () {
  28950. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  28951. };
  28952. Object3D.prototype.applyMatrix = function ( matrix ) {
  28953. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  28954. return this.applyMatrix4( matrix );
  28955. };
  28956. Object.defineProperties( Object3D.prototype, {
  28957. eulerOrder: {
  28958. get: function () {
  28959. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28960. return this.rotation.order;
  28961. },
  28962. set: function ( value ) {
  28963. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28964. this.rotation.order = value;
  28965. }
  28966. },
  28967. useQuaternion: {
  28968. get: function () {
  28969. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28970. },
  28971. set: function () {
  28972. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28973. }
  28974. }
  28975. } );
  28976. Mesh.prototype.setDrawMode = function () {
  28977. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28978. };
  28979. Object.defineProperties( Mesh.prototype, {
  28980. drawMode: {
  28981. get: function () {
  28982. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  28983. return TrianglesDrawMode;
  28984. },
  28985. set: function () {
  28986. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28987. }
  28988. }
  28989. } );
  28990. SkinnedMesh.prototype.initBones = function () {
  28991. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  28992. };
  28993. //
  28994. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  28995. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  28996. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  28997. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  28998. this.setFocalLength( focalLength );
  28999. };
  29000. //
  29001. Object.defineProperties( Light.prototype, {
  29002. onlyShadow: {
  29003. set: function () {
  29004. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29005. }
  29006. },
  29007. shadowCameraFov: {
  29008. set: function ( value ) {
  29009. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29010. this.shadow.camera.fov = value;
  29011. }
  29012. },
  29013. shadowCameraLeft: {
  29014. set: function ( value ) {
  29015. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29016. this.shadow.camera.left = value;
  29017. }
  29018. },
  29019. shadowCameraRight: {
  29020. set: function ( value ) {
  29021. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29022. this.shadow.camera.right = value;
  29023. }
  29024. },
  29025. shadowCameraTop: {
  29026. set: function ( value ) {
  29027. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29028. this.shadow.camera.top = value;
  29029. }
  29030. },
  29031. shadowCameraBottom: {
  29032. set: function ( value ) {
  29033. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29034. this.shadow.camera.bottom = value;
  29035. }
  29036. },
  29037. shadowCameraNear: {
  29038. set: function ( value ) {
  29039. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29040. this.shadow.camera.near = value;
  29041. }
  29042. },
  29043. shadowCameraFar: {
  29044. set: function ( value ) {
  29045. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29046. this.shadow.camera.far = value;
  29047. }
  29048. },
  29049. shadowCameraVisible: {
  29050. set: function () {
  29051. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29052. }
  29053. },
  29054. shadowBias: {
  29055. set: function ( value ) {
  29056. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29057. this.shadow.bias = value;
  29058. }
  29059. },
  29060. shadowDarkness: {
  29061. set: function () {
  29062. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29063. }
  29064. },
  29065. shadowMapWidth: {
  29066. set: function ( value ) {
  29067. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29068. this.shadow.mapSize.width = value;
  29069. }
  29070. },
  29071. shadowMapHeight: {
  29072. set: function ( value ) {
  29073. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29074. this.shadow.mapSize.height = value;
  29075. }
  29076. }
  29077. } );
  29078. //
  29079. Object.defineProperties( BufferAttribute.prototype, {
  29080. length: {
  29081. get: function () {
  29082. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29083. return this.array.length;
  29084. }
  29085. },
  29086. dynamic: {
  29087. get: function () {
  29088. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29089. return this.usage === DynamicDrawUsage;
  29090. },
  29091. set: function ( /* value */ ) {
  29092. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29093. this.setUsage( DynamicDrawUsage );
  29094. }
  29095. }
  29096. } );
  29097. BufferAttribute.prototype.setDynamic = function ( value ) {
  29098. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29099. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29100. return this;
  29101. };
  29102. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  29103. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  29104. },
  29105. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  29106. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29107. };
  29108. //
  29109. BufferGeometry.prototype.addIndex = function ( index ) {
  29110. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29111. this.setIndex( index );
  29112. };
  29113. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  29114. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  29115. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  29116. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  29117. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  29118. }
  29119. if ( name === 'index' ) {
  29120. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  29121. this.setIndex( attribute );
  29122. return this;
  29123. }
  29124. return this.setAttribute( name, attribute );
  29125. };
  29126. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  29127. if ( indexOffset !== undefined ) {
  29128. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29129. }
  29130. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29131. this.addGroup( start, count );
  29132. };
  29133. BufferGeometry.prototype.clearDrawCalls = function () {
  29134. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29135. this.clearGroups();
  29136. };
  29137. BufferGeometry.prototype.computeOffsets = function () {
  29138. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29139. };
  29140. BufferGeometry.prototype.removeAttribute = function ( name ) {
  29141. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  29142. return this.deleteAttribute( name );
  29143. };
  29144. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  29145. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29146. return this.applyMatrix4( matrix );
  29147. };
  29148. Object.defineProperties( BufferGeometry.prototype, {
  29149. drawcalls: {
  29150. get: function () {
  29151. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29152. return this.groups;
  29153. }
  29154. },
  29155. offsets: {
  29156. get: function () {
  29157. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29158. return this.groups;
  29159. }
  29160. }
  29161. } );
  29162. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  29163. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29164. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29165. return this;
  29166. };
  29167. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  29168. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29169. };
  29170. //
  29171. ExtrudeGeometry.prototype.getArrays = function () {
  29172. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  29173. };
  29174. ExtrudeGeometry.prototype.addShapeList = function () {
  29175. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  29176. };
  29177. ExtrudeGeometry.prototype.addShape = function () {
  29178. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  29179. };
  29180. //
  29181. Scene.prototype.dispose = function () {
  29182. console.error( 'THREE.Scene: .dispose() has been removed.' );
  29183. };
  29184. //
  29185. Uniform.prototype.onUpdate = function () {
  29186. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29187. return this;
  29188. };
  29189. //
  29190. Object.defineProperties( Material.prototype, {
  29191. wrapAround: {
  29192. get: function () {
  29193. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29194. },
  29195. set: function () {
  29196. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29197. }
  29198. },
  29199. overdraw: {
  29200. get: function () {
  29201. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29202. },
  29203. set: function () {
  29204. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29205. }
  29206. },
  29207. wrapRGB: {
  29208. get: function () {
  29209. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  29210. return new Color();
  29211. }
  29212. },
  29213. shading: {
  29214. get: function () {
  29215. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29216. },
  29217. set: function ( value ) {
  29218. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29219. this.flatShading = ( value === FlatShading );
  29220. }
  29221. },
  29222. stencilMask: {
  29223. get: function () {
  29224. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29225. return this.stencilFuncMask;
  29226. },
  29227. set: function ( value ) {
  29228. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29229. this.stencilFuncMask = value;
  29230. }
  29231. },
  29232. vertexTangents: {
  29233. get: function () {
  29234. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29235. },
  29236. set: function () {
  29237. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29238. }
  29239. },
  29240. } );
  29241. Object.defineProperties( ShaderMaterial.prototype, {
  29242. derivatives: {
  29243. get: function () {
  29244. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29245. return this.extensions.derivatives;
  29246. },
  29247. set: function ( value ) {
  29248. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29249. this.extensions.derivatives = value;
  29250. }
  29251. }
  29252. } );
  29253. //
  29254. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  29255. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  29256. this.setRenderTarget( renderTarget );
  29257. this.clear( color, depth, stencil );
  29258. };
  29259. WebGLRenderer.prototype.animate = function ( callback ) {
  29260. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  29261. this.setAnimationLoop( callback );
  29262. };
  29263. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  29264. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  29265. return this.getRenderTarget();
  29266. };
  29267. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  29268. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  29269. return this.capabilities.getMaxAnisotropy();
  29270. };
  29271. WebGLRenderer.prototype.getPrecision = function () {
  29272. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  29273. return this.capabilities.precision;
  29274. };
  29275. WebGLRenderer.prototype.resetGLState = function () {
  29276. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  29277. return this.state.reset();
  29278. };
  29279. WebGLRenderer.prototype.supportsFloatTextures = function () {
  29280. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29281. return this.extensions.get( 'OES_texture_float' );
  29282. };
  29283. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  29284. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29285. return this.extensions.get( 'OES_texture_half_float' );
  29286. };
  29287. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  29288. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29289. return this.extensions.get( 'OES_standard_derivatives' );
  29290. };
  29291. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  29292. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29293. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29294. };
  29295. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  29296. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29297. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29298. };
  29299. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  29300. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29301. return this.extensions.get( 'EXT_blend_minmax' );
  29302. };
  29303. WebGLRenderer.prototype.supportsVertexTextures = function () {
  29304. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29305. return this.capabilities.vertexTextures;
  29306. };
  29307. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  29308. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29309. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29310. };
  29311. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  29312. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29313. this.setScissorTest( boolean );
  29314. };
  29315. WebGLRenderer.prototype.initMaterial = function () {
  29316. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29317. };
  29318. WebGLRenderer.prototype.addPrePlugin = function () {
  29319. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29320. };
  29321. WebGLRenderer.prototype.addPostPlugin = function () {
  29322. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29323. };
  29324. WebGLRenderer.prototype.updateShadowMap = function () {
  29325. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29326. };
  29327. WebGLRenderer.prototype.setFaceCulling = function () {
  29328. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  29329. };
  29330. WebGLRenderer.prototype.allocTextureUnit = function () {
  29331. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  29332. };
  29333. WebGLRenderer.prototype.setTexture = function () {
  29334. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  29335. };
  29336. WebGLRenderer.prototype.setTexture2D = function () {
  29337. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  29338. };
  29339. WebGLRenderer.prototype.setTextureCube = function () {
  29340. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  29341. };
  29342. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29343. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  29344. return this.getActiveMipmapLevel();
  29345. };
  29346. Object.defineProperties( WebGLRenderer.prototype, {
  29347. shadowMapEnabled: {
  29348. get: function () {
  29349. return this.shadowMap.enabled;
  29350. },
  29351. set: function ( value ) {
  29352. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29353. this.shadowMap.enabled = value;
  29354. }
  29355. },
  29356. shadowMapType: {
  29357. get: function () {
  29358. return this.shadowMap.type;
  29359. },
  29360. set: function ( value ) {
  29361. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29362. this.shadowMap.type = value;
  29363. }
  29364. },
  29365. shadowMapCullFace: {
  29366. get: function () {
  29367. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29368. return undefined;
  29369. },
  29370. set: function ( /* value */ ) {
  29371. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29372. }
  29373. },
  29374. context: {
  29375. get: function () {
  29376. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  29377. return this.getContext();
  29378. }
  29379. },
  29380. vr: {
  29381. get: function () {
  29382. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  29383. return this.xr;
  29384. }
  29385. },
  29386. gammaInput: {
  29387. get: function () {
  29388. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29389. return false;
  29390. },
  29391. set: function () {
  29392. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29393. }
  29394. },
  29395. gammaOutput: {
  29396. get: function () {
  29397. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29398. return false;
  29399. },
  29400. set: function ( value ) {
  29401. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29402. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  29403. }
  29404. },
  29405. toneMappingWhitePoint: {
  29406. get: function () {
  29407. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29408. return 1.0;
  29409. },
  29410. set: function () {
  29411. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29412. }
  29413. },
  29414. } );
  29415. Object.defineProperties( WebGLShadowMap.prototype, {
  29416. cullFace: {
  29417. get: function () {
  29418. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29419. return undefined;
  29420. },
  29421. set: function ( /* cullFace */ ) {
  29422. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29423. }
  29424. },
  29425. renderReverseSided: {
  29426. get: function () {
  29427. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29428. return undefined;
  29429. },
  29430. set: function () {
  29431. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29432. }
  29433. },
  29434. renderSingleSided: {
  29435. get: function () {
  29436. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29437. return undefined;
  29438. },
  29439. set: function () {
  29440. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29441. }
  29442. }
  29443. } );
  29444. function WebGLRenderTargetCube( width, height, options ) {
  29445. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  29446. return new WebGLCubeRenderTarget( width, options );
  29447. }
  29448. //
  29449. Object.defineProperties( WebGLRenderTarget.prototype, {
  29450. wrapS: {
  29451. get: function () {
  29452. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29453. return this.texture.wrapS;
  29454. },
  29455. set: function ( value ) {
  29456. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29457. this.texture.wrapS = value;
  29458. }
  29459. },
  29460. wrapT: {
  29461. get: function () {
  29462. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29463. return this.texture.wrapT;
  29464. },
  29465. set: function ( value ) {
  29466. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29467. this.texture.wrapT = value;
  29468. }
  29469. },
  29470. magFilter: {
  29471. get: function () {
  29472. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29473. return this.texture.magFilter;
  29474. },
  29475. set: function ( value ) {
  29476. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29477. this.texture.magFilter = value;
  29478. }
  29479. },
  29480. minFilter: {
  29481. get: function () {
  29482. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29483. return this.texture.minFilter;
  29484. },
  29485. set: function ( value ) {
  29486. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29487. this.texture.minFilter = value;
  29488. }
  29489. },
  29490. anisotropy: {
  29491. get: function () {
  29492. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29493. return this.texture.anisotropy;
  29494. },
  29495. set: function ( value ) {
  29496. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29497. this.texture.anisotropy = value;
  29498. }
  29499. },
  29500. offset: {
  29501. get: function () {
  29502. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29503. return this.texture.offset;
  29504. },
  29505. set: function ( value ) {
  29506. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29507. this.texture.offset = value;
  29508. }
  29509. },
  29510. repeat: {
  29511. get: function () {
  29512. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29513. return this.texture.repeat;
  29514. },
  29515. set: function ( value ) {
  29516. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29517. this.texture.repeat = value;
  29518. }
  29519. },
  29520. format: {
  29521. get: function () {
  29522. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29523. return this.texture.format;
  29524. },
  29525. set: function ( value ) {
  29526. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29527. this.texture.format = value;
  29528. }
  29529. },
  29530. type: {
  29531. get: function () {
  29532. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29533. return this.texture.type;
  29534. },
  29535. set: function ( value ) {
  29536. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29537. this.texture.type = value;
  29538. }
  29539. },
  29540. generateMipmaps: {
  29541. get: function () {
  29542. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29543. return this.texture.generateMipmaps;
  29544. },
  29545. set: function ( value ) {
  29546. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29547. this.texture.generateMipmaps = value;
  29548. }
  29549. }
  29550. } );
  29551. //
  29552. Audio.prototype.load = function ( file ) {
  29553. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29554. const scope = this;
  29555. const audioLoader = new AudioLoader();
  29556. audioLoader.load( file, function ( buffer ) {
  29557. scope.setBuffer( buffer );
  29558. } );
  29559. return this;
  29560. };
  29561. AudioAnalyser.prototype.getData = function () {
  29562. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29563. return this.getFrequencyData();
  29564. };
  29565. //
  29566. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29567. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29568. return this.update( renderer, scene );
  29569. };
  29570. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29571. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29572. return this.renderTarget.clear( renderer, color, depth, stencil );
  29573. };
  29574. ImageUtils.crossOrigin = undefined;
  29575. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29576. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29577. const loader = new TextureLoader();
  29578. loader.setCrossOrigin( this.crossOrigin );
  29579. const texture = loader.load( url, onLoad, undefined, onError );
  29580. if ( mapping ) texture.mapping = mapping;
  29581. return texture;
  29582. };
  29583. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29584. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29585. const loader = new CubeTextureLoader();
  29586. loader.setCrossOrigin( this.crossOrigin );
  29587. const texture = loader.load( urls, onLoad, undefined, onError );
  29588. if ( mapping ) texture.mapping = mapping;
  29589. return texture;
  29590. };
  29591. ImageUtils.loadCompressedTexture = function () {
  29592. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29593. };
  29594. ImageUtils.loadCompressedTextureCube = function () {
  29595. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29596. };
  29597. //
  29598. function CanvasRenderer() {
  29599. console.error( 'THREE.CanvasRenderer has been removed' );
  29600. }
  29601. //
  29602. function JSONLoader() {
  29603. console.error( 'THREE.JSONLoader has been removed.' );
  29604. }
  29605. //
  29606. const SceneUtils = {
  29607. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29608. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29609. },
  29610. detach: function ( /* child, parent, scene */ ) {
  29611. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29612. },
  29613. attach: function ( /* child, scene, parent */ ) {
  29614. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29615. }
  29616. };
  29617. //
  29618. function LensFlare() {
  29619. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29620. }
  29621. //
  29622. function ParametricGeometry() {
  29623. console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' );
  29624. return new BufferGeometry();
  29625. }
  29626. function TextGeometry() {
  29627. console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' );
  29628. return new BufferGeometry();
  29629. }
  29630. function FontLoader() {
  29631. console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' );
  29632. }
  29633. function Font() {
  29634. console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' );
  29635. }
  29636. function ImmediateRenderObject() {
  29637. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29638. }
  29639. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29640. /* eslint-disable no-undef */
  29641. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29642. revision: REVISION,
  29643. } } ) );
  29644. /* eslint-enable no-undef */
  29645. }
  29646. if ( typeof window !== 'undefined' ) {
  29647. if ( window.__THREE__ ) {
  29648. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29649. } else {
  29650. window.__THREE__ = REVISION;
  29651. }
  29652. }
  29653. 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, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, 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, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GammaEncoding, 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, 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, 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, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, 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, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry as ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, 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, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGL1Renderer, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };