three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '137';
  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 UnsignedInt248Type = 1020;
  92. const AlphaFormat = 1021;
  93. const RGBFormat = 1022;
  94. const RGBAFormat = 1023;
  95. const LuminanceFormat = 1024;
  96. const LuminanceAlphaFormat = 1025;
  97. const DepthFormat = 1026;
  98. const DepthStencilFormat = 1027;
  99. const RedFormat = 1028;
  100. const RedIntegerFormat = 1029;
  101. const RGFormat = 1030;
  102. const RGIntegerFormat = 1031;
  103. const RGBAIntegerFormat = 1033;
  104. const RGB_S3TC_DXT1_Format = 33776;
  105. const RGBA_S3TC_DXT1_Format = 33777;
  106. const RGBA_S3TC_DXT3_Format = 33778;
  107. const RGBA_S3TC_DXT5_Format = 33779;
  108. const RGB_PVRTC_4BPPV1_Format = 35840;
  109. const RGB_PVRTC_2BPPV1_Format = 35841;
  110. const RGBA_PVRTC_4BPPV1_Format = 35842;
  111. const RGBA_PVRTC_2BPPV1_Format = 35843;
  112. const RGB_ETC1_Format = 36196;
  113. const RGB_ETC2_Format = 37492;
  114. const RGBA_ETC2_EAC_Format = 37496;
  115. const RGBA_ASTC_4x4_Format = 37808;
  116. const RGBA_ASTC_5x4_Format = 37809;
  117. const RGBA_ASTC_5x5_Format = 37810;
  118. const RGBA_ASTC_6x5_Format = 37811;
  119. const RGBA_ASTC_6x6_Format = 37812;
  120. const RGBA_ASTC_8x5_Format = 37813;
  121. const RGBA_ASTC_8x6_Format = 37814;
  122. const RGBA_ASTC_8x8_Format = 37815;
  123. const RGBA_ASTC_10x5_Format = 37816;
  124. const RGBA_ASTC_10x6_Format = 37817;
  125. const RGBA_ASTC_10x8_Format = 37818;
  126. const RGBA_ASTC_10x10_Format = 37819;
  127. const RGBA_ASTC_12x10_Format = 37820;
  128. const RGBA_ASTC_12x12_Format = 37821;
  129. const RGBA_BPTC_Format = 36492;
  130. const LoopOnce = 2200;
  131. const LoopRepeat = 2201;
  132. const LoopPingPong = 2202;
  133. const InterpolateDiscrete = 2300;
  134. const InterpolateLinear = 2301;
  135. const InterpolateSmooth = 2302;
  136. const ZeroCurvatureEnding = 2400;
  137. const ZeroSlopeEnding = 2401;
  138. const WrapAroundEnding = 2402;
  139. const NormalAnimationBlendMode = 2500;
  140. const AdditiveAnimationBlendMode = 2501;
  141. const TrianglesDrawMode = 0;
  142. const TriangleStripDrawMode = 1;
  143. const TriangleFanDrawMode = 2;
  144. const LinearEncoding = 3000;
  145. const sRGBEncoding = 3001;
  146. const BasicDepthPacking = 3200;
  147. const RGBADepthPacking = 3201;
  148. const TangentSpaceNormalMap = 0;
  149. const ObjectSpaceNormalMap = 1;
  150. const ZeroStencilOp = 0;
  151. const KeepStencilOp = 7680;
  152. const ReplaceStencilOp = 7681;
  153. const IncrementStencilOp = 7682;
  154. const DecrementStencilOp = 7683;
  155. const IncrementWrapStencilOp = 34055;
  156. const DecrementWrapStencilOp = 34056;
  157. const InvertStencilOp = 5386;
  158. const NeverStencilFunc = 512;
  159. const LessStencilFunc = 513;
  160. const EqualStencilFunc = 514;
  161. const LessEqualStencilFunc = 515;
  162. const GreaterStencilFunc = 516;
  163. const NotEqualStencilFunc = 517;
  164. const GreaterEqualStencilFunc = 518;
  165. const AlwaysStencilFunc = 519;
  166. const StaticDrawUsage = 35044;
  167. const DynamicDrawUsage = 35048;
  168. const StreamDrawUsage = 35040;
  169. const StaticReadUsage = 35045;
  170. const DynamicReadUsage = 35049;
  171. const StreamReadUsage = 35041;
  172. const StaticCopyUsage = 35046;
  173. const DynamicCopyUsage = 35050;
  174. const StreamCopyUsage = 35042;
  175. const GLSL1 = '100';
  176. const GLSL3 = '300 es';
  177. const _SRGBAFormat = 1035; // fallback for WebGL 1
  178. /**
  179. * https://github.com/mrdoob/eventdispatcher.js/
  180. */
  181. class EventDispatcher {
  182. addEventListener( type, listener ) {
  183. if ( this._listeners === undefined ) this._listeners = {};
  184. const listeners = this._listeners;
  185. if ( listeners[ type ] === undefined ) {
  186. listeners[ type ] = [];
  187. }
  188. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  189. listeners[ type ].push( listener );
  190. }
  191. }
  192. hasEventListener( type, listener ) {
  193. if ( this._listeners === undefined ) return false;
  194. const listeners = this._listeners;
  195. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  196. }
  197. removeEventListener( type, listener ) {
  198. if ( this._listeners === undefined ) return;
  199. const listeners = this._listeners;
  200. const listenerArray = listeners[ type ];
  201. if ( listenerArray !== undefined ) {
  202. const index = listenerArray.indexOf( listener );
  203. if ( index !== - 1 ) {
  204. listenerArray.splice( index, 1 );
  205. }
  206. }
  207. }
  208. dispatchEvent( event ) {
  209. if ( this._listeners === undefined ) return;
  210. const listeners = this._listeners;
  211. const listenerArray = listeners[ event.type ];
  212. if ( listenerArray !== undefined ) {
  213. event.target = this;
  214. // Make a copy, in case listeners are removed while iterating.
  215. const array = listenerArray.slice( 0 );
  216. for ( let i = 0, l = array.length; i < l; i ++ ) {
  217. array[ i ].call( this, event );
  218. }
  219. event.target = null;
  220. }
  221. }
  222. }
  223. const _lut = [];
  224. for ( let i = 0; i < 256; i ++ ) {
  225. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  226. }
  227. let _seed = 1234567;
  228. const DEG2RAD = Math.PI / 180;
  229. const RAD2DEG = 180 / Math.PI;
  230. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  231. function generateUUID() {
  232. const d0 = Math.random() * 0xffffffff | 0;
  233. const d1 = Math.random() * 0xffffffff | 0;
  234. const d2 = Math.random() * 0xffffffff | 0;
  235. const d3 = Math.random() * 0xffffffff | 0;
  236. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  237. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  238. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  239. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  240. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  241. return uuid.toUpperCase();
  242. }
  243. function clamp( value, min, max ) {
  244. return Math.max( min, Math.min( max, value ) );
  245. }
  246. // compute euclidian modulo of m % n
  247. // https://en.wikipedia.org/wiki/Modulo_operation
  248. function euclideanModulo( n, m ) {
  249. return ( ( n % m ) + m ) % m;
  250. }
  251. // Linear mapping from range <a1, a2> to range <b1, b2>
  252. function mapLinear( x, a1, a2, b1, b2 ) {
  253. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  254. }
  255. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  256. function inverseLerp( x, y, value ) {
  257. if ( x !== y ) {
  258. return ( value - x ) / ( y - x );
  259. } else {
  260. return 0;
  261. }
  262. }
  263. // https://en.wikipedia.org/wiki/Linear_interpolation
  264. function lerp( x, y, t ) {
  265. return ( 1 - t ) * x + t * y;
  266. }
  267. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  268. function damp( x, y, lambda, dt ) {
  269. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  270. }
  271. // https://www.desmos.com/calculator/vcsjnyz7x4
  272. function pingpong( x, length = 1 ) {
  273. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  274. }
  275. // http://en.wikipedia.org/wiki/Smoothstep
  276. function smoothstep( x, min, max ) {
  277. if ( x <= min ) return 0;
  278. if ( x >= max ) return 1;
  279. x = ( x - min ) / ( max - min );
  280. return x * x * ( 3 - 2 * x );
  281. }
  282. function smootherstep( x, min, max ) {
  283. if ( x <= min ) return 0;
  284. if ( x >= max ) return 1;
  285. x = ( x - min ) / ( max - min );
  286. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  287. }
  288. // Random integer from <low, high> interval
  289. function randInt( low, high ) {
  290. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  291. }
  292. // Random float from <low, high> interval
  293. function randFloat( low, high ) {
  294. return low + Math.random() * ( high - low );
  295. }
  296. // Random float from <-range/2, range/2> interval
  297. function randFloatSpread( range ) {
  298. return range * ( 0.5 - Math.random() );
  299. }
  300. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  301. function seededRandom( s ) {
  302. if ( s !== undefined ) _seed = s % 2147483647;
  303. // Park-Miller algorithm
  304. _seed = _seed * 16807 % 2147483647;
  305. return ( _seed - 1 ) / 2147483646;
  306. }
  307. function degToRad( degrees ) {
  308. return degrees * DEG2RAD;
  309. }
  310. function radToDeg( radians ) {
  311. return radians * RAD2DEG;
  312. }
  313. function isPowerOfTwo( value ) {
  314. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  315. }
  316. function ceilPowerOfTwo( value ) {
  317. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  318. }
  319. function floorPowerOfTwo( value ) {
  320. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  321. }
  322. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  323. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  324. // rotations are applied to the axes in the order specified by 'order'
  325. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  326. // angles are in radians
  327. const cos = Math.cos;
  328. const sin = Math.sin;
  329. const c2 = cos( b / 2 );
  330. const s2 = sin( b / 2 );
  331. const c13 = cos( ( a + c ) / 2 );
  332. const s13 = sin( ( a + c ) / 2 );
  333. const c1_3 = cos( ( a - c ) / 2 );
  334. const s1_3 = sin( ( a - c ) / 2 );
  335. const c3_1 = cos( ( c - a ) / 2 );
  336. const s3_1 = sin( ( c - a ) / 2 );
  337. switch ( order ) {
  338. case 'XYX':
  339. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  340. break;
  341. case 'YZY':
  342. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  343. break;
  344. case 'ZXZ':
  345. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  346. break;
  347. case 'XZX':
  348. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  349. break;
  350. case 'YXY':
  351. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  352. break;
  353. case 'ZYZ':
  354. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  355. break;
  356. default:
  357. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  358. }
  359. }
  360. var MathUtils = /*#__PURE__*/Object.freeze({
  361. __proto__: null,
  362. DEG2RAD: DEG2RAD,
  363. RAD2DEG: RAD2DEG,
  364. generateUUID: generateUUID,
  365. clamp: clamp,
  366. euclideanModulo: euclideanModulo,
  367. mapLinear: mapLinear,
  368. inverseLerp: inverseLerp,
  369. lerp: lerp,
  370. damp: damp,
  371. pingpong: pingpong,
  372. smoothstep: smoothstep,
  373. smootherstep: smootherstep,
  374. randInt: randInt,
  375. randFloat: randFloat,
  376. randFloatSpread: randFloatSpread,
  377. seededRandom: seededRandom,
  378. degToRad: degToRad,
  379. radToDeg: radToDeg,
  380. isPowerOfTwo: isPowerOfTwo,
  381. ceilPowerOfTwo: ceilPowerOfTwo,
  382. floorPowerOfTwo: floorPowerOfTwo,
  383. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  384. });
  385. class Vector2 {
  386. constructor( x = 0, y = 0 ) {
  387. this.x = x;
  388. this.y = y;
  389. }
  390. get width() {
  391. return this.x;
  392. }
  393. set width( value ) {
  394. this.x = value;
  395. }
  396. get height() {
  397. return this.y;
  398. }
  399. set height( value ) {
  400. this.y = value;
  401. }
  402. set( x, y ) {
  403. this.x = x;
  404. this.y = y;
  405. return this;
  406. }
  407. setScalar( scalar ) {
  408. this.x = scalar;
  409. this.y = scalar;
  410. return this;
  411. }
  412. setX( x ) {
  413. this.x = x;
  414. return this;
  415. }
  416. setY( y ) {
  417. this.y = y;
  418. return this;
  419. }
  420. setComponent( index, value ) {
  421. switch ( index ) {
  422. case 0: this.x = value; break;
  423. case 1: this.y = value; break;
  424. default: throw new Error( 'index is out of range: ' + index );
  425. }
  426. return this;
  427. }
  428. getComponent( index ) {
  429. switch ( index ) {
  430. case 0: return this.x;
  431. case 1: return this.y;
  432. default: throw new Error( 'index is out of range: ' + index );
  433. }
  434. }
  435. clone() {
  436. return new this.constructor( this.x, this.y );
  437. }
  438. copy( v ) {
  439. this.x = v.x;
  440. this.y = v.y;
  441. return this;
  442. }
  443. add( v, w ) {
  444. if ( w !== undefined ) {
  445. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  446. return this.addVectors( v, w );
  447. }
  448. this.x += v.x;
  449. this.y += v.y;
  450. return this;
  451. }
  452. addScalar( s ) {
  453. this.x += s;
  454. this.y += s;
  455. return this;
  456. }
  457. addVectors( a, b ) {
  458. this.x = a.x + b.x;
  459. this.y = a.y + b.y;
  460. return this;
  461. }
  462. addScaledVector( v, s ) {
  463. this.x += v.x * s;
  464. this.y += v.y * s;
  465. return this;
  466. }
  467. sub( v, w ) {
  468. if ( w !== undefined ) {
  469. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  470. return this.subVectors( v, w );
  471. }
  472. this.x -= v.x;
  473. this.y -= v.y;
  474. return this;
  475. }
  476. subScalar( s ) {
  477. this.x -= s;
  478. this.y -= s;
  479. return this;
  480. }
  481. subVectors( a, b ) {
  482. this.x = a.x - b.x;
  483. this.y = a.y - b.y;
  484. return this;
  485. }
  486. multiply( v ) {
  487. this.x *= v.x;
  488. this.y *= v.y;
  489. return this;
  490. }
  491. multiplyScalar( scalar ) {
  492. this.x *= scalar;
  493. this.y *= scalar;
  494. return this;
  495. }
  496. divide( v ) {
  497. this.x /= v.x;
  498. this.y /= v.y;
  499. return this;
  500. }
  501. divideScalar( scalar ) {
  502. return this.multiplyScalar( 1 / scalar );
  503. }
  504. applyMatrix3( m ) {
  505. const x = this.x, y = this.y;
  506. const e = m.elements;
  507. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  508. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  509. return this;
  510. }
  511. min( v ) {
  512. this.x = Math.min( this.x, v.x );
  513. this.y = Math.min( this.y, v.y );
  514. return this;
  515. }
  516. max( v ) {
  517. this.x = Math.max( this.x, v.x );
  518. this.y = Math.max( this.y, v.y );
  519. return this;
  520. }
  521. clamp( min, max ) {
  522. // assumes min < max, componentwise
  523. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  524. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  525. return this;
  526. }
  527. clampScalar( minVal, maxVal ) {
  528. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  529. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  530. return this;
  531. }
  532. clampLength( min, max ) {
  533. const length = this.length();
  534. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  535. }
  536. floor() {
  537. this.x = Math.floor( this.x );
  538. this.y = Math.floor( this.y );
  539. return this;
  540. }
  541. ceil() {
  542. this.x = Math.ceil( this.x );
  543. this.y = Math.ceil( this.y );
  544. return this;
  545. }
  546. round() {
  547. this.x = Math.round( this.x );
  548. this.y = Math.round( this.y );
  549. return this;
  550. }
  551. roundToZero() {
  552. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  553. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  554. return this;
  555. }
  556. negate() {
  557. this.x = - this.x;
  558. this.y = - this.y;
  559. return this;
  560. }
  561. dot( v ) {
  562. return this.x * v.x + this.y * v.y;
  563. }
  564. cross( v ) {
  565. return this.x * v.y - this.y * v.x;
  566. }
  567. lengthSq() {
  568. return this.x * this.x + this.y * this.y;
  569. }
  570. length() {
  571. return Math.sqrt( this.x * this.x + this.y * this.y );
  572. }
  573. manhattanLength() {
  574. return Math.abs( this.x ) + Math.abs( this.y );
  575. }
  576. normalize() {
  577. return this.divideScalar( this.length() || 1 );
  578. }
  579. angle() {
  580. // computes the angle in radians with respect to the positive x-axis
  581. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  582. return angle;
  583. }
  584. distanceTo( v ) {
  585. return Math.sqrt( this.distanceToSquared( v ) );
  586. }
  587. distanceToSquared( v ) {
  588. const dx = this.x - v.x, dy = this.y - v.y;
  589. return dx * dx + dy * dy;
  590. }
  591. manhattanDistanceTo( v ) {
  592. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  593. }
  594. setLength( length ) {
  595. return this.normalize().multiplyScalar( length );
  596. }
  597. lerp( v, alpha ) {
  598. this.x += ( v.x - this.x ) * alpha;
  599. this.y += ( v.y - this.y ) * alpha;
  600. return this;
  601. }
  602. lerpVectors( v1, v2, alpha ) {
  603. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  604. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  605. return this;
  606. }
  607. equals( v ) {
  608. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  609. }
  610. fromArray( array, offset = 0 ) {
  611. this.x = array[ offset ];
  612. this.y = array[ offset + 1 ];
  613. return this;
  614. }
  615. toArray( array = [], offset = 0 ) {
  616. array[ offset ] = this.x;
  617. array[ offset + 1 ] = this.y;
  618. return array;
  619. }
  620. fromBufferAttribute( attribute, index, offset ) {
  621. if ( offset !== undefined ) {
  622. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  623. }
  624. this.x = attribute.getX( index );
  625. this.y = attribute.getY( index );
  626. return this;
  627. }
  628. rotateAround( center, angle ) {
  629. const c = Math.cos( angle ), s = Math.sin( angle );
  630. const x = this.x - center.x;
  631. const y = this.y - center.y;
  632. this.x = x * c - y * s + center.x;
  633. this.y = x * s + y * c + center.y;
  634. return this;
  635. }
  636. random() {
  637. this.x = Math.random();
  638. this.y = Math.random();
  639. return this;
  640. }
  641. *[ Symbol.iterator ]() {
  642. yield this.x;
  643. yield this.y;
  644. }
  645. }
  646. Vector2.prototype.isVector2 = true;
  647. class Matrix3 {
  648. constructor() {
  649. this.elements = [
  650. 1, 0, 0,
  651. 0, 1, 0,
  652. 0, 0, 1
  653. ];
  654. if ( arguments.length > 0 ) {
  655. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  656. }
  657. }
  658. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  659. const te = this.elements;
  660. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  661. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  662. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  663. return this;
  664. }
  665. identity() {
  666. this.set(
  667. 1, 0, 0,
  668. 0, 1, 0,
  669. 0, 0, 1
  670. );
  671. return this;
  672. }
  673. copy( m ) {
  674. const te = this.elements;
  675. const me = m.elements;
  676. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  677. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  678. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  679. return this;
  680. }
  681. extractBasis( xAxis, yAxis, zAxis ) {
  682. xAxis.setFromMatrix3Column( this, 0 );
  683. yAxis.setFromMatrix3Column( this, 1 );
  684. zAxis.setFromMatrix3Column( this, 2 );
  685. return this;
  686. }
  687. setFromMatrix4( m ) {
  688. const me = m.elements;
  689. this.set(
  690. me[ 0 ], me[ 4 ], me[ 8 ],
  691. me[ 1 ], me[ 5 ], me[ 9 ],
  692. me[ 2 ], me[ 6 ], me[ 10 ]
  693. );
  694. return this;
  695. }
  696. multiply( m ) {
  697. return this.multiplyMatrices( this, m );
  698. }
  699. premultiply( m ) {
  700. return this.multiplyMatrices( m, this );
  701. }
  702. multiplyMatrices( a, b ) {
  703. const ae = a.elements;
  704. const be = b.elements;
  705. const te = this.elements;
  706. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  707. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  708. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  709. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  710. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  711. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  712. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  713. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  714. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  715. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  716. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  717. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  718. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  719. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  720. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  721. return this;
  722. }
  723. multiplyScalar( s ) {
  724. const te = this.elements;
  725. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  726. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  727. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  728. return this;
  729. }
  730. determinant() {
  731. const te = this.elements;
  732. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  733. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  734. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  735. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  736. }
  737. invert() {
  738. const te = this.elements,
  739. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  740. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  741. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  742. t11 = n33 * n22 - n32 * n23,
  743. t12 = n32 * n13 - n33 * n12,
  744. t13 = n23 * n12 - n22 * n13,
  745. det = n11 * t11 + n21 * t12 + n31 * t13;
  746. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  747. const detInv = 1 / det;
  748. te[ 0 ] = t11 * detInv;
  749. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  750. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  751. te[ 3 ] = t12 * detInv;
  752. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  753. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  754. te[ 6 ] = t13 * detInv;
  755. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  756. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  757. return this;
  758. }
  759. transpose() {
  760. let tmp;
  761. const m = this.elements;
  762. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  763. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  764. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  765. return this;
  766. }
  767. getNormalMatrix( matrix4 ) {
  768. return this.setFromMatrix4( matrix4 ).invert().transpose();
  769. }
  770. transposeIntoArray( r ) {
  771. const m = this.elements;
  772. r[ 0 ] = m[ 0 ];
  773. r[ 1 ] = m[ 3 ];
  774. r[ 2 ] = m[ 6 ];
  775. r[ 3 ] = m[ 1 ];
  776. r[ 4 ] = m[ 4 ];
  777. r[ 5 ] = m[ 7 ];
  778. r[ 6 ] = m[ 2 ];
  779. r[ 7 ] = m[ 5 ];
  780. r[ 8 ] = m[ 8 ];
  781. return this;
  782. }
  783. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  784. const c = Math.cos( rotation );
  785. const s = Math.sin( rotation );
  786. this.set(
  787. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  788. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  789. 0, 0, 1
  790. );
  791. return this;
  792. }
  793. scale( sx, sy ) {
  794. const te = this.elements;
  795. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  796. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  797. return this;
  798. }
  799. rotate( theta ) {
  800. const c = Math.cos( theta );
  801. const s = Math.sin( theta );
  802. const te = this.elements;
  803. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  804. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  805. te[ 0 ] = c * a11 + s * a21;
  806. te[ 3 ] = c * a12 + s * a22;
  807. te[ 6 ] = c * a13 + s * a23;
  808. te[ 1 ] = - s * a11 + c * a21;
  809. te[ 4 ] = - s * a12 + c * a22;
  810. te[ 7 ] = - s * a13 + c * a23;
  811. return this;
  812. }
  813. translate( tx, ty ) {
  814. const te = this.elements;
  815. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  816. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  817. return this;
  818. }
  819. equals( matrix ) {
  820. const te = this.elements;
  821. const me = matrix.elements;
  822. for ( let i = 0; i < 9; i ++ ) {
  823. if ( te[ i ] !== me[ i ] ) return false;
  824. }
  825. return true;
  826. }
  827. fromArray( array, offset = 0 ) {
  828. for ( let i = 0; i < 9; i ++ ) {
  829. this.elements[ i ] = array[ i + offset ];
  830. }
  831. return this;
  832. }
  833. toArray( array = [], offset = 0 ) {
  834. const te = this.elements;
  835. array[ offset ] = te[ 0 ];
  836. array[ offset + 1 ] = te[ 1 ];
  837. array[ offset + 2 ] = te[ 2 ];
  838. array[ offset + 3 ] = te[ 3 ];
  839. array[ offset + 4 ] = te[ 4 ];
  840. array[ offset + 5 ] = te[ 5 ];
  841. array[ offset + 6 ] = te[ 6 ];
  842. array[ offset + 7 ] = te[ 7 ];
  843. array[ offset + 8 ] = te[ 8 ];
  844. return array;
  845. }
  846. clone() {
  847. return new this.constructor().fromArray( this.elements );
  848. }
  849. }
  850. Matrix3.prototype.isMatrix3 = true;
  851. function arrayNeedsUint32( array ) {
  852. // assumes larger values usually on last
  853. for ( let i = array.length - 1; i >= 0; -- i ) {
  854. if ( array[ i ] > 65535 ) return true;
  855. }
  856. return false;
  857. }
  858. const TYPED_ARRAYS = {
  859. Int8Array: Int8Array,
  860. Uint8Array: Uint8Array,
  861. Uint8ClampedArray: Uint8ClampedArray,
  862. Int16Array: Int16Array,
  863. Uint16Array: Uint16Array,
  864. Int32Array: Int32Array,
  865. Uint32Array: Uint32Array,
  866. Float32Array: Float32Array,
  867. Float64Array: Float64Array
  868. };
  869. function getTypedArray( type, buffer ) {
  870. return new TYPED_ARRAYS[ type ]( buffer );
  871. }
  872. function createElementNS( name ) {
  873. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  874. }
  875. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  876. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  877. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  878. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  879. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  880. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  881. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  882. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  883. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  884. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  885. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  886. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  887. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  888. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  889. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  890. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  891. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  892. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  893. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  894. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  895. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  896. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  897. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  898. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  899. const _hslA = { h: 0, s: 0, l: 0 };
  900. const _hslB = { h: 0, s: 0, l: 0 };
  901. function hue2rgb( p, q, t ) {
  902. if ( t < 0 ) t += 1;
  903. if ( t > 1 ) t -= 1;
  904. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  905. if ( t < 1 / 2 ) return q;
  906. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  907. return p;
  908. }
  909. function SRGBToLinear( c ) {
  910. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  911. }
  912. function LinearToSRGB( c ) {
  913. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  914. }
  915. class Color {
  916. constructor( r, g, b ) {
  917. if ( g === undefined && b === undefined ) {
  918. // r is THREE.Color, hex or string
  919. return this.set( r );
  920. }
  921. return this.setRGB( r, g, b );
  922. }
  923. set( value ) {
  924. if ( value && value.isColor ) {
  925. this.copy( value );
  926. } else if ( typeof value === 'number' ) {
  927. this.setHex( value );
  928. } else if ( typeof value === 'string' ) {
  929. this.setStyle( value );
  930. }
  931. return this;
  932. }
  933. setScalar( scalar ) {
  934. this.r = scalar;
  935. this.g = scalar;
  936. this.b = scalar;
  937. return this;
  938. }
  939. setHex( hex ) {
  940. hex = Math.floor( hex );
  941. this.r = ( hex >> 16 & 255 ) / 255;
  942. this.g = ( hex >> 8 & 255 ) / 255;
  943. this.b = ( hex & 255 ) / 255;
  944. return this;
  945. }
  946. setRGB( r, g, b ) {
  947. this.r = r;
  948. this.g = g;
  949. this.b = b;
  950. return this;
  951. }
  952. setHSL( h, s, l ) {
  953. // h,s,l ranges are in 0.0 - 1.0
  954. h = euclideanModulo( h, 1 );
  955. s = clamp( s, 0, 1 );
  956. l = clamp( l, 0, 1 );
  957. if ( s === 0 ) {
  958. this.r = this.g = this.b = l;
  959. } else {
  960. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  961. const q = ( 2 * l ) - p;
  962. this.r = hue2rgb( q, p, h + 1 / 3 );
  963. this.g = hue2rgb( q, p, h );
  964. this.b = hue2rgb( q, p, h - 1 / 3 );
  965. }
  966. return this;
  967. }
  968. setStyle( style ) {
  969. function handleAlpha( string ) {
  970. if ( string === undefined ) return;
  971. if ( parseFloat( string ) < 1 ) {
  972. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  973. }
  974. }
  975. let m;
  976. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  977. // rgb / hsl
  978. let color;
  979. const name = m[ 1 ];
  980. const components = m[ 2 ];
  981. switch ( name ) {
  982. case 'rgb':
  983. case 'rgba':
  984. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  985. // rgb(255,0,0) rgba(255,0,0,0.5)
  986. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  987. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  988. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  989. handleAlpha( color[ 4 ] );
  990. return this;
  991. }
  992. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  993. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  994. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  995. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  996. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  997. handleAlpha( color[ 4 ] );
  998. return this;
  999. }
  1000. break;
  1001. case 'hsl':
  1002. case 'hsla':
  1003. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1004. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1005. const h = parseFloat( color[ 1 ] ) / 360;
  1006. const s = parseInt( color[ 2 ], 10 ) / 100;
  1007. const l = parseInt( color[ 3 ], 10 ) / 100;
  1008. handleAlpha( color[ 4 ] );
  1009. return this.setHSL( h, s, l );
  1010. }
  1011. break;
  1012. }
  1013. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1014. // hex color
  1015. const hex = m[ 1 ];
  1016. const size = hex.length;
  1017. if ( size === 3 ) {
  1018. // #ff0
  1019. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1020. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1021. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1022. return this;
  1023. } else if ( size === 6 ) {
  1024. // #ff0000
  1025. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1026. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1027. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1028. return this;
  1029. }
  1030. }
  1031. if ( style && style.length > 0 ) {
  1032. return this.setColorName( style );
  1033. }
  1034. return this;
  1035. }
  1036. setColorName( style ) {
  1037. // color keywords
  1038. const hex = _colorKeywords[ style.toLowerCase() ];
  1039. if ( hex !== undefined ) {
  1040. // red
  1041. this.setHex( hex );
  1042. } else {
  1043. // unknown color
  1044. console.warn( 'THREE.Color: Unknown color ' + style );
  1045. }
  1046. return this;
  1047. }
  1048. clone() {
  1049. return new this.constructor( this.r, this.g, this.b );
  1050. }
  1051. copy( color ) {
  1052. this.r = color.r;
  1053. this.g = color.g;
  1054. this.b = color.b;
  1055. return this;
  1056. }
  1057. copySRGBToLinear( color ) {
  1058. this.r = SRGBToLinear( color.r );
  1059. this.g = SRGBToLinear( color.g );
  1060. this.b = SRGBToLinear( color.b );
  1061. return this;
  1062. }
  1063. copyLinearToSRGB( color ) {
  1064. this.r = LinearToSRGB( color.r );
  1065. this.g = LinearToSRGB( color.g );
  1066. this.b = LinearToSRGB( color.b );
  1067. return this;
  1068. }
  1069. convertSRGBToLinear() {
  1070. this.copySRGBToLinear( this );
  1071. return this;
  1072. }
  1073. convertLinearToSRGB() {
  1074. this.copyLinearToSRGB( this );
  1075. return this;
  1076. }
  1077. getHex() {
  1078. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  1079. }
  1080. getHexString() {
  1081. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  1082. }
  1083. getHSL( target ) {
  1084. // h,s,l ranges are in 0.0 - 1.0
  1085. const r = this.r, g = this.g, b = this.b;
  1086. const max = Math.max( r, g, b );
  1087. const min = Math.min( r, g, b );
  1088. let hue, saturation;
  1089. const lightness = ( min + max ) / 2.0;
  1090. if ( min === max ) {
  1091. hue = 0;
  1092. saturation = 0;
  1093. } else {
  1094. const delta = max - min;
  1095. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1096. switch ( max ) {
  1097. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1098. case g: hue = ( b - r ) / delta + 2; break;
  1099. case b: hue = ( r - g ) / delta + 4; break;
  1100. }
  1101. hue /= 6;
  1102. }
  1103. target.h = hue;
  1104. target.s = saturation;
  1105. target.l = lightness;
  1106. return target;
  1107. }
  1108. getStyle() {
  1109. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  1110. }
  1111. offsetHSL( h, s, l ) {
  1112. this.getHSL( _hslA );
  1113. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1114. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1115. return this;
  1116. }
  1117. add( color ) {
  1118. this.r += color.r;
  1119. this.g += color.g;
  1120. this.b += color.b;
  1121. return this;
  1122. }
  1123. addColors( color1, color2 ) {
  1124. this.r = color1.r + color2.r;
  1125. this.g = color1.g + color2.g;
  1126. this.b = color1.b + color2.b;
  1127. return this;
  1128. }
  1129. addScalar( s ) {
  1130. this.r += s;
  1131. this.g += s;
  1132. this.b += s;
  1133. return this;
  1134. }
  1135. sub( color ) {
  1136. this.r = Math.max( 0, this.r - color.r );
  1137. this.g = Math.max( 0, this.g - color.g );
  1138. this.b = Math.max( 0, this.b - color.b );
  1139. return this;
  1140. }
  1141. multiply( color ) {
  1142. this.r *= color.r;
  1143. this.g *= color.g;
  1144. this.b *= color.b;
  1145. return this;
  1146. }
  1147. multiplyScalar( s ) {
  1148. this.r *= s;
  1149. this.g *= s;
  1150. this.b *= s;
  1151. return this;
  1152. }
  1153. lerp( color, alpha ) {
  1154. this.r += ( color.r - this.r ) * alpha;
  1155. this.g += ( color.g - this.g ) * alpha;
  1156. this.b += ( color.b - this.b ) * alpha;
  1157. return this;
  1158. }
  1159. lerpColors( color1, color2, alpha ) {
  1160. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1161. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1162. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1163. return this;
  1164. }
  1165. lerpHSL( color, alpha ) {
  1166. this.getHSL( _hslA );
  1167. color.getHSL( _hslB );
  1168. const h = lerp( _hslA.h, _hslB.h, alpha );
  1169. const s = lerp( _hslA.s, _hslB.s, alpha );
  1170. const l = lerp( _hslA.l, _hslB.l, alpha );
  1171. this.setHSL( h, s, l );
  1172. return this;
  1173. }
  1174. equals( c ) {
  1175. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1176. }
  1177. fromArray( array, offset = 0 ) {
  1178. this.r = array[ offset ];
  1179. this.g = array[ offset + 1 ];
  1180. this.b = array[ offset + 2 ];
  1181. return this;
  1182. }
  1183. toArray( array = [], offset = 0 ) {
  1184. array[ offset ] = this.r;
  1185. array[ offset + 1 ] = this.g;
  1186. array[ offset + 2 ] = this.b;
  1187. return array;
  1188. }
  1189. fromBufferAttribute( attribute, index ) {
  1190. this.r = attribute.getX( index );
  1191. this.g = attribute.getY( index );
  1192. this.b = attribute.getZ( index );
  1193. if ( attribute.normalized === true ) {
  1194. // assuming Uint8Array
  1195. this.r /= 255;
  1196. this.g /= 255;
  1197. this.b /= 255;
  1198. }
  1199. return this;
  1200. }
  1201. toJSON() {
  1202. return this.getHex();
  1203. }
  1204. }
  1205. Color.NAMES = _colorKeywords;
  1206. Color.prototype.isColor = true;
  1207. Color.prototype.r = 1;
  1208. Color.prototype.g = 1;
  1209. Color.prototype.b = 1;
  1210. let _canvas;
  1211. class ImageUtils {
  1212. static getDataURL( image ) {
  1213. if ( /^data:/i.test( image.src ) ) {
  1214. return image.src;
  1215. }
  1216. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1217. return image.src;
  1218. }
  1219. let canvas;
  1220. if ( image instanceof HTMLCanvasElement ) {
  1221. canvas = image;
  1222. } else {
  1223. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1224. _canvas.width = image.width;
  1225. _canvas.height = image.height;
  1226. const context = _canvas.getContext( '2d' );
  1227. if ( image instanceof ImageData ) {
  1228. context.putImageData( image, 0, 0 );
  1229. } else {
  1230. context.drawImage( image, 0, 0, image.width, image.height );
  1231. }
  1232. canvas = _canvas;
  1233. }
  1234. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1235. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1236. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1237. } else {
  1238. return canvas.toDataURL( 'image/png' );
  1239. }
  1240. }
  1241. static sRGBToLinear( image ) {
  1242. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1243. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1244. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1245. const canvas = createElementNS( 'canvas' );
  1246. canvas.width = image.width;
  1247. canvas.height = image.height;
  1248. const context = canvas.getContext( '2d' );
  1249. context.drawImage( image, 0, 0, image.width, image.height );
  1250. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1251. const data = imageData.data;
  1252. for ( let i = 0; i < data.length; i ++ ) {
  1253. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1254. }
  1255. context.putImageData( imageData, 0, 0 );
  1256. return canvas;
  1257. } else if ( image.data ) {
  1258. const data = image.data.slice( 0 );
  1259. for ( let i = 0; i < data.length; i ++ ) {
  1260. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1261. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1262. } else {
  1263. // assuming float
  1264. data[ i ] = SRGBToLinear( data[ i ] );
  1265. }
  1266. }
  1267. return {
  1268. data: data,
  1269. width: image.width,
  1270. height: image.height
  1271. };
  1272. } else {
  1273. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1274. return image;
  1275. }
  1276. }
  1277. }
  1278. let textureId = 0;
  1279. class Texture extends EventDispatcher {
  1280. 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 ) {
  1281. super();
  1282. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1283. this.uuid = generateUUID();
  1284. this.name = '';
  1285. this.image = image;
  1286. this.mipmaps = [];
  1287. this.mapping = mapping;
  1288. this.wrapS = wrapS;
  1289. this.wrapT = wrapT;
  1290. this.magFilter = magFilter;
  1291. this.minFilter = minFilter;
  1292. this.anisotropy = anisotropy;
  1293. this.format = format;
  1294. this.internalFormat = null;
  1295. this.type = type;
  1296. this.offset = new Vector2( 0, 0 );
  1297. this.repeat = new Vector2( 1, 1 );
  1298. this.center = new Vector2( 0, 0 );
  1299. this.rotation = 0;
  1300. this.matrixAutoUpdate = true;
  1301. this.matrix = new Matrix3();
  1302. this.generateMipmaps = true;
  1303. this.premultiplyAlpha = false;
  1304. this.flipY = true;
  1305. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1306. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1307. //
  1308. // Also changing the encoding after already used by a Material will not automatically make the Material
  1309. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1310. this.encoding = encoding;
  1311. this.userData = {};
  1312. this.version = 0;
  1313. this.onUpdate = null;
  1314. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1315. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1316. }
  1317. updateMatrix() {
  1318. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1319. }
  1320. clone() {
  1321. return new this.constructor().copy( this );
  1322. }
  1323. copy( source ) {
  1324. this.name = source.name;
  1325. this.image = source.image;
  1326. this.mipmaps = source.mipmaps.slice( 0 );
  1327. this.mapping = source.mapping;
  1328. this.wrapS = source.wrapS;
  1329. this.wrapT = source.wrapT;
  1330. this.magFilter = source.magFilter;
  1331. this.minFilter = source.minFilter;
  1332. this.anisotropy = source.anisotropy;
  1333. this.format = source.format;
  1334. this.internalFormat = source.internalFormat;
  1335. this.type = source.type;
  1336. this.offset.copy( source.offset );
  1337. this.repeat.copy( source.repeat );
  1338. this.center.copy( source.center );
  1339. this.rotation = source.rotation;
  1340. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1341. this.matrix.copy( source.matrix );
  1342. this.generateMipmaps = source.generateMipmaps;
  1343. this.premultiplyAlpha = source.premultiplyAlpha;
  1344. this.flipY = source.flipY;
  1345. this.unpackAlignment = source.unpackAlignment;
  1346. this.encoding = source.encoding;
  1347. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1348. return this;
  1349. }
  1350. toJSON( meta ) {
  1351. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1352. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1353. return meta.textures[ this.uuid ];
  1354. }
  1355. const output = {
  1356. metadata: {
  1357. version: 4.5,
  1358. type: 'Texture',
  1359. generator: 'Texture.toJSON'
  1360. },
  1361. uuid: this.uuid,
  1362. name: this.name,
  1363. mapping: this.mapping,
  1364. repeat: [ this.repeat.x, this.repeat.y ],
  1365. offset: [ this.offset.x, this.offset.y ],
  1366. center: [ this.center.x, this.center.y ],
  1367. rotation: this.rotation,
  1368. wrap: [ this.wrapS, this.wrapT ],
  1369. format: this.format,
  1370. type: this.type,
  1371. encoding: this.encoding,
  1372. minFilter: this.minFilter,
  1373. magFilter: this.magFilter,
  1374. anisotropy: this.anisotropy,
  1375. flipY: this.flipY,
  1376. premultiplyAlpha: this.premultiplyAlpha,
  1377. unpackAlignment: this.unpackAlignment
  1378. };
  1379. if ( this.image !== undefined ) {
  1380. // TODO: Move to THREE.Image
  1381. const image = this.image;
  1382. if ( image.uuid === undefined ) {
  1383. image.uuid = generateUUID(); // UGH
  1384. }
  1385. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1386. let url;
  1387. if ( Array.isArray( image ) ) {
  1388. // process array of images e.g. CubeTexture
  1389. url = [];
  1390. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1391. // check cube texture with data textures
  1392. if ( image[ i ].isDataTexture ) {
  1393. url.push( serializeImage( image[ i ].image ) );
  1394. } else {
  1395. url.push( serializeImage( image[ i ] ) );
  1396. }
  1397. }
  1398. } else {
  1399. // process single image
  1400. url = serializeImage( image );
  1401. }
  1402. meta.images[ image.uuid ] = {
  1403. uuid: image.uuid,
  1404. url: url
  1405. };
  1406. }
  1407. output.image = image.uuid;
  1408. }
  1409. if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData;
  1410. if ( ! isRootObject ) {
  1411. meta.textures[ this.uuid ] = output;
  1412. }
  1413. return output;
  1414. }
  1415. dispose() {
  1416. this.dispatchEvent( { type: 'dispose' } );
  1417. }
  1418. transformUv( uv ) {
  1419. if ( this.mapping !== UVMapping ) return uv;
  1420. uv.applyMatrix3( this.matrix );
  1421. if ( uv.x < 0 || uv.x > 1 ) {
  1422. switch ( this.wrapS ) {
  1423. case RepeatWrapping:
  1424. uv.x = uv.x - Math.floor( uv.x );
  1425. break;
  1426. case ClampToEdgeWrapping:
  1427. uv.x = uv.x < 0 ? 0 : 1;
  1428. break;
  1429. case MirroredRepeatWrapping:
  1430. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1431. uv.x = Math.ceil( uv.x ) - uv.x;
  1432. } else {
  1433. uv.x = uv.x - Math.floor( uv.x );
  1434. }
  1435. break;
  1436. }
  1437. }
  1438. if ( uv.y < 0 || uv.y > 1 ) {
  1439. switch ( this.wrapT ) {
  1440. case RepeatWrapping:
  1441. uv.y = uv.y - Math.floor( uv.y );
  1442. break;
  1443. case ClampToEdgeWrapping:
  1444. uv.y = uv.y < 0 ? 0 : 1;
  1445. break;
  1446. case MirroredRepeatWrapping:
  1447. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1448. uv.y = Math.ceil( uv.y ) - uv.y;
  1449. } else {
  1450. uv.y = uv.y - Math.floor( uv.y );
  1451. }
  1452. break;
  1453. }
  1454. }
  1455. if ( this.flipY ) {
  1456. uv.y = 1 - uv.y;
  1457. }
  1458. return uv;
  1459. }
  1460. set needsUpdate( value ) {
  1461. if ( value === true ) this.version ++;
  1462. }
  1463. }
  1464. Texture.DEFAULT_IMAGE = undefined;
  1465. Texture.DEFAULT_MAPPING = UVMapping;
  1466. Texture.prototype.isTexture = true;
  1467. function serializeImage( image ) {
  1468. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1469. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1470. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1471. // default images
  1472. return ImageUtils.getDataURL( image );
  1473. } else {
  1474. if ( image.data ) {
  1475. // images of DataTexture
  1476. return {
  1477. data: Array.prototype.slice.call( image.data ),
  1478. width: image.width,
  1479. height: image.height,
  1480. type: image.data.constructor.name
  1481. };
  1482. } else {
  1483. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1484. return {};
  1485. }
  1486. }
  1487. }
  1488. class Vector4 {
  1489. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1490. this.x = x;
  1491. this.y = y;
  1492. this.z = z;
  1493. this.w = w;
  1494. }
  1495. get width() {
  1496. return this.z;
  1497. }
  1498. set width( value ) {
  1499. this.z = value;
  1500. }
  1501. get height() {
  1502. return this.w;
  1503. }
  1504. set height( value ) {
  1505. this.w = value;
  1506. }
  1507. set( x, y, z, w ) {
  1508. this.x = x;
  1509. this.y = y;
  1510. this.z = z;
  1511. this.w = w;
  1512. return this;
  1513. }
  1514. setScalar( scalar ) {
  1515. this.x = scalar;
  1516. this.y = scalar;
  1517. this.z = scalar;
  1518. this.w = scalar;
  1519. return this;
  1520. }
  1521. setX( x ) {
  1522. this.x = x;
  1523. return this;
  1524. }
  1525. setY( y ) {
  1526. this.y = y;
  1527. return this;
  1528. }
  1529. setZ( z ) {
  1530. this.z = z;
  1531. return this;
  1532. }
  1533. setW( w ) {
  1534. this.w = w;
  1535. return this;
  1536. }
  1537. setComponent( index, value ) {
  1538. switch ( index ) {
  1539. case 0: this.x = value; break;
  1540. case 1: this.y = value; break;
  1541. case 2: this.z = value; break;
  1542. case 3: this.w = value; break;
  1543. default: throw new Error( 'index is out of range: ' + index );
  1544. }
  1545. return this;
  1546. }
  1547. getComponent( index ) {
  1548. switch ( index ) {
  1549. case 0: return this.x;
  1550. case 1: return this.y;
  1551. case 2: return this.z;
  1552. case 3: return this.w;
  1553. default: throw new Error( 'index is out of range: ' + index );
  1554. }
  1555. }
  1556. clone() {
  1557. return new this.constructor( this.x, this.y, this.z, this.w );
  1558. }
  1559. copy( v ) {
  1560. this.x = v.x;
  1561. this.y = v.y;
  1562. this.z = v.z;
  1563. this.w = ( v.w !== undefined ) ? v.w : 1;
  1564. return this;
  1565. }
  1566. add( v, w ) {
  1567. if ( w !== undefined ) {
  1568. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1569. return this.addVectors( v, w );
  1570. }
  1571. this.x += v.x;
  1572. this.y += v.y;
  1573. this.z += v.z;
  1574. this.w += v.w;
  1575. return this;
  1576. }
  1577. addScalar( s ) {
  1578. this.x += s;
  1579. this.y += s;
  1580. this.z += s;
  1581. this.w += s;
  1582. return this;
  1583. }
  1584. addVectors( a, b ) {
  1585. this.x = a.x + b.x;
  1586. this.y = a.y + b.y;
  1587. this.z = a.z + b.z;
  1588. this.w = a.w + b.w;
  1589. return this;
  1590. }
  1591. addScaledVector( v, s ) {
  1592. this.x += v.x * s;
  1593. this.y += v.y * s;
  1594. this.z += v.z * s;
  1595. this.w += v.w * s;
  1596. return this;
  1597. }
  1598. sub( v, w ) {
  1599. if ( w !== undefined ) {
  1600. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1601. return this.subVectors( v, w );
  1602. }
  1603. this.x -= v.x;
  1604. this.y -= v.y;
  1605. this.z -= v.z;
  1606. this.w -= v.w;
  1607. return this;
  1608. }
  1609. subScalar( s ) {
  1610. this.x -= s;
  1611. this.y -= s;
  1612. this.z -= s;
  1613. this.w -= s;
  1614. return this;
  1615. }
  1616. subVectors( a, b ) {
  1617. this.x = a.x - b.x;
  1618. this.y = a.y - b.y;
  1619. this.z = a.z - b.z;
  1620. this.w = a.w - b.w;
  1621. return this;
  1622. }
  1623. multiply( v ) {
  1624. this.x *= v.x;
  1625. this.y *= v.y;
  1626. this.z *= v.z;
  1627. this.w *= v.w;
  1628. return this;
  1629. }
  1630. multiplyScalar( scalar ) {
  1631. this.x *= scalar;
  1632. this.y *= scalar;
  1633. this.z *= scalar;
  1634. this.w *= scalar;
  1635. return this;
  1636. }
  1637. applyMatrix4( m ) {
  1638. const x = this.x, y = this.y, z = this.z, w = this.w;
  1639. const e = m.elements;
  1640. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1641. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1642. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1643. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1644. return this;
  1645. }
  1646. divideScalar( scalar ) {
  1647. return this.multiplyScalar( 1 / scalar );
  1648. }
  1649. setAxisAngleFromQuaternion( q ) {
  1650. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1651. // q is assumed to be normalized
  1652. this.w = 2 * Math.acos( q.w );
  1653. const s = Math.sqrt( 1 - q.w * q.w );
  1654. if ( s < 0.0001 ) {
  1655. this.x = 1;
  1656. this.y = 0;
  1657. this.z = 0;
  1658. } else {
  1659. this.x = q.x / s;
  1660. this.y = q.y / s;
  1661. this.z = q.z / s;
  1662. }
  1663. return this;
  1664. }
  1665. setAxisAngleFromRotationMatrix( m ) {
  1666. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1667. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1668. let angle, x, y, z; // variables for result
  1669. const epsilon = 0.01, // margin to allow for rounding errors
  1670. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1671. te = m.elements,
  1672. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1673. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1674. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1675. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1676. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1677. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1678. // singularity found
  1679. // first check for identity matrix which must have +1 for all terms
  1680. // in leading diagonal and zero in other terms
  1681. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1682. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1683. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1684. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1685. // this singularity is identity matrix so angle = 0
  1686. this.set( 1, 0, 0, 0 );
  1687. return this; // zero angle, arbitrary axis
  1688. }
  1689. // otherwise this singularity is angle = 180
  1690. angle = Math.PI;
  1691. const xx = ( m11 + 1 ) / 2;
  1692. const yy = ( m22 + 1 ) / 2;
  1693. const zz = ( m33 + 1 ) / 2;
  1694. const xy = ( m12 + m21 ) / 4;
  1695. const xz = ( m13 + m31 ) / 4;
  1696. const yz = ( m23 + m32 ) / 4;
  1697. if ( ( xx > yy ) && ( xx > zz ) ) {
  1698. // m11 is the largest diagonal term
  1699. if ( xx < epsilon ) {
  1700. x = 0;
  1701. y = 0.707106781;
  1702. z = 0.707106781;
  1703. } else {
  1704. x = Math.sqrt( xx );
  1705. y = xy / x;
  1706. z = xz / x;
  1707. }
  1708. } else if ( yy > zz ) {
  1709. // m22 is the largest diagonal term
  1710. if ( yy < epsilon ) {
  1711. x = 0.707106781;
  1712. y = 0;
  1713. z = 0.707106781;
  1714. } else {
  1715. y = Math.sqrt( yy );
  1716. x = xy / y;
  1717. z = yz / y;
  1718. }
  1719. } else {
  1720. // m33 is the largest diagonal term so base result on this
  1721. if ( zz < epsilon ) {
  1722. x = 0.707106781;
  1723. y = 0.707106781;
  1724. z = 0;
  1725. } else {
  1726. z = Math.sqrt( zz );
  1727. x = xz / z;
  1728. y = yz / z;
  1729. }
  1730. }
  1731. this.set( x, y, z, angle );
  1732. return this; // return 180 deg rotation
  1733. }
  1734. // as we have reached here there are no singularities so we can handle normally
  1735. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1736. ( m13 - m31 ) * ( m13 - m31 ) +
  1737. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1738. if ( Math.abs( s ) < 0.001 ) s = 1;
  1739. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1740. // caught by singularity test above, but I've left it in just in case
  1741. this.x = ( m32 - m23 ) / s;
  1742. this.y = ( m13 - m31 ) / s;
  1743. this.z = ( m21 - m12 ) / s;
  1744. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1745. return this;
  1746. }
  1747. min( v ) {
  1748. this.x = Math.min( this.x, v.x );
  1749. this.y = Math.min( this.y, v.y );
  1750. this.z = Math.min( this.z, v.z );
  1751. this.w = Math.min( this.w, v.w );
  1752. return this;
  1753. }
  1754. max( v ) {
  1755. this.x = Math.max( this.x, v.x );
  1756. this.y = Math.max( this.y, v.y );
  1757. this.z = Math.max( this.z, v.z );
  1758. this.w = Math.max( this.w, v.w );
  1759. return this;
  1760. }
  1761. clamp( min, max ) {
  1762. // assumes min < max, componentwise
  1763. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1764. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1765. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1766. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1767. return this;
  1768. }
  1769. clampScalar( minVal, maxVal ) {
  1770. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1771. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1772. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1773. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1774. return this;
  1775. }
  1776. clampLength( min, max ) {
  1777. const length = this.length();
  1778. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1779. }
  1780. floor() {
  1781. this.x = Math.floor( this.x );
  1782. this.y = Math.floor( this.y );
  1783. this.z = Math.floor( this.z );
  1784. this.w = Math.floor( this.w );
  1785. return this;
  1786. }
  1787. ceil() {
  1788. this.x = Math.ceil( this.x );
  1789. this.y = Math.ceil( this.y );
  1790. this.z = Math.ceil( this.z );
  1791. this.w = Math.ceil( this.w );
  1792. return this;
  1793. }
  1794. round() {
  1795. this.x = Math.round( this.x );
  1796. this.y = Math.round( this.y );
  1797. this.z = Math.round( this.z );
  1798. this.w = Math.round( this.w );
  1799. return this;
  1800. }
  1801. roundToZero() {
  1802. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1803. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1804. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1805. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1806. return this;
  1807. }
  1808. negate() {
  1809. this.x = - this.x;
  1810. this.y = - this.y;
  1811. this.z = - this.z;
  1812. this.w = - this.w;
  1813. return this;
  1814. }
  1815. dot( v ) {
  1816. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1817. }
  1818. lengthSq() {
  1819. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1820. }
  1821. length() {
  1822. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1823. }
  1824. manhattanLength() {
  1825. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1826. }
  1827. normalize() {
  1828. return this.divideScalar( this.length() || 1 );
  1829. }
  1830. setLength( length ) {
  1831. return this.normalize().multiplyScalar( length );
  1832. }
  1833. lerp( v, alpha ) {
  1834. this.x += ( v.x - this.x ) * alpha;
  1835. this.y += ( v.y - this.y ) * alpha;
  1836. this.z += ( v.z - this.z ) * alpha;
  1837. this.w += ( v.w - this.w ) * alpha;
  1838. return this;
  1839. }
  1840. lerpVectors( v1, v2, alpha ) {
  1841. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1842. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1843. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1844. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1845. return this;
  1846. }
  1847. equals( v ) {
  1848. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1849. }
  1850. fromArray( array, offset = 0 ) {
  1851. this.x = array[ offset ];
  1852. this.y = array[ offset + 1 ];
  1853. this.z = array[ offset + 2 ];
  1854. this.w = array[ offset + 3 ];
  1855. return this;
  1856. }
  1857. toArray( array = [], offset = 0 ) {
  1858. array[ offset ] = this.x;
  1859. array[ offset + 1 ] = this.y;
  1860. array[ offset + 2 ] = this.z;
  1861. array[ offset + 3 ] = this.w;
  1862. return array;
  1863. }
  1864. fromBufferAttribute( attribute, index, offset ) {
  1865. if ( offset !== undefined ) {
  1866. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1867. }
  1868. this.x = attribute.getX( index );
  1869. this.y = attribute.getY( index );
  1870. this.z = attribute.getZ( index );
  1871. this.w = attribute.getW( index );
  1872. return this;
  1873. }
  1874. random() {
  1875. this.x = Math.random();
  1876. this.y = Math.random();
  1877. this.z = Math.random();
  1878. this.w = Math.random();
  1879. return this;
  1880. }
  1881. *[ Symbol.iterator ]() {
  1882. yield this.x;
  1883. yield this.y;
  1884. yield this.z;
  1885. yield this.w;
  1886. }
  1887. }
  1888. Vector4.prototype.isVector4 = true;
  1889. /*
  1890. In options, we can specify:
  1891. * Texture parameters for an auto-generated target texture
  1892. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1893. */
  1894. class WebGLRenderTarget extends EventDispatcher {
  1895. constructor( width, height, options = {} ) {
  1896. super();
  1897. this.width = width;
  1898. this.height = height;
  1899. this.depth = 1;
  1900. this.scissor = new Vector4( 0, 0, width, height );
  1901. this.scissorTest = false;
  1902. this.viewport = new Vector4( 0, 0, width, height );
  1903. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1904. this.texture.isRenderTargetTexture = true;
  1905. this.texture.image = { width: width, height: height, depth: 1 };
  1906. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1907. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1908. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1909. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1910. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1911. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1912. }
  1913. setTexture( texture ) {
  1914. texture.image = {
  1915. width: this.width,
  1916. height: this.height,
  1917. depth: this.depth
  1918. };
  1919. this.texture = texture;
  1920. }
  1921. setSize( width, height, depth = 1 ) {
  1922. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1923. this.width = width;
  1924. this.height = height;
  1925. this.depth = depth;
  1926. this.texture.image.width = width;
  1927. this.texture.image.height = height;
  1928. this.texture.image.depth = depth;
  1929. this.dispose();
  1930. }
  1931. this.viewport.set( 0, 0, width, height );
  1932. this.scissor.set( 0, 0, width, height );
  1933. }
  1934. clone() {
  1935. return new this.constructor().copy( this );
  1936. }
  1937. copy( source ) {
  1938. this.width = source.width;
  1939. this.height = source.height;
  1940. this.depth = source.depth;
  1941. this.viewport.copy( source.viewport );
  1942. this.texture = source.texture.clone();
  1943. // ensure image object is not shared, see #20328
  1944. this.texture.image = Object.assign( {}, source.texture.image );
  1945. this.depthBuffer = source.depthBuffer;
  1946. this.stencilBuffer = source.stencilBuffer;
  1947. this.depthTexture = source.depthTexture;
  1948. return this;
  1949. }
  1950. dispose() {
  1951. this.dispatchEvent( { type: 'dispose' } );
  1952. }
  1953. }
  1954. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1955. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1956. constructor( width, height, count ) {
  1957. super( width, height );
  1958. const texture = this.texture;
  1959. this.texture = [];
  1960. for ( let i = 0; i < count; i ++ ) {
  1961. this.texture[ i ] = texture.clone();
  1962. }
  1963. }
  1964. setSize( width, height, depth = 1 ) {
  1965. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1966. this.width = width;
  1967. this.height = height;
  1968. this.depth = depth;
  1969. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1970. this.texture[ i ].image.width = width;
  1971. this.texture[ i ].image.height = height;
  1972. this.texture[ i ].image.depth = depth;
  1973. }
  1974. this.dispose();
  1975. }
  1976. this.viewport.set( 0, 0, width, height );
  1977. this.scissor.set( 0, 0, width, height );
  1978. return this;
  1979. }
  1980. copy( source ) {
  1981. this.dispose();
  1982. this.width = source.width;
  1983. this.height = source.height;
  1984. this.depth = source.depth;
  1985. this.viewport.set( 0, 0, this.width, this.height );
  1986. this.scissor.set( 0, 0, this.width, this.height );
  1987. this.depthBuffer = source.depthBuffer;
  1988. this.stencilBuffer = source.stencilBuffer;
  1989. this.depthTexture = source.depthTexture;
  1990. this.texture.length = 0;
  1991. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1992. this.texture[ i ] = source.texture[ i ].clone();
  1993. }
  1994. return this;
  1995. }
  1996. }
  1997. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1998. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1999. constructor( width, height, options = {} ) {
  2000. super( width, height, options );
  2001. this.samples = 4;
  2002. this.ignoreDepthForMultisampleCopy = options.ignoreDepth !== undefined ? options.ignoreDepth : true;
  2003. this.useRenderToTexture = ( options.useRenderToTexture !== undefined ) ? options.useRenderToTexture : false;
  2004. this.useRenderbuffer = this.useRenderToTexture === false;
  2005. }
  2006. copy( source ) {
  2007. super.copy.call( this, source );
  2008. this.samples = source.samples;
  2009. this.useRenderToTexture = source.useRenderToTexture;
  2010. this.useRenderbuffer = source.useRenderbuffer;
  2011. return this;
  2012. }
  2013. }
  2014. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  2015. class Quaternion {
  2016. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2017. this._x = x;
  2018. this._y = y;
  2019. this._z = z;
  2020. this._w = w;
  2021. }
  2022. static slerp( qa, qb, qm, t ) {
  2023. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  2024. return qm.slerpQuaternions( qa, qb, t );
  2025. }
  2026. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2027. // fuzz-free, array-based Quaternion SLERP operation
  2028. let x0 = src0[ srcOffset0 + 0 ],
  2029. y0 = src0[ srcOffset0 + 1 ],
  2030. z0 = src0[ srcOffset0 + 2 ],
  2031. w0 = src0[ srcOffset0 + 3 ];
  2032. const x1 = src1[ srcOffset1 + 0 ],
  2033. y1 = src1[ srcOffset1 + 1 ],
  2034. z1 = src1[ srcOffset1 + 2 ],
  2035. w1 = src1[ srcOffset1 + 3 ];
  2036. if ( t === 0 ) {
  2037. dst[ dstOffset + 0 ] = x0;
  2038. dst[ dstOffset + 1 ] = y0;
  2039. dst[ dstOffset + 2 ] = z0;
  2040. dst[ dstOffset + 3 ] = w0;
  2041. return;
  2042. }
  2043. if ( t === 1 ) {
  2044. dst[ dstOffset + 0 ] = x1;
  2045. dst[ dstOffset + 1 ] = y1;
  2046. dst[ dstOffset + 2 ] = z1;
  2047. dst[ dstOffset + 3 ] = w1;
  2048. return;
  2049. }
  2050. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2051. let s = 1 - t;
  2052. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2053. dir = ( cos >= 0 ? 1 : - 1 ),
  2054. sqrSin = 1 - cos * cos;
  2055. // Skip the Slerp for tiny steps to avoid numeric problems:
  2056. if ( sqrSin > Number.EPSILON ) {
  2057. const sin = Math.sqrt( sqrSin ),
  2058. len = Math.atan2( sin, cos * dir );
  2059. s = Math.sin( s * len ) / sin;
  2060. t = Math.sin( t * len ) / sin;
  2061. }
  2062. const tDir = t * dir;
  2063. x0 = x0 * s + x1 * tDir;
  2064. y0 = y0 * s + y1 * tDir;
  2065. z0 = z0 * s + z1 * tDir;
  2066. w0 = w0 * s + w1 * tDir;
  2067. // Normalize in case we just did a lerp:
  2068. if ( s === 1 - t ) {
  2069. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2070. x0 *= f;
  2071. y0 *= f;
  2072. z0 *= f;
  2073. w0 *= f;
  2074. }
  2075. }
  2076. dst[ dstOffset ] = x0;
  2077. dst[ dstOffset + 1 ] = y0;
  2078. dst[ dstOffset + 2 ] = z0;
  2079. dst[ dstOffset + 3 ] = w0;
  2080. }
  2081. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2082. const x0 = src0[ srcOffset0 ];
  2083. const y0 = src0[ srcOffset0 + 1 ];
  2084. const z0 = src0[ srcOffset0 + 2 ];
  2085. const w0 = src0[ srcOffset0 + 3 ];
  2086. const x1 = src1[ srcOffset1 ];
  2087. const y1 = src1[ srcOffset1 + 1 ];
  2088. const z1 = src1[ srcOffset1 + 2 ];
  2089. const w1 = src1[ srcOffset1 + 3 ];
  2090. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2091. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2092. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2093. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2094. return dst;
  2095. }
  2096. get x() {
  2097. return this._x;
  2098. }
  2099. set x( value ) {
  2100. this._x = value;
  2101. this._onChangeCallback();
  2102. }
  2103. get y() {
  2104. return this._y;
  2105. }
  2106. set y( value ) {
  2107. this._y = value;
  2108. this._onChangeCallback();
  2109. }
  2110. get z() {
  2111. return this._z;
  2112. }
  2113. set z( value ) {
  2114. this._z = value;
  2115. this._onChangeCallback();
  2116. }
  2117. get w() {
  2118. return this._w;
  2119. }
  2120. set w( value ) {
  2121. this._w = value;
  2122. this._onChangeCallback();
  2123. }
  2124. set( x, y, z, w ) {
  2125. this._x = x;
  2126. this._y = y;
  2127. this._z = z;
  2128. this._w = w;
  2129. this._onChangeCallback();
  2130. return this;
  2131. }
  2132. clone() {
  2133. return new this.constructor( this._x, this._y, this._z, this._w );
  2134. }
  2135. copy( quaternion ) {
  2136. this._x = quaternion.x;
  2137. this._y = quaternion.y;
  2138. this._z = quaternion.z;
  2139. this._w = quaternion.w;
  2140. this._onChangeCallback();
  2141. return this;
  2142. }
  2143. setFromEuler( euler, update ) {
  2144. if ( ! ( euler && euler.isEuler ) ) {
  2145. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2146. }
  2147. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2148. // http://www.mathworks.com/matlabcentral/fileexchange/
  2149. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2150. // content/SpinCalc.m
  2151. const cos = Math.cos;
  2152. const sin = Math.sin;
  2153. const c1 = cos( x / 2 );
  2154. const c2 = cos( y / 2 );
  2155. const c3 = cos( z / 2 );
  2156. const s1 = sin( x / 2 );
  2157. const s2 = sin( y / 2 );
  2158. const s3 = sin( z / 2 );
  2159. switch ( order ) {
  2160. case 'XYZ':
  2161. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2162. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2163. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2164. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2165. break;
  2166. case 'YXZ':
  2167. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2168. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2169. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2170. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2171. break;
  2172. case 'ZXY':
  2173. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2174. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2175. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2176. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2177. break;
  2178. case 'ZYX':
  2179. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2180. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2181. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2182. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2183. break;
  2184. case 'YZX':
  2185. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2186. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2187. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2188. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2189. break;
  2190. case 'XZY':
  2191. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2192. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2193. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2194. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2195. break;
  2196. default:
  2197. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2198. }
  2199. if ( update !== false ) this._onChangeCallback();
  2200. return this;
  2201. }
  2202. setFromAxisAngle( axis, angle ) {
  2203. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2204. // assumes axis is normalized
  2205. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2206. this._x = axis.x * s;
  2207. this._y = axis.y * s;
  2208. this._z = axis.z * s;
  2209. this._w = Math.cos( halfAngle );
  2210. this._onChangeCallback();
  2211. return this;
  2212. }
  2213. setFromRotationMatrix( m ) {
  2214. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2215. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2216. const te = m.elements,
  2217. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2218. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2219. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2220. trace = m11 + m22 + m33;
  2221. if ( trace > 0 ) {
  2222. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2223. this._w = 0.25 / s;
  2224. this._x = ( m32 - m23 ) * s;
  2225. this._y = ( m13 - m31 ) * s;
  2226. this._z = ( m21 - m12 ) * s;
  2227. } else if ( m11 > m22 && m11 > m33 ) {
  2228. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2229. this._w = ( m32 - m23 ) / s;
  2230. this._x = 0.25 * s;
  2231. this._y = ( m12 + m21 ) / s;
  2232. this._z = ( m13 + m31 ) / s;
  2233. } else if ( m22 > m33 ) {
  2234. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2235. this._w = ( m13 - m31 ) / s;
  2236. this._x = ( m12 + m21 ) / s;
  2237. this._y = 0.25 * s;
  2238. this._z = ( m23 + m32 ) / s;
  2239. } else {
  2240. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2241. this._w = ( m21 - m12 ) / s;
  2242. this._x = ( m13 + m31 ) / s;
  2243. this._y = ( m23 + m32 ) / s;
  2244. this._z = 0.25 * s;
  2245. }
  2246. this._onChangeCallback();
  2247. return this;
  2248. }
  2249. setFromUnitVectors( vFrom, vTo ) {
  2250. // assumes direction vectors vFrom and vTo are normalized
  2251. let r = vFrom.dot( vTo ) + 1;
  2252. if ( r < Number.EPSILON ) {
  2253. // vFrom and vTo point in opposite directions
  2254. r = 0;
  2255. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2256. this._x = - vFrom.y;
  2257. this._y = vFrom.x;
  2258. this._z = 0;
  2259. this._w = r;
  2260. } else {
  2261. this._x = 0;
  2262. this._y = - vFrom.z;
  2263. this._z = vFrom.y;
  2264. this._w = r;
  2265. }
  2266. } else {
  2267. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2268. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2269. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2270. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2271. this._w = r;
  2272. }
  2273. return this.normalize();
  2274. }
  2275. angleTo( q ) {
  2276. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2277. }
  2278. rotateTowards( q, step ) {
  2279. const angle = this.angleTo( q );
  2280. if ( angle === 0 ) return this;
  2281. const t = Math.min( 1, step / angle );
  2282. this.slerp( q, t );
  2283. return this;
  2284. }
  2285. identity() {
  2286. return this.set( 0, 0, 0, 1 );
  2287. }
  2288. invert() {
  2289. // quaternion is assumed to have unit length
  2290. return this.conjugate();
  2291. }
  2292. conjugate() {
  2293. this._x *= - 1;
  2294. this._y *= - 1;
  2295. this._z *= - 1;
  2296. this._onChangeCallback();
  2297. return this;
  2298. }
  2299. dot( v ) {
  2300. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2301. }
  2302. lengthSq() {
  2303. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2304. }
  2305. length() {
  2306. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2307. }
  2308. normalize() {
  2309. let l = this.length();
  2310. if ( l === 0 ) {
  2311. this._x = 0;
  2312. this._y = 0;
  2313. this._z = 0;
  2314. this._w = 1;
  2315. } else {
  2316. l = 1 / l;
  2317. this._x = this._x * l;
  2318. this._y = this._y * l;
  2319. this._z = this._z * l;
  2320. this._w = this._w * l;
  2321. }
  2322. this._onChangeCallback();
  2323. return this;
  2324. }
  2325. multiply( q, p ) {
  2326. if ( p !== undefined ) {
  2327. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2328. return this.multiplyQuaternions( q, p );
  2329. }
  2330. return this.multiplyQuaternions( this, q );
  2331. }
  2332. premultiply( q ) {
  2333. return this.multiplyQuaternions( q, this );
  2334. }
  2335. multiplyQuaternions( a, b ) {
  2336. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2337. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2338. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2339. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2340. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2341. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2342. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2343. this._onChangeCallback();
  2344. return this;
  2345. }
  2346. slerp( qb, t ) {
  2347. if ( t === 0 ) return this;
  2348. if ( t === 1 ) return this.copy( qb );
  2349. const x = this._x, y = this._y, z = this._z, w = this._w;
  2350. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2351. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2352. if ( cosHalfTheta < 0 ) {
  2353. this._w = - qb._w;
  2354. this._x = - qb._x;
  2355. this._y = - qb._y;
  2356. this._z = - qb._z;
  2357. cosHalfTheta = - cosHalfTheta;
  2358. } else {
  2359. this.copy( qb );
  2360. }
  2361. if ( cosHalfTheta >= 1.0 ) {
  2362. this._w = w;
  2363. this._x = x;
  2364. this._y = y;
  2365. this._z = z;
  2366. return this;
  2367. }
  2368. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2369. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2370. const s = 1 - t;
  2371. this._w = s * w + t * this._w;
  2372. this._x = s * x + t * this._x;
  2373. this._y = s * y + t * this._y;
  2374. this._z = s * z + t * this._z;
  2375. this.normalize();
  2376. this._onChangeCallback();
  2377. return this;
  2378. }
  2379. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2380. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2381. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2382. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2383. this._w = ( w * ratioA + this._w * ratioB );
  2384. this._x = ( x * ratioA + this._x * ratioB );
  2385. this._y = ( y * ratioA + this._y * ratioB );
  2386. this._z = ( z * ratioA + this._z * ratioB );
  2387. this._onChangeCallback();
  2388. return this;
  2389. }
  2390. slerpQuaternions( qa, qb, t ) {
  2391. return this.copy( qa ).slerp( qb, t );
  2392. }
  2393. random() {
  2394. // Derived from http://planning.cs.uiuc.edu/node198.html
  2395. // Note, this source uses w, x, y, z ordering,
  2396. // so we swap the order below.
  2397. const u1 = Math.random();
  2398. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2399. const sqrtu1 = Math.sqrt( u1 );
  2400. const u2 = 2 * Math.PI * Math.random();
  2401. const u3 = 2 * Math.PI * Math.random();
  2402. return this.set(
  2403. sqrt1u1 * Math.cos( u2 ),
  2404. sqrtu1 * Math.sin( u3 ),
  2405. sqrtu1 * Math.cos( u3 ),
  2406. sqrt1u1 * Math.sin( u2 ),
  2407. );
  2408. }
  2409. equals( quaternion ) {
  2410. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2411. }
  2412. fromArray( array, offset = 0 ) {
  2413. this._x = array[ offset ];
  2414. this._y = array[ offset + 1 ];
  2415. this._z = array[ offset + 2 ];
  2416. this._w = array[ offset + 3 ];
  2417. this._onChangeCallback();
  2418. return this;
  2419. }
  2420. toArray( array = [], offset = 0 ) {
  2421. array[ offset ] = this._x;
  2422. array[ offset + 1 ] = this._y;
  2423. array[ offset + 2 ] = this._z;
  2424. array[ offset + 3 ] = this._w;
  2425. return array;
  2426. }
  2427. fromBufferAttribute( attribute, index ) {
  2428. this._x = attribute.getX( index );
  2429. this._y = attribute.getY( index );
  2430. this._z = attribute.getZ( index );
  2431. this._w = attribute.getW( index );
  2432. return this;
  2433. }
  2434. _onChange( callback ) {
  2435. this._onChangeCallback = callback;
  2436. return this;
  2437. }
  2438. _onChangeCallback() {}
  2439. }
  2440. Quaternion.prototype.isQuaternion = true;
  2441. class Vector3 {
  2442. constructor( x = 0, y = 0, z = 0 ) {
  2443. this.x = x;
  2444. this.y = y;
  2445. this.z = z;
  2446. }
  2447. set( x, y, z ) {
  2448. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2449. this.x = x;
  2450. this.y = y;
  2451. this.z = z;
  2452. return this;
  2453. }
  2454. setScalar( scalar ) {
  2455. this.x = scalar;
  2456. this.y = scalar;
  2457. this.z = scalar;
  2458. return this;
  2459. }
  2460. setX( x ) {
  2461. this.x = x;
  2462. return this;
  2463. }
  2464. setY( y ) {
  2465. this.y = y;
  2466. return this;
  2467. }
  2468. setZ( z ) {
  2469. this.z = z;
  2470. return this;
  2471. }
  2472. setComponent( index, value ) {
  2473. switch ( index ) {
  2474. case 0: this.x = value; break;
  2475. case 1: this.y = value; break;
  2476. case 2: this.z = value; break;
  2477. default: throw new Error( 'index is out of range: ' + index );
  2478. }
  2479. return this;
  2480. }
  2481. getComponent( index ) {
  2482. switch ( index ) {
  2483. case 0: return this.x;
  2484. case 1: return this.y;
  2485. case 2: return this.z;
  2486. default: throw new Error( 'index is out of range: ' + index );
  2487. }
  2488. }
  2489. clone() {
  2490. return new this.constructor( this.x, this.y, this.z );
  2491. }
  2492. copy( v ) {
  2493. this.x = v.x;
  2494. this.y = v.y;
  2495. this.z = v.z;
  2496. return this;
  2497. }
  2498. add( v, w ) {
  2499. if ( w !== undefined ) {
  2500. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2501. return this.addVectors( v, w );
  2502. }
  2503. this.x += v.x;
  2504. this.y += v.y;
  2505. this.z += v.z;
  2506. return this;
  2507. }
  2508. addScalar( s ) {
  2509. this.x += s;
  2510. this.y += s;
  2511. this.z += s;
  2512. return this;
  2513. }
  2514. addVectors( a, b ) {
  2515. this.x = a.x + b.x;
  2516. this.y = a.y + b.y;
  2517. this.z = a.z + b.z;
  2518. return this;
  2519. }
  2520. addScaledVector( v, s ) {
  2521. this.x += v.x * s;
  2522. this.y += v.y * s;
  2523. this.z += v.z * s;
  2524. return this;
  2525. }
  2526. sub( v, w ) {
  2527. if ( w !== undefined ) {
  2528. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2529. return this.subVectors( v, w );
  2530. }
  2531. this.x -= v.x;
  2532. this.y -= v.y;
  2533. this.z -= v.z;
  2534. return this;
  2535. }
  2536. subScalar( s ) {
  2537. this.x -= s;
  2538. this.y -= s;
  2539. this.z -= s;
  2540. return this;
  2541. }
  2542. subVectors( a, b ) {
  2543. this.x = a.x - b.x;
  2544. this.y = a.y - b.y;
  2545. this.z = a.z - b.z;
  2546. return this;
  2547. }
  2548. multiply( v, w ) {
  2549. if ( w !== undefined ) {
  2550. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2551. return this.multiplyVectors( v, w );
  2552. }
  2553. this.x *= v.x;
  2554. this.y *= v.y;
  2555. this.z *= v.z;
  2556. return this;
  2557. }
  2558. multiplyScalar( scalar ) {
  2559. this.x *= scalar;
  2560. this.y *= scalar;
  2561. this.z *= scalar;
  2562. return this;
  2563. }
  2564. multiplyVectors( a, b ) {
  2565. this.x = a.x * b.x;
  2566. this.y = a.y * b.y;
  2567. this.z = a.z * b.z;
  2568. return this;
  2569. }
  2570. applyEuler( euler ) {
  2571. if ( ! ( euler && euler.isEuler ) ) {
  2572. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2573. }
  2574. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2575. }
  2576. applyAxisAngle( axis, angle ) {
  2577. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2578. }
  2579. applyMatrix3( m ) {
  2580. const x = this.x, y = this.y, z = this.z;
  2581. const e = m.elements;
  2582. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2583. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2584. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2585. return this;
  2586. }
  2587. applyNormalMatrix( m ) {
  2588. return this.applyMatrix3( m ).normalize();
  2589. }
  2590. applyMatrix4( m ) {
  2591. const x = this.x, y = this.y, z = this.z;
  2592. const e = m.elements;
  2593. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2594. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2595. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2596. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2597. return this;
  2598. }
  2599. applyQuaternion( q ) {
  2600. const x = this.x, y = this.y, z = this.z;
  2601. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2602. // calculate quat * vector
  2603. const ix = qw * x + qy * z - qz * y;
  2604. const iy = qw * y + qz * x - qx * z;
  2605. const iz = qw * z + qx * y - qy * x;
  2606. const iw = - qx * x - qy * y - qz * z;
  2607. // calculate result * inverse quat
  2608. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2609. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2610. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2611. return this;
  2612. }
  2613. project( camera ) {
  2614. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2615. }
  2616. unproject( camera ) {
  2617. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2618. }
  2619. transformDirection( m ) {
  2620. // input: THREE.Matrix4 affine matrix
  2621. // vector interpreted as a direction
  2622. const x = this.x, y = this.y, z = this.z;
  2623. const e = m.elements;
  2624. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2625. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2626. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2627. return this.normalize();
  2628. }
  2629. divide( v ) {
  2630. this.x /= v.x;
  2631. this.y /= v.y;
  2632. this.z /= v.z;
  2633. return this;
  2634. }
  2635. divideScalar( scalar ) {
  2636. return this.multiplyScalar( 1 / scalar );
  2637. }
  2638. min( v ) {
  2639. this.x = Math.min( this.x, v.x );
  2640. this.y = Math.min( this.y, v.y );
  2641. this.z = Math.min( this.z, v.z );
  2642. return this;
  2643. }
  2644. max( v ) {
  2645. this.x = Math.max( this.x, v.x );
  2646. this.y = Math.max( this.y, v.y );
  2647. this.z = Math.max( this.z, v.z );
  2648. return this;
  2649. }
  2650. clamp( min, max ) {
  2651. // assumes min < max, componentwise
  2652. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2653. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2654. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2655. return this;
  2656. }
  2657. clampScalar( minVal, maxVal ) {
  2658. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2659. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2660. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2661. return this;
  2662. }
  2663. clampLength( min, max ) {
  2664. const length = this.length();
  2665. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2666. }
  2667. floor() {
  2668. this.x = Math.floor( this.x );
  2669. this.y = Math.floor( this.y );
  2670. this.z = Math.floor( this.z );
  2671. return this;
  2672. }
  2673. ceil() {
  2674. this.x = Math.ceil( this.x );
  2675. this.y = Math.ceil( this.y );
  2676. this.z = Math.ceil( this.z );
  2677. return this;
  2678. }
  2679. round() {
  2680. this.x = Math.round( this.x );
  2681. this.y = Math.round( this.y );
  2682. this.z = Math.round( this.z );
  2683. return this;
  2684. }
  2685. roundToZero() {
  2686. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2687. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2688. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2689. return this;
  2690. }
  2691. negate() {
  2692. this.x = - this.x;
  2693. this.y = - this.y;
  2694. this.z = - this.z;
  2695. return this;
  2696. }
  2697. dot( v ) {
  2698. return this.x * v.x + this.y * v.y + this.z * v.z;
  2699. }
  2700. // TODO lengthSquared?
  2701. lengthSq() {
  2702. return this.x * this.x + this.y * this.y + this.z * this.z;
  2703. }
  2704. length() {
  2705. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2706. }
  2707. manhattanLength() {
  2708. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2709. }
  2710. normalize() {
  2711. return this.divideScalar( this.length() || 1 );
  2712. }
  2713. setLength( length ) {
  2714. return this.normalize().multiplyScalar( length );
  2715. }
  2716. lerp( v, alpha ) {
  2717. this.x += ( v.x - this.x ) * alpha;
  2718. this.y += ( v.y - this.y ) * alpha;
  2719. this.z += ( v.z - this.z ) * alpha;
  2720. return this;
  2721. }
  2722. lerpVectors( v1, v2, alpha ) {
  2723. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2724. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2725. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2726. return this;
  2727. }
  2728. cross( v, w ) {
  2729. if ( w !== undefined ) {
  2730. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2731. return this.crossVectors( v, w );
  2732. }
  2733. return this.crossVectors( this, v );
  2734. }
  2735. crossVectors( a, b ) {
  2736. const ax = a.x, ay = a.y, az = a.z;
  2737. const bx = b.x, by = b.y, bz = b.z;
  2738. this.x = ay * bz - az * by;
  2739. this.y = az * bx - ax * bz;
  2740. this.z = ax * by - ay * bx;
  2741. return this;
  2742. }
  2743. projectOnVector( v ) {
  2744. const denominator = v.lengthSq();
  2745. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2746. const scalar = v.dot( this ) / denominator;
  2747. return this.copy( v ).multiplyScalar( scalar );
  2748. }
  2749. projectOnPlane( planeNormal ) {
  2750. _vector$c.copy( this ).projectOnVector( planeNormal );
  2751. return this.sub( _vector$c );
  2752. }
  2753. reflect( normal ) {
  2754. // reflect incident vector off plane orthogonal to normal
  2755. // normal is assumed to have unit length
  2756. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2757. }
  2758. angleTo( v ) {
  2759. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2760. if ( denominator === 0 ) return Math.PI / 2;
  2761. const theta = this.dot( v ) / denominator;
  2762. // clamp, to handle numerical problems
  2763. return Math.acos( clamp( theta, - 1, 1 ) );
  2764. }
  2765. distanceTo( v ) {
  2766. return Math.sqrt( this.distanceToSquared( v ) );
  2767. }
  2768. distanceToSquared( v ) {
  2769. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2770. return dx * dx + dy * dy + dz * dz;
  2771. }
  2772. manhattanDistanceTo( v ) {
  2773. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2774. }
  2775. setFromSpherical( s ) {
  2776. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2777. }
  2778. setFromSphericalCoords( radius, phi, theta ) {
  2779. const sinPhiRadius = Math.sin( phi ) * radius;
  2780. this.x = sinPhiRadius * Math.sin( theta );
  2781. this.y = Math.cos( phi ) * radius;
  2782. this.z = sinPhiRadius * Math.cos( theta );
  2783. return this;
  2784. }
  2785. setFromCylindrical( c ) {
  2786. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2787. }
  2788. setFromCylindricalCoords( radius, theta, y ) {
  2789. this.x = radius * Math.sin( theta );
  2790. this.y = y;
  2791. this.z = radius * Math.cos( theta );
  2792. return this;
  2793. }
  2794. setFromMatrixPosition( m ) {
  2795. const e = m.elements;
  2796. this.x = e[ 12 ];
  2797. this.y = e[ 13 ];
  2798. this.z = e[ 14 ];
  2799. return this;
  2800. }
  2801. setFromMatrixScale( m ) {
  2802. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2803. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2804. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2805. this.x = sx;
  2806. this.y = sy;
  2807. this.z = sz;
  2808. return this;
  2809. }
  2810. setFromMatrixColumn( m, index ) {
  2811. return this.fromArray( m.elements, index * 4 );
  2812. }
  2813. setFromMatrix3Column( m, index ) {
  2814. return this.fromArray( m.elements, index * 3 );
  2815. }
  2816. equals( v ) {
  2817. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2818. }
  2819. fromArray( array, offset = 0 ) {
  2820. this.x = array[ offset ];
  2821. this.y = array[ offset + 1 ];
  2822. this.z = array[ offset + 2 ];
  2823. return this;
  2824. }
  2825. toArray( array = [], offset = 0 ) {
  2826. array[ offset ] = this.x;
  2827. array[ offset + 1 ] = this.y;
  2828. array[ offset + 2 ] = this.z;
  2829. return array;
  2830. }
  2831. fromBufferAttribute( attribute, index, offset ) {
  2832. if ( offset !== undefined ) {
  2833. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2834. }
  2835. this.x = attribute.getX( index );
  2836. this.y = attribute.getY( index );
  2837. this.z = attribute.getZ( index );
  2838. return this;
  2839. }
  2840. random() {
  2841. this.x = Math.random();
  2842. this.y = Math.random();
  2843. this.z = Math.random();
  2844. return this;
  2845. }
  2846. randomDirection() {
  2847. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2848. const u = ( Math.random() - 0.5 ) * 2;
  2849. const t = Math.random() * Math.PI * 2;
  2850. const f = Math.sqrt( 1 - u ** 2 );
  2851. this.x = f * Math.cos( t );
  2852. this.y = f * Math.sin( t );
  2853. this.z = u;
  2854. return this;
  2855. }
  2856. *[ Symbol.iterator ]() {
  2857. yield this.x;
  2858. yield this.y;
  2859. yield this.z;
  2860. }
  2861. }
  2862. Vector3.prototype.isVector3 = true;
  2863. const _vector$c = /*@__PURE__*/ new Vector3();
  2864. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2865. class Box3 {
  2866. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2867. this.min = min;
  2868. this.max = max;
  2869. }
  2870. set( min, max ) {
  2871. this.min.copy( min );
  2872. this.max.copy( max );
  2873. return this;
  2874. }
  2875. setFromArray( array ) {
  2876. let minX = + Infinity;
  2877. let minY = + Infinity;
  2878. let minZ = + Infinity;
  2879. let maxX = - Infinity;
  2880. let maxY = - Infinity;
  2881. let maxZ = - Infinity;
  2882. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2883. const x = array[ i ];
  2884. const y = array[ i + 1 ];
  2885. const z = array[ i + 2 ];
  2886. if ( x < minX ) minX = x;
  2887. if ( y < minY ) minY = y;
  2888. if ( z < minZ ) minZ = z;
  2889. if ( x > maxX ) maxX = x;
  2890. if ( y > maxY ) maxY = y;
  2891. if ( z > maxZ ) maxZ = z;
  2892. }
  2893. this.min.set( minX, minY, minZ );
  2894. this.max.set( maxX, maxY, maxZ );
  2895. return this;
  2896. }
  2897. setFromBufferAttribute( attribute ) {
  2898. let minX = + Infinity;
  2899. let minY = + Infinity;
  2900. let minZ = + Infinity;
  2901. let maxX = - Infinity;
  2902. let maxY = - Infinity;
  2903. let maxZ = - Infinity;
  2904. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2905. const x = attribute.getX( i );
  2906. const y = attribute.getY( i );
  2907. const z = attribute.getZ( i );
  2908. if ( x < minX ) minX = x;
  2909. if ( y < minY ) minY = y;
  2910. if ( z < minZ ) minZ = z;
  2911. if ( x > maxX ) maxX = x;
  2912. if ( y > maxY ) maxY = y;
  2913. if ( z > maxZ ) maxZ = z;
  2914. }
  2915. this.min.set( minX, minY, minZ );
  2916. this.max.set( maxX, maxY, maxZ );
  2917. return this;
  2918. }
  2919. setFromPoints( points ) {
  2920. this.makeEmpty();
  2921. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2922. this.expandByPoint( points[ i ] );
  2923. }
  2924. return this;
  2925. }
  2926. setFromCenterAndSize( center, size ) {
  2927. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2928. this.min.copy( center ).sub( halfSize );
  2929. this.max.copy( center ).add( halfSize );
  2930. return this;
  2931. }
  2932. setFromObject( object, precise = false ) {
  2933. this.makeEmpty();
  2934. return this.expandByObject( object, precise );
  2935. }
  2936. clone() {
  2937. return new this.constructor().copy( this );
  2938. }
  2939. copy( box ) {
  2940. this.min.copy( box.min );
  2941. this.max.copy( box.max );
  2942. return this;
  2943. }
  2944. makeEmpty() {
  2945. this.min.x = this.min.y = this.min.z = + Infinity;
  2946. this.max.x = this.max.y = this.max.z = - Infinity;
  2947. return this;
  2948. }
  2949. isEmpty() {
  2950. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2951. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2952. }
  2953. getCenter( target ) {
  2954. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2955. }
  2956. getSize( target ) {
  2957. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2958. }
  2959. expandByPoint( point ) {
  2960. this.min.min( point );
  2961. this.max.max( point );
  2962. return this;
  2963. }
  2964. expandByVector( vector ) {
  2965. this.min.sub( vector );
  2966. this.max.add( vector );
  2967. return this;
  2968. }
  2969. expandByScalar( scalar ) {
  2970. this.min.addScalar( - scalar );
  2971. this.max.addScalar( scalar );
  2972. return this;
  2973. }
  2974. expandByObject( object, precise = false ) {
  2975. // Computes the world-axis-aligned bounding box of an object (including its children),
  2976. // accounting for both the object's, and children's, world transforms
  2977. object.updateWorldMatrix( false, false );
  2978. const geometry = object.geometry;
  2979. if ( geometry !== undefined ) {
  2980. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  2981. const position = geometry.attributes.position;
  2982. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2983. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2984. this.expandByPoint( _vector$b );
  2985. }
  2986. } else {
  2987. if ( geometry.boundingBox === null ) {
  2988. geometry.computeBoundingBox();
  2989. }
  2990. _box$3.copy( geometry.boundingBox );
  2991. _box$3.applyMatrix4( object.matrixWorld );
  2992. this.union( _box$3 );
  2993. }
  2994. }
  2995. const children = object.children;
  2996. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2997. this.expandByObject( children[ i ], precise );
  2998. }
  2999. return this;
  3000. }
  3001. containsPoint( point ) {
  3002. return point.x < this.min.x || point.x > this.max.x ||
  3003. point.y < this.min.y || point.y > this.max.y ||
  3004. point.z < this.min.z || point.z > this.max.z ? false : true;
  3005. }
  3006. containsBox( box ) {
  3007. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3008. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3009. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3010. }
  3011. getParameter( point, target ) {
  3012. // This can potentially have a divide by zero if the box
  3013. // has a size dimension of 0.
  3014. return target.set(
  3015. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3016. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3017. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3018. );
  3019. }
  3020. intersectsBox( box ) {
  3021. // using 6 splitting planes to rule out intersections.
  3022. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3023. box.max.y < this.min.y || box.min.y > this.max.y ||
  3024. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3025. }
  3026. intersectsSphere( sphere ) {
  3027. // Find the point on the AABB closest to the sphere center.
  3028. this.clampPoint( sphere.center, _vector$b );
  3029. // If that point is inside the sphere, the AABB and sphere intersect.
  3030. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3031. }
  3032. intersectsPlane( plane ) {
  3033. // We compute the minimum and maximum dot product values. If those values
  3034. // are on the same side (back or front) of the plane, then there is no intersection.
  3035. let min, max;
  3036. if ( plane.normal.x > 0 ) {
  3037. min = plane.normal.x * this.min.x;
  3038. max = plane.normal.x * this.max.x;
  3039. } else {
  3040. min = plane.normal.x * this.max.x;
  3041. max = plane.normal.x * this.min.x;
  3042. }
  3043. if ( plane.normal.y > 0 ) {
  3044. min += plane.normal.y * this.min.y;
  3045. max += plane.normal.y * this.max.y;
  3046. } else {
  3047. min += plane.normal.y * this.max.y;
  3048. max += plane.normal.y * this.min.y;
  3049. }
  3050. if ( plane.normal.z > 0 ) {
  3051. min += plane.normal.z * this.min.z;
  3052. max += plane.normal.z * this.max.z;
  3053. } else {
  3054. min += plane.normal.z * this.max.z;
  3055. max += plane.normal.z * this.min.z;
  3056. }
  3057. return ( min <= - plane.constant && max >= - plane.constant );
  3058. }
  3059. intersectsTriangle( triangle ) {
  3060. if ( this.isEmpty() ) {
  3061. return false;
  3062. }
  3063. // compute box center and extents
  3064. this.getCenter( _center );
  3065. _extents.subVectors( this.max, _center );
  3066. // translate triangle to aabb origin
  3067. _v0$2.subVectors( triangle.a, _center );
  3068. _v1$7.subVectors( triangle.b, _center );
  3069. _v2$3.subVectors( triangle.c, _center );
  3070. // compute edge vectors for triangle
  3071. _f0.subVectors( _v1$7, _v0$2 );
  3072. _f1.subVectors( _v2$3, _v1$7 );
  3073. _f2.subVectors( _v0$2, _v2$3 );
  3074. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3075. // 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
  3076. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3077. let axes = [
  3078. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3079. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3080. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3081. ];
  3082. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3083. return false;
  3084. }
  3085. // test 3 face normals from the aabb
  3086. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3087. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3088. return false;
  3089. }
  3090. // finally testing the face normal of the triangle
  3091. // use already existing triangle edge vectors here
  3092. _triangleNormal.crossVectors( _f0, _f1 );
  3093. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3094. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  3095. }
  3096. clampPoint( point, target ) {
  3097. return target.copy( point ).clamp( this.min, this.max );
  3098. }
  3099. distanceToPoint( point ) {
  3100. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3101. return clampedPoint.sub( point ).length();
  3102. }
  3103. getBoundingSphere( target ) {
  3104. this.getCenter( target.center );
  3105. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3106. return target;
  3107. }
  3108. intersect( box ) {
  3109. this.min.max( box.min );
  3110. this.max.min( box.max );
  3111. // 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.
  3112. if ( this.isEmpty() ) this.makeEmpty();
  3113. return this;
  3114. }
  3115. union( box ) {
  3116. this.min.min( box.min );
  3117. this.max.max( box.max );
  3118. return this;
  3119. }
  3120. applyMatrix4( matrix ) {
  3121. // transform of empty box is an empty box.
  3122. if ( this.isEmpty() ) return this;
  3123. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3124. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3125. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3126. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3127. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3128. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3129. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3130. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3131. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3132. this.setFromPoints( _points );
  3133. return this;
  3134. }
  3135. translate( offset ) {
  3136. this.min.add( offset );
  3137. this.max.add( offset );
  3138. return this;
  3139. }
  3140. equals( box ) {
  3141. return box.min.equals( this.min ) && box.max.equals( this.max );
  3142. }
  3143. }
  3144. Box3.prototype.isBox3 = true;
  3145. const _points = [
  3146. /*@__PURE__*/ new Vector3(),
  3147. /*@__PURE__*/ new Vector3(),
  3148. /*@__PURE__*/ new Vector3(),
  3149. /*@__PURE__*/ new Vector3(),
  3150. /*@__PURE__*/ new Vector3(),
  3151. /*@__PURE__*/ new Vector3(),
  3152. /*@__PURE__*/ new Vector3(),
  3153. /*@__PURE__*/ new Vector3()
  3154. ];
  3155. const _vector$b = /*@__PURE__*/ new Vector3();
  3156. const _box$3 = /*@__PURE__*/ new Box3();
  3157. // triangle centered vertices
  3158. const _v0$2 = /*@__PURE__*/ new Vector3();
  3159. const _v1$7 = /*@__PURE__*/ new Vector3();
  3160. const _v2$3 = /*@__PURE__*/ new Vector3();
  3161. // triangle edge vectors
  3162. const _f0 = /*@__PURE__*/ new Vector3();
  3163. const _f1 = /*@__PURE__*/ new Vector3();
  3164. const _f2 = /*@__PURE__*/ new Vector3();
  3165. const _center = /*@__PURE__*/ new Vector3();
  3166. const _extents = /*@__PURE__*/ new Vector3();
  3167. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3168. const _testAxis = /*@__PURE__*/ new Vector3();
  3169. function satForAxes( axes, v0, v1, v2, extents ) {
  3170. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3171. _testAxis.fromArray( axes, i );
  3172. // project the aabb onto the seperating axis
  3173. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3174. // project all 3 vertices of the triangle onto the seperating axis
  3175. const p0 = v0.dot( _testAxis );
  3176. const p1 = v1.dot( _testAxis );
  3177. const p2 = v2.dot( _testAxis );
  3178. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3179. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3180. // points of the projected triangle are outside the projected half-length of the aabb
  3181. // the axis is seperating and we can exit
  3182. return false;
  3183. }
  3184. }
  3185. return true;
  3186. }
  3187. const _box$2 = /*@__PURE__*/ new Box3();
  3188. const _v1$6 = /*@__PURE__*/ new Vector3();
  3189. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  3190. const _toPoint = /*@__PURE__*/ new Vector3();
  3191. class Sphere {
  3192. constructor( center = new Vector3(), radius = - 1 ) {
  3193. this.center = center;
  3194. this.radius = radius;
  3195. }
  3196. set( center, radius ) {
  3197. this.center.copy( center );
  3198. this.radius = radius;
  3199. return this;
  3200. }
  3201. setFromPoints( points, optionalCenter ) {
  3202. const center = this.center;
  3203. if ( optionalCenter !== undefined ) {
  3204. center.copy( optionalCenter );
  3205. } else {
  3206. _box$2.setFromPoints( points ).getCenter( center );
  3207. }
  3208. let maxRadiusSq = 0;
  3209. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3210. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3211. }
  3212. this.radius = Math.sqrt( maxRadiusSq );
  3213. return this;
  3214. }
  3215. copy( sphere ) {
  3216. this.center.copy( sphere.center );
  3217. this.radius = sphere.radius;
  3218. return this;
  3219. }
  3220. isEmpty() {
  3221. return ( this.radius < 0 );
  3222. }
  3223. makeEmpty() {
  3224. this.center.set( 0, 0, 0 );
  3225. this.radius = - 1;
  3226. return this;
  3227. }
  3228. containsPoint( point ) {
  3229. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3230. }
  3231. distanceToPoint( point ) {
  3232. return ( point.distanceTo( this.center ) - this.radius );
  3233. }
  3234. intersectsSphere( sphere ) {
  3235. const radiusSum = this.radius + sphere.radius;
  3236. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3237. }
  3238. intersectsBox( box ) {
  3239. return box.intersectsSphere( this );
  3240. }
  3241. intersectsPlane( plane ) {
  3242. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3243. }
  3244. clampPoint( point, target ) {
  3245. const deltaLengthSq = this.center.distanceToSquared( point );
  3246. target.copy( point );
  3247. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3248. target.sub( this.center ).normalize();
  3249. target.multiplyScalar( this.radius ).add( this.center );
  3250. }
  3251. return target;
  3252. }
  3253. getBoundingBox( target ) {
  3254. if ( this.isEmpty() ) {
  3255. // Empty sphere produces empty bounding box
  3256. target.makeEmpty();
  3257. return target;
  3258. }
  3259. target.set( this.center, this.center );
  3260. target.expandByScalar( this.radius );
  3261. return target;
  3262. }
  3263. applyMatrix4( matrix ) {
  3264. this.center.applyMatrix4( matrix );
  3265. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3266. return this;
  3267. }
  3268. translate( offset ) {
  3269. this.center.add( offset );
  3270. return this;
  3271. }
  3272. expandByPoint( point ) {
  3273. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3274. _toPoint.subVectors( point, this.center );
  3275. const lengthSq = _toPoint.lengthSq();
  3276. if ( lengthSq > ( this.radius * this.radius ) ) {
  3277. const length = Math.sqrt( lengthSq );
  3278. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  3279. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3280. // and the other half to position. This gives a tighter enclosure, instead of if
  3281. // the whole missing distance were just added to radius.
  3282. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  3283. this.radius += missingRadiusHalf;
  3284. }
  3285. return this;
  3286. }
  3287. union( sphere ) {
  3288. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3289. // To enclose another sphere into this sphere, we only need to enclose two points:
  3290. // 1) Enclose the farthest point on the other sphere into this sphere.
  3291. // 2) Enclose the opposite point of the farthest point into this sphere.
  3292. if ( this.center.equals( sphere.center ) === true ) {
  3293. _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius );
  3294. } else {
  3295. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  3296. }
  3297. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  3298. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  3299. return this;
  3300. }
  3301. equals( sphere ) {
  3302. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3303. }
  3304. clone() {
  3305. return new this.constructor().copy( this );
  3306. }
  3307. }
  3308. const _vector$a = /*@__PURE__*/ new Vector3();
  3309. const _segCenter = /*@__PURE__*/ new Vector3();
  3310. const _segDir = /*@__PURE__*/ new Vector3();
  3311. const _diff = /*@__PURE__*/ new Vector3();
  3312. const _edge1 = /*@__PURE__*/ new Vector3();
  3313. const _edge2 = /*@__PURE__*/ new Vector3();
  3314. const _normal$1 = /*@__PURE__*/ new Vector3();
  3315. class Ray {
  3316. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3317. this.origin = origin;
  3318. this.direction = direction;
  3319. }
  3320. set( origin, direction ) {
  3321. this.origin.copy( origin );
  3322. this.direction.copy( direction );
  3323. return this;
  3324. }
  3325. copy( ray ) {
  3326. this.origin.copy( ray.origin );
  3327. this.direction.copy( ray.direction );
  3328. return this;
  3329. }
  3330. at( t, target ) {
  3331. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3332. }
  3333. lookAt( v ) {
  3334. this.direction.copy( v ).sub( this.origin ).normalize();
  3335. return this;
  3336. }
  3337. recast( t ) {
  3338. this.origin.copy( this.at( t, _vector$a ) );
  3339. return this;
  3340. }
  3341. closestPointToPoint( point, target ) {
  3342. target.subVectors( point, this.origin );
  3343. const directionDistance = target.dot( this.direction );
  3344. if ( directionDistance < 0 ) {
  3345. return target.copy( this.origin );
  3346. }
  3347. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3348. }
  3349. distanceToPoint( point ) {
  3350. return Math.sqrt( this.distanceSqToPoint( point ) );
  3351. }
  3352. distanceSqToPoint( point ) {
  3353. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3354. // point behind the ray
  3355. if ( directionDistance < 0 ) {
  3356. return this.origin.distanceToSquared( point );
  3357. }
  3358. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3359. return _vector$a.distanceToSquared( point );
  3360. }
  3361. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3362. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3363. // It returns the min distance between the ray and the segment
  3364. // defined by v0 and v1
  3365. // It can also set two optional targets :
  3366. // - The closest point on the ray
  3367. // - The closest point on the segment
  3368. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3369. _segDir.copy( v1 ).sub( v0 ).normalize();
  3370. _diff.copy( this.origin ).sub( _segCenter );
  3371. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3372. const a01 = - this.direction.dot( _segDir );
  3373. const b0 = _diff.dot( this.direction );
  3374. const b1 = - _diff.dot( _segDir );
  3375. const c = _diff.lengthSq();
  3376. const det = Math.abs( 1 - a01 * a01 );
  3377. let s0, s1, sqrDist, extDet;
  3378. if ( det > 0 ) {
  3379. // The ray and segment are not parallel.
  3380. s0 = a01 * b1 - b0;
  3381. s1 = a01 * b0 - b1;
  3382. extDet = segExtent * det;
  3383. if ( s0 >= 0 ) {
  3384. if ( s1 >= - extDet ) {
  3385. if ( s1 <= extDet ) {
  3386. // region 0
  3387. // Minimum at interior points of ray and segment.
  3388. const invDet = 1 / det;
  3389. s0 *= invDet;
  3390. s1 *= invDet;
  3391. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3392. } else {
  3393. // region 1
  3394. s1 = segExtent;
  3395. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3396. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3397. }
  3398. } else {
  3399. // region 5
  3400. s1 = - segExtent;
  3401. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3402. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3403. }
  3404. } else {
  3405. if ( s1 <= - extDet ) {
  3406. // region 4
  3407. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3408. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3409. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3410. } else if ( s1 <= extDet ) {
  3411. // region 3
  3412. s0 = 0;
  3413. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3414. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3415. } else {
  3416. // region 2
  3417. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3418. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3419. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3420. }
  3421. }
  3422. } else {
  3423. // Ray and segment are parallel.
  3424. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3425. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3426. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3427. }
  3428. if ( optionalPointOnRay ) {
  3429. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3430. }
  3431. if ( optionalPointOnSegment ) {
  3432. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3433. }
  3434. return sqrDist;
  3435. }
  3436. intersectSphere( sphere, target ) {
  3437. _vector$a.subVectors( sphere.center, this.origin );
  3438. const tca = _vector$a.dot( this.direction );
  3439. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3440. const radius2 = sphere.radius * sphere.radius;
  3441. if ( d2 > radius2 ) return null;
  3442. const thc = Math.sqrt( radius2 - d2 );
  3443. // t0 = first intersect point - entrance on front of sphere
  3444. const t0 = tca - thc;
  3445. // t1 = second intersect point - exit point on back of sphere
  3446. const t1 = tca + thc;
  3447. // test to see if both t0 and t1 are behind the ray - if so, return null
  3448. if ( t0 < 0 && t1 < 0 ) return null;
  3449. // test to see if t0 is behind the ray:
  3450. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3451. // in order to always return an intersect point that is in front of the ray.
  3452. if ( t0 < 0 ) return this.at( t1, target );
  3453. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3454. return this.at( t0, target );
  3455. }
  3456. intersectsSphere( sphere ) {
  3457. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3458. }
  3459. distanceToPlane( plane ) {
  3460. const denominator = plane.normal.dot( this.direction );
  3461. if ( denominator === 0 ) {
  3462. // line is coplanar, return origin
  3463. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3464. return 0;
  3465. }
  3466. // Null is preferable to undefined since undefined means.... it is undefined
  3467. return null;
  3468. }
  3469. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3470. // Return if the ray never intersects the plane
  3471. return t >= 0 ? t : null;
  3472. }
  3473. intersectPlane( plane, target ) {
  3474. const t = this.distanceToPlane( plane );
  3475. if ( t === null ) {
  3476. return null;
  3477. }
  3478. return this.at( t, target );
  3479. }
  3480. intersectsPlane( plane ) {
  3481. // check if the ray lies on the plane first
  3482. const distToPoint = plane.distanceToPoint( this.origin );
  3483. if ( distToPoint === 0 ) {
  3484. return true;
  3485. }
  3486. const denominator = plane.normal.dot( this.direction );
  3487. if ( denominator * distToPoint < 0 ) {
  3488. return true;
  3489. }
  3490. // ray origin is behind the plane (and is pointing behind it)
  3491. return false;
  3492. }
  3493. intersectBox( box, target ) {
  3494. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3495. const invdirx = 1 / this.direction.x,
  3496. invdiry = 1 / this.direction.y,
  3497. invdirz = 1 / this.direction.z;
  3498. const origin = this.origin;
  3499. if ( invdirx >= 0 ) {
  3500. tmin = ( box.min.x - origin.x ) * invdirx;
  3501. tmax = ( box.max.x - origin.x ) * invdirx;
  3502. } else {
  3503. tmin = ( box.max.x - origin.x ) * invdirx;
  3504. tmax = ( box.min.x - origin.x ) * invdirx;
  3505. }
  3506. if ( invdiry >= 0 ) {
  3507. tymin = ( box.min.y - origin.y ) * invdiry;
  3508. tymax = ( box.max.y - origin.y ) * invdiry;
  3509. } else {
  3510. tymin = ( box.max.y - origin.y ) * invdiry;
  3511. tymax = ( box.min.y - origin.y ) * invdiry;
  3512. }
  3513. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3514. // These lines also handle the case where tmin or tmax is NaN
  3515. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3516. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3517. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3518. if ( invdirz >= 0 ) {
  3519. tzmin = ( box.min.z - origin.z ) * invdirz;
  3520. tzmax = ( box.max.z - origin.z ) * invdirz;
  3521. } else {
  3522. tzmin = ( box.max.z - origin.z ) * invdirz;
  3523. tzmax = ( box.min.z - origin.z ) * invdirz;
  3524. }
  3525. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3526. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3527. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3528. //return point closest to the ray (positive side)
  3529. if ( tmax < 0 ) return null;
  3530. return this.at( tmin >= 0 ? tmin : tmax, target );
  3531. }
  3532. intersectsBox( box ) {
  3533. return this.intersectBox( box, _vector$a ) !== null;
  3534. }
  3535. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3536. // Compute the offset origin, edges, and normal.
  3537. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3538. _edge1.subVectors( b, a );
  3539. _edge2.subVectors( c, a );
  3540. _normal$1.crossVectors( _edge1, _edge2 );
  3541. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3542. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3543. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3544. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3545. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3546. let DdN = this.direction.dot( _normal$1 );
  3547. let sign;
  3548. if ( DdN > 0 ) {
  3549. if ( backfaceCulling ) return null;
  3550. sign = 1;
  3551. } else if ( DdN < 0 ) {
  3552. sign = - 1;
  3553. DdN = - DdN;
  3554. } else {
  3555. return null;
  3556. }
  3557. _diff.subVectors( this.origin, a );
  3558. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3559. // b1 < 0, no intersection
  3560. if ( DdQxE2 < 0 ) {
  3561. return null;
  3562. }
  3563. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3564. // b2 < 0, no intersection
  3565. if ( DdE1xQ < 0 ) {
  3566. return null;
  3567. }
  3568. // b1+b2 > 1, no intersection
  3569. if ( DdQxE2 + DdE1xQ > DdN ) {
  3570. return null;
  3571. }
  3572. // Line intersects triangle, check if ray does.
  3573. const QdN = - sign * _diff.dot( _normal$1 );
  3574. // t < 0, no intersection
  3575. if ( QdN < 0 ) {
  3576. return null;
  3577. }
  3578. // Ray intersects triangle.
  3579. return this.at( QdN / DdN, target );
  3580. }
  3581. applyMatrix4( matrix4 ) {
  3582. this.origin.applyMatrix4( matrix4 );
  3583. this.direction.transformDirection( matrix4 );
  3584. return this;
  3585. }
  3586. equals( ray ) {
  3587. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3588. }
  3589. clone() {
  3590. return new this.constructor().copy( this );
  3591. }
  3592. }
  3593. class Matrix4 {
  3594. constructor() {
  3595. this.elements = [
  3596. 1, 0, 0, 0,
  3597. 0, 1, 0, 0,
  3598. 0, 0, 1, 0,
  3599. 0, 0, 0, 1
  3600. ];
  3601. if ( arguments.length > 0 ) {
  3602. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3603. }
  3604. }
  3605. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3606. const te = this.elements;
  3607. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3608. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3609. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3610. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3611. return this;
  3612. }
  3613. identity() {
  3614. this.set(
  3615. 1, 0, 0, 0,
  3616. 0, 1, 0, 0,
  3617. 0, 0, 1, 0,
  3618. 0, 0, 0, 1
  3619. );
  3620. return this;
  3621. }
  3622. clone() {
  3623. return new Matrix4().fromArray( this.elements );
  3624. }
  3625. copy( m ) {
  3626. const te = this.elements;
  3627. const me = m.elements;
  3628. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3629. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3630. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3631. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3632. return this;
  3633. }
  3634. copyPosition( m ) {
  3635. const te = this.elements, me = m.elements;
  3636. te[ 12 ] = me[ 12 ];
  3637. te[ 13 ] = me[ 13 ];
  3638. te[ 14 ] = me[ 14 ];
  3639. return this;
  3640. }
  3641. setFromMatrix3( m ) {
  3642. const me = m.elements;
  3643. this.set(
  3644. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3645. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3646. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3647. 0, 0, 0, 1
  3648. );
  3649. return this;
  3650. }
  3651. extractBasis( xAxis, yAxis, zAxis ) {
  3652. xAxis.setFromMatrixColumn( this, 0 );
  3653. yAxis.setFromMatrixColumn( this, 1 );
  3654. zAxis.setFromMatrixColumn( this, 2 );
  3655. return this;
  3656. }
  3657. makeBasis( xAxis, yAxis, zAxis ) {
  3658. this.set(
  3659. xAxis.x, yAxis.x, zAxis.x, 0,
  3660. xAxis.y, yAxis.y, zAxis.y, 0,
  3661. xAxis.z, yAxis.z, zAxis.z, 0,
  3662. 0, 0, 0, 1
  3663. );
  3664. return this;
  3665. }
  3666. extractRotation( m ) {
  3667. // this method does not support reflection matrices
  3668. const te = this.elements;
  3669. const me = m.elements;
  3670. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3671. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3672. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3673. te[ 0 ] = me[ 0 ] * scaleX;
  3674. te[ 1 ] = me[ 1 ] * scaleX;
  3675. te[ 2 ] = me[ 2 ] * scaleX;
  3676. te[ 3 ] = 0;
  3677. te[ 4 ] = me[ 4 ] * scaleY;
  3678. te[ 5 ] = me[ 5 ] * scaleY;
  3679. te[ 6 ] = me[ 6 ] * scaleY;
  3680. te[ 7 ] = 0;
  3681. te[ 8 ] = me[ 8 ] * scaleZ;
  3682. te[ 9 ] = me[ 9 ] * scaleZ;
  3683. te[ 10 ] = me[ 10 ] * scaleZ;
  3684. te[ 11 ] = 0;
  3685. te[ 12 ] = 0;
  3686. te[ 13 ] = 0;
  3687. te[ 14 ] = 0;
  3688. te[ 15 ] = 1;
  3689. return this;
  3690. }
  3691. makeRotationFromEuler( euler ) {
  3692. if ( ! ( euler && euler.isEuler ) ) {
  3693. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3694. }
  3695. const te = this.elements;
  3696. const x = euler.x, y = euler.y, z = euler.z;
  3697. const a = Math.cos( x ), b = Math.sin( x );
  3698. const c = Math.cos( y ), d = Math.sin( y );
  3699. const e = Math.cos( z ), f = Math.sin( z );
  3700. if ( euler.order === 'XYZ' ) {
  3701. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3702. te[ 0 ] = c * e;
  3703. te[ 4 ] = - c * f;
  3704. te[ 8 ] = d;
  3705. te[ 1 ] = af + be * d;
  3706. te[ 5 ] = ae - bf * d;
  3707. te[ 9 ] = - b * c;
  3708. te[ 2 ] = bf - ae * d;
  3709. te[ 6 ] = be + af * d;
  3710. te[ 10 ] = a * c;
  3711. } else if ( euler.order === 'YXZ' ) {
  3712. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3713. te[ 0 ] = ce + df * b;
  3714. te[ 4 ] = de * b - cf;
  3715. te[ 8 ] = a * d;
  3716. te[ 1 ] = a * f;
  3717. te[ 5 ] = a * e;
  3718. te[ 9 ] = - b;
  3719. te[ 2 ] = cf * b - de;
  3720. te[ 6 ] = df + ce * b;
  3721. te[ 10 ] = a * c;
  3722. } else if ( euler.order === 'ZXY' ) {
  3723. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3724. te[ 0 ] = ce - df * b;
  3725. te[ 4 ] = - a * f;
  3726. te[ 8 ] = de + cf * b;
  3727. te[ 1 ] = cf + de * b;
  3728. te[ 5 ] = a * e;
  3729. te[ 9 ] = df - ce * b;
  3730. te[ 2 ] = - a * d;
  3731. te[ 6 ] = b;
  3732. te[ 10 ] = a * c;
  3733. } else if ( euler.order === 'ZYX' ) {
  3734. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3735. te[ 0 ] = c * e;
  3736. te[ 4 ] = be * d - af;
  3737. te[ 8 ] = ae * d + bf;
  3738. te[ 1 ] = c * f;
  3739. te[ 5 ] = bf * d + ae;
  3740. te[ 9 ] = af * d - be;
  3741. te[ 2 ] = - d;
  3742. te[ 6 ] = b * c;
  3743. te[ 10 ] = a * c;
  3744. } else if ( euler.order === 'YZX' ) {
  3745. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3746. te[ 0 ] = c * e;
  3747. te[ 4 ] = bd - ac * f;
  3748. te[ 8 ] = bc * f + ad;
  3749. te[ 1 ] = f;
  3750. te[ 5 ] = a * e;
  3751. te[ 9 ] = - b * e;
  3752. te[ 2 ] = - d * e;
  3753. te[ 6 ] = ad * f + bc;
  3754. te[ 10 ] = ac - bd * f;
  3755. } else if ( euler.order === 'XZY' ) {
  3756. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3757. te[ 0 ] = c * e;
  3758. te[ 4 ] = - f;
  3759. te[ 8 ] = d * e;
  3760. te[ 1 ] = ac * f + bd;
  3761. te[ 5 ] = a * e;
  3762. te[ 9 ] = ad * f - bc;
  3763. te[ 2 ] = bc * f - ad;
  3764. te[ 6 ] = b * e;
  3765. te[ 10 ] = bd * f + ac;
  3766. }
  3767. // bottom row
  3768. te[ 3 ] = 0;
  3769. te[ 7 ] = 0;
  3770. te[ 11 ] = 0;
  3771. // last column
  3772. te[ 12 ] = 0;
  3773. te[ 13 ] = 0;
  3774. te[ 14 ] = 0;
  3775. te[ 15 ] = 1;
  3776. return this;
  3777. }
  3778. makeRotationFromQuaternion( q ) {
  3779. return this.compose( _zero, q, _one );
  3780. }
  3781. lookAt( eye, target, up ) {
  3782. const te = this.elements;
  3783. _z.subVectors( eye, target );
  3784. if ( _z.lengthSq() === 0 ) {
  3785. // eye and target are in the same position
  3786. _z.z = 1;
  3787. }
  3788. _z.normalize();
  3789. _x.crossVectors( up, _z );
  3790. if ( _x.lengthSq() === 0 ) {
  3791. // up and z are parallel
  3792. if ( Math.abs( up.z ) === 1 ) {
  3793. _z.x += 0.0001;
  3794. } else {
  3795. _z.z += 0.0001;
  3796. }
  3797. _z.normalize();
  3798. _x.crossVectors( up, _z );
  3799. }
  3800. _x.normalize();
  3801. _y.crossVectors( _z, _x );
  3802. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3803. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3804. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3805. return this;
  3806. }
  3807. multiply( m, n ) {
  3808. if ( n !== undefined ) {
  3809. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3810. return this.multiplyMatrices( m, n );
  3811. }
  3812. return this.multiplyMatrices( this, m );
  3813. }
  3814. premultiply( m ) {
  3815. return this.multiplyMatrices( m, this );
  3816. }
  3817. multiplyMatrices( a, b ) {
  3818. const ae = a.elements;
  3819. const be = b.elements;
  3820. const te = this.elements;
  3821. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3822. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3823. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3824. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3825. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3826. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3827. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3828. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3829. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3830. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3831. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3832. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3833. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3834. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3835. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3836. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3837. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3838. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3839. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3840. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3841. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3842. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3843. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3844. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3845. return this;
  3846. }
  3847. multiplyScalar( s ) {
  3848. const te = this.elements;
  3849. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3850. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3851. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3852. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3853. return this;
  3854. }
  3855. determinant() {
  3856. const te = this.elements;
  3857. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3858. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3859. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3860. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3861. //TODO: make this more efficient
  3862. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3863. return (
  3864. n41 * (
  3865. + n14 * n23 * n32
  3866. - n13 * n24 * n32
  3867. - n14 * n22 * n33
  3868. + n12 * n24 * n33
  3869. + n13 * n22 * n34
  3870. - n12 * n23 * n34
  3871. ) +
  3872. n42 * (
  3873. + n11 * n23 * n34
  3874. - n11 * n24 * n33
  3875. + n14 * n21 * n33
  3876. - n13 * n21 * n34
  3877. + n13 * n24 * n31
  3878. - n14 * n23 * n31
  3879. ) +
  3880. n43 * (
  3881. + n11 * n24 * n32
  3882. - n11 * n22 * n34
  3883. - n14 * n21 * n32
  3884. + n12 * n21 * n34
  3885. + n14 * n22 * n31
  3886. - n12 * n24 * n31
  3887. ) +
  3888. n44 * (
  3889. - n13 * n22 * n31
  3890. - n11 * n23 * n32
  3891. + n11 * n22 * n33
  3892. + n13 * n21 * n32
  3893. - n12 * n21 * n33
  3894. + n12 * n23 * n31
  3895. )
  3896. );
  3897. }
  3898. transpose() {
  3899. const te = this.elements;
  3900. let tmp;
  3901. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3902. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3903. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3904. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3905. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3906. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3907. return this;
  3908. }
  3909. setPosition( x, y, z ) {
  3910. const te = this.elements;
  3911. if ( x.isVector3 ) {
  3912. te[ 12 ] = x.x;
  3913. te[ 13 ] = x.y;
  3914. te[ 14 ] = x.z;
  3915. } else {
  3916. te[ 12 ] = x;
  3917. te[ 13 ] = y;
  3918. te[ 14 ] = z;
  3919. }
  3920. return this;
  3921. }
  3922. invert() {
  3923. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3924. const te = this.elements,
  3925. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3926. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3927. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3928. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3929. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3930. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3931. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3932. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3933. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3934. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3935. const detInv = 1 / det;
  3936. te[ 0 ] = t11 * detInv;
  3937. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3938. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3939. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3940. te[ 4 ] = t12 * detInv;
  3941. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3942. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3943. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3944. te[ 8 ] = t13 * detInv;
  3945. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3946. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3947. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3948. te[ 12 ] = t14 * detInv;
  3949. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3950. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3951. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3952. return this;
  3953. }
  3954. scale( v ) {
  3955. const te = this.elements;
  3956. const x = v.x, y = v.y, z = v.z;
  3957. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3958. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3959. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3960. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3961. return this;
  3962. }
  3963. getMaxScaleOnAxis() {
  3964. const te = this.elements;
  3965. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3966. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3967. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3968. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3969. }
  3970. makeTranslation( x, y, z ) {
  3971. this.set(
  3972. 1, 0, 0, x,
  3973. 0, 1, 0, y,
  3974. 0, 0, 1, z,
  3975. 0, 0, 0, 1
  3976. );
  3977. return this;
  3978. }
  3979. makeRotationX( theta ) {
  3980. const c = Math.cos( theta ), s = Math.sin( theta );
  3981. this.set(
  3982. 1, 0, 0, 0,
  3983. 0, c, - s, 0,
  3984. 0, s, c, 0,
  3985. 0, 0, 0, 1
  3986. );
  3987. return this;
  3988. }
  3989. makeRotationY( theta ) {
  3990. const c = Math.cos( theta ), s = Math.sin( theta );
  3991. this.set(
  3992. c, 0, s, 0,
  3993. 0, 1, 0, 0,
  3994. - s, 0, c, 0,
  3995. 0, 0, 0, 1
  3996. );
  3997. return this;
  3998. }
  3999. makeRotationZ( theta ) {
  4000. const c = Math.cos( theta ), s = Math.sin( theta );
  4001. this.set(
  4002. c, - s, 0, 0,
  4003. s, c, 0, 0,
  4004. 0, 0, 1, 0,
  4005. 0, 0, 0, 1
  4006. );
  4007. return this;
  4008. }
  4009. makeRotationAxis( axis, angle ) {
  4010. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4011. const c = Math.cos( angle );
  4012. const s = Math.sin( angle );
  4013. const t = 1 - c;
  4014. const x = axis.x, y = axis.y, z = axis.z;
  4015. const tx = t * x, ty = t * y;
  4016. this.set(
  4017. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4018. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4019. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4020. 0, 0, 0, 1
  4021. );
  4022. return this;
  4023. }
  4024. makeScale( x, y, z ) {
  4025. this.set(
  4026. x, 0, 0, 0,
  4027. 0, y, 0, 0,
  4028. 0, 0, z, 0,
  4029. 0, 0, 0, 1
  4030. );
  4031. return this;
  4032. }
  4033. makeShear( xy, xz, yx, yz, zx, zy ) {
  4034. this.set(
  4035. 1, yx, zx, 0,
  4036. xy, 1, zy, 0,
  4037. xz, yz, 1, 0,
  4038. 0, 0, 0, 1
  4039. );
  4040. return this;
  4041. }
  4042. compose( position, quaternion, scale ) {
  4043. const te = this.elements;
  4044. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4045. const x2 = x + x, y2 = y + y, z2 = z + z;
  4046. const xx = x * x2, xy = x * y2, xz = x * z2;
  4047. const yy = y * y2, yz = y * z2, zz = z * z2;
  4048. const wx = w * x2, wy = w * y2, wz = w * z2;
  4049. const sx = scale.x, sy = scale.y, sz = scale.z;
  4050. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4051. te[ 1 ] = ( xy + wz ) * sx;
  4052. te[ 2 ] = ( xz - wy ) * sx;
  4053. te[ 3 ] = 0;
  4054. te[ 4 ] = ( xy - wz ) * sy;
  4055. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4056. te[ 6 ] = ( yz + wx ) * sy;
  4057. te[ 7 ] = 0;
  4058. te[ 8 ] = ( xz + wy ) * sz;
  4059. te[ 9 ] = ( yz - wx ) * sz;
  4060. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4061. te[ 11 ] = 0;
  4062. te[ 12 ] = position.x;
  4063. te[ 13 ] = position.y;
  4064. te[ 14 ] = position.z;
  4065. te[ 15 ] = 1;
  4066. return this;
  4067. }
  4068. decompose( position, quaternion, scale ) {
  4069. const te = this.elements;
  4070. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4071. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4072. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4073. // if determine is negative, we need to invert one scale
  4074. const det = this.determinant();
  4075. if ( det < 0 ) sx = - sx;
  4076. position.x = te[ 12 ];
  4077. position.y = te[ 13 ];
  4078. position.z = te[ 14 ];
  4079. // scale the rotation part
  4080. _m1$2.copy( this );
  4081. const invSX = 1 / sx;
  4082. const invSY = 1 / sy;
  4083. const invSZ = 1 / sz;
  4084. _m1$2.elements[ 0 ] *= invSX;
  4085. _m1$2.elements[ 1 ] *= invSX;
  4086. _m1$2.elements[ 2 ] *= invSX;
  4087. _m1$2.elements[ 4 ] *= invSY;
  4088. _m1$2.elements[ 5 ] *= invSY;
  4089. _m1$2.elements[ 6 ] *= invSY;
  4090. _m1$2.elements[ 8 ] *= invSZ;
  4091. _m1$2.elements[ 9 ] *= invSZ;
  4092. _m1$2.elements[ 10 ] *= invSZ;
  4093. quaternion.setFromRotationMatrix( _m1$2 );
  4094. scale.x = sx;
  4095. scale.y = sy;
  4096. scale.z = sz;
  4097. return this;
  4098. }
  4099. makePerspective( left, right, top, bottom, near, far ) {
  4100. if ( far === undefined ) {
  4101. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4102. }
  4103. const te = this.elements;
  4104. const x = 2 * near / ( right - left );
  4105. const y = 2 * near / ( top - bottom );
  4106. const a = ( right + left ) / ( right - left );
  4107. const b = ( top + bottom ) / ( top - bottom );
  4108. const c = - ( far + near ) / ( far - near );
  4109. const d = - 2 * far * near / ( far - near );
  4110. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4111. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4112. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4113. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4114. return this;
  4115. }
  4116. makeOrthographic( left, right, top, bottom, near, far ) {
  4117. const te = this.elements;
  4118. const w = 1.0 / ( right - left );
  4119. const h = 1.0 / ( top - bottom );
  4120. const p = 1.0 / ( far - near );
  4121. const x = ( right + left ) * w;
  4122. const y = ( top + bottom ) * h;
  4123. const z = ( far + near ) * p;
  4124. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4125. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4126. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4127. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4128. return this;
  4129. }
  4130. equals( matrix ) {
  4131. const te = this.elements;
  4132. const me = matrix.elements;
  4133. for ( let i = 0; i < 16; i ++ ) {
  4134. if ( te[ i ] !== me[ i ] ) return false;
  4135. }
  4136. return true;
  4137. }
  4138. fromArray( array, offset = 0 ) {
  4139. for ( let i = 0; i < 16; i ++ ) {
  4140. this.elements[ i ] = array[ i + offset ];
  4141. }
  4142. return this;
  4143. }
  4144. toArray( array = [], offset = 0 ) {
  4145. const te = this.elements;
  4146. array[ offset ] = te[ 0 ];
  4147. array[ offset + 1 ] = te[ 1 ];
  4148. array[ offset + 2 ] = te[ 2 ];
  4149. array[ offset + 3 ] = te[ 3 ];
  4150. array[ offset + 4 ] = te[ 4 ];
  4151. array[ offset + 5 ] = te[ 5 ];
  4152. array[ offset + 6 ] = te[ 6 ];
  4153. array[ offset + 7 ] = te[ 7 ];
  4154. array[ offset + 8 ] = te[ 8 ];
  4155. array[ offset + 9 ] = te[ 9 ];
  4156. array[ offset + 10 ] = te[ 10 ];
  4157. array[ offset + 11 ] = te[ 11 ];
  4158. array[ offset + 12 ] = te[ 12 ];
  4159. array[ offset + 13 ] = te[ 13 ];
  4160. array[ offset + 14 ] = te[ 14 ];
  4161. array[ offset + 15 ] = te[ 15 ];
  4162. return array;
  4163. }
  4164. }
  4165. Matrix4.prototype.isMatrix4 = true;
  4166. const _v1$5 = /*@__PURE__*/ new Vector3();
  4167. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4168. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4169. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4170. const _x = /*@__PURE__*/ new Vector3();
  4171. const _y = /*@__PURE__*/ new Vector3();
  4172. const _z = /*@__PURE__*/ new Vector3();
  4173. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4174. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4175. class Euler {
  4176. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4177. this._x = x;
  4178. this._y = y;
  4179. this._z = z;
  4180. this._order = order;
  4181. }
  4182. get x() {
  4183. return this._x;
  4184. }
  4185. set x( value ) {
  4186. this._x = value;
  4187. this._onChangeCallback();
  4188. }
  4189. get y() {
  4190. return this._y;
  4191. }
  4192. set y( value ) {
  4193. this._y = value;
  4194. this._onChangeCallback();
  4195. }
  4196. get z() {
  4197. return this._z;
  4198. }
  4199. set z( value ) {
  4200. this._z = value;
  4201. this._onChangeCallback();
  4202. }
  4203. get order() {
  4204. return this._order;
  4205. }
  4206. set order( value ) {
  4207. this._order = value;
  4208. this._onChangeCallback();
  4209. }
  4210. set( x, y, z, order = this._order ) {
  4211. this._x = x;
  4212. this._y = y;
  4213. this._z = z;
  4214. this._order = order;
  4215. this._onChangeCallback();
  4216. return this;
  4217. }
  4218. clone() {
  4219. return new this.constructor( this._x, this._y, this._z, this._order );
  4220. }
  4221. copy( euler ) {
  4222. this._x = euler._x;
  4223. this._y = euler._y;
  4224. this._z = euler._z;
  4225. this._order = euler._order;
  4226. this._onChangeCallback();
  4227. return this;
  4228. }
  4229. setFromRotationMatrix( m, order = this._order, update = true ) {
  4230. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4231. const te = m.elements;
  4232. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4233. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4234. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4235. switch ( order ) {
  4236. case 'XYZ':
  4237. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4238. if ( Math.abs( m13 ) < 0.9999999 ) {
  4239. this._x = Math.atan2( - m23, m33 );
  4240. this._z = Math.atan2( - m12, m11 );
  4241. } else {
  4242. this._x = Math.atan2( m32, m22 );
  4243. this._z = 0;
  4244. }
  4245. break;
  4246. case 'YXZ':
  4247. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4248. if ( Math.abs( m23 ) < 0.9999999 ) {
  4249. this._y = Math.atan2( m13, m33 );
  4250. this._z = Math.atan2( m21, m22 );
  4251. } else {
  4252. this._y = Math.atan2( - m31, m11 );
  4253. this._z = 0;
  4254. }
  4255. break;
  4256. case 'ZXY':
  4257. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4258. if ( Math.abs( m32 ) < 0.9999999 ) {
  4259. this._y = Math.atan2( - m31, m33 );
  4260. this._z = Math.atan2( - m12, m22 );
  4261. } else {
  4262. this._y = 0;
  4263. this._z = Math.atan2( m21, m11 );
  4264. }
  4265. break;
  4266. case 'ZYX':
  4267. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4268. if ( Math.abs( m31 ) < 0.9999999 ) {
  4269. this._x = Math.atan2( m32, m33 );
  4270. this._z = Math.atan2( m21, m11 );
  4271. } else {
  4272. this._x = 0;
  4273. this._z = Math.atan2( - m12, m22 );
  4274. }
  4275. break;
  4276. case 'YZX':
  4277. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4278. if ( Math.abs( m21 ) < 0.9999999 ) {
  4279. this._x = Math.atan2( - m23, m22 );
  4280. this._y = Math.atan2( - m31, m11 );
  4281. } else {
  4282. this._x = 0;
  4283. this._y = Math.atan2( m13, m33 );
  4284. }
  4285. break;
  4286. case 'XZY':
  4287. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4288. if ( Math.abs( m12 ) < 0.9999999 ) {
  4289. this._x = Math.atan2( m32, m22 );
  4290. this._y = Math.atan2( m13, m11 );
  4291. } else {
  4292. this._x = Math.atan2( - m23, m33 );
  4293. this._y = 0;
  4294. }
  4295. break;
  4296. default:
  4297. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4298. }
  4299. this._order = order;
  4300. if ( update === true ) this._onChangeCallback();
  4301. return this;
  4302. }
  4303. setFromQuaternion( q, order, update ) {
  4304. _matrix$1.makeRotationFromQuaternion( q );
  4305. return this.setFromRotationMatrix( _matrix$1, order, update );
  4306. }
  4307. setFromVector3( v, order = this._order ) {
  4308. return this.set( v.x, v.y, v.z, order );
  4309. }
  4310. reorder( newOrder ) {
  4311. // WARNING: this discards revolution information -bhouston
  4312. _quaternion$3.setFromEuler( this );
  4313. return this.setFromQuaternion( _quaternion$3, newOrder );
  4314. }
  4315. equals( euler ) {
  4316. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4317. }
  4318. fromArray( array ) {
  4319. this._x = array[ 0 ];
  4320. this._y = array[ 1 ];
  4321. this._z = array[ 2 ];
  4322. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4323. this._onChangeCallback();
  4324. return this;
  4325. }
  4326. toArray( array = [], offset = 0 ) {
  4327. array[ offset ] = this._x;
  4328. array[ offset + 1 ] = this._y;
  4329. array[ offset + 2 ] = this._z;
  4330. array[ offset + 3 ] = this._order;
  4331. return array;
  4332. }
  4333. toVector3( optionalResult ) {
  4334. if ( optionalResult ) {
  4335. return optionalResult.set( this._x, this._y, this._z );
  4336. } else {
  4337. return new Vector3( this._x, this._y, this._z );
  4338. }
  4339. }
  4340. _onChange( callback ) {
  4341. this._onChangeCallback = callback;
  4342. return this;
  4343. }
  4344. _onChangeCallback() {}
  4345. }
  4346. Euler.prototype.isEuler = true;
  4347. Euler.DefaultOrder = 'XYZ';
  4348. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4349. class Layers {
  4350. constructor() {
  4351. this.mask = 1 | 0;
  4352. }
  4353. set( channel ) {
  4354. this.mask = ( 1 << channel | 0 ) >>> 0;
  4355. }
  4356. enable( channel ) {
  4357. this.mask |= 1 << channel | 0;
  4358. }
  4359. enableAll() {
  4360. this.mask = 0xffffffff | 0;
  4361. }
  4362. toggle( channel ) {
  4363. this.mask ^= 1 << channel | 0;
  4364. }
  4365. disable( channel ) {
  4366. this.mask &= ~ ( 1 << channel | 0 );
  4367. }
  4368. disableAll() {
  4369. this.mask = 0;
  4370. }
  4371. test( layers ) {
  4372. return ( this.mask & layers.mask ) !== 0;
  4373. }
  4374. isEnabled( channel ) {
  4375. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4376. }
  4377. }
  4378. let _object3DId = 0;
  4379. const _v1$4 = /*@__PURE__*/ new Vector3();
  4380. const _q1 = /*@__PURE__*/ new Quaternion();
  4381. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4382. const _target = /*@__PURE__*/ new Vector3();
  4383. const _position$3 = /*@__PURE__*/ new Vector3();
  4384. const _scale$2 = /*@__PURE__*/ new Vector3();
  4385. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4386. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4387. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4388. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4389. const _addedEvent = { type: 'added' };
  4390. const _removedEvent = { type: 'removed' };
  4391. class Object3D extends EventDispatcher {
  4392. constructor() {
  4393. super();
  4394. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4395. this.uuid = generateUUID();
  4396. this.name = '';
  4397. this.type = 'Object3D';
  4398. this.parent = null;
  4399. this.children = [];
  4400. this.up = Object3D.DefaultUp.clone();
  4401. const position = new Vector3();
  4402. const rotation = new Euler();
  4403. const quaternion = new Quaternion();
  4404. const scale = new Vector3( 1, 1, 1 );
  4405. function onRotationChange() {
  4406. quaternion.setFromEuler( rotation, false );
  4407. }
  4408. function onQuaternionChange() {
  4409. rotation.setFromQuaternion( quaternion, undefined, false );
  4410. }
  4411. rotation._onChange( onRotationChange );
  4412. quaternion._onChange( onQuaternionChange );
  4413. Object.defineProperties( this, {
  4414. position: {
  4415. configurable: true,
  4416. enumerable: true,
  4417. value: position
  4418. },
  4419. rotation: {
  4420. configurable: true,
  4421. enumerable: true,
  4422. value: rotation
  4423. },
  4424. quaternion: {
  4425. configurable: true,
  4426. enumerable: true,
  4427. value: quaternion
  4428. },
  4429. scale: {
  4430. configurable: true,
  4431. enumerable: true,
  4432. value: scale
  4433. },
  4434. modelViewMatrix: {
  4435. value: new Matrix4()
  4436. },
  4437. normalMatrix: {
  4438. value: new Matrix3()
  4439. }
  4440. } );
  4441. this.matrix = new Matrix4();
  4442. this.matrixWorld = new Matrix4();
  4443. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4444. this.matrixWorldNeedsUpdate = false;
  4445. this.layers = new Layers();
  4446. this.visible = true;
  4447. this.castShadow = false;
  4448. this.receiveShadow = false;
  4449. this.frustumCulled = true;
  4450. this.renderOrder = 0;
  4451. this.animations = [];
  4452. this.userData = {};
  4453. }
  4454. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4455. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4456. applyMatrix4( matrix ) {
  4457. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4458. this.matrix.premultiply( matrix );
  4459. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4460. }
  4461. applyQuaternion( q ) {
  4462. this.quaternion.premultiply( q );
  4463. return this;
  4464. }
  4465. setRotationFromAxisAngle( axis, angle ) {
  4466. // assumes axis is normalized
  4467. this.quaternion.setFromAxisAngle( axis, angle );
  4468. }
  4469. setRotationFromEuler( euler ) {
  4470. this.quaternion.setFromEuler( euler, true );
  4471. }
  4472. setRotationFromMatrix( m ) {
  4473. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4474. this.quaternion.setFromRotationMatrix( m );
  4475. }
  4476. setRotationFromQuaternion( q ) {
  4477. // assumes q is normalized
  4478. this.quaternion.copy( q );
  4479. }
  4480. rotateOnAxis( axis, angle ) {
  4481. // rotate object on axis in object space
  4482. // axis is assumed to be normalized
  4483. _q1.setFromAxisAngle( axis, angle );
  4484. this.quaternion.multiply( _q1 );
  4485. return this;
  4486. }
  4487. rotateOnWorldAxis( axis, angle ) {
  4488. // rotate object on axis in world space
  4489. // axis is assumed to be normalized
  4490. // method assumes no rotated parent
  4491. _q1.setFromAxisAngle( axis, angle );
  4492. this.quaternion.premultiply( _q1 );
  4493. return this;
  4494. }
  4495. rotateX( angle ) {
  4496. return this.rotateOnAxis( _xAxis, angle );
  4497. }
  4498. rotateY( angle ) {
  4499. return this.rotateOnAxis( _yAxis, angle );
  4500. }
  4501. rotateZ( angle ) {
  4502. return this.rotateOnAxis( _zAxis, angle );
  4503. }
  4504. translateOnAxis( axis, distance ) {
  4505. // translate object by distance along axis in object space
  4506. // axis is assumed to be normalized
  4507. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4508. this.position.add( _v1$4.multiplyScalar( distance ) );
  4509. return this;
  4510. }
  4511. translateX( distance ) {
  4512. return this.translateOnAxis( _xAxis, distance );
  4513. }
  4514. translateY( distance ) {
  4515. return this.translateOnAxis( _yAxis, distance );
  4516. }
  4517. translateZ( distance ) {
  4518. return this.translateOnAxis( _zAxis, distance );
  4519. }
  4520. localToWorld( vector ) {
  4521. return vector.applyMatrix4( this.matrixWorld );
  4522. }
  4523. worldToLocal( vector ) {
  4524. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4525. }
  4526. lookAt( x, y, z ) {
  4527. // This method does not support objects having non-uniformly-scaled parent(s)
  4528. if ( x.isVector3 ) {
  4529. _target.copy( x );
  4530. } else {
  4531. _target.set( x, y, z );
  4532. }
  4533. const parent = this.parent;
  4534. this.updateWorldMatrix( true, false );
  4535. _position$3.setFromMatrixPosition( this.matrixWorld );
  4536. if ( this.isCamera || this.isLight ) {
  4537. _m1$1.lookAt( _position$3, _target, this.up );
  4538. } else {
  4539. _m1$1.lookAt( _target, _position$3, this.up );
  4540. }
  4541. this.quaternion.setFromRotationMatrix( _m1$1 );
  4542. if ( parent ) {
  4543. _m1$1.extractRotation( parent.matrixWorld );
  4544. _q1.setFromRotationMatrix( _m1$1 );
  4545. this.quaternion.premultiply( _q1.invert() );
  4546. }
  4547. }
  4548. add( object ) {
  4549. if ( arguments.length > 1 ) {
  4550. for ( let i = 0; i < arguments.length; i ++ ) {
  4551. this.add( arguments[ i ] );
  4552. }
  4553. return this;
  4554. }
  4555. if ( object === this ) {
  4556. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4557. return this;
  4558. }
  4559. if ( object && object.isObject3D ) {
  4560. if ( object.parent !== null ) {
  4561. object.parent.remove( object );
  4562. }
  4563. object.parent = this;
  4564. this.children.push( object );
  4565. object.dispatchEvent( _addedEvent );
  4566. } else {
  4567. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4568. }
  4569. return this;
  4570. }
  4571. remove( object ) {
  4572. if ( arguments.length > 1 ) {
  4573. for ( let i = 0; i < arguments.length; i ++ ) {
  4574. this.remove( arguments[ i ] );
  4575. }
  4576. return this;
  4577. }
  4578. const index = this.children.indexOf( object );
  4579. if ( index !== - 1 ) {
  4580. object.parent = null;
  4581. this.children.splice( index, 1 );
  4582. object.dispatchEvent( _removedEvent );
  4583. }
  4584. return this;
  4585. }
  4586. removeFromParent() {
  4587. const parent = this.parent;
  4588. if ( parent !== null ) {
  4589. parent.remove( this );
  4590. }
  4591. return this;
  4592. }
  4593. clear() {
  4594. for ( let i = 0; i < this.children.length; i ++ ) {
  4595. const object = this.children[ i ];
  4596. object.parent = null;
  4597. object.dispatchEvent( _removedEvent );
  4598. }
  4599. this.children.length = 0;
  4600. return this;
  4601. }
  4602. attach( object ) {
  4603. // adds object as a child of this, while maintaining the object's world transform
  4604. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4605. this.updateWorldMatrix( true, false );
  4606. _m1$1.copy( this.matrixWorld ).invert();
  4607. if ( object.parent !== null ) {
  4608. object.parent.updateWorldMatrix( true, false );
  4609. _m1$1.multiply( object.parent.matrixWorld );
  4610. }
  4611. object.applyMatrix4( _m1$1 );
  4612. this.add( object );
  4613. object.updateWorldMatrix( false, true );
  4614. return this;
  4615. }
  4616. getObjectById( id ) {
  4617. return this.getObjectByProperty( 'id', id );
  4618. }
  4619. getObjectByName( name ) {
  4620. return this.getObjectByProperty( 'name', name );
  4621. }
  4622. getObjectByProperty( name, value ) {
  4623. if ( this[ name ] === value ) return this;
  4624. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4625. const child = this.children[ i ];
  4626. const object = child.getObjectByProperty( name, value );
  4627. if ( object !== undefined ) {
  4628. return object;
  4629. }
  4630. }
  4631. return undefined;
  4632. }
  4633. getWorldPosition( target ) {
  4634. this.updateWorldMatrix( true, false );
  4635. return target.setFromMatrixPosition( this.matrixWorld );
  4636. }
  4637. getWorldQuaternion( target ) {
  4638. this.updateWorldMatrix( true, false );
  4639. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4640. return target;
  4641. }
  4642. getWorldScale( target ) {
  4643. this.updateWorldMatrix( true, false );
  4644. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4645. return target;
  4646. }
  4647. getWorldDirection( target ) {
  4648. this.updateWorldMatrix( true, false );
  4649. const e = this.matrixWorld.elements;
  4650. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4651. }
  4652. raycast( /* raycaster, intersects */ ) {}
  4653. traverse( callback ) {
  4654. callback( this );
  4655. const children = this.children;
  4656. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4657. children[ i ].traverse( callback );
  4658. }
  4659. }
  4660. traverseVisible( callback ) {
  4661. if ( this.visible === false ) return;
  4662. callback( this );
  4663. const children = this.children;
  4664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4665. children[ i ].traverseVisible( callback );
  4666. }
  4667. }
  4668. traverseAncestors( callback ) {
  4669. const parent = this.parent;
  4670. if ( parent !== null ) {
  4671. callback( parent );
  4672. parent.traverseAncestors( callback );
  4673. }
  4674. }
  4675. updateMatrix() {
  4676. this.matrix.compose( this.position, this.quaternion, this.scale );
  4677. this.matrixWorldNeedsUpdate = true;
  4678. }
  4679. updateMatrixWorld( force ) {
  4680. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4681. if ( this.matrixWorldNeedsUpdate || force ) {
  4682. if ( this.parent === null ) {
  4683. this.matrixWorld.copy( this.matrix );
  4684. } else {
  4685. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4686. }
  4687. this.matrixWorldNeedsUpdate = false;
  4688. force = true;
  4689. }
  4690. // update children
  4691. const children = this.children;
  4692. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4693. children[ i ].updateMatrixWorld( force );
  4694. }
  4695. }
  4696. updateWorldMatrix( updateParents, updateChildren ) {
  4697. const parent = this.parent;
  4698. if ( updateParents === true && parent !== null ) {
  4699. parent.updateWorldMatrix( true, false );
  4700. }
  4701. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4702. if ( this.parent === null ) {
  4703. this.matrixWorld.copy( this.matrix );
  4704. } else {
  4705. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4706. }
  4707. // update children
  4708. if ( updateChildren === true ) {
  4709. const children = this.children;
  4710. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4711. children[ i ].updateWorldMatrix( false, true );
  4712. }
  4713. }
  4714. }
  4715. toJSON( meta ) {
  4716. // meta is a string when called from JSON.stringify
  4717. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4718. const output = {};
  4719. // meta is a hash used to collect geometries, materials.
  4720. // not providing it implies that this is the root object
  4721. // being serialized.
  4722. if ( isRootObject ) {
  4723. // initialize meta obj
  4724. meta = {
  4725. geometries: {},
  4726. materials: {},
  4727. textures: {},
  4728. images: {},
  4729. shapes: {},
  4730. skeletons: {},
  4731. animations: {}
  4732. };
  4733. output.metadata = {
  4734. version: 4.5,
  4735. type: 'Object',
  4736. generator: 'Object3D.toJSON'
  4737. };
  4738. }
  4739. // standard Object3D serialization
  4740. const object = {};
  4741. object.uuid = this.uuid;
  4742. object.type = this.type;
  4743. if ( this.name !== '' ) object.name = this.name;
  4744. if ( this.castShadow === true ) object.castShadow = true;
  4745. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4746. if ( this.visible === false ) object.visible = false;
  4747. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4748. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4749. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4750. object.layers = this.layers.mask;
  4751. object.matrix = this.matrix.toArray();
  4752. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4753. // object specific properties
  4754. if ( this.isInstancedMesh ) {
  4755. object.type = 'InstancedMesh';
  4756. object.count = this.count;
  4757. object.instanceMatrix = this.instanceMatrix.toJSON();
  4758. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4759. }
  4760. //
  4761. function serialize( library, element ) {
  4762. if ( library[ element.uuid ] === undefined ) {
  4763. library[ element.uuid ] = element.toJSON( meta );
  4764. }
  4765. return element.uuid;
  4766. }
  4767. if ( this.isScene ) {
  4768. if ( this.background ) {
  4769. if ( this.background.isColor ) {
  4770. object.background = this.background.toJSON();
  4771. } else if ( this.background.isTexture ) {
  4772. object.background = this.background.toJSON( meta ).uuid;
  4773. }
  4774. }
  4775. if ( this.environment && this.environment.isTexture ) {
  4776. object.environment = this.environment.toJSON( meta ).uuid;
  4777. }
  4778. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4779. object.geometry = serialize( meta.geometries, this.geometry );
  4780. const parameters = this.geometry.parameters;
  4781. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4782. const shapes = parameters.shapes;
  4783. if ( Array.isArray( shapes ) ) {
  4784. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4785. const shape = shapes[ i ];
  4786. serialize( meta.shapes, shape );
  4787. }
  4788. } else {
  4789. serialize( meta.shapes, shapes );
  4790. }
  4791. }
  4792. }
  4793. if ( this.isSkinnedMesh ) {
  4794. object.bindMode = this.bindMode;
  4795. object.bindMatrix = this.bindMatrix.toArray();
  4796. if ( this.skeleton !== undefined ) {
  4797. serialize( meta.skeletons, this.skeleton );
  4798. object.skeleton = this.skeleton.uuid;
  4799. }
  4800. }
  4801. if ( this.material !== undefined ) {
  4802. if ( Array.isArray( this.material ) ) {
  4803. const uuids = [];
  4804. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4805. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4806. }
  4807. object.material = uuids;
  4808. } else {
  4809. object.material = serialize( meta.materials, this.material );
  4810. }
  4811. }
  4812. //
  4813. if ( this.children.length > 0 ) {
  4814. object.children = [];
  4815. for ( let i = 0; i < this.children.length; i ++ ) {
  4816. object.children.push( this.children[ i ].toJSON( meta ).object );
  4817. }
  4818. }
  4819. //
  4820. if ( this.animations.length > 0 ) {
  4821. object.animations = [];
  4822. for ( let i = 0; i < this.animations.length; i ++ ) {
  4823. const animation = this.animations[ i ];
  4824. object.animations.push( serialize( meta.animations, animation ) );
  4825. }
  4826. }
  4827. if ( isRootObject ) {
  4828. const geometries = extractFromCache( meta.geometries );
  4829. const materials = extractFromCache( meta.materials );
  4830. const textures = extractFromCache( meta.textures );
  4831. const images = extractFromCache( meta.images );
  4832. const shapes = extractFromCache( meta.shapes );
  4833. const skeletons = extractFromCache( meta.skeletons );
  4834. const animations = extractFromCache( meta.animations );
  4835. if ( geometries.length > 0 ) output.geometries = geometries;
  4836. if ( materials.length > 0 ) output.materials = materials;
  4837. if ( textures.length > 0 ) output.textures = textures;
  4838. if ( images.length > 0 ) output.images = images;
  4839. if ( shapes.length > 0 ) output.shapes = shapes;
  4840. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4841. if ( animations.length > 0 ) output.animations = animations;
  4842. }
  4843. output.object = object;
  4844. return output;
  4845. // extract data from the cache hash
  4846. // remove metadata on each item
  4847. // and return as array
  4848. function extractFromCache( cache ) {
  4849. const values = [];
  4850. for ( const key in cache ) {
  4851. const data = cache[ key ];
  4852. delete data.metadata;
  4853. values.push( data );
  4854. }
  4855. return values;
  4856. }
  4857. }
  4858. clone( recursive ) {
  4859. return new this.constructor().copy( this, recursive );
  4860. }
  4861. copy( source, recursive = true ) {
  4862. this.name = source.name;
  4863. this.up.copy( source.up );
  4864. this.position.copy( source.position );
  4865. this.rotation.order = source.rotation.order;
  4866. this.quaternion.copy( source.quaternion );
  4867. this.scale.copy( source.scale );
  4868. this.matrix.copy( source.matrix );
  4869. this.matrixWorld.copy( source.matrixWorld );
  4870. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4871. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4872. this.layers.mask = source.layers.mask;
  4873. this.visible = source.visible;
  4874. this.castShadow = source.castShadow;
  4875. this.receiveShadow = source.receiveShadow;
  4876. this.frustumCulled = source.frustumCulled;
  4877. this.renderOrder = source.renderOrder;
  4878. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4879. if ( recursive === true ) {
  4880. for ( let i = 0; i < source.children.length; i ++ ) {
  4881. const child = source.children[ i ];
  4882. this.add( child.clone() );
  4883. }
  4884. }
  4885. return this;
  4886. }
  4887. }
  4888. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4889. Object3D.DefaultMatrixAutoUpdate = true;
  4890. Object3D.prototype.isObject3D = true;
  4891. const _v0$1 = /*@__PURE__*/ new Vector3();
  4892. const _v1$3 = /*@__PURE__*/ new Vector3();
  4893. const _v2$2 = /*@__PURE__*/ new Vector3();
  4894. const _v3$1 = /*@__PURE__*/ new Vector3();
  4895. const _vab = /*@__PURE__*/ new Vector3();
  4896. const _vac = /*@__PURE__*/ new Vector3();
  4897. const _vbc = /*@__PURE__*/ new Vector3();
  4898. const _vap = /*@__PURE__*/ new Vector3();
  4899. const _vbp = /*@__PURE__*/ new Vector3();
  4900. const _vcp = /*@__PURE__*/ new Vector3();
  4901. class Triangle {
  4902. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4903. this.a = a;
  4904. this.b = b;
  4905. this.c = c;
  4906. }
  4907. static getNormal( a, b, c, target ) {
  4908. target.subVectors( c, b );
  4909. _v0$1.subVectors( a, b );
  4910. target.cross( _v0$1 );
  4911. const targetLengthSq = target.lengthSq();
  4912. if ( targetLengthSq > 0 ) {
  4913. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4914. }
  4915. return target.set( 0, 0, 0 );
  4916. }
  4917. // static/instance method to calculate barycentric coordinates
  4918. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4919. static getBarycoord( point, a, b, c, target ) {
  4920. _v0$1.subVectors( c, a );
  4921. _v1$3.subVectors( b, a );
  4922. _v2$2.subVectors( point, a );
  4923. const dot00 = _v0$1.dot( _v0$1 );
  4924. const dot01 = _v0$1.dot( _v1$3 );
  4925. const dot02 = _v0$1.dot( _v2$2 );
  4926. const dot11 = _v1$3.dot( _v1$3 );
  4927. const dot12 = _v1$3.dot( _v2$2 );
  4928. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4929. // collinear or singular triangle
  4930. if ( denom === 0 ) {
  4931. // arbitrary location outside of triangle?
  4932. // not sure if this is the best idea, maybe should be returning undefined
  4933. return target.set( - 2, - 1, - 1 );
  4934. }
  4935. const invDenom = 1 / denom;
  4936. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4937. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4938. // barycentric coordinates must always sum to 1
  4939. return target.set( 1 - u - v, v, u );
  4940. }
  4941. static containsPoint( point, a, b, c ) {
  4942. this.getBarycoord( point, a, b, c, _v3$1 );
  4943. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4944. }
  4945. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4946. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4947. target.set( 0, 0 );
  4948. target.addScaledVector( uv1, _v3$1.x );
  4949. target.addScaledVector( uv2, _v3$1.y );
  4950. target.addScaledVector( uv3, _v3$1.z );
  4951. return target;
  4952. }
  4953. static isFrontFacing( a, b, c, direction ) {
  4954. _v0$1.subVectors( c, b );
  4955. _v1$3.subVectors( a, b );
  4956. // strictly front facing
  4957. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4958. }
  4959. set( a, b, c ) {
  4960. this.a.copy( a );
  4961. this.b.copy( b );
  4962. this.c.copy( c );
  4963. return this;
  4964. }
  4965. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4966. this.a.copy( points[ i0 ] );
  4967. this.b.copy( points[ i1 ] );
  4968. this.c.copy( points[ i2 ] );
  4969. return this;
  4970. }
  4971. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4972. this.a.fromBufferAttribute( attribute, i0 );
  4973. this.b.fromBufferAttribute( attribute, i1 );
  4974. this.c.fromBufferAttribute( attribute, i2 );
  4975. return this;
  4976. }
  4977. clone() {
  4978. return new this.constructor().copy( this );
  4979. }
  4980. copy( triangle ) {
  4981. this.a.copy( triangle.a );
  4982. this.b.copy( triangle.b );
  4983. this.c.copy( triangle.c );
  4984. return this;
  4985. }
  4986. getArea() {
  4987. _v0$1.subVectors( this.c, this.b );
  4988. _v1$3.subVectors( this.a, this.b );
  4989. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4990. }
  4991. getMidpoint( target ) {
  4992. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4993. }
  4994. getNormal( target ) {
  4995. return Triangle.getNormal( this.a, this.b, this.c, target );
  4996. }
  4997. getPlane( target ) {
  4998. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4999. }
  5000. getBarycoord( point, target ) {
  5001. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5002. }
  5003. getUV( point, uv1, uv2, uv3, target ) {
  5004. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5005. }
  5006. containsPoint( point ) {
  5007. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5008. }
  5009. isFrontFacing( direction ) {
  5010. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5011. }
  5012. intersectsBox( box ) {
  5013. return box.intersectsTriangle( this );
  5014. }
  5015. closestPointToPoint( p, target ) {
  5016. const a = this.a, b = this.b, c = this.c;
  5017. let v, w;
  5018. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5019. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5020. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5021. // basically, we're distinguishing which of the voronoi regions of the triangle
  5022. // the point lies in with the minimum amount of redundant computation.
  5023. _vab.subVectors( b, a );
  5024. _vac.subVectors( c, a );
  5025. _vap.subVectors( p, a );
  5026. const d1 = _vab.dot( _vap );
  5027. const d2 = _vac.dot( _vap );
  5028. if ( d1 <= 0 && d2 <= 0 ) {
  5029. // vertex region of A; barycentric coords (1, 0, 0)
  5030. return target.copy( a );
  5031. }
  5032. _vbp.subVectors( p, b );
  5033. const d3 = _vab.dot( _vbp );
  5034. const d4 = _vac.dot( _vbp );
  5035. if ( d3 >= 0 && d4 <= d3 ) {
  5036. // vertex region of B; barycentric coords (0, 1, 0)
  5037. return target.copy( b );
  5038. }
  5039. const vc = d1 * d4 - d3 * d2;
  5040. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5041. v = d1 / ( d1 - d3 );
  5042. // edge region of AB; barycentric coords (1-v, v, 0)
  5043. return target.copy( a ).addScaledVector( _vab, v );
  5044. }
  5045. _vcp.subVectors( p, c );
  5046. const d5 = _vab.dot( _vcp );
  5047. const d6 = _vac.dot( _vcp );
  5048. if ( d6 >= 0 && d5 <= d6 ) {
  5049. // vertex region of C; barycentric coords (0, 0, 1)
  5050. return target.copy( c );
  5051. }
  5052. const vb = d5 * d2 - d1 * d6;
  5053. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5054. w = d2 / ( d2 - d6 );
  5055. // edge region of AC; barycentric coords (1-w, 0, w)
  5056. return target.copy( a ).addScaledVector( _vac, w );
  5057. }
  5058. const va = d3 * d6 - d5 * d4;
  5059. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5060. _vbc.subVectors( c, b );
  5061. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5062. // edge region of BC; barycentric coords (0, 1-w, w)
  5063. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5064. }
  5065. // face region
  5066. const denom = 1 / ( va + vb + vc );
  5067. // u = va * denom
  5068. v = vb * denom;
  5069. w = vc * denom;
  5070. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5071. }
  5072. equals( triangle ) {
  5073. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5074. }
  5075. }
  5076. let materialId = 0;
  5077. class Material extends EventDispatcher {
  5078. constructor() {
  5079. super();
  5080. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5081. this.uuid = generateUUID();
  5082. this.name = '';
  5083. this.type = 'Material';
  5084. this.fog = true;
  5085. this.blending = NormalBlending;
  5086. this.side = FrontSide;
  5087. this.vertexColors = false;
  5088. this.opacity = 1;
  5089. this.transparent = false;
  5090. this.blendSrc = SrcAlphaFactor;
  5091. this.blendDst = OneMinusSrcAlphaFactor;
  5092. this.blendEquation = AddEquation;
  5093. this.blendSrcAlpha = null;
  5094. this.blendDstAlpha = null;
  5095. this.blendEquationAlpha = null;
  5096. this.depthFunc = LessEqualDepth;
  5097. this.depthTest = true;
  5098. this.depthWrite = true;
  5099. this.stencilWriteMask = 0xff;
  5100. this.stencilFunc = AlwaysStencilFunc;
  5101. this.stencilRef = 0;
  5102. this.stencilFuncMask = 0xff;
  5103. this.stencilFail = KeepStencilOp;
  5104. this.stencilZFail = KeepStencilOp;
  5105. this.stencilZPass = KeepStencilOp;
  5106. this.stencilWrite = false;
  5107. this.clippingPlanes = null;
  5108. this.clipIntersection = false;
  5109. this.clipShadows = false;
  5110. this.shadowSide = null;
  5111. this.colorWrite = true;
  5112. this.precision = null; // override the renderer's default precision for this material
  5113. this.polygonOffset = false;
  5114. this.polygonOffsetFactor = 0;
  5115. this.polygonOffsetUnits = 0;
  5116. this.dithering = false;
  5117. this.alphaToCoverage = false;
  5118. this.premultipliedAlpha = false;
  5119. this.visible = true;
  5120. this.toneMapped = true;
  5121. this.userData = {};
  5122. this.version = 0;
  5123. this._alphaTest = 0;
  5124. }
  5125. get alphaTest() {
  5126. return this._alphaTest;
  5127. }
  5128. set alphaTest( value ) {
  5129. if ( this._alphaTest > 0 !== value > 0 ) {
  5130. this.version ++;
  5131. }
  5132. this._alphaTest = value;
  5133. }
  5134. onBuild( /* shaderobject, renderer */ ) {}
  5135. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5136. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5137. customProgramCacheKey() {
  5138. return this.onBeforeCompile.toString();
  5139. }
  5140. setValues( values ) {
  5141. if ( values === undefined ) return;
  5142. for ( const key in values ) {
  5143. const newValue = values[ key ];
  5144. if ( newValue === undefined ) {
  5145. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5146. continue;
  5147. }
  5148. // for backward compatability if shading is set in the constructor
  5149. if ( key === 'shading' ) {
  5150. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5151. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5152. continue;
  5153. }
  5154. const currentValue = this[ key ];
  5155. if ( currentValue === undefined ) {
  5156. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5157. continue;
  5158. }
  5159. if ( currentValue && currentValue.isColor ) {
  5160. currentValue.set( newValue );
  5161. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5162. currentValue.copy( newValue );
  5163. } else {
  5164. this[ key ] = newValue;
  5165. }
  5166. }
  5167. }
  5168. toJSON( meta ) {
  5169. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5170. if ( isRoot ) {
  5171. meta = {
  5172. textures: {},
  5173. images: {}
  5174. };
  5175. }
  5176. const data = {
  5177. metadata: {
  5178. version: 4.5,
  5179. type: 'Material',
  5180. generator: 'Material.toJSON'
  5181. }
  5182. };
  5183. // standard Material serialization
  5184. data.uuid = this.uuid;
  5185. data.type = this.type;
  5186. if ( this.name !== '' ) data.name = this.name;
  5187. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5188. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5189. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5190. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5191. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5192. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5193. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5194. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5195. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5196. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5197. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5198. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5199. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5200. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5201. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5202. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5203. }
  5204. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5205. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5206. }
  5207. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5208. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5209. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5210. }
  5211. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5212. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5213. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5214. if ( this.lightMap && this.lightMap.isTexture ) {
  5215. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5216. data.lightMapIntensity = this.lightMapIntensity;
  5217. }
  5218. if ( this.aoMap && this.aoMap.isTexture ) {
  5219. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5220. data.aoMapIntensity = this.aoMapIntensity;
  5221. }
  5222. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5223. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5224. data.bumpScale = this.bumpScale;
  5225. }
  5226. if ( this.normalMap && this.normalMap.isTexture ) {
  5227. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5228. data.normalMapType = this.normalMapType;
  5229. data.normalScale = this.normalScale.toArray();
  5230. }
  5231. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5232. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5233. data.displacementScale = this.displacementScale;
  5234. data.displacementBias = this.displacementBias;
  5235. }
  5236. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5237. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5238. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5239. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5240. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5241. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5242. if ( this.envMap && this.envMap.isTexture ) {
  5243. data.envMap = this.envMap.toJSON( meta ).uuid;
  5244. if ( this.combine !== undefined ) data.combine = this.combine;
  5245. }
  5246. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5247. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5248. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5249. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5250. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5251. }
  5252. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5253. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5254. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5255. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5256. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  5257. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5258. if ( this.size !== undefined ) data.size = this.size;
  5259. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5260. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5261. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5262. if ( this.side !== FrontSide ) data.side = this.side;
  5263. if ( this.vertexColors ) data.vertexColors = true;
  5264. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5265. if ( this.transparent === true ) data.transparent = this.transparent;
  5266. data.depthFunc = this.depthFunc;
  5267. data.depthTest = this.depthTest;
  5268. data.depthWrite = this.depthWrite;
  5269. data.colorWrite = this.colorWrite;
  5270. data.stencilWrite = this.stencilWrite;
  5271. data.stencilWriteMask = this.stencilWriteMask;
  5272. data.stencilFunc = this.stencilFunc;
  5273. data.stencilRef = this.stencilRef;
  5274. data.stencilFuncMask = this.stencilFuncMask;
  5275. data.stencilFail = this.stencilFail;
  5276. data.stencilZFail = this.stencilZFail;
  5277. data.stencilZPass = this.stencilZPass;
  5278. // rotation (SpriteMaterial)
  5279. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5280. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5281. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5282. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5283. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5284. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5285. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5286. if ( this.scale !== undefined ) data.scale = this.scale;
  5287. if ( this.dithering === true ) data.dithering = true;
  5288. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5289. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5290. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5291. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5292. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5293. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5294. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5295. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5296. if ( this.visible === false ) data.visible = false;
  5297. if ( this.toneMapped === false ) data.toneMapped = false;
  5298. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5299. // TODO: Copied from Object3D.toJSON
  5300. function extractFromCache( cache ) {
  5301. const values = [];
  5302. for ( const key in cache ) {
  5303. const data = cache[ key ];
  5304. delete data.metadata;
  5305. values.push( data );
  5306. }
  5307. return values;
  5308. }
  5309. if ( isRoot ) {
  5310. const textures = extractFromCache( meta.textures );
  5311. const images = extractFromCache( meta.images );
  5312. if ( textures.length > 0 ) data.textures = textures;
  5313. if ( images.length > 0 ) data.images = images;
  5314. }
  5315. return data;
  5316. }
  5317. clone() {
  5318. return new this.constructor().copy( this );
  5319. }
  5320. copy( source ) {
  5321. this.name = source.name;
  5322. this.fog = source.fog;
  5323. this.blending = source.blending;
  5324. this.side = source.side;
  5325. this.vertexColors = source.vertexColors;
  5326. this.opacity = source.opacity;
  5327. this.transparent = source.transparent;
  5328. this.blendSrc = source.blendSrc;
  5329. this.blendDst = source.blendDst;
  5330. this.blendEquation = source.blendEquation;
  5331. this.blendSrcAlpha = source.blendSrcAlpha;
  5332. this.blendDstAlpha = source.blendDstAlpha;
  5333. this.blendEquationAlpha = source.blendEquationAlpha;
  5334. this.depthFunc = source.depthFunc;
  5335. this.depthTest = source.depthTest;
  5336. this.depthWrite = source.depthWrite;
  5337. this.stencilWriteMask = source.stencilWriteMask;
  5338. this.stencilFunc = source.stencilFunc;
  5339. this.stencilRef = source.stencilRef;
  5340. this.stencilFuncMask = source.stencilFuncMask;
  5341. this.stencilFail = source.stencilFail;
  5342. this.stencilZFail = source.stencilZFail;
  5343. this.stencilZPass = source.stencilZPass;
  5344. this.stencilWrite = source.stencilWrite;
  5345. const srcPlanes = source.clippingPlanes;
  5346. let dstPlanes = null;
  5347. if ( srcPlanes !== null ) {
  5348. const n = srcPlanes.length;
  5349. dstPlanes = new Array( n );
  5350. for ( let i = 0; i !== n; ++ i ) {
  5351. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5352. }
  5353. }
  5354. this.clippingPlanes = dstPlanes;
  5355. this.clipIntersection = source.clipIntersection;
  5356. this.clipShadows = source.clipShadows;
  5357. this.shadowSide = source.shadowSide;
  5358. this.colorWrite = source.colorWrite;
  5359. this.precision = source.precision;
  5360. this.polygonOffset = source.polygonOffset;
  5361. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5362. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5363. this.dithering = source.dithering;
  5364. this.alphaTest = source.alphaTest;
  5365. this.alphaToCoverage = source.alphaToCoverage;
  5366. this.premultipliedAlpha = source.premultipliedAlpha;
  5367. this.visible = source.visible;
  5368. this.toneMapped = source.toneMapped;
  5369. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5370. return this;
  5371. }
  5372. dispose() {
  5373. this.dispatchEvent( { type: 'dispose' } );
  5374. }
  5375. set needsUpdate( value ) {
  5376. if ( value === true ) this.version ++;
  5377. }
  5378. }
  5379. Material.prototype.isMaterial = true;
  5380. /**
  5381. * parameters = {
  5382. * color: <hex>,
  5383. * opacity: <float>,
  5384. * map: new THREE.Texture( <Image> ),
  5385. *
  5386. * lightMap: new THREE.Texture( <Image> ),
  5387. * lightMapIntensity: <float>
  5388. *
  5389. * aoMap: new THREE.Texture( <Image> ),
  5390. * aoMapIntensity: <float>
  5391. *
  5392. * specularMap: new THREE.Texture( <Image> ),
  5393. *
  5394. * alphaMap: new THREE.Texture( <Image> ),
  5395. *
  5396. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5397. * combine: THREE.Multiply,
  5398. * reflectivity: <float>,
  5399. * refractionRatio: <float>,
  5400. *
  5401. * depthTest: <bool>,
  5402. * depthWrite: <bool>,
  5403. *
  5404. * wireframe: <boolean>,
  5405. * wireframeLinewidth: <float>,
  5406. * }
  5407. */
  5408. class MeshBasicMaterial extends Material {
  5409. constructor( parameters ) {
  5410. super();
  5411. this.type = 'MeshBasicMaterial';
  5412. this.color = new Color( 0xffffff ); // emissive
  5413. this.map = null;
  5414. this.lightMap = null;
  5415. this.lightMapIntensity = 1.0;
  5416. this.aoMap = null;
  5417. this.aoMapIntensity = 1.0;
  5418. this.specularMap = null;
  5419. this.alphaMap = null;
  5420. this.envMap = null;
  5421. this.combine = MultiplyOperation;
  5422. this.reflectivity = 1;
  5423. this.refractionRatio = 0.98;
  5424. this.wireframe = false;
  5425. this.wireframeLinewidth = 1;
  5426. this.wireframeLinecap = 'round';
  5427. this.wireframeLinejoin = 'round';
  5428. this.setValues( parameters );
  5429. }
  5430. copy( source ) {
  5431. super.copy( source );
  5432. this.color.copy( source.color );
  5433. this.map = source.map;
  5434. this.lightMap = source.lightMap;
  5435. this.lightMapIntensity = source.lightMapIntensity;
  5436. this.aoMap = source.aoMap;
  5437. this.aoMapIntensity = source.aoMapIntensity;
  5438. this.specularMap = source.specularMap;
  5439. this.alphaMap = source.alphaMap;
  5440. this.envMap = source.envMap;
  5441. this.combine = source.combine;
  5442. this.reflectivity = source.reflectivity;
  5443. this.refractionRatio = source.refractionRatio;
  5444. this.wireframe = source.wireframe;
  5445. this.wireframeLinewidth = source.wireframeLinewidth;
  5446. this.wireframeLinecap = source.wireframeLinecap;
  5447. this.wireframeLinejoin = source.wireframeLinejoin;
  5448. return this;
  5449. }
  5450. }
  5451. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5452. const _vector$9 = /*@__PURE__*/ new Vector3();
  5453. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5454. class BufferAttribute {
  5455. constructor( array, itemSize, normalized ) {
  5456. if ( Array.isArray( array ) ) {
  5457. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5458. }
  5459. this.name = '';
  5460. this.array = array;
  5461. this.itemSize = itemSize;
  5462. this.count = array !== undefined ? array.length / itemSize : 0;
  5463. this.normalized = normalized === true;
  5464. this.usage = StaticDrawUsage;
  5465. this.updateRange = { offset: 0, count: - 1 };
  5466. this.version = 0;
  5467. }
  5468. onUploadCallback() {}
  5469. set needsUpdate( value ) {
  5470. if ( value === true ) this.version ++;
  5471. }
  5472. setUsage( value ) {
  5473. this.usage = value;
  5474. return this;
  5475. }
  5476. copy( source ) {
  5477. this.name = source.name;
  5478. this.array = new source.array.constructor( source.array );
  5479. this.itemSize = source.itemSize;
  5480. this.count = source.count;
  5481. this.normalized = source.normalized;
  5482. this.usage = source.usage;
  5483. return this;
  5484. }
  5485. copyAt( index1, attribute, index2 ) {
  5486. index1 *= this.itemSize;
  5487. index2 *= attribute.itemSize;
  5488. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5489. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5490. }
  5491. return this;
  5492. }
  5493. copyArray( array ) {
  5494. this.array.set( array );
  5495. return this;
  5496. }
  5497. copyColorsArray( colors ) {
  5498. const array = this.array;
  5499. let offset = 0;
  5500. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5501. let color = colors[ i ];
  5502. if ( color === undefined ) {
  5503. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5504. color = new Color();
  5505. }
  5506. array[ offset ++ ] = color.r;
  5507. array[ offset ++ ] = color.g;
  5508. array[ offset ++ ] = color.b;
  5509. }
  5510. return this;
  5511. }
  5512. copyVector2sArray( vectors ) {
  5513. const array = this.array;
  5514. let offset = 0;
  5515. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5516. let vector = vectors[ i ];
  5517. if ( vector === undefined ) {
  5518. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5519. vector = new Vector2();
  5520. }
  5521. array[ offset ++ ] = vector.x;
  5522. array[ offset ++ ] = vector.y;
  5523. }
  5524. return this;
  5525. }
  5526. copyVector3sArray( vectors ) {
  5527. const array = this.array;
  5528. let offset = 0;
  5529. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5530. let vector = vectors[ i ];
  5531. if ( vector === undefined ) {
  5532. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5533. vector = new Vector3();
  5534. }
  5535. array[ offset ++ ] = vector.x;
  5536. array[ offset ++ ] = vector.y;
  5537. array[ offset ++ ] = vector.z;
  5538. }
  5539. return this;
  5540. }
  5541. copyVector4sArray( vectors ) {
  5542. const array = this.array;
  5543. let offset = 0;
  5544. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5545. let vector = vectors[ i ];
  5546. if ( vector === undefined ) {
  5547. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5548. vector = new Vector4();
  5549. }
  5550. array[ offset ++ ] = vector.x;
  5551. array[ offset ++ ] = vector.y;
  5552. array[ offset ++ ] = vector.z;
  5553. array[ offset ++ ] = vector.w;
  5554. }
  5555. return this;
  5556. }
  5557. applyMatrix3( m ) {
  5558. if ( this.itemSize === 2 ) {
  5559. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5560. _vector2$1.fromBufferAttribute( this, i );
  5561. _vector2$1.applyMatrix3( m );
  5562. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5563. }
  5564. } else if ( this.itemSize === 3 ) {
  5565. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5566. _vector$9.fromBufferAttribute( this, i );
  5567. _vector$9.applyMatrix3( m );
  5568. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5569. }
  5570. }
  5571. return this;
  5572. }
  5573. applyMatrix4( m ) {
  5574. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5575. _vector$9.x = this.getX( i );
  5576. _vector$9.y = this.getY( i );
  5577. _vector$9.z = this.getZ( i );
  5578. _vector$9.applyMatrix4( m );
  5579. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5580. }
  5581. return this;
  5582. }
  5583. applyNormalMatrix( m ) {
  5584. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5585. _vector$9.x = this.getX( i );
  5586. _vector$9.y = this.getY( i );
  5587. _vector$9.z = this.getZ( i );
  5588. _vector$9.applyNormalMatrix( m );
  5589. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5590. }
  5591. return this;
  5592. }
  5593. transformDirection( m ) {
  5594. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5595. _vector$9.x = this.getX( i );
  5596. _vector$9.y = this.getY( i );
  5597. _vector$9.z = this.getZ( i );
  5598. _vector$9.transformDirection( m );
  5599. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5600. }
  5601. return this;
  5602. }
  5603. set( value, offset = 0 ) {
  5604. this.array.set( value, offset );
  5605. return this;
  5606. }
  5607. getX( index ) {
  5608. return this.array[ index * this.itemSize ];
  5609. }
  5610. setX( index, x ) {
  5611. this.array[ index * this.itemSize ] = x;
  5612. return this;
  5613. }
  5614. getY( index ) {
  5615. return this.array[ index * this.itemSize + 1 ];
  5616. }
  5617. setY( index, y ) {
  5618. this.array[ index * this.itemSize + 1 ] = y;
  5619. return this;
  5620. }
  5621. getZ( index ) {
  5622. return this.array[ index * this.itemSize + 2 ];
  5623. }
  5624. setZ( index, z ) {
  5625. this.array[ index * this.itemSize + 2 ] = z;
  5626. return this;
  5627. }
  5628. getW( index ) {
  5629. return this.array[ index * this.itemSize + 3 ];
  5630. }
  5631. setW( index, w ) {
  5632. this.array[ index * this.itemSize + 3 ] = w;
  5633. return this;
  5634. }
  5635. setXY( index, x, y ) {
  5636. index *= this.itemSize;
  5637. this.array[ index + 0 ] = x;
  5638. this.array[ index + 1 ] = y;
  5639. return this;
  5640. }
  5641. setXYZ( index, x, y, z ) {
  5642. index *= this.itemSize;
  5643. this.array[ index + 0 ] = x;
  5644. this.array[ index + 1 ] = y;
  5645. this.array[ index + 2 ] = z;
  5646. return this;
  5647. }
  5648. setXYZW( index, x, y, z, w ) {
  5649. index *= this.itemSize;
  5650. this.array[ index + 0 ] = x;
  5651. this.array[ index + 1 ] = y;
  5652. this.array[ index + 2 ] = z;
  5653. this.array[ index + 3 ] = w;
  5654. return this;
  5655. }
  5656. onUpload( callback ) {
  5657. this.onUploadCallback = callback;
  5658. return this;
  5659. }
  5660. clone() {
  5661. return new this.constructor( this.array, this.itemSize ).copy( this );
  5662. }
  5663. toJSON() {
  5664. const data = {
  5665. itemSize: this.itemSize,
  5666. type: this.array.constructor.name,
  5667. array: Array.prototype.slice.call( this.array ),
  5668. normalized: this.normalized
  5669. };
  5670. if ( this.name !== '' ) data.name = this.name;
  5671. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5672. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5673. return data;
  5674. }
  5675. }
  5676. BufferAttribute.prototype.isBufferAttribute = true;
  5677. //
  5678. class Int8BufferAttribute extends BufferAttribute {
  5679. constructor( array, itemSize, normalized ) {
  5680. super( new Int8Array( array ), itemSize, normalized );
  5681. }
  5682. }
  5683. class Uint8BufferAttribute extends BufferAttribute {
  5684. constructor( array, itemSize, normalized ) {
  5685. super( new Uint8Array( array ), itemSize, normalized );
  5686. }
  5687. }
  5688. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5689. constructor( array, itemSize, normalized ) {
  5690. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5691. }
  5692. }
  5693. class Int16BufferAttribute extends BufferAttribute {
  5694. constructor( array, itemSize, normalized ) {
  5695. super( new Int16Array( array ), itemSize, normalized );
  5696. }
  5697. }
  5698. class Uint16BufferAttribute extends BufferAttribute {
  5699. constructor( array, itemSize, normalized ) {
  5700. super( new Uint16Array( array ), itemSize, normalized );
  5701. }
  5702. }
  5703. class Int32BufferAttribute extends BufferAttribute {
  5704. constructor( array, itemSize, normalized ) {
  5705. super( new Int32Array( array ), itemSize, normalized );
  5706. }
  5707. }
  5708. class Uint32BufferAttribute extends BufferAttribute {
  5709. constructor( array, itemSize, normalized ) {
  5710. super( new Uint32Array( array ), itemSize, normalized );
  5711. }
  5712. }
  5713. class Float16BufferAttribute extends BufferAttribute {
  5714. constructor( array, itemSize, normalized ) {
  5715. super( new Uint16Array( array ), itemSize, normalized );
  5716. }
  5717. }
  5718. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5719. class Float32BufferAttribute extends BufferAttribute {
  5720. constructor( array, itemSize, normalized ) {
  5721. super( new Float32Array( array ), itemSize, normalized );
  5722. }
  5723. }
  5724. class Float64BufferAttribute extends BufferAttribute {
  5725. constructor( array, itemSize, normalized ) {
  5726. super( new Float64Array( array ), itemSize, normalized );
  5727. }
  5728. }
  5729. let _id$1 = 0;
  5730. const _m1 = /*@__PURE__*/ new Matrix4();
  5731. const _obj = /*@__PURE__*/ new Object3D();
  5732. const _offset = /*@__PURE__*/ new Vector3();
  5733. const _box$1 = /*@__PURE__*/ new Box3();
  5734. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5735. const _vector$8 = /*@__PURE__*/ new Vector3();
  5736. class BufferGeometry extends EventDispatcher {
  5737. constructor() {
  5738. super();
  5739. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5740. this.uuid = generateUUID();
  5741. this.name = '';
  5742. this.type = 'BufferGeometry';
  5743. this.index = null;
  5744. this.attributes = {};
  5745. this.morphAttributes = {};
  5746. this.morphTargetsRelative = false;
  5747. this.groups = [];
  5748. this.boundingBox = null;
  5749. this.boundingSphere = null;
  5750. this.drawRange = { start: 0, count: Infinity };
  5751. this.userData = {};
  5752. }
  5753. getIndex() {
  5754. return this.index;
  5755. }
  5756. setIndex( index ) {
  5757. if ( Array.isArray( index ) ) {
  5758. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5759. } else {
  5760. this.index = index;
  5761. }
  5762. return this;
  5763. }
  5764. getAttribute( name ) {
  5765. return this.attributes[ name ];
  5766. }
  5767. setAttribute( name, attribute ) {
  5768. this.attributes[ name ] = attribute;
  5769. return this;
  5770. }
  5771. deleteAttribute( name ) {
  5772. delete this.attributes[ name ];
  5773. return this;
  5774. }
  5775. hasAttribute( name ) {
  5776. return this.attributes[ name ] !== undefined;
  5777. }
  5778. addGroup( start, count, materialIndex = 0 ) {
  5779. this.groups.push( {
  5780. start: start,
  5781. count: count,
  5782. materialIndex: materialIndex
  5783. } );
  5784. }
  5785. clearGroups() {
  5786. this.groups = [];
  5787. }
  5788. setDrawRange( start, count ) {
  5789. this.drawRange.start = start;
  5790. this.drawRange.count = count;
  5791. }
  5792. applyMatrix4( matrix ) {
  5793. const position = this.attributes.position;
  5794. if ( position !== undefined ) {
  5795. position.applyMatrix4( matrix );
  5796. position.needsUpdate = true;
  5797. }
  5798. const normal = this.attributes.normal;
  5799. if ( normal !== undefined ) {
  5800. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5801. normal.applyNormalMatrix( normalMatrix );
  5802. normal.needsUpdate = true;
  5803. }
  5804. const tangent = this.attributes.tangent;
  5805. if ( tangent !== undefined ) {
  5806. tangent.transformDirection( matrix );
  5807. tangent.needsUpdate = true;
  5808. }
  5809. if ( this.boundingBox !== null ) {
  5810. this.computeBoundingBox();
  5811. }
  5812. if ( this.boundingSphere !== null ) {
  5813. this.computeBoundingSphere();
  5814. }
  5815. return this;
  5816. }
  5817. applyQuaternion( q ) {
  5818. _m1.makeRotationFromQuaternion( q );
  5819. this.applyMatrix4( _m1 );
  5820. return this;
  5821. }
  5822. rotateX( angle ) {
  5823. // rotate geometry around world x-axis
  5824. _m1.makeRotationX( angle );
  5825. this.applyMatrix4( _m1 );
  5826. return this;
  5827. }
  5828. rotateY( angle ) {
  5829. // rotate geometry around world y-axis
  5830. _m1.makeRotationY( angle );
  5831. this.applyMatrix4( _m1 );
  5832. return this;
  5833. }
  5834. rotateZ( angle ) {
  5835. // rotate geometry around world z-axis
  5836. _m1.makeRotationZ( angle );
  5837. this.applyMatrix4( _m1 );
  5838. return this;
  5839. }
  5840. translate( x, y, z ) {
  5841. // translate geometry
  5842. _m1.makeTranslation( x, y, z );
  5843. this.applyMatrix4( _m1 );
  5844. return this;
  5845. }
  5846. scale( x, y, z ) {
  5847. // scale geometry
  5848. _m1.makeScale( x, y, z );
  5849. this.applyMatrix4( _m1 );
  5850. return this;
  5851. }
  5852. lookAt( vector ) {
  5853. _obj.lookAt( vector );
  5854. _obj.updateMatrix();
  5855. this.applyMatrix4( _obj.matrix );
  5856. return this;
  5857. }
  5858. center() {
  5859. this.computeBoundingBox();
  5860. this.boundingBox.getCenter( _offset ).negate();
  5861. this.translate( _offset.x, _offset.y, _offset.z );
  5862. return this;
  5863. }
  5864. setFromPoints( points ) {
  5865. const position = [];
  5866. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5867. const point = points[ i ];
  5868. position.push( point.x, point.y, point.z || 0 );
  5869. }
  5870. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5871. return this;
  5872. }
  5873. computeBoundingBox() {
  5874. if ( this.boundingBox === null ) {
  5875. this.boundingBox = new Box3();
  5876. }
  5877. const position = this.attributes.position;
  5878. const morphAttributesPosition = this.morphAttributes.position;
  5879. if ( position && position.isGLBufferAttribute ) {
  5880. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5881. this.boundingBox.set(
  5882. new Vector3( - Infinity, - Infinity, - Infinity ),
  5883. new Vector3( + Infinity, + Infinity, + Infinity )
  5884. );
  5885. return;
  5886. }
  5887. if ( position !== undefined ) {
  5888. this.boundingBox.setFromBufferAttribute( position );
  5889. // process morph attributes if present
  5890. if ( morphAttributesPosition ) {
  5891. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5892. const morphAttribute = morphAttributesPosition[ i ];
  5893. _box$1.setFromBufferAttribute( morphAttribute );
  5894. if ( this.morphTargetsRelative ) {
  5895. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5896. this.boundingBox.expandByPoint( _vector$8 );
  5897. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5898. this.boundingBox.expandByPoint( _vector$8 );
  5899. } else {
  5900. this.boundingBox.expandByPoint( _box$1.min );
  5901. this.boundingBox.expandByPoint( _box$1.max );
  5902. }
  5903. }
  5904. }
  5905. } else {
  5906. this.boundingBox.makeEmpty();
  5907. }
  5908. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5909. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5910. }
  5911. }
  5912. computeBoundingSphere() {
  5913. if ( this.boundingSphere === null ) {
  5914. this.boundingSphere = new Sphere();
  5915. }
  5916. const position = this.attributes.position;
  5917. const morphAttributesPosition = this.morphAttributes.position;
  5918. if ( position && position.isGLBufferAttribute ) {
  5919. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5920. this.boundingSphere.set( new Vector3(), Infinity );
  5921. return;
  5922. }
  5923. if ( position ) {
  5924. // first, find the center of the bounding sphere
  5925. const center = this.boundingSphere.center;
  5926. _box$1.setFromBufferAttribute( position );
  5927. // process morph attributes if present
  5928. if ( morphAttributesPosition ) {
  5929. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5930. const morphAttribute = morphAttributesPosition[ i ];
  5931. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  5932. if ( this.morphTargetsRelative ) {
  5933. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  5934. _box$1.expandByPoint( _vector$8 );
  5935. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  5936. _box$1.expandByPoint( _vector$8 );
  5937. } else {
  5938. _box$1.expandByPoint( _boxMorphTargets.min );
  5939. _box$1.expandByPoint( _boxMorphTargets.max );
  5940. }
  5941. }
  5942. }
  5943. _box$1.getCenter( center );
  5944. // second, try to find a boundingSphere with a radius smaller than the
  5945. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5946. let maxRadiusSq = 0;
  5947. for ( let i = 0, il = position.count; i < il; i ++ ) {
  5948. _vector$8.fromBufferAttribute( position, i );
  5949. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5950. }
  5951. // process morph attributes if present
  5952. if ( morphAttributesPosition ) {
  5953. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5954. const morphAttribute = morphAttributesPosition[ i ];
  5955. const morphTargetsRelative = this.morphTargetsRelative;
  5956. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  5957. _vector$8.fromBufferAttribute( morphAttribute, j );
  5958. if ( morphTargetsRelative ) {
  5959. _offset.fromBufferAttribute( position, j );
  5960. _vector$8.add( _offset );
  5961. }
  5962. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5963. }
  5964. }
  5965. }
  5966. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5967. if ( isNaN( this.boundingSphere.radius ) ) {
  5968. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5969. }
  5970. }
  5971. }
  5972. computeTangents() {
  5973. const index = this.index;
  5974. const attributes = this.attributes;
  5975. // based on http://www.terathon.com/code/tangent.html
  5976. // (per vertex tangents)
  5977. if ( index === null ||
  5978. attributes.position === undefined ||
  5979. attributes.normal === undefined ||
  5980. attributes.uv === undefined ) {
  5981. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  5982. return;
  5983. }
  5984. const indices = index.array;
  5985. const positions = attributes.position.array;
  5986. const normals = attributes.normal.array;
  5987. const uvs = attributes.uv.array;
  5988. const nVertices = positions.length / 3;
  5989. if ( attributes.tangent === undefined ) {
  5990. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5991. }
  5992. const tangents = attributes.tangent.array;
  5993. const tan1 = [], tan2 = [];
  5994. for ( let i = 0; i < nVertices; i ++ ) {
  5995. tan1[ i ] = new Vector3();
  5996. tan2[ i ] = new Vector3();
  5997. }
  5998. const vA = new Vector3(),
  5999. vB = new Vector3(),
  6000. vC = new Vector3(),
  6001. uvA = new Vector2(),
  6002. uvB = new Vector2(),
  6003. uvC = new Vector2(),
  6004. sdir = new Vector3(),
  6005. tdir = new Vector3();
  6006. function handleTriangle( a, b, c ) {
  6007. vA.fromArray( positions, a * 3 );
  6008. vB.fromArray( positions, b * 3 );
  6009. vC.fromArray( positions, c * 3 );
  6010. uvA.fromArray( uvs, a * 2 );
  6011. uvB.fromArray( uvs, b * 2 );
  6012. uvC.fromArray( uvs, c * 2 );
  6013. vB.sub( vA );
  6014. vC.sub( vA );
  6015. uvB.sub( uvA );
  6016. uvC.sub( uvA );
  6017. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6018. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6019. if ( ! isFinite( r ) ) return;
  6020. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6021. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6022. tan1[ a ].add( sdir );
  6023. tan1[ b ].add( sdir );
  6024. tan1[ c ].add( sdir );
  6025. tan2[ a ].add( tdir );
  6026. tan2[ b ].add( tdir );
  6027. tan2[ c ].add( tdir );
  6028. }
  6029. let groups = this.groups;
  6030. if ( groups.length === 0 ) {
  6031. groups = [ {
  6032. start: 0,
  6033. count: indices.length
  6034. } ];
  6035. }
  6036. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6037. const group = groups[ i ];
  6038. const start = group.start;
  6039. const count = group.count;
  6040. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6041. handleTriangle(
  6042. indices[ j + 0 ],
  6043. indices[ j + 1 ],
  6044. indices[ j + 2 ]
  6045. );
  6046. }
  6047. }
  6048. const tmp = new Vector3(), tmp2 = new Vector3();
  6049. const n = new Vector3(), n2 = new Vector3();
  6050. function handleVertex( v ) {
  6051. n.fromArray( normals, v * 3 );
  6052. n2.copy( n );
  6053. const t = tan1[ v ];
  6054. // Gram-Schmidt orthogonalize
  6055. tmp.copy( t );
  6056. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6057. // Calculate handedness
  6058. tmp2.crossVectors( n2, t );
  6059. const test = tmp2.dot( tan2[ v ] );
  6060. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6061. tangents[ v * 4 ] = tmp.x;
  6062. tangents[ v * 4 + 1 ] = tmp.y;
  6063. tangents[ v * 4 + 2 ] = tmp.z;
  6064. tangents[ v * 4 + 3 ] = w;
  6065. }
  6066. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6067. const group = groups[ i ];
  6068. const start = group.start;
  6069. const count = group.count;
  6070. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6071. handleVertex( indices[ j + 0 ] );
  6072. handleVertex( indices[ j + 1 ] );
  6073. handleVertex( indices[ j + 2 ] );
  6074. }
  6075. }
  6076. }
  6077. computeVertexNormals() {
  6078. const index = this.index;
  6079. const positionAttribute = this.getAttribute( 'position' );
  6080. if ( positionAttribute !== undefined ) {
  6081. let normalAttribute = this.getAttribute( 'normal' );
  6082. if ( normalAttribute === undefined ) {
  6083. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6084. this.setAttribute( 'normal', normalAttribute );
  6085. } else {
  6086. // reset existing normals to zero
  6087. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6088. normalAttribute.setXYZ( i, 0, 0, 0 );
  6089. }
  6090. }
  6091. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6092. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6093. const cb = new Vector3(), ab = new Vector3();
  6094. // indexed elements
  6095. if ( index ) {
  6096. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6097. const vA = index.getX( i + 0 );
  6098. const vB = index.getX( i + 1 );
  6099. const vC = index.getX( i + 2 );
  6100. pA.fromBufferAttribute( positionAttribute, vA );
  6101. pB.fromBufferAttribute( positionAttribute, vB );
  6102. pC.fromBufferAttribute( positionAttribute, vC );
  6103. cb.subVectors( pC, pB );
  6104. ab.subVectors( pA, pB );
  6105. cb.cross( ab );
  6106. nA.fromBufferAttribute( normalAttribute, vA );
  6107. nB.fromBufferAttribute( normalAttribute, vB );
  6108. nC.fromBufferAttribute( normalAttribute, vC );
  6109. nA.add( cb );
  6110. nB.add( cb );
  6111. nC.add( cb );
  6112. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6113. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6114. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6115. }
  6116. } else {
  6117. // non-indexed elements (unconnected triangle soup)
  6118. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6119. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6120. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6121. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6122. cb.subVectors( pC, pB );
  6123. ab.subVectors( pA, pB );
  6124. cb.cross( ab );
  6125. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6126. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6127. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6128. }
  6129. }
  6130. this.normalizeNormals();
  6131. normalAttribute.needsUpdate = true;
  6132. }
  6133. }
  6134. merge( geometry, offset ) {
  6135. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6136. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6137. return;
  6138. }
  6139. if ( offset === undefined ) {
  6140. offset = 0;
  6141. console.warn(
  6142. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6143. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6144. );
  6145. }
  6146. const attributes = this.attributes;
  6147. for ( const key in attributes ) {
  6148. if ( geometry.attributes[ key ] === undefined ) continue;
  6149. const attribute1 = attributes[ key ];
  6150. const attributeArray1 = attribute1.array;
  6151. const attribute2 = geometry.attributes[ key ];
  6152. const attributeArray2 = attribute2.array;
  6153. const attributeOffset = attribute2.itemSize * offset;
  6154. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6155. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6156. attributeArray1[ j ] = attributeArray2[ i ];
  6157. }
  6158. }
  6159. return this;
  6160. }
  6161. normalizeNormals() {
  6162. const normals = this.attributes.normal;
  6163. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6164. _vector$8.fromBufferAttribute( normals, i );
  6165. _vector$8.normalize();
  6166. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6167. }
  6168. }
  6169. toNonIndexed() {
  6170. function convertBufferAttribute( attribute, indices ) {
  6171. const array = attribute.array;
  6172. const itemSize = attribute.itemSize;
  6173. const normalized = attribute.normalized;
  6174. const array2 = new array.constructor( indices.length * itemSize );
  6175. let index = 0, index2 = 0;
  6176. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6177. if ( attribute.isInterleavedBufferAttribute ) {
  6178. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6179. } else {
  6180. index = indices[ i ] * itemSize;
  6181. }
  6182. for ( let j = 0; j < itemSize; j ++ ) {
  6183. array2[ index2 ++ ] = array[ index ++ ];
  6184. }
  6185. }
  6186. return new BufferAttribute( array2, itemSize, normalized );
  6187. }
  6188. //
  6189. if ( this.index === null ) {
  6190. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6191. return this;
  6192. }
  6193. const geometry2 = new BufferGeometry();
  6194. const indices = this.index.array;
  6195. const attributes = this.attributes;
  6196. // attributes
  6197. for ( const name in attributes ) {
  6198. const attribute = attributes[ name ];
  6199. const newAttribute = convertBufferAttribute( attribute, indices );
  6200. geometry2.setAttribute( name, newAttribute );
  6201. }
  6202. // morph attributes
  6203. const morphAttributes = this.morphAttributes;
  6204. for ( const name in morphAttributes ) {
  6205. const morphArray = [];
  6206. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6207. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6208. const attribute = morphAttribute[ i ];
  6209. const newAttribute = convertBufferAttribute( attribute, indices );
  6210. morphArray.push( newAttribute );
  6211. }
  6212. geometry2.morphAttributes[ name ] = morphArray;
  6213. }
  6214. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6215. // groups
  6216. const groups = this.groups;
  6217. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6218. const group = groups[ i ];
  6219. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6220. }
  6221. return geometry2;
  6222. }
  6223. toJSON() {
  6224. const data = {
  6225. metadata: {
  6226. version: 4.5,
  6227. type: 'BufferGeometry',
  6228. generator: 'BufferGeometry.toJSON'
  6229. }
  6230. };
  6231. // standard BufferGeometry serialization
  6232. data.uuid = this.uuid;
  6233. data.type = this.type;
  6234. if ( this.name !== '' ) data.name = this.name;
  6235. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6236. if ( this.parameters !== undefined ) {
  6237. const parameters = this.parameters;
  6238. for ( const key in parameters ) {
  6239. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6240. }
  6241. return data;
  6242. }
  6243. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6244. data.data = { attributes: {} };
  6245. const index = this.index;
  6246. if ( index !== null ) {
  6247. data.data.index = {
  6248. type: index.array.constructor.name,
  6249. array: Array.prototype.slice.call( index.array )
  6250. };
  6251. }
  6252. const attributes = this.attributes;
  6253. for ( const key in attributes ) {
  6254. const attribute = attributes[ key ];
  6255. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6256. }
  6257. const morphAttributes = {};
  6258. let hasMorphAttributes = false;
  6259. for ( const key in this.morphAttributes ) {
  6260. const attributeArray = this.morphAttributes[ key ];
  6261. const array = [];
  6262. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6263. const attribute = attributeArray[ i ];
  6264. array.push( attribute.toJSON( data.data ) );
  6265. }
  6266. if ( array.length > 0 ) {
  6267. morphAttributes[ key ] = array;
  6268. hasMorphAttributes = true;
  6269. }
  6270. }
  6271. if ( hasMorphAttributes ) {
  6272. data.data.morphAttributes = morphAttributes;
  6273. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6274. }
  6275. const groups = this.groups;
  6276. if ( groups.length > 0 ) {
  6277. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6278. }
  6279. const boundingSphere = this.boundingSphere;
  6280. if ( boundingSphere !== null ) {
  6281. data.data.boundingSphere = {
  6282. center: boundingSphere.center.toArray(),
  6283. radius: boundingSphere.radius
  6284. };
  6285. }
  6286. return data;
  6287. }
  6288. clone() {
  6289. return new this.constructor().copy( this );
  6290. }
  6291. copy( source ) {
  6292. // reset
  6293. this.index = null;
  6294. this.attributes = {};
  6295. this.morphAttributes = {};
  6296. this.groups = [];
  6297. this.boundingBox = null;
  6298. this.boundingSphere = null;
  6299. // used for storing cloned, shared data
  6300. const data = {};
  6301. // name
  6302. this.name = source.name;
  6303. // index
  6304. const index = source.index;
  6305. if ( index !== null ) {
  6306. this.setIndex( index.clone( data ) );
  6307. }
  6308. // attributes
  6309. const attributes = source.attributes;
  6310. for ( const name in attributes ) {
  6311. const attribute = attributes[ name ];
  6312. this.setAttribute( name, attribute.clone( data ) );
  6313. }
  6314. // morph attributes
  6315. const morphAttributes = source.morphAttributes;
  6316. for ( const name in morphAttributes ) {
  6317. const array = [];
  6318. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6319. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6320. array.push( morphAttribute[ i ].clone( data ) );
  6321. }
  6322. this.morphAttributes[ name ] = array;
  6323. }
  6324. this.morphTargetsRelative = source.morphTargetsRelative;
  6325. // groups
  6326. const groups = source.groups;
  6327. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6328. const group = groups[ i ];
  6329. this.addGroup( group.start, group.count, group.materialIndex );
  6330. }
  6331. // bounding box
  6332. const boundingBox = source.boundingBox;
  6333. if ( boundingBox !== null ) {
  6334. this.boundingBox = boundingBox.clone();
  6335. }
  6336. // bounding sphere
  6337. const boundingSphere = source.boundingSphere;
  6338. if ( boundingSphere !== null ) {
  6339. this.boundingSphere = boundingSphere.clone();
  6340. }
  6341. // draw range
  6342. this.drawRange.start = source.drawRange.start;
  6343. this.drawRange.count = source.drawRange.count;
  6344. // user data
  6345. this.userData = source.userData;
  6346. // geometry generator parameters
  6347. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6348. return this;
  6349. }
  6350. dispose() {
  6351. this.dispatchEvent( { type: 'dispose' } );
  6352. }
  6353. }
  6354. BufferGeometry.prototype.isBufferGeometry = true;
  6355. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6356. const _ray$2 = /*@__PURE__*/ new Ray();
  6357. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6358. const _vA$1 = /*@__PURE__*/ new Vector3();
  6359. const _vB$1 = /*@__PURE__*/ new Vector3();
  6360. const _vC$1 = /*@__PURE__*/ new Vector3();
  6361. const _tempA = /*@__PURE__*/ new Vector3();
  6362. const _tempB = /*@__PURE__*/ new Vector3();
  6363. const _tempC = /*@__PURE__*/ new Vector3();
  6364. const _morphA = /*@__PURE__*/ new Vector3();
  6365. const _morphB = /*@__PURE__*/ new Vector3();
  6366. const _morphC = /*@__PURE__*/ new Vector3();
  6367. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6368. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6369. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6370. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6371. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6372. class Mesh extends Object3D {
  6373. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6374. super();
  6375. this.type = 'Mesh';
  6376. this.geometry = geometry;
  6377. this.material = material;
  6378. this.updateMorphTargets();
  6379. }
  6380. copy( source ) {
  6381. super.copy( source );
  6382. if ( source.morphTargetInfluences !== undefined ) {
  6383. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6384. }
  6385. if ( source.morphTargetDictionary !== undefined ) {
  6386. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6387. }
  6388. this.material = source.material;
  6389. this.geometry = source.geometry;
  6390. return this;
  6391. }
  6392. updateMorphTargets() {
  6393. const geometry = this.geometry;
  6394. if ( geometry.isBufferGeometry ) {
  6395. const morphAttributes = geometry.morphAttributes;
  6396. const keys = Object.keys( morphAttributes );
  6397. if ( keys.length > 0 ) {
  6398. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6399. if ( morphAttribute !== undefined ) {
  6400. this.morphTargetInfluences = [];
  6401. this.morphTargetDictionary = {};
  6402. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6403. const name = morphAttribute[ m ].name || String( m );
  6404. this.morphTargetInfluences.push( 0 );
  6405. this.morphTargetDictionary[ name ] = m;
  6406. }
  6407. }
  6408. }
  6409. } else {
  6410. const morphTargets = geometry.morphTargets;
  6411. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6412. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6413. }
  6414. }
  6415. }
  6416. raycast( raycaster, intersects ) {
  6417. const geometry = this.geometry;
  6418. const material = this.material;
  6419. const matrixWorld = this.matrixWorld;
  6420. if ( material === undefined ) return;
  6421. // Checking boundingSphere distance to ray
  6422. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6423. _sphere$3.copy( geometry.boundingSphere );
  6424. _sphere$3.applyMatrix4( matrixWorld );
  6425. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6426. //
  6427. _inverseMatrix$2.copy( matrixWorld ).invert();
  6428. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6429. // Check boundingBox before continuing
  6430. if ( geometry.boundingBox !== null ) {
  6431. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6432. }
  6433. let intersection;
  6434. if ( geometry.isBufferGeometry ) {
  6435. const index = geometry.index;
  6436. const position = geometry.attributes.position;
  6437. const morphPosition = geometry.morphAttributes.position;
  6438. const morphTargetsRelative = geometry.morphTargetsRelative;
  6439. const uv = geometry.attributes.uv;
  6440. const uv2 = geometry.attributes.uv2;
  6441. const groups = geometry.groups;
  6442. const drawRange = geometry.drawRange;
  6443. if ( index !== null ) {
  6444. // indexed buffer geometry
  6445. if ( Array.isArray( material ) ) {
  6446. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6447. const group = groups[ i ];
  6448. const groupMaterial = material[ group.materialIndex ];
  6449. const start = Math.max( group.start, drawRange.start );
  6450. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6451. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6452. const a = index.getX( j );
  6453. const b = index.getX( j + 1 );
  6454. const c = index.getX( j + 2 );
  6455. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6456. if ( intersection ) {
  6457. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6458. intersection.face.materialIndex = group.materialIndex;
  6459. intersects.push( intersection );
  6460. }
  6461. }
  6462. }
  6463. } else {
  6464. const start = Math.max( 0, drawRange.start );
  6465. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6466. for ( let i = start, il = end; i < il; i += 3 ) {
  6467. const a = index.getX( i );
  6468. const b = index.getX( i + 1 );
  6469. const c = index.getX( i + 2 );
  6470. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6471. if ( intersection ) {
  6472. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6473. intersects.push( intersection );
  6474. }
  6475. }
  6476. }
  6477. } else if ( position !== undefined ) {
  6478. // non-indexed buffer geometry
  6479. if ( Array.isArray( material ) ) {
  6480. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6481. const group = groups[ i ];
  6482. const groupMaterial = material[ group.materialIndex ];
  6483. const start = Math.max( group.start, drawRange.start );
  6484. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6485. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6486. const a = j;
  6487. const b = j + 1;
  6488. const c = j + 2;
  6489. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6490. if ( intersection ) {
  6491. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6492. intersection.face.materialIndex = group.materialIndex;
  6493. intersects.push( intersection );
  6494. }
  6495. }
  6496. }
  6497. } else {
  6498. const start = Math.max( 0, drawRange.start );
  6499. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6500. for ( let i = start, il = end; i < il; i += 3 ) {
  6501. const a = i;
  6502. const b = i + 1;
  6503. const c = i + 2;
  6504. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6505. if ( intersection ) {
  6506. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6507. intersects.push( intersection );
  6508. }
  6509. }
  6510. }
  6511. }
  6512. } else if ( geometry.isGeometry ) {
  6513. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6514. }
  6515. }
  6516. }
  6517. Mesh.prototype.isMesh = true;
  6518. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6519. let intersect;
  6520. if ( material.side === BackSide ) {
  6521. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6522. } else {
  6523. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6524. }
  6525. if ( intersect === null ) return null;
  6526. _intersectionPointWorld.copy( point );
  6527. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6528. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6529. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6530. return {
  6531. distance: distance,
  6532. point: _intersectionPointWorld.clone(),
  6533. object: object
  6534. };
  6535. }
  6536. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6537. _vA$1.fromBufferAttribute( position, a );
  6538. _vB$1.fromBufferAttribute( position, b );
  6539. _vC$1.fromBufferAttribute( position, c );
  6540. const morphInfluences = object.morphTargetInfluences;
  6541. if ( morphPosition && morphInfluences ) {
  6542. _morphA.set( 0, 0, 0 );
  6543. _morphB.set( 0, 0, 0 );
  6544. _morphC.set( 0, 0, 0 );
  6545. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6546. const influence = morphInfluences[ i ];
  6547. const morphAttribute = morphPosition[ i ];
  6548. if ( influence === 0 ) continue;
  6549. _tempA.fromBufferAttribute( morphAttribute, a );
  6550. _tempB.fromBufferAttribute( morphAttribute, b );
  6551. _tempC.fromBufferAttribute( morphAttribute, c );
  6552. if ( morphTargetsRelative ) {
  6553. _morphA.addScaledVector( _tempA, influence );
  6554. _morphB.addScaledVector( _tempB, influence );
  6555. _morphC.addScaledVector( _tempC, influence );
  6556. } else {
  6557. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6558. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6559. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6560. }
  6561. }
  6562. _vA$1.add( _morphA );
  6563. _vB$1.add( _morphB );
  6564. _vC$1.add( _morphC );
  6565. }
  6566. if ( object.isSkinnedMesh ) {
  6567. object.boneTransform( a, _vA$1 );
  6568. object.boneTransform( b, _vB$1 );
  6569. object.boneTransform( c, _vC$1 );
  6570. }
  6571. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6572. if ( intersection ) {
  6573. if ( uv ) {
  6574. _uvA$1.fromBufferAttribute( uv, a );
  6575. _uvB$1.fromBufferAttribute( uv, b );
  6576. _uvC$1.fromBufferAttribute( uv, c );
  6577. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6578. }
  6579. if ( uv2 ) {
  6580. _uvA$1.fromBufferAttribute( uv2, a );
  6581. _uvB$1.fromBufferAttribute( uv2, b );
  6582. _uvC$1.fromBufferAttribute( uv2, c );
  6583. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6584. }
  6585. const face = {
  6586. a: a,
  6587. b: b,
  6588. c: c,
  6589. normal: new Vector3(),
  6590. materialIndex: 0
  6591. };
  6592. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6593. intersection.face = face;
  6594. }
  6595. return intersection;
  6596. }
  6597. class BoxGeometry extends BufferGeometry {
  6598. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6599. super();
  6600. this.type = 'BoxGeometry';
  6601. this.parameters = {
  6602. width: width,
  6603. height: height,
  6604. depth: depth,
  6605. widthSegments: widthSegments,
  6606. heightSegments: heightSegments,
  6607. depthSegments: depthSegments
  6608. };
  6609. const scope = this;
  6610. // segments
  6611. widthSegments = Math.floor( widthSegments );
  6612. heightSegments = Math.floor( heightSegments );
  6613. depthSegments = Math.floor( depthSegments );
  6614. // buffers
  6615. const indices = [];
  6616. const vertices = [];
  6617. const normals = [];
  6618. const uvs = [];
  6619. // helper variables
  6620. let numberOfVertices = 0;
  6621. let groupStart = 0;
  6622. // build each side of the box geometry
  6623. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6624. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6625. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6626. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6627. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6628. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6629. // build geometry
  6630. this.setIndex( indices );
  6631. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6632. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6633. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6634. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6635. const segmentWidth = width / gridX;
  6636. const segmentHeight = height / gridY;
  6637. const widthHalf = width / 2;
  6638. const heightHalf = height / 2;
  6639. const depthHalf = depth / 2;
  6640. const gridX1 = gridX + 1;
  6641. const gridY1 = gridY + 1;
  6642. let vertexCounter = 0;
  6643. let groupCount = 0;
  6644. const vector = new Vector3();
  6645. // generate vertices, normals and uvs
  6646. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6647. const y = iy * segmentHeight - heightHalf;
  6648. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6649. const x = ix * segmentWidth - widthHalf;
  6650. // set values to correct vector component
  6651. vector[ u ] = x * udir;
  6652. vector[ v ] = y * vdir;
  6653. vector[ w ] = depthHalf;
  6654. // now apply vector to vertex buffer
  6655. vertices.push( vector.x, vector.y, vector.z );
  6656. // set values to correct vector component
  6657. vector[ u ] = 0;
  6658. vector[ v ] = 0;
  6659. vector[ w ] = depth > 0 ? 1 : - 1;
  6660. // now apply vector to normal buffer
  6661. normals.push( vector.x, vector.y, vector.z );
  6662. // uvs
  6663. uvs.push( ix / gridX );
  6664. uvs.push( 1 - ( iy / gridY ) );
  6665. // counters
  6666. vertexCounter += 1;
  6667. }
  6668. }
  6669. // indices
  6670. // 1. you need three indices to draw a single face
  6671. // 2. a single segment consists of two faces
  6672. // 3. so we need to generate six (2*3) indices per segment
  6673. for ( let iy = 0; iy < gridY; iy ++ ) {
  6674. for ( let ix = 0; ix < gridX; ix ++ ) {
  6675. const a = numberOfVertices + ix + gridX1 * iy;
  6676. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6677. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6678. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6679. // faces
  6680. indices.push( a, b, d );
  6681. indices.push( b, c, d );
  6682. // increase counter
  6683. groupCount += 6;
  6684. }
  6685. }
  6686. // add a group to the geometry. this will ensure multi material support
  6687. scope.addGroup( groupStart, groupCount, materialIndex );
  6688. // calculate new start value for groups
  6689. groupStart += groupCount;
  6690. // update total number of vertices
  6691. numberOfVertices += vertexCounter;
  6692. }
  6693. }
  6694. static fromJSON( data ) {
  6695. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6696. }
  6697. }
  6698. /**
  6699. * Uniform Utilities
  6700. */
  6701. function cloneUniforms( src ) {
  6702. const dst = {};
  6703. for ( const u in src ) {
  6704. dst[ u ] = {};
  6705. for ( const p in src[ u ] ) {
  6706. const property = src[ u ][ p ];
  6707. if ( property && ( property.isColor ||
  6708. property.isMatrix3 || property.isMatrix4 ||
  6709. property.isVector2 || property.isVector3 || property.isVector4 ||
  6710. property.isTexture || property.isQuaternion ) ) {
  6711. dst[ u ][ p ] = property.clone();
  6712. } else if ( Array.isArray( property ) ) {
  6713. dst[ u ][ p ] = property.slice();
  6714. } else {
  6715. dst[ u ][ p ] = property;
  6716. }
  6717. }
  6718. }
  6719. return dst;
  6720. }
  6721. function mergeUniforms( uniforms ) {
  6722. const merged = {};
  6723. for ( let u = 0; u < uniforms.length; u ++ ) {
  6724. const tmp = cloneUniforms( uniforms[ u ] );
  6725. for ( const p in tmp ) {
  6726. merged[ p ] = tmp[ p ];
  6727. }
  6728. }
  6729. return merged;
  6730. }
  6731. // Legacy
  6732. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6733. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6734. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6735. /**
  6736. * parameters = {
  6737. * defines: { "label" : "value" },
  6738. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6739. *
  6740. * fragmentShader: <string>,
  6741. * vertexShader: <string>,
  6742. *
  6743. * wireframe: <boolean>,
  6744. * wireframeLinewidth: <float>,
  6745. *
  6746. * lights: <bool>
  6747. * }
  6748. */
  6749. class ShaderMaterial extends Material {
  6750. constructor( parameters ) {
  6751. super();
  6752. this.type = 'ShaderMaterial';
  6753. this.defines = {};
  6754. this.uniforms = {};
  6755. this.vertexShader = default_vertex;
  6756. this.fragmentShader = default_fragment;
  6757. this.linewidth = 1;
  6758. this.wireframe = false;
  6759. this.wireframeLinewidth = 1;
  6760. this.fog = false; // set to use scene fog
  6761. this.lights = false; // set to use scene lights
  6762. this.clipping = false; // set to use user-defined clipping planes
  6763. this.extensions = {
  6764. derivatives: false, // set to use derivatives
  6765. fragDepth: false, // set to use fragment depth values
  6766. drawBuffers: false, // set to use draw buffers
  6767. shaderTextureLOD: false // set to use shader texture LOD
  6768. };
  6769. // When rendered geometry doesn't include these attributes but the material does,
  6770. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6771. this.defaultAttributeValues = {
  6772. 'color': [ 1, 1, 1 ],
  6773. 'uv': [ 0, 0 ],
  6774. 'uv2': [ 0, 0 ]
  6775. };
  6776. this.index0AttributeName = undefined;
  6777. this.uniformsNeedUpdate = false;
  6778. this.glslVersion = null;
  6779. if ( parameters !== undefined ) {
  6780. if ( parameters.attributes !== undefined ) {
  6781. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6782. }
  6783. this.setValues( parameters );
  6784. }
  6785. }
  6786. copy( source ) {
  6787. super.copy( source );
  6788. this.fragmentShader = source.fragmentShader;
  6789. this.vertexShader = source.vertexShader;
  6790. this.uniforms = cloneUniforms( source.uniforms );
  6791. this.defines = Object.assign( {}, source.defines );
  6792. this.wireframe = source.wireframe;
  6793. this.wireframeLinewidth = source.wireframeLinewidth;
  6794. this.lights = source.lights;
  6795. this.clipping = source.clipping;
  6796. this.extensions = Object.assign( {}, source.extensions );
  6797. this.glslVersion = source.glslVersion;
  6798. return this;
  6799. }
  6800. toJSON( meta ) {
  6801. const data = super.toJSON( meta );
  6802. data.glslVersion = this.glslVersion;
  6803. data.uniforms = {};
  6804. for ( const name in this.uniforms ) {
  6805. const uniform = this.uniforms[ name ];
  6806. const value = uniform.value;
  6807. if ( value && value.isTexture ) {
  6808. data.uniforms[ name ] = {
  6809. type: 't',
  6810. value: value.toJSON( meta ).uuid
  6811. };
  6812. } else if ( value && value.isColor ) {
  6813. data.uniforms[ name ] = {
  6814. type: 'c',
  6815. value: value.getHex()
  6816. };
  6817. } else if ( value && value.isVector2 ) {
  6818. data.uniforms[ name ] = {
  6819. type: 'v2',
  6820. value: value.toArray()
  6821. };
  6822. } else if ( value && value.isVector3 ) {
  6823. data.uniforms[ name ] = {
  6824. type: 'v3',
  6825. value: value.toArray()
  6826. };
  6827. } else if ( value && value.isVector4 ) {
  6828. data.uniforms[ name ] = {
  6829. type: 'v4',
  6830. value: value.toArray()
  6831. };
  6832. } else if ( value && value.isMatrix3 ) {
  6833. data.uniforms[ name ] = {
  6834. type: 'm3',
  6835. value: value.toArray()
  6836. };
  6837. } else if ( value && value.isMatrix4 ) {
  6838. data.uniforms[ name ] = {
  6839. type: 'm4',
  6840. value: value.toArray()
  6841. };
  6842. } else {
  6843. data.uniforms[ name ] = {
  6844. value: value
  6845. };
  6846. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6847. }
  6848. }
  6849. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6850. data.vertexShader = this.vertexShader;
  6851. data.fragmentShader = this.fragmentShader;
  6852. const extensions = {};
  6853. for ( const key in this.extensions ) {
  6854. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6855. }
  6856. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6857. return data;
  6858. }
  6859. }
  6860. ShaderMaterial.prototype.isShaderMaterial = true;
  6861. class Camera extends Object3D {
  6862. constructor() {
  6863. super();
  6864. this.type = 'Camera';
  6865. this.matrixWorldInverse = new Matrix4();
  6866. this.projectionMatrix = new Matrix4();
  6867. this.projectionMatrixInverse = new Matrix4();
  6868. }
  6869. copy( source, recursive ) {
  6870. super.copy( source, recursive );
  6871. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6872. this.projectionMatrix.copy( source.projectionMatrix );
  6873. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6874. return this;
  6875. }
  6876. getWorldDirection( target ) {
  6877. this.updateWorldMatrix( true, false );
  6878. const e = this.matrixWorld.elements;
  6879. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6880. }
  6881. updateMatrixWorld( force ) {
  6882. super.updateMatrixWorld( force );
  6883. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6884. }
  6885. updateWorldMatrix( updateParents, updateChildren ) {
  6886. super.updateWorldMatrix( updateParents, updateChildren );
  6887. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6888. }
  6889. clone() {
  6890. return new this.constructor().copy( this );
  6891. }
  6892. }
  6893. Camera.prototype.isCamera = true;
  6894. class PerspectiveCamera extends Camera {
  6895. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6896. super();
  6897. this.type = 'PerspectiveCamera';
  6898. this.fov = fov;
  6899. this.zoom = 1;
  6900. this.near = near;
  6901. this.far = far;
  6902. this.focus = 10;
  6903. this.aspect = aspect;
  6904. this.view = null;
  6905. this.filmGauge = 35; // width of the film (default in millimeters)
  6906. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6907. this.updateProjectionMatrix();
  6908. }
  6909. copy( source, recursive ) {
  6910. super.copy( source, recursive );
  6911. this.fov = source.fov;
  6912. this.zoom = source.zoom;
  6913. this.near = source.near;
  6914. this.far = source.far;
  6915. this.focus = source.focus;
  6916. this.aspect = source.aspect;
  6917. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6918. this.filmGauge = source.filmGauge;
  6919. this.filmOffset = source.filmOffset;
  6920. return this;
  6921. }
  6922. /**
  6923. * Sets the FOV by focal length in respect to the current .filmGauge.
  6924. *
  6925. * The default film gauge is 35, so that the focal length can be specified for
  6926. * a 35mm (full frame) camera.
  6927. *
  6928. * Values for focal length and film gauge must have the same unit.
  6929. */
  6930. setFocalLength( focalLength ) {
  6931. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6932. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6933. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6934. this.updateProjectionMatrix();
  6935. }
  6936. /**
  6937. * Calculates the focal length from the current .fov and .filmGauge.
  6938. */
  6939. getFocalLength() {
  6940. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6941. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6942. }
  6943. getEffectiveFOV() {
  6944. return RAD2DEG * 2 * Math.atan(
  6945. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6946. }
  6947. getFilmWidth() {
  6948. // film not completely covered in portrait format (aspect < 1)
  6949. return this.filmGauge * Math.min( this.aspect, 1 );
  6950. }
  6951. getFilmHeight() {
  6952. // film not completely covered in landscape format (aspect > 1)
  6953. return this.filmGauge / Math.max( this.aspect, 1 );
  6954. }
  6955. /**
  6956. * Sets an offset in a larger frustum. This is useful for multi-window or
  6957. * multi-monitor/multi-machine setups.
  6958. *
  6959. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6960. * the monitors are in grid like this
  6961. *
  6962. * +---+---+---+
  6963. * | A | B | C |
  6964. * +---+---+---+
  6965. * | D | E | F |
  6966. * +---+---+---+
  6967. *
  6968. * then for each monitor you would call it like this
  6969. *
  6970. * const w = 1920;
  6971. * const h = 1080;
  6972. * const fullWidth = w * 3;
  6973. * const fullHeight = h * 2;
  6974. *
  6975. * --A--
  6976. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6977. * --B--
  6978. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6979. * --C--
  6980. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6981. * --D--
  6982. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6983. * --E--
  6984. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6985. * --F--
  6986. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6987. *
  6988. * Note there is no reason monitors have to be the same size or in a grid.
  6989. */
  6990. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  6991. this.aspect = fullWidth / fullHeight;
  6992. if ( this.view === null ) {
  6993. this.view = {
  6994. enabled: true,
  6995. fullWidth: 1,
  6996. fullHeight: 1,
  6997. offsetX: 0,
  6998. offsetY: 0,
  6999. width: 1,
  7000. height: 1
  7001. };
  7002. }
  7003. this.view.enabled = true;
  7004. this.view.fullWidth = fullWidth;
  7005. this.view.fullHeight = fullHeight;
  7006. this.view.offsetX = x;
  7007. this.view.offsetY = y;
  7008. this.view.width = width;
  7009. this.view.height = height;
  7010. this.updateProjectionMatrix();
  7011. }
  7012. clearViewOffset() {
  7013. if ( this.view !== null ) {
  7014. this.view.enabled = false;
  7015. }
  7016. this.updateProjectionMatrix();
  7017. }
  7018. updateProjectionMatrix() {
  7019. const near = this.near;
  7020. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7021. let height = 2 * top;
  7022. let width = this.aspect * height;
  7023. let left = - 0.5 * width;
  7024. const view = this.view;
  7025. if ( this.view !== null && this.view.enabled ) {
  7026. const fullWidth = view.fullWidth,
  7027. fullHeight = view.fullHeight;
  7028. left += view.offsetX * width / fullWidth;
  7029. top -= view.offsetY * height / fullHeight;
  7030. width *= view.width / fullWidth;
  7031. height *= view.height / fullHeight;
  7032. }
  7033. const skew = this.filmOffset;
  7034. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7035. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7036. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7037. }
  7038. toJSON( meta ) {
  7039. const data = super.toJSON( meta );
  7040. data.object.fov = this.fov;
  7041. data.object.zoom = this.zoom;
  7042. data.object.near = this.near;
  7043. data.object.far = this.far;
  7044. data.object.focus = this.focus;
  7045. data.object.aspect = this.aspect;
  7046. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7047. data.object.filmGauge = this.filmGauge;
  7048. data.object.filmOffset = this.filmOffset;
  7049. return data;
  7050. }
  7051. }
  7052. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7053. const fov = 90, aspect = 1;
  7054. class CubeCamera extends Object3D {
  7055. constructor( near, far, renderTarget ) {
  7056. super();
  7057. this.type = 'CubeCamera';
  7058. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7059. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7060. return;
  7061. }
  7062. this.renderTarget = renderTarget;
  7063. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7064. cameraPX.layers = this.layers;
  7065. cameraPX.up.set( 0, - 1, 0 );
  7066. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7067. this.add( cameraPX );
  7068. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7069. cameraNX.layers = this.layers;
  7070. cameraNX.up.set( 0, - 1, 0 );
  7071. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7072. this.add( cameraNX );
  7073. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7074. cameraPY.layers = this.layers;
  7075. cameraPY.up.set( 0, 0, 1 );
  7076. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7077. this.add( cameraPY );
  7078. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7079. cameraNY.layers = this.layers;
  7080. cameraNY.up.set( 0, 0, - 1 );
  7081. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7082. this.add( cameraNY );
  7083. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7084. cameraPZ.layers = this.layers;
  7085. cameraPZ.up.set( 0, - 1, 0 );
  7086. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7087. this.add( cameraPZ );
  7088. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7089. cameraNZ.layers = this.layers;
  7090. cameraNZ.up.set( 0, - 1, 0 );
  7091. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7092. this.add( cameraNZ );
  7093. }
  7094. update( renderer, scene ) {
  7095. if ( this.parent === null ) this.updateMatrixWorld();
  7096. const renderTarget = this.renderTarget;
  7097. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7098. const currentXrEnabled = renderer.xr.enabled;
  7099. const currentRenderTarget = renderer.getRenderTarget();
  7100. renderer.xr.enabled = false;
  7101. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7102. renderTarget.texture.generateMipmaps = false;
  7103. renderer.setRenderTarget( renderTarget, 0 );
  7104. renderer.render( scene, cameraPX );
  7105. renderer.setRenderTarget( renderTarget, 1 );
  7106. renderer.render( scene, cameraNX );
  7107. renderer.setRenderTarget( renderTarget, 2 );
  7108. renderer.render( scene, cameraPY );
  7109. renderer.setRenderTarget( renderTarget, 3 );
  7110. renderer.render( scene, cameraNY );
  7111. renderer.setRenderTarget( renderTarget, 4 );
  7112. renderer.render( scene, cameraPZ );
  7113. renderTarget.texture.generateMipmaps = generateMipmaps;
  7114. renderer.setRenderTarget( renderTarget, 5 );
  7115. renderer.render( scene, cameraNZ );
  7116. renderer.setRenderTarget( currentRenderTarget );
  7117. renderer.xr.enabled = currentXrEnabled;
  7118. renderTarget.texture.needsPMREMUpdate = true;
  7119. }
  7120. }
  7121. class CubeTexture extends Texture {
  7122. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7123. images = images !== undefined ? images : [];
  7124. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7125. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7126. this.flipY = false;
  7127. }
  7128. get images() {
  7129. return this.image;
  7130. }
  7131. set images( value ) {
  7132. this.image = value;
  7133. }
  7134. }
  7135. CubeTexture.prototype.isCubeTexture = true;
  7136. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7137. constructor( size, options, dummy ) {
  7138. if ( Number.isInteger( options ) ) {
  7139. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7140. options = dummy;
  7141. }
  7142. super( size, size, options );
  7143. options = options || {};
  7144. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7145. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7146. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7147. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7148. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7149. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7150. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7151. this.texture.isRenderTargetTexture = true;
  7152. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7153. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7154. }
  7155. fromEquirectangularTexture( renderer, texture ) {
  7156. this.texture.type = texture.type;
  7157. this.texture.format = RGBAFormat; // see #18859
  7158. this.texture.encoding = texture.encoding;
  7159. this.texture.generateMipmaps = texture.generateMipmaps;
  7160. this.texture.minFilter = texture.minFilter;
  7161. this.texture.magFilter = texture.magFilter;
  7162. const shader = {
  7163. uniforms: {
  7164. tEquirect: { value: null },
  7165. },
  7166. vertexShader: /* glsl */`
  7167. varying vec3 vWorldDirection;
  7168. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7169. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7170. }
  7171. void main() {
  7172. vWorldDirection = transformDirection( position, modelMatrix );
  7173. #include <begin_vertex>
  7174. #include <project_vertex>
  7175. }
  7176. `,
  7177. fragmentShader: /* glsl */`
  7178. uniform sampler2D tEquirect;
  7179. varying vec3 vWorldDirection;
  7180. #include <common>
  7181. void main() {
  7182. vec3 direction = normalize( vWorldDirection );
  7183. vec2 sampleUV = equirectUv( direction );
  7184. gl_FragColor = texture2D( tEquirect, sampleUV );
  7185. }
  7186. `
  7187. };
  7188. const geometry = new BoxGeometry( 5, 5, 5 );
  7189. const material = new ShaderMaterial( {
  7190. name: 'CubemapFromEquirect',
  7191. uniforms: cloneUniforms( shader.uniforms ),
  7192. vertexShader: shader.vertexShader,
  7193. fragmentShader: shader.fragmentShader,
  7194. side: BackSide,
  7195. blending: NoBlending
  7196. } );
  7197. material.uniforms.tEquirect.value = texture;
  7198. const mesh = new Mesh( geometry, material );
  7199. const currentMinFilter = texture.minFilter;
  7200. // Avoid blurred poles
  7201. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7202. const camera = new CubeCamera( 1, 10, this );
  7203. camera.update( renderer, mesh );
  7204. texture.minFilter = currentMinFilter;
  7205. mesh.geometry.dispose();
  7206. mesh.material.dispose();
  7207. return this;
  7208. }
  7209. clear( renderer, color, depth, stencil ) {
  7210. const currentRenderTarget = renderer.getRenderTarget();
  7211. for ( let i = 0; i < 6; i ++ ) {
  7212. renderer.setRenderTarget( this, i );
  7213. renderer.clear( color, depth, stencil );
  7214. }
  7215. renderer.setRenderTarget( currentRenderTarget );
  7216. }
  7217. }
  7218. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7219. const _vector1 = /*@__PURE__*/ new Vector3();
  7220. const _vector2 = /*@__PURE__*/ new Vector3();
  7221. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7222. class Plane {
  7223. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7224. // normal is assumed to be normalized
  7225. this.normal = normal;
  7226. this.constant = constant;
  7227. }
  7228. set( normal, constant ) {
  7229. this.normal.copy( normal );
  7230. this.constant = constant;
  7231. return this;
  7232. }
  7233. setComponents( x, y, z, w ) {
  7234. this.normal.set( x, y, z );
  7235. this.constant = w;
  7236. return this;
  7237. }
  7238. setFromNormalAndCoplanarPoint( normal, point ) {
  7239. this.normal.copy( normal );
  7240. this.constant = - point.dot( this.normal );
  7241. return this;
  7242. }
  7243. setFromCoplanarPoints( a, b, c ) {
  7244. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7245. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7246. this.setFromNormalAndCoplanarPoint( normal, a );
  7247. return this;
  7248. }
  7249. copy( plane ) {
  7250. this.normal.copy( plane.normal );
  7251. this.constant = plane.constant;
  7252. return this;
  7253. }
  7254. normalize() {
  7255. // Note: will lead to a divide by zero if the plane is invalid.
  7256. const inverseNormalLength = 1.0 / this.normal.length();
  7257. this.normal.multiplyScalar( inverseNormalLength );
  7258. this.constant *= inverseNormalLength;
  7259. return this;
  7260. }
  7261. negate() {
  7262. this.constant *= - 1;
  7263. this.normal.negate();
  7264. return this;
  7265. }
  7266. distanceToPoint( point ) {
  7267. return this.normal.dot( point ) + this.constant;
  7268. }
  7269. distanceToSphere( sphere ) {
  7270. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7271. }
  7272. projectPoint( point, target ) {
  7273. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7274. }
  7275. intersectLine( line, target ) {
  7276. const direction = line.delta( _vector1 );
  7277. const denominator = this.normal.dot( direction );
  7278. if ( denominator === 0 ) {
  7279. // line is coplanar, return origin
  7280. if ( this.distanceToPoint( line.start ) === 0 ) {
  7281. return target.copy( line.start );
  7282. }
  7283. // Unsure if this is the correct method to handle this case.
  7284. return null;
  7285. }
  7286. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7287. if ( t < 0 || t > 1 ) {
  7288. return null;
  7289. }
  7290. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7291. }
  7292. intersectsLine( line ) {
  7293. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7294. const startSign = this.distanceToPoint( line.start );
  7295. const endSign = this.distanceToPoint( line.end );
  7296. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7297. }
  7298. intersectsBox( box ) {
  7299. return box.intersectsPlane( this );
  7300. }
  7301. intersectsSphere( sphere ) {
  7302. return sphere.intersectsPlane( this );
  7303. }
  7304. coplanarPoint( target ) {
  7305. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7306. }
  7307. applyMatrix4( matrix, optionalNormalMatrix ) {
  7308. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7309. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7310. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7311. this.constant = - referencePoint.dot( normal );
  7312. return this;
  7313. }
  7314. translate( offset ) {
  7315. this.constant -= offset.dot( this.normal );
  7316. return this;
  7317. }
  7318. equals( plane ) {
  7319. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7320. }
  7321. clone() {
  7322. return new this.constructor().copy( this );
  7323. }
  7324. }
  7325. Plane.prototype.isPlane = true;
  7326. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7327. const _vector$7 = /*@__PURE__*/ new Vector3();
  7328. class Frustum {
  7329. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7330. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7331. }
  7332. set( p0, p1, p2, p3, p4, p5 ) {
  7333. const planes = this.planes;
  7334. planes[ 0 ].copy( p0 );
  7335. planes[ 1 ].copy( p1 );
  7336. planes[ 2 ].copy( p2 );
  7337. planes[ 3 ].copy( p3 );
  7338. planes[ 4 ].copy( p4 );
  7339. planes[ 5 ].copy( p5 );
  7340. return this;
  7341. }
  7342. copy( frustum ) {
  7343. const planes = this.planes;
  7344. for ( let i = 0; i < 6; i ++ ) {
  7345. planes[ i ].copy( frustum.planes[ i ] );
  7346. }
  7347. return this;
  7348. }
  7349. setFromProjectionMatrix( m ) {
  7350. const planes = this.planes;
  7351. const me = m.elements;
  7352. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7353. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7354. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7355. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7356. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7357. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7358. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7359. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7360. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7361. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7362. return this;
  7363. }
  7364. intersectsObject( object ) {
  7365. const geometry = object.geometry;
  7366. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7367. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7368. return this.intersectsSphere( _sphere$2 );
  7369. }
  7370. intersectsSprite( sprite ) {
  7371. _sphere$2.center.set( 0, 0, 0 );
  7372. _sphere$2.radius = 0.7071067811865476;
  7373. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7374. return this.intersectsSphere( _sphere$2 );
  7375. }
  7376. intersectsSphere( sphere ) {
  7377. const planes = this.planes;
  7378. const center = sphere.center;
  7379. const negRadius = - sphere.radius;
  7380. for ( let i = 0; i < 6; i ++ ) {
  7381. const distance = planes[ i ].distanceToPoint( center );
  7382. if ( distance < negRadius ) {
  7383. return false;
  7384. }
  7385. }
  7386. return true;
  7387. }
  7388. intersectsBox( box ) {
  7389. const planes = this.planes;
  7390. for ( let i = 0; i < 6; i ++ ) {
  7391. const plane = planes[ i ];
  7392. // corner at max distance
  7393. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7394. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7395. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7396. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7397. return false;
  7398. }
  7399. }
  7400. return true;
  7401. }
  7402. containsPoint( point ) {
  7403. const planes = this.planes;
  7404. for ( let i = 0; i < 6; i ++ ) {
  7405. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7406. return false;
  7407. }
  7408. }
  7409. return true;
  7410. }
  7411. clone() {
  7412. return new this.constructor().copy( this );
  7413. }
  7414. }
  7415. function WebGLAnimation() {
  7416. let context = null;
  7417. let isAnimating = false;
  7418. let animationLoop = null;
  7419. let requestId = null;
  7420. function onAnimationFrame( time, frame ) {
  7421. animationLoop( time, frame );
  7422. requestId = context.requestAnimationFrame( onAnimationFrame );
  7423. }
  7424. return {
  7425. start: function () {
  7426. if ( isAnimating === true ) return;
  7427. if ( animationLoop === null ) return;
  7428. requestId = context.requestAnimationFrame( onAnimationFrame );
  7429. isAnimating = true;
  7430. },
  7431. stop: function () {
  7432. context.cancelAnimationFrame( requestId );
  7433. isAnimating = false;
  7434. },
  7435. setAnimationLoop: function ( callback ) {
  7436. animationLoop = callback;
  7437. },
  7438. setContext: function ( value ) {
  7439. context = value;
  7440. }
  7441. };
  7442. }
  7443. function WebGLAttributes( gl, capabilities ) {
  7444. const isWebGL2 = capabilities.isWebGL2;
  7445. const buffers = new WeakMap();
  7446. function createBuffer( attribute, bufferType ) {
  7447. const array = attribute.array;
  7448. const usage = attribute.usage;
  7449. const buffer = gl.createBuffer();
  7450. gl.bindBuffer( bufferType, buffer );
  7451. gl.bufferData( bufferType, array, usage );
  7452. attribute.onUploadCallback();
  7453. let type = 5126;
  7454. if ( array instanceof Float32Array ) {
  7455. type = 5126;
  7456. } else if ( array instanceof Float64Array ) {
  7457. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7458. } else if ( array instanceof Uint16Array ) {
  7459. if ( attribute.isFloat16BufferAttribute ) {
  7460. if ( isWebGL2 ) {
  7461. type = 5131;
  7462. } else {
  7463. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7464. }
  7465. } else {
  7466. type = 5123;
  7467. }
  7468. } else if ( array instanceof Int16Array ) {
  7469. type = 5122;
  7470. } else if ( array instanceof Uint32Array ) {
  7471. type = 5125;
  7472. } else if ( array instanceof Int32Array ) {
  7473. type = 5124;
  7474. } else if ( array instanceof Int8Array ) {
  7475. type = 5120;
  7476. } else if ( array instanceof Uint8Array ) {
  7477. type = 5121;
  7478. } else if ( array instanceof Uint8ClampedArray ) {
  7479. type = 5121;
  7480. }
  7481. return {
  7482. buffer: buffer,
  7483. type: type,
  7484. bytesPerElement: array.BYTES_PER_ELEMENT,
  7485. version: attribute.version
  7486. };
  7487. }
  7488. function updateBuffer( buffer, attribute, bufferType ) {
  7489. const array = attribute.array;
  7490. const updateRange = attribute.updateRange;
  7491. gl.bindBuffer( bufferType, buffer );
  7492. if ( updateRange.count === - 1 ) {
  7493. // Not using update ranges
  7494. gl.bufferSubData( bufferType, 0, array );
  7495. } else {
  7496. if ( isWebGL2 ) {
  7497. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7498. array, updateRange.offset, updateRange.count );
  7499. } else {
  7500. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7501. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7502. }
  7503. updateRange.count = - 1; // reset range
  7504. }
  7505. }
  7506. //
  7507. function get( attribute ) {
  7508. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7509. return buffers.get( attribute );
  7510. }
  7511. function remove( attribute ) {
  7512. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7513. const data = buffers.get( attribute );
  7514. if ( data ) {
  7515. gl.deleteBuffer( data.buffer );
  7516. buffers.delete( attribute );
  7517. }
  7518. }
  7519. function update( attribute, bufferType ) {
  7520. if ( attribute.isGLBufferAttribute ) {
  7521. const cached = buffers.get( attribute );
  7522. if ( ! cached || cached.version < attribute.version ) {
  7523. buffers.set( attribute, {
  7524. buffer: attribute.buffer,
  7525. type: attribute.type,
  7526. bytesPerElement: attribute.elementSize,
  7527. version: attribute.version
  7528. } );
  7529. }
  7530. return;
  7531. }
  7532. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7533. const data = buffers.get( attribute );
  7534. if ( data === undefined ) {
  7535. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7536. } else if ( data.version < attribute.version ) {
  7537. updateBuffer( data.buffer, attribute, bufferType );
  7538. data.version = attribute.version;
  7539. }
  7540. }
  7541. return {
  7542. get: get,
  7543. remove: remove,
  7544. update: update
  7545. };
  7546. }
  7547. class PlaneGeometry extends BufferGeometry {
  7548. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7549. super();
  7550. this.type = 'PlaneGeometry';
  7551. this.parameters = {
  7552. width: width,
  7553. height: height,
  7554. widthSegments: widthSegments,
  7555. heightSegments: heightSegments
  7556. };
  7557. const width_half = width / 2;
  7558. const height_half = height / 2;
  7559. const gridX = Math.floor( widthSegments );
  7560. const gridY = Math.floor( heightSegments );
  7561. const gridX1 = gridX + 1;
  7562. const gridY1 = gridY + 1;
  7563. const segment_width = width / gridX;
  7564. const segment_height = height / gridY;
  7565. //
  7566. const indices = [];
  7567. const vertices = [];
  7568. const normals = [];
  7569. const uvs = [];
  7570. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7571. const y = iy * segment_height - height_half;
  7572. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7573. const x = ix * segment_width - width_half;
  7574. vertices.push( x, - y, 0 );
  7575. normals.push( 0, 0, 1 );
  7576. uvs.push( ix / gridX );
  7577. uvs.push( 1 - ( iy / gridY ) );
  7578. }
  7579. }
  7580. for ( let iy = 0; iy < gridY; iy ++ ) {
  7581. for ( let ix = 0; ix < gridX; ix ++ ) {
  7582. const a = ix + gridX1 * iy;
  7583. const b = ix + gridX1 * ( iy + 1 );
  7584. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7585. const d = ( ix + 1 ) + gridX1 * iy;
  7586. indices.push( a, b, d );
  7587. indices.push( b, c, d );
  7588. }
  7589. }
  7590. this.setIndex( indices );
  7591. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7592. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7593. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7594. }
  7595. static fromJSON( data ) {
  7596. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7597. }
  7598. }
  7599. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7600. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7601. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7602. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7603. 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";
  7604. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7605. var begin_vertex = "vec3 transformed = vec3( position );";
  7606. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7607. 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";
  7608. 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";
  7609. 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";
  7610. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7611. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7612. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7613. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7614. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7615. 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";
  7616. 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";
  7617. 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}";
  7618. 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 ) + 0.5;\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\treturn texture2D( envMap, uv ).rgb;\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";
  7619. 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";
  7620. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7621. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7622. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7623. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7624. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7625. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  7626. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7627. 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";
  7628. 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";
  7629. 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";
  7630. 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";
  7631. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7632. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7633. 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";
  7634. 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";
  7635. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7636. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7637. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7638. 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";
  7639. 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";
  7640. 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";
  7641. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7642. 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)";
  7643. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7644. 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)";
  7645. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7646. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7647. 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";
  7648. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\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";
  7649. 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";
  7650. 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";
  7651. 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";
  7652. 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";
  7653. 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";
  7654. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7655. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7656. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7657. 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";
  7658. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7659. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7660. 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";
  7661. 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";
  7662. 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";
  7663. 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;";
  7664. 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";
  7665. 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";
  7666. 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";
  7667. 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";
  7668. 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";
  7669. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7670. 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";
  7671. 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";
  7672. 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 );";
  7673. 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}";
  7674. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7675. 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;";
  7676. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7677. 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";
  7678. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7679. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7680. 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";
  7681. 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";
  7682. 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";
  7683. 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}";
  7684. 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";
  7685. 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";
  7686. 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";
  7687. 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";
  7688. 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";
  7689. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7690. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7691. 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; }";
  7692. 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";
  7693. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef 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( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7694. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7695. 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";
  7696. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7697. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7698. 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";
  7699. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7700. 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";
  7701. 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}";
  7702. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7703. 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}";
  7704. 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}";
  7705. 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}";
  7706. 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}";
  7707. 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}";
  7708. 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}";
  7709. 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}";
  7710. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7711. 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}";
  7712. 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}";
  7713. 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}";
  7714. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity;\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}";
  7715. 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}";
  7716. 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}";
  7717. 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}";
  7718. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7719. 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}";
  7720. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  7721. 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}";
  7722. 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}";
  7723. 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}";
  7724. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7725. 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}";
  7726. 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}";
  7727. 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}";
  7728. 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}";
  7729. 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}";
  7730. 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}";
  7731. 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}";
  7732. 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}";
  7733. const ShaderChunk = {
  7734. alphamap_fragment: alphamap_fragment,
  7735. alphamap_pars_fragment: alphamap_pars_fragment,
  7736. alphatest_fragment: alphatest_fragment,
  7737. alphatest_pars_fragment: alphatest_pars_fragment,
  7738. aomap_fragment: aomap_fragment,
  7739. aomap_pars_fragment: aomap_pars_fragment,
  7740. begin_vertex: begin_vertex,
  7741. beginnormal_vertex: beginnormal_vertex,
  7742. bsdfs: bsdfs,
  7743. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7744. clipping_planes_fragment: clipping_planes_fragment,
  7745. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7746. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7747. clipping_planes_vertex: clipping_planes_vertex,
  7748. color_fragment: color_fragment,
  7749. color_pars_fragment: color_pars_fragment,
  7750. color_pars_vertex: color_pars_vertex,
  7751. color_vertex: color_vertex,
  7752. common: common,
  7753. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7754. defaultnormal_vertex: defaultnormal_vertex,
  7755. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7756. displacementmap_vertex: displacementmap_vertex,
  7757. emissivemap_fragment: emissivemap_fragment,
  7758. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7759. encodings_fragment: encodings_fragment,
  7760. encodings_pars_fragment: encodings_pars_fragment,
  7761. envmap_fragment: envmap_fragment,
  7762. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7763. envmap_pars_fragment: envmap_pars_fragment,
  7764. envmap_pars_vertex: envmap_pars_vertex,
  7765. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7766. envmap_vertex: envmap_vertex,
  7767. fog_vertex: fog_vertex,
  7768. fog_pars_vertex: fog_pars_vertex,
  7769. fog_fragment: fog_fragment,
  7770. fog_pars_fragment: fog_pars_fragment,
  7771. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7772. lightmap_fragment: lightmap_fragment,
  7773. lightmap_pars_fragment: lightmap_pars_fragment,
  7774. lights_lambert_vertex: lights_lambert_vertex,
  7775. lights_pars_begin: lights_pars_begin,
  7776. lights_toon_fragment: lights_toon_fragment,
  7777. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7778. lights_phong_fragment: lights_phong_fragment,
  7779. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7780. lights_physical_fragment: lights_physical_fragment,
  7781. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7782. lights_fragment_begin: lights_fragment_begin,
  7783. lights_fragment_maps: lights_fragment_maps,
  7784. lights_fragment_end: lights_fragment_end,
  7785. logdepthbuf_fragment: logdepthbuf_fragment,
  7786. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7787. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7788. logdepthbuf_vertex: logdepthbuf_vertex,
  7789. map_fragment: map_fragment,
  7790. map_pars_fragment: map_pars_fragment,
  7791. map_particle_fragment: map_particle_fragment,
  7792. map_particle_pars_fragment: map_particle_pars_fragment,
  7793. metalnessmap_fragment: metalnessmap_fragment,
  7794. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7795. morphnormal_vertex: morphnormal_vertex,
  7796. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7797. morphtarget_vertex: morphtarget_vertex,
  7798. normal_fragment_begin: normal_fragment_begin,
  7799. normal_fragment_maps: normal_fragment_maps,
  7800. normal_pars_fragment: normal_pars_fragment,
  7801. normal_pars_vertex: normal_pars_vertex,
  7802. normal_vertex: normal_vertex,
  7803. normalmap_pars_fragment: normalmap_pars_fragment,
  7804. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7805. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7806. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7807. output_fragment: output_fragment,
  7808. packing: packing,
  7809. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7810. project_vertex: project_vertex,
  7811. dithering_fragment: dithering_fragment,
  7812. dithering_pars_fragment: dithering_pars_fragment,
  7813. roughnessmap_fragment: roughnessmap_fragment,
  7814. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7815. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7816. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7817. shadowmap_vertex: shadowmap_vertex,
  7818. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7819. skinbase_vertex: skinbase_vertex,
  7820. skinning_pars_vertex: skinning_pars_vertex,
  7821. skinning_vertex: skinning_vertex,
  7822. skinnormal_vertex: skinnormal_vertex,
  7823. specularmap_fragment: specularmap_fragment,
  7824. specularmap_pars_fragment: specularmap_pars_fragment,
  7825. tonemapping_fragment: tonemapping_fragment,
  7826. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7827. transmission_fragment: transmission_fragment,
  7828. transmission_pars_fragment: transmission_pars_fragment,
  7829. uv_pars_fragment: uv_pars_fragment,
  7830. uv_pars_vertex: uv_pars_vertex,
  7831. uv_vertex: uv_vertex,
  7832. uv2_pars_fragment: uv2_pars_fragment,
  7833. uv2_pars_vertex: uv2_pars_vertex,
  7834. uv2_vertex: uv2_vertex,
  7835. worldpos_vertex: worldpos_vertex,
  7836. background_vert: vertex$g,
  7837. background_frag: fragment$g,
  7838. cube_vert: vertex$f,
  7839. cube_frag: fragment$f,
  7840. depth_vert: vertex$e,
  7841. depth_frag: fragment$e,
  7842. distanceRGBA_vert: vertex$d,
  7843. distanceRGBA_frag: fragment$d,
  7844. equirect_vert: vertex$c,
  7845. equirect_frag: fragment$c,
  7846. linedashed_vert: vertex$b,
  7847. linedashed_frag: fragment$b,
  7848. meshbasic_vert: vertex$a,
  7849. meshbasic_frag: fragment$a,
  7850. meshlambert_vert: vertex$9,
  7851. meshlambert_frag: fragment$9,
  7852. meshmatcap_vert: vertex$8,
  7853. meshmatcap_frag: fragment$8,
  7854. meshnormal_vert: vertex$7,
  7855. meshnormal_frag: fragment$7,
  7856. meshphong_vert: vertex$6,
  7857. meshphong_frag: fragment$6,
  7858. meshphysical_vert: vertex$5,
  7859. meshphysical_frag: fragment$5,
  7860. meshtoon_vert: vertex$4,
  7861. meshtoon_frag: fragment$4,
  7862. points_vert: vertex$3,
  7863. points_frag: fragment$3,
  7864. shadow_vert: vertex$2,
  7865. shadow_frag: fragment$2,
  7866. sprite_vert: vertex$1,
  7867. sprite_frag: fragment$1
  7868. };
  7869. /**
  7870. * Uniforms library for shared webgl shaders
  7871. */
  7872. const UniformsLib = {
  7873. common: {
  7874. diffuse: { value: new Color( 0xffffff ) },
  7875. opacity: { value: 1.0 },
  7876. map: { value: null },
  7877. uvTransform: { value: new Matrix3() },
  7878. uv2Transform: { value: new Matrix3() },
  7879. alphaMap: { value: null },
  7880. alphaTest: { value: 0 }
  7881. },
  7882. specularmap: {
  7883. specularMap: { value: null },
  7884. },
  7885. envmap: {
  7886. envMap: { value: null },
  7887. flipEnvMap: { value: - 1 },
  7888. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7889. ior: { value: 1.5 }, // standard, physical
  7890. refractionRatio: { value: 0.98 }
  7891. },
  7892. aomap: {
  7893. aoMap: { value: null },
  7894. aoMapIntensity: { value: 1 }
  7895. },
  7896. lightmap: {
  7897. lightMap: { value: null },
  7898. lightMapIntensity: { value: 1 }
  7899. },
  7900. emissivemap: {
  7901. emissiveMap: { value: null }
  7902. },
  7903. bumpmap: {
  7904. bumpMap: { value: null },
  7905. bumpScale: { value: 1 }
  7906. },
  7907. normalmap: {
  7908. normalMap: { value: null },
  7909. normalScale: { value: new Vector2( 1, 1 ) }
  7910. },
  7911. displacementmap: {
  7912. displacementMap: { value: null },
  7913. displacementScale: { value: 1 },
  7914. displacementBias: { value: 0 }
  7915. },
  7916. roughnessmap: {
  7917. roughnessMap: { value: null }
  7918. },
  7919. metalnessmap: {
  7920. metalnessMap: { value: null }
  7921. },
  7922. gradientmap: {
  7923. gradientMap: { value: null }
  7924. },
  7925. fog: {
  7926. fogDensity: { value: 0.00025 },
  7927. fogNear: { value: 1 },
  7928. fogFar: { value: 2000 },
  7929. fogColor: { value: new Color( 0xffffff ) }
  7930. },
  7931. lights: {
  7932. ambientLightColor: { value: [] },
  7933. lightProbe: { value: [] },
  7934. directionalLights: { value: [], properties: {
  7935. direction: {},
  7936. color: {}
  7937. } },
  7938. directionalLightShadows: { value: [], properties: {
  7939. shadowBias: {},
  7940. shadowNormalBias: {},
  7941. shadowRadius: {},
  7942. shadowMapSize: {}
  7943. } },
  7944. directionalShadowMap: { value: [] },
  7945. directionalShadowMatrix: { value: [] },
  7946. spotLights: { value: [], properties: {
  7947. color: {},
  7948. position: {},
  7949. direction: {},
  7950. distance: {},
  7951. coneCos: {},
  7952. penumbraCos: {},
  7953. decay: {}
  7954. } },
  7955. spotLightShadows: { value: [], properties: {
  7956. shadowBias: {},
  7957. shadowNormalBias: {},
  7958. shadowRadius: {},
  7959. shadowMapSize: {}
  7960. } },
  7961. spotShadowMap: { value: [] },
  7962. spotShadowMatrix: { value: [] },
  7963. pointLights: { value: [], properties: {
  7964. color: {},
  7965. position: {},
  7966. decay: {},
  7967. distance: {}
  7968. } },
  7969. pointLightShadows: { value: [], properties: {
  7970. shadowBias: {},
  7971. shadowNormalBias: {},
  7972. shadowRadius: {},
  7973. shadowMapSize: {},
  7974. shadowCameraNear: {},
  7975. shadowCameraFar: {}
  7976. } },
  7977. pointShadowMap: { value: [] },
  7978. pointShadowMatrix: { value: [] },
  7979. hemisphereLights: { value: [], properties: {
  7980. direction: {},
  7981. skyColor: {},
  7982. groundColor: {}
  7983. } },
  7984. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7985. rectAreaLights: { value: [], properties: {
  7986. color: {},
  7987. position: {},
  7988. width: {},
  7989. height: {}
  7990. } },
  7991. ltc_1: { value: null },
  7992. ltc_2: { value: null }
  7993. },
  7994. points: {
  7995. diffuse: { value: new Color( 0xffffff ) },
  7996. opacity: { value: 1.0 },
  7997. size: { value: 1.0 },
  7998. scale: { value: 1.0 },
  7999. map: { value: null },
  8000. alphaMap: { value: null },
  8001. alphaTest: { value: 0 },
  8002. uvTransform: { value: new Matrix3() }
  8003. },
  8004. sprite: {
  8005. diffuse: { value: new Color( 0xffffff ) },
  8006. opacity: { value: 1.0 },
  8007. center: { value: new Vector2( 0.5, 0.5 ) },
  8008. rotation: { value: 0.0 },
  8009. map: { value: null },
  8010. alphaMap: { value: null },
  8011. alphaTest: { value: 0 },
  8012. uvTransform: { value: new Matrix3() }
  8013. }
  8014. };
  8015. const ShaderLib = {
  8016. basic: {
  8017. uniforms: mergeUniforms( [
  8018. UniformsLib.common,
  8019. UniformsLib.specularmap,
  8020. UniformsLib.envmap,
  8021. UniformsLib.aomap,
  8022. UniformsLib.lightmap,
  8023. UniformsLib.fog
  8024. ] ),
  8025. vertexShader: ShaderChunk.meshbasic_vert,
  8026. fragmentShader: ShaderChunk.meshbasic_frag
  8027. },
  8028. lambert: {
  8029. uniforms: mergeUniforms( [
  8030. UniformsLib.common,
  8031. UniformsLib.specularmap,
  8032. UniformsLib.envmap,
  8033. UniformsLib.aomap,
  8034. UniformsLib.lightmap,
  8035. UniformsLib.emissivemap,
  8036. UniformsLib.fog,
  8037. UniformsLib.lights,
  8038. {
  8039. emissive: { value: new Color( 0x000000 ) }
  8040. }
  8041. ] ),
  8042. vertexShader: ShaderChunk.meshlambert_vert,
  8043. fragmentShader: ShaderChunk.meshlambert_frag
  8044. },
  8045. phong: {
  8046. uniforms: mergeUniforms( [
  8047. UniformsLib.common,
  8048. UniformsLib.specularmap,
  8049. UniformsLib.envmap,
  8050. UniformsLib.aomap,
  8051. UniformsLib.lightmap,
  8052. UniformsLib.emissivemap,
  8053. UniformsLib.bumpmap,
  8054. UniformsLib.normalmap,
  8055. UniformsLib.displacementmap,
  8056. UniformsLib.fog,
  8057. UniformsLib.lights,
  8058. {
  8059. emissive: { value: new Color( 0x000000 ) },
  8060. specular: { value: new Color( 0x111111 ) },
  8061. shininess: { value: 30 }
  8062. }
  8063. ] ),
  8064. vertexShader: ShaderChunk.meshphong_vert,
  8065. fragmentShader: ShaderChunk.meshphong_frag
  8066. },
  8067. standard: {
  8068. uniforms: mergeUniforms( [
  8069. UniformsLib.common,
  8070. UniformsLib.envmap,
  8071. UniformsLib.aomap,
  8072. UniformsLib.lightmap,
  8073. UniformsLib.emissivemap,
  8074. UniformsLib.bumpmap,
  8075. UniformsLib.normalmap,
  8076. UniformsLib.displacementmap,
  8077. UniformsLib.roughnessmap,
  8078. UniformsLib.metalnessmap,
  8079. UniformsLib.fog,
  8080. UniformsLib.lights,
  8081. {
  8082. emissive: { value: new Color( 0x000000 ) },
  8083. roughness: { value: 1.0 },
  8084. metalness: { value: 0.0 },
  8085. envMapIntensity: { value: 1 } // temporary
  8086. }
  8087. ] ),
  8088. vertexShader: ShaderChunk.meshphysical_vert,
  8089. fragmentShader: ShaderChunk.meshphysical_frag
  8090. },
  8091. toon: {
  8092. uniforms: mergeUniforms( [
  8093. UniformsLib.common,
  8094. UniformsLib.aomap,
  8095. UniformsLib.lightmap,
  8096. UniformsLib.emissivemap,
  8097. UniformsLib.bumpmap,
  8098. UniformsLib.normalmap,
  8099. UniformsLib.displacementmap,
  8100. UniformsLib.gradientmap,
  8101. UniformsLib.fog,
  8102. UniformsLib.lights,
  8103. {
  8104. emissive: { value: new Color( 0x000000 ) }
  8105. }
  8106. ] ),
  8107. vertexShader: ShaderChunk.meshtoon_vert,
  8108. fragmentShader: ShaderChunk.meshtoon_frag
  8109. },
  8110. matcap: {
  8111. uniforms: mergeUniforms( [
  8112. UniformsLib.common,
  8113. UniformsLib.bumpmap,
  8114. UniformsLib.normalmap,
  8115. UniformsLib.displacementmap,
  8116. UniformsLib.fog,
  8117. {
  8118. matcap: { value: null }
  8119. }
  8120. ] ),
  8121. vertexShader: ShaderChunk.meshmatcap_vert,
  8122. fragmentShader: ShaderChunk.meshmatcap_frag
  8123. },
  8124. points: {
  8125. uniforms: mergeUniforms( [
  8126. UniformsLib.points,
  8127. UniformsLib.fog
  8128. ] ),
  8129. vertexShader: ShaderChunk.points_vert,
  8130. fragmentShader: ShaderChunk.points_frag
  8131. },
  8132. dashed: {
  8133. uniforms: mergeUniforms( [
  8134. UniformsLib.common,
  8135. UniformsLib.fog,
  8136. {
  8137. scale: { value: 1 },
  8138. dashSize: { value: 1 },
  8139. totalSize: { value: 2 }
  8140. }
  8141. ] ),
  8142. vertexShader: ShaderChunk.linedashed_vert,
  8143. fragmentShader: ShaderChunk.linedashed_frag
  8144. },
  8145. depth: {
  8146. uniforms: mergeUniforms( [
  8147. UniformsLib.common,
  8148. UniformsLib.displacementmap
  8149. ] ),
  8150. vertexShader: ShaderChunk.depth_vert,
  8151. fragmentShader: ShaderChunk.depth_frag
  8152. },
  8153. normal: {
  8154. uniforms: mergeUniforms( [
  8155. UniformsLib.common,
  8156. UniformsLib.bumpmap,
  8157. UniformsLib.normalmap,
  8158. UniformsLib.displacementmap,
  8159. {
  8160. opacity: { value: 1.0 }
  8161. }
  8162. ] ),
  8163. vertexShader: ShaderChunk.meshnormal_vert,
  8164. fragmentShader: ShaderChunk.meshnormal_frag
  8165. },
  8166. sprite: {
  8167. uniforms: mergeUniforms( [
  8168. UniformsLib.sprite,
  8169. UniformsLib.fog
  8170. ] ),
  8171. vertexShader: ShaderChunk.sprite_vert,
  8172. fragmentShader: ShaderChunk.sprite_frag
  8173. },
  8174. background: {
  8175. uniforms: {
  8176. uvTransform: { value: new Matrix3() },
  8177. t2D: { value: null },
  8178. },
  8179. vertexShader: ShaderChunk.background_vert,
  8180. fragmentShader: ShaderChunk.background_frag
  8181. },
  8182. /* -------------------------------------------------------------------------
  8183. // Cube map shader
  8184. ------------------------------------------------------------------------- */
  8185. cube: {
  8186. uniforms: mergeUniforms( [
  8187. UniformsLib.envmap,
  8188. {
  8189. opacity: { value: 1.0 }
  8190. }
  8191. ] ),
  8192. vertexShader: ShaderChunk.cube_vert,
  8193. fragmentShader: ShaderChunk.cube_frag
  8194. },
  8195. equirect: {
  8196. uniforms: {
  8197. tEquirect: { value: null },
  8198. },
  8199. vertexShader: ShaderChunk.equirect_vert,
  8200. fragmentShader: ShaderChunk.equirect_frag
  8201. },
  8202. distanceRGBA: {
  8203. uniforms: mergeUniforms( [
  8204. UniformsLib.common,
  8205. UniformsLib.displacementmap,
  8206. {
  8207. referencePosition: { value: new Vector3() },
  8208. nearDistance: { value: 1 },
  8209. farDistance: { value: 1000 }
  8210. }
  8211. ] ),
  8212. vertexShader: ShaderChunk.distanceRGBA_vert,
  8213. fragmentShader: ShaderChunk.distanceRGBA_frag
  8214. },
  8215. shadow: {
  8216. uniforms: mergeUniforms( [
  8217. UniformsLib.lights,
  8218. UniformsLib.fog,
  8219. {
  8220. color: { value: new Color( 0x00000 ) },
  8221. opacity: { value: 1.0 }
  8222. },
  8223. ] ),
  8224. vertexShader: ShaderChunk.shadow_vert,
  8225. fragmentShader: ShaderChunk.shadow_frag
  8226. }
  8227. };
  8228. ShaderLib.physical = {
  8229. uniforms: mergeUniforms( [
  8230. ShaderLib.standard.uniforms,
  8231. {
  8232. clearcoat: { value: 0 },
  8233. clearcoatMap: { value: null },
  8234. clearcoatRoughness: { value: 0 },
  8235. clearcoatRoughnessMap: { value: null },
  8236. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8237. clearcoatNormalMap: { value: null },
  8238. sheen: { value: 0 },
  8239. sheenColor: { value: new Color( 0x000000 ) },
  8240. sheenColorMap: { value: null },
  8241. sheenRoughness: { value: 1 },
  8242. sheenRoughnessMap: { value: null },
  8243. transmission: { value: 0 },
  8244. transmissionMap: { value: null },
  8245. transmissionSamplerSize: { value: new Vector2() },
  8246. transmissionSamplerMap: { value: null },
  8247. thickness: { value: 0 },
  8248. thicknessMap: { value: null },
  8249. attenuationDistance: { value: 0 },
  8250. attenuationColor: { value: new Color( 0x000000 ) },
  8251. specularIntensity: { value: 1 },
  8252. specularIntensityMap: { value: null },
  8253. specularColor: { value: new Color( 1, 1, 1 ) },
  8254. specularColorMap: { value: null },
  8255. }
  8256. ] ),
  8257. vertexShader: ShaderChunk.meshphysical_vert,
  8258. fragmentShader: ShaderChunk.meshphysical_frag
  8259. };
  8260. function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
  8261. const clearColor = new Color( 0x000000 );
  8262. let clearAlpha = alpha === true ? 0 : 1;
  8263. let planeMesh;
  8264. let boxMesh;
  8265. let currentBackground = null;
  8266. let currentBackgroundVersion = 0;
  8267. let currentTonemapping = null;
  8268. function render( renderList, scene ) {
  8269. let forceClear = false;
  8270. let background = scene.isScene === true ? scene.background : null;
  8271. if ( background && background.isTexture ) {
  8272. background = cubemaps.get( background );
  8273. }
  8274. // Ignore background in AR
  8275. // TODO: Reconsider this.
  8276. const xr = renderer.xr;
  8277. const session = xr.getSession && xr.getSession();
  8278. if ( session && session.environmentBlendMode === 'additive' ) {
  8279. background = null;
  8280. }
  8281. if ( background === null ) {
  8282. setClear( clearColor, clearAlpha );
  8283. } else if ( background && background.isColor ) {
  8284. setClear( background, 1 );
  8285. forceClear = true;
  8286. }
  8287. if ( renderer.autoClear || forceClear ) {
  8288. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8289. }
  8290. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8291. if ( boxMesh === undefined ) {
  8292. boxMesh = new Mesh(
  8293. new BoxGeometry( 1, 1, 1 ),
  8294. new ShaderMaterial( {
  8295. name: 'BackgroundCubeMaterial',
  8296. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8297. vertexShader: ShaderLib.cube.vertexShader,
  8298. fragmentShader: ShaderLib.cube.fragmentShader,
  8299. side: BackSide,
  8300. depthTest: false,
  8301. depthWrite: false,
  8302. fog: false
  8303. } )
  8304. );
  8305. boxMesh.geometry.deleteAttribute( 'normal' );
  8306. boxMesh.geometry.deleteAttribute( 'uv' );
  8307. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8308. this.matrixWorld.copyPosition( camera.matrixWorld );
  8309. };
  8310. // enable code injection for non-built-in material
  8311. Object.defineProperty( boxMesh.material, 'envMap', {
  8312. get: function () {
  8313. return this.uniforms.envMap.value;
  8314. }
  8315. } );
  8316. objects.update( boxMesh );
  8317. }
  8318. boxMesh.material.uniforms.envMap.value = background;
  8319. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8320. if ( currentBackground !== background ||
  8321. currentBackgroundVersion !== background.version ||
  8322. currentTonemapping !== renderer.toneMapping ) {
  8323. boxMesh.material.needsUpdate = true;
  8324. currentBackground = background;
  8325. currentBackgroundVersion = background.version;
  8326. currentTonemapping = renderer.toneMapping;
  8327. }
  8328. // push to the pre-sorted opaque render list
  8329. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8330. } else if ( background && background.isTexture ) {
  8331. if ( planeMesh === undefined ) {
  8332. planeMesh = new Mesh(
  8333. new PlaneGeometry( 2, 2 ),
  8334. new ShaderMaterial( {
  8335. name: 'BackgroundMaterial',
  8336. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8337. vertexShader: ShaderLib.background.vertexShader,
  8338. fragmentShader: ShaderLib.background.fragmentShader,
  8339. side: FrontSide,
  8340. depthTest: false,
  8341. depthWrite: false,
  8342. fog: false
  8343. } )
  8344. );
  8345. planeMesh.geometry.deleteAttribute( 'normal' );
  8346. // enable code injection for non-built-in material
  8347. Object.defineProperty( planeMesh.material, 'map', {
  8348. get: function () {
  8349. return this.uniforms.t2D.value;
  8350. }
  8351. } );
  8352. objects.update( planeMesh );
  8353. }
  8354. planeMesh.material.uniforms.t2D.value = background;
  8355. if ( background.matrixAutoUpdate === true ) {
  8356. background.updateMatrix();
  8357. }
  8358. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8359. if ( currentBackground !== background ||
  8360. currentBackgroundVersion !== background.version ||
  8361. currentTonemapping !== renderer.toneMapping ) {
  8362. planeMesh.material.needsUpdate = true;
  8363. currentBackground = background;
  8364. currentBackgroundVersion = background.version;
  8365. currentTonemapping = renderer.toneMapping;
  8366. }
  8367. // push to the pre-sorted opaque render list
  8368. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8369. }
  8370. }
  8371. function setClear( color, alpha ) {
  8372. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8373. }
  8374. return {
  8375. getClearColor: function () {
  8376. return clearColor;
  8377. },
  8378. setClearColor: function ( color, alpha = 1 ) {
  8379. clearColor.set( color );
  8380. clearAlpha = alpha;
  8381. setClear( clearColor, clearAlpha );
  8382. },
  8383. getClearAlpha: function () {
  8384. return clearAlpha;
  8385. },
  8386. setClearAlpha: function ( alpha ) {
  8387. clearAlpha = alpha;
  8388. setClear( clearColor, clearAlpha );
  8389. },
  8390. render: render
  8391. };
  8392. }
  8393. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8394. const maxVertexAttributes = gl.getParameter( 34921 );
  8395. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8396. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8397. const bindingStates = {};
  8398. const defaultState = createBindingState( null );
  8399. let currentState = defaultState;
  8400. function setup( object, material, program, geometry, index ) {
  8401. let updateBuffers = false;
  8402. if ( vaoAvailable ) {
  8403. const state = getBindingState( geometry, program, material );
  8404. if ( currentState !== state ) {
  8405. currentState = state;
  8406. bindVertexArrayObject( currentState.object );
  8407. }
  8408. updateBuffers = needsUpdate( geometry, index );
  8409. if ( updateBuffers ) saveCache( geometry, index );
  8410. } else {
  8411. const wireframe = ( material.wireframe === true );
  8412. if ( currentState.geometry !== geometry.id ||
  8413. currentState.program !== program.id ||
  8414. currentState.wireframe !== wireframe ) {
  8415. currentState.geometry = geometry.id;
  8416. currentState.program = program.id;
  8417. currentState.wireframe = wireframe;
  8418. updateBuffers = true;
  8419. }
  8420. }
  8421. if ( object.isInstancedMesh === true ) {
  8422. updateBuffers = true;
  8423. }
  8424. if ( index !== null ) {
  8425. attributes.update( index, 34963 );
  8426. }
  8427. if ( updateBuffers ) {
  8428. setupVertexAttributes( object, material, program, geometry );
  8429. if ( index !== null ) {
  8430. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8431. }
  8432. }
  8433. }
  8434. function createVertexArrayObject() {
  8435. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8436. return extension.createVertexArrayOES();
  8437. }
  8438. function bindVertexArrayObject( vao ) {
  8439. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8440. return extension.bindVertexArrayOES( vao );
  8441. }
  8442. function deleteVertexArrayObject( vao ) {
  8443. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8444. return extension.deleteVertexArrayOES( vao );
  8445. }
  8446. function getBindingState( geometry, program, material ) {
  8447. const wireframe = ( material.wireframe === true );
  8448. let programMap = bindingStates[ geometry.id ];
  8449. if ( programMap === undefined ) {
  8450. programMap = {};
  8451. bindingStates[ geometry.id ] = programMap;
  8452. }
  8453. let stateMap = programMap[ program.id ];
  8454. if ( stateMap === undefined ) {
  8455. stateMap = {};
  8456. programMap[ program.id ] = stateMap;
  8457. }
  8458. let state = stateMap[ wireframe ];
  8459. if ( state === undefined ) {
  8460. state = createBindingState( createVertexArrayObject() );
  8461. stateMap[ wireframe ] = state;
  8462. }
  8463. return state;
  8464. }
  8465. function createBindingState( vao ) {
  8466. const newAttributes = [];
  8467. const enabledAttributes = [];
  8468. const attributeDivisors = [];
  8469. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8470. newAttributes[ i ] = 0;
  8471. enabledAttributes[ i ] = 0;
  8472. attributeDivisors[ i ] = 0;
  8473. }
  8474. return {
  8475. // for backward compatibility on non-VAO support browser
  8476. geometry: null,
  8477. program: null,
  8478. wireframe: false,
  8479. newAttributes: newAttributes,
  8480. enabledAttributes: enabledAttributes,
  8481. attributeDivisors: attributeDivisors,
  8482. object: vao,
  8483. attributes: {},
  8484. index: null
  8485. };
  8486. }
  8487. function needsUpdate( geometry, index ) {
  8488. const cachedAttributes = currentState.attributes;
  8489. const geometryAttributes = geometry.attributes;
  8490. let attributesNum = 0;
  8491. for ( const key in geometryAttributes ) {
  8492. const cachedAttribute = cachedAttributes[ key ];
  8493. const geometryAttribute = geometryAttributes[ key ];
  8494. if ( cachedAttribute === undefined ) return true;
  8495. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8496. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8497. attributesNum ++;
  8498. }
  8499. if ( currentState.attributesNum !== attributesNum ) return true;
  8500. if ( currentState.index !== index ) return true;
  8501. return false;
  8502. }
  8503. function saveCache( geometry, index ) {
  8504. const cache = {};
  8505. const attributes = geometry.attributes;
  8506. let attributesNum = 0;
  8507. for ( const key in attributes ) {
  8508. const attribute = attributes[ key ];
  8509. const data = {};
  8510. data.attribute = attribute;
  8511. if ( attribute.data ) {
  8512. data.data = attribute.data;
  8513. }
  8514. cache[ key ] = data;
  8515. attributesNum ++;
  8516. }
  8517. currentState.attributes = cache;
  8518. currentState.attributesNum = attributesNum;
  8519. currentState.index = index;
  8520. }
  8521. function initAttributes() {
  8522. const newAttributes = currentState.newAttributes;
  8523. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8524. newAttributes[ i ] = 0;
  8525. }
  8526. }
  8527. function enableAttribute( attribute ) {
  8528. enableAttributeAndDivisor( attribute, 0 );
  8529. }
  8530. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8531. const newAttributes = currentState.newAttributes;
  8532. const enabledAttributes = currentState.enabledAttributes;
  8533. const attributeDivisors = currentState.attributeDivisors;
  8534. newAttributes[ attribute ] = 1;
  8535. if ( enabledAttributes[ attribute ] === 0 ) {
  8536. gl.enableVertexAttribArray( attribute );
  8537. enabledAttributes[ attribute ] = 1;
  8538. }
  8539. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8540. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8541. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8542. attributeDivisors[ attribute ] = meshPerAttribute;
  8543. }
  8544. }
  8545. function disableUnusedAttributes() {
  8546. const newAttributes = currentState.newAttributes;
  8547. const enabledAttributes = currentState.enabledAttributes;
  8548. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8549. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8550. gl.disableVertexAttribArray( i );
  8551. enabledAttributes[ i ] = 0;
  8552. }
  8553. }
  8554. }
  8555. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8556. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8557. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8558. } else {
  8559. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8560. }
  8561. }
  8562. function setupVertexAttributes( object, material, program, geometry ) {
  8563. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8564. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8565. }
  8566. initAttributes();
  8567. const geometryAttributes = geometry.attributes;
  8568. const programAttributes = program.getAttributes();
  8569. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8570. for ( const name in programAttributes ) {
  8571. const programAttribute = programAttributes[ name ];
  8572. if ( programAttribute.location >= 0 ) {
  8573. let geometryAttribute = geometryAttributes[ name ];
  8574. if ( geometryAttribute === undefined ) {
  8575. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8576. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8577. }
  8578. if ( geometryAttribute !== undefined ) {
  8579. const normalized = geometryAttribute.normalized;
  8580. const size = geometryAttribute.itemSize;
  8581. const attribute = attributes.get( geometryAttribute );
  8582. // TODO Attribute may not be available on context restore
  8583. if ( attribute === undefined ) continue;
  8584. const buffer = attribute.buffer;
  8585. const type = attribute.type;
  8586. const bytesPerElement = attribute.bytesPerElement;
  8587. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8588. const data = geometryAttribute.data;
  8589. const stride = data.stride;
  8590. const offset = geometryAttribute.offset;
  8591. if ( data && data.isInstancedInterleavedBuffer ) {
  8592. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8593. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8594. }
  8595. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8596. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8597. }
  8598. } else {
  8599. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8600. enableAttribute( programAttribute.location + i );
  8601. }
  8602. }
  8603. gl.bindBuffer( 34962, buffer );
  8604. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8605. vertexAttribPointer(
  8606. programAttribute.location + i,
  8607. size / programAttribute.locationSize,
  8608. type,
  8609. normalized,
  8610. stride * bytesPerElement,
  8611. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8612. );
  8613. }
  8614. } else {
  8615. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8616. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8617. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8618. }
  8619. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8620. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8621. }
  8622. } else {
  8623. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8624. enableAttribute( programAttribute.location + i );
  8625. }
  8626. }
  8627. gl.bindBuffer( 34962, buffer );
  8628. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8629. vertexAttribPointer(
  8630. programAttribute.location + i,
  8631. size / programAttribute.locationSize,
  8632. type,
  8633. normalized,
  8634. size * bytesPerElement,
  8635. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8636. );
  8637. }
  8638. }
  8639. } else if ( materialDefaultAttributeValues !== undefined ) {
  8640. const value = materialDefaultAttributeValues[ name ];
  8641. if ( value !== undefined ) {
  8642. switch ( value.length ) {
  8643. case 2:
  8644. gl.vertexAttrib2fv( programAttribute.location, value );
  8645. break;
  8646. case 3:
  8647. gl.vertexAttrib3fv( programAttribute.location, value );
  8648. break;
  8649. case 4:
  8650. gl.vertexAttrib4fv( programAttribute.location, value );
  8651. break;
  8652. default:
  8653. gl.vertexAttrib1fv( programAttribute.location, value );
  8654. }
  8655. }
  8656. }
  8657. }
  8658. }
  8659. disableUnusedAttributes();
  8660. }
  8661. function dispose() {
  8662. reset();
  8663. for ( const geometryId in bindingStates ) {
  8664. const programMap = bindingStates[ geometryId ];
  8665. for ( const programId in programMap ) {
  8666. const stateMap = programMap[ programId ];
  8667. for ( const wireframe in stateMap ) {
  8668. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8669. delete stateMap[ wireframe ];
  8670. }
  8671. delete programMap[ programId ];
  8672. }
  8673. delete bindingStates[ geometryId ];
  8674. }
  8675. }
  8676. function releaseStatesOfGeometry( geometry ) {
  8677. if ( bindingStates[ geometry.id ] === undefined ) return;
  8678. const programMap = bindingStates[ geometry.id ];
  8679. for ( const programId in programMap ) {
  8680. const stateMap = programMap[ programId ];
  8681. for ( const wireframe in stateMap ) {
  8682. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8683. delete stateMap[ wireframe ];
  8684. }
  8685. delete programMap[ programId ];
  8686. }
  8687. delete bindingStates[ geometry.id ];
  8688. }
  8689. function releaseStatesOfProgram( program ) {
  8690. for ( const geometryId in bindingStates ) {
  8691. const programMap = bindingStates[ geometryId ];
  8692. if ( programMap[ program.id ] === undefined ) continue;
  8693. const stateMap = programMap[ program.id ];
  8694. for ( const wireframe in stateMap ) {
  8695. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8696. delete stateMap[ wireframe ];
  8697. }
  8698. delete programMap[ program.id ];
  8699. }
  8700. }
  8701. function reset() {
  8702. resetDefaultState();
  8703. if ( currentState === defaultState ) return;
  8704. currentState = defaultState;
  8705. bindVertexArrayObject( currentState.object );
  8706. }
  8707. // for backward-compatilibity
  8708. function resetDefaultState() {
  8709. defaultState.geometry = null;
  8710. defaultState.program = null;
  8711. defaultState.wireframe = false;
  8712. }
  8713. return {
  8714. setup: setup,
  8715. reset: reset,
  8716. resetDefaultState: resetDefaultState,
  8717. dispose: dispose,
  8718. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8719. releaseStatesOfProgram: releaseStatesOfProgram,
  8720. initAttributes: initAttributes,
  8721. enableAttribute: enableAttribute,
  8722. disableUnusedAttributes: disableUnusedAttributes
  8723. };
  8724. }
  8725. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8726. const isWebGL2 = capabilities.isWebGL2;
  8727. let mode;
  8728. function setMode( value ) {
  8729. mode = value;
  8730. }
  8731. function render( start, count ) {
  8732. gl.drawArrays( mode, start, count );
  8733. info.update( count, mode, 1 );
  8734. }
  8735. function renderInstances( start, count, primcount ) {
  8736. if ( primcount === 0 ) return;
  8737. let extension, methodName;
  8738. if ( isWebGL2 ) {
  8739. extension = gl;
  8740. methodName = 'drawArraysInstanced';
  8741. } else {
  8742. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8743. methodName = 'drawArraysInstancedANGLE';
  8744. if ( extension === null ) {
  8745. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8746. return;
  8747. }
  8748. }
  8749. extension[ methodName ]( mode, start, count, primcount );
  8750. info.update( count, mode, primcount );
  8751. }
  8752. //
  8753. this.setMode = setMode;
  8754. this.render = render;
  8755. this.renderInstances = renderInstances;
  8756. }
  8757. function WebGLCapabilities( gl, extensions, parameters ) {
  8758. let maxAnisotropy;
  8759. function getMaxAnisotropy() {
  8760. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8761. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8762. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8763. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8764. } else {
  8765. maxAnisotropy = 0;
  8766. }
  8767. return maxAnisotropy;
  8768. }
  8769. function getMaxPrecision( precision ) {
  8770. if ( precision === 'highp' ) {
  8771. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8772. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8773. return 'highp';
  8774. }
  8775. precision = 'mediump';
  8776. }
  8777. if ( precision === 'mediump' ) {
  8778. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8779. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8780. return 'mediump';
  8781. }
  8782. }
  8783. return 'lowp';
  8784. }
  8785. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8786. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8787. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8788. const maxPrecision = getMaxPrecision( precision );
  8789. if ( maxPrecision !== precision ) {
  8790. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8791. precision = maxPrecision;
  8792. }
  8793. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8794. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8795. const maxTextures = gl.getParameter( 34930 );
  8796. const maxVertexTextures = gl.getParameter( 35660 );
  8797. const maxTextureSize = gl.getParameter( 3379 );
  8798. const maxCubemapSize = gl.getParameter( 34076 );
  8799. const maxAttributes = gl.getParameter( 34921 );
  8800. const maxVertexUniforms = gl.getParameter( 36347 );
  8801. const maxVaryings = gl.getParameter( 36348 );
  8802. const maxFragmentUniforms = gl.getParameter( 36349 );
  8803. const vertexTextures = maxVertexTextures > 0;
  8804. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8805. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8806. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8807. return {
  8808. isWebGL2: isWebGL2,
  8809. drawBuffers: drawBuffers,
  8810. getMaxAnisotropy: getMaxAnisotropy,
  8811. getMaxPrecision: getMaxPrecision,
  8812. precision: precision,
  8813. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8814. maxTextures: maxTextures,
  8815. maxVertexTextures: maxVertexTextures,
  8816. maxTextureSize: maxTextureSize,
  8817. maxCubemapSize: maxCubemapSize,
  8818. maxAttributes: maxAttributes,
  8819. maxVertexUniforms: maxVertexUniforms,
  8820. maxVaryings: maxVaryings,
  8821. maxFragmentUniforms: maxFragmentUniforms,
  8822. vertexTextures: vertexTextures,
  8823. floatFragmentTextures: floatFragmentTextures,
  8824. floatVertexTextures: floatVertexTextures,
  8825. maxSamples: maxSamples
  8826. };
  8827. }
  8828. function WebGLClipping( properties ) {
  8829. const scope = this;
  8830. let globalState = null,
  8831. numGlobalPlanes = 0,
  8832. localClippingEnabled = false,
  8833. renderingShadows = false;
  8834. const plane = new Plane(),
  8835. viewNormalMatrix = new Matrix3(),
  8836. uniform = { value: null, needsUpdate: false };
  8837. this.uniform = uniform;
  8838. this.numPlanes = 0;
  8839. this.numIntersection = 0;
  8840. this.init = function ( planes, enableLocalClipping, camera ) {
  8841. const enabled =
  8842. planes.length !== 0 ||
  8843. enableLocalClipping ||
  8844. // enable state of previous frame - the clipping code has to
  8845. // run another frame in order to reset the state:
  8846. numGlobalPlanes !== 0 ||
  8847. localClippingEnabled;
  8848. localClippingEnabled = enableLocalClipping;
  8849. globalState = projectPlanes( planes, camera, 0 );
  8850. numGlobalPlanes = planes.length;
  8851. return enabled;
  8852. };
  8853. this.beginShadows = function () {
  8854. renderingShadows = true;
  8855. projectPlanes( null );
  8856. };
  8857. this.endShadows = function () {
  8858. renderingShadows = false;
  8859. resetGlobalState();
  8860. };
  8861. this.setState = function ( material, camera, useCache ) {
  8862. const planes = material.clippingPlanes,
  8863. clipIntersection = material.clipIntersection,
  8864. clipShadows = material.clipShadows;
  8865. const materialProperties = properties.get( material );
  8866. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8867. // there's no local clipping
  8868. if ( renderingShadows ) {
  8869. // there's no global clipping
  8870. projectPlanes( null );
  8871. } else {
  8872. resetGlobalState();
  8873. }
  8874. } else {
  8875. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8876. lGlobal = nGlobal * 4;
  8877. let dstArray = materialProperties.clippingState || null;
  8878. uniform.value = dstArray; // ensure unique state
  8879. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8880. for ( let i = 0; i !== lGlobal; ++ i ) {
  8881. dstArray[ i ] = globalState[ i ];
  8882. }
  8883. materialProperties.clippingState = dstArray;
  8884. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8885. this.numPlanes += nGlobal;
  8886. }
  8887. };
  8888. function resetGlobalState() {
  8889. if ( uniform.value !== globalState ) {
  8890. uniform.value = globalState;
  8891. uniform.needsUpdate = numGlobalPlanes > 0;
  8892. }
  8893. scope.numPlanes = numGlobalPlanes;
  8894. scope.numIntersection = 0;
  8895. }
  8896. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8897. const nPlanes = planes !== null ? planes.length : 0;
  8898. let dstArray = null;
  8899. if ( nPlanes !== 0 ) {
  8900. dstArray = uniform.value;
  8901. if ( skipTransform !== true || dstArray === null ) {
  8902. const flatSize = dstOffset + nPlanes * 4,
  8903. viewMatrix = camera.matrixWorldInverse;
  8904. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8905. if ( dstArray === null || dstArray.length < flatSize ) {
  8906. dstArray = new Float32Array( flatSize );
  8907. }
  8908. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8909. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8910. plane.normal.toArray( dstArray, i4 );
  8911. dstArray[ i4 + 3 ] = plane.constant;
  8912. }
  8913. }
  8914. uniform.value = dstArray;
  8915. uniform.needsUpdate = true;
  8916. }
  8917. scope.numPlanes = nPlanes;
  8918. scope.numIntersection = 0;
  8919. return dstArray;
  8920. }
  8921. }
  8922. function WebGLCubeMaps( renderer ) {
  8923. let cubemaps = new WeakMap();
  8924. function mapTextureMapping( texture, mapping ) {
  8925. if ( mapping === EquirectangularReflectionMapping ) {
  8926. texture.mapping = CubeReflectionMapping;
  8927. } else if ( mapping === EquirectangularRefractionMapping ) {
  8928. texture.mapping = CubeRefractionMapping;
  8929. }
  8930. return texture;
  8931. }
  8932. function get( texture ) {
  8933. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8934. const mapping = texture.mapping;
  8935. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8936. if ( cubemaps.has( texture ) ) {
  8937. const cubemap = cubemaps.get( texture ).texture;
  8938. return mapTextureMapping( cubemap, texture.mapping );
  8939. } else {
  8940. const image = texture.image;
  8941. if ( image && image.height > 0 ) {
  8942. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8943. renderTarget.fromEquirectangularTexture( renderer, texture );
  8944. cubemaps.set( texture, renderTarget );
  8945. texture.addEventListener( 'dispose', onTextureDispose );
  8946. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8947. } else {
  8948. // image not yet ready. try the conversion next frame
  8949. return null;
  8950. }
  8951. }
  8952. }
  8953. }
  8954. return texture;
  8955. }
  8956. function onTextureDispose( event ) {
  8957. const texture = event.target;
  8958. texture.removeEventListener( 'dispose', onTextureDispose );
  8959. const cubemap = cubemaps.get( texture );
  8960. if ( cubemap !== undefined ) {
  8961. cubemaps.delete( texture );
  8962. cubemap.dispose();
  8963. }
  8964. }
  8965. function dispose() {
  8966. cubemaps = new WeakMap();
  8967. }
  8968. return {
  8969. get: get,
  8970. dispose: dispose
  8971. };
  8972. }
  8973. class OrthographicCamera extends Camera {
  8974. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  8975. super();
  8976. this.type = 'OrthographicCamera';
  8977. this.zoom = 1;
  8978. this.view = null;
  8979. this.left = left;
  8980. this.right = right;
  8981. this.top = top;
  8982. this.bottom = bottom;
  8983. this.near = near;
  8984. this.far = far;
  8985. this.updateProjectionMatrix();
  8986. }
  8987. copy( source, recursive ) {
  8988. super.copy( source, recursive );
  8989. this.left = source.left;
  8990. this.right = source.right;
  8991. this.top = source.top;
  8992. this.bottom = source.bottom;
  8993. this.near = source.near;
  8994. this.far = source.far;
  8995. this.zoom = source.zoom;
  8996. this.view = source.view === null ? null : Object.assign( {}, source.view );
  8997. return this;
  8998. }
  8999. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9000. if ( this.view === null ) {
  9001. this.view = {
  9002. enabled: true,
  9003. fullWidth: 1,
  9004. fullHeight: 1,
  9005. offsetX: 0,
  9006. offsetY: 0,
  9007. width: 1,
  9008. height: 1
  9009. };
  9010. }
  9011. this.view.enabled = true;
  9012. this.view.fullWidth = fullWidth;
  9013. this.view.fullHeight = fullHeight;
  9014. this.view.offsetX = x;
  9015. this.view.offsetY = y;
  9016. this.view.width = width;
  9017. this.view.height = height;
  9018. this.updateProjectionMatrix();
  9019. }
  9020. clearViewOffset() {
  9021. if ( this.view !== null ) {
  9022. this.view.enabled = false;
  9023. }
  9024. this.updateProjectionMatrix();
  9025. }
  9026. updateProjectionMatrix() {
  9027. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9028. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9029. const cx = ( this.right + this.left ) / 2;
  9030. const cy = ( this.top + this.bottom ) / 2;
  9031. let left = cx - dx;
  9032. let right = cx + dx;
  9033. let top = cy + dy;
  9034. let bottom = cy - dy;
  9035. if ( this.view !== null && this.view.enabled ) {
  9036. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9037. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9038. left += scaleW * this.view.offsetX;
  9039. right = left + scaleW * this.view.width;
  9040. top -= scaleH * this.view.offsetY;
  9041. bottom = top - scaleH * this.view.height;
  9042. }
  9043. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9044. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9045. }
  9046. toJSON( meta ) {
  9047. const data = super.toJSON( meta );
  9048. data.object.zoom = this.zoom;
  9049. data.object.left = this.left;
  9050. data.object.right = this.right;
  9051. data.object.top = this.top;
  9052. data.object.bottom = this.bottom;
  9053. data.object.near = this.near;
  9054. data.object.far = this.far;
  9055. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9056. return data;
  9057. }
  9058. }
  9059. OrthographicCamera.prototype.isOrthographicCamera = true;
  9060. class RawShaderMaterial extends ShaderMaterial {
  9061. constructor( parameters ) {
  9062. super( parameters );
  9063. this.type = 'RawShaderMaterial';
  9064. }
  9065. }
  9066. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9067. const LOD_MIN = 4;
  9068. const LOD_MAX = 8;
  9069. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  9070. // The standard deviations (radians) associated with the extra mips. These are
  9071. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9072. // geometric shadowing function. These sigma values squared must match the
  9073. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9074. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9075. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9076. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9077. // samples and exit early, but not recompile the shader.
  9078. const MAX_SAMPLES = 20;
  9079. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9080. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  9081. const _clearColor = /*@__PURE__*/ new Color();
  9082. let _oldTarget = null;
  9083. // Golden Ratio
  9084. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9085. const INV_PHI = 1 / PHI;
  9086. // Vertices of a dodecahedron (except the opposites, which represent the
  9087. // same axis), used as axis directions evenly spread on a sphere.
  9088. const _axisDirections = [
  9089. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9090. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9091. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9092. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9093. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9094. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9095. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9096. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9097. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9098. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9099. /**
  9100. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9101. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9102. * blur to be quickly accessed based on material roughness. It is packed into a
  9103. * special CubeUV format that allows us to perform custom interpolation so that
  9104. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9105. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9106. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9107. * higher roughness levels. In this way we maintain resolution to smoothly
  9108. * interpolate diffuse lighting while limiting sampling computation.
  9109. *
  9110. * Paper: Fast, Accurate Image-Based Lighting
  9111. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9112. */
  9113. class PMREMGenerator {
  9114. constructor( renderer ) {
  9115. this._renderer = renderer;
  9116. this._pingPongRenderTarget = null;
  9117. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  9118. this._equirectShader = null;
  9119. this._cubemapShader = null;
  9120. this._compileMaterial( this._blurMaterial );
  9121. }
  9122. /**
  9123. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9124. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9125. * in radians to be applied to the scene before PMREM generation. Optional near
  9126. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9127. * is placed at the origin).
  9128. */
  9129. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9130. _oldTarget = this._renderer.getRenderTarget();
  9131. const cubeUVRenderTarget = this._allocateTargets();
  9132. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9133. if ( sigma > 0 ) {
  9134. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9135. }
  9136. this._applyPMREM( cubeUVRenderTarget );
  9137. this._cleanup( cubeUVRenderTarget );
  9138. return cubeUVRenderTarget;
  9139. }
  9140. /**
  9141. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9142. * or HDR. The ideal input image size is 1k (1024 x 512),
  9143. * as this matches best with the 256 x 256 cubemap output.
  9144. */
  9145. fromEquirectangular( equirectangular, renderTarget = null ) {
  9146. return this._fromTexture( equirectangular, renderTarget );
  9147. }
  9148. /**
  9149. * Generates a PMREM from an cubemap texture, which can be either LDR
  9150. * or HDR. The ideal input cube size is 256 x 256,
  9151. * as this matches best with the 256 x 256 cubemap output.
  9152. */
  9153. fromCubemap( cubemap, renderTarget = null ) {
  9154. return this._fromTexture( cubemap, renderTarget );
  9155. }
  9156. /**
  9157. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9158. * your texture's network fetch for increased concurrency.
  9159. */
  9160. compileCubemapShader() {
  9161. if ( this._cubemapShader === null ) {
  9162. this._cubemapShader = _getCubemapShader();
  9163. this._compileMaterial( this._cubemapShader );
  9164. }
  9165. }
  9166. /**
  9167. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9168. * your texture's network fetch for increased concurrency.
  9169. */
  9170. compileEquirectangularShader() {
  9171. if ( this._equirectShader === null ) {
  9172. this._equirectShader = _getEquirectShader();
  9173. this._compileMaterial( this._equirectShader );
  9174. }
  9175. }
  9176. /**
  9177. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9178. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9179. * one of them will cause any others to also become unusable.
  9180. */
  9181. dispose() {
  9182. this._blurMaterial.dispose();
  9183. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9184. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  9185. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  9186. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  9187. _lodPlanes[ i ].dispose();
  9188. }
  9189. }
  9190. // private interface
  9191. _cleanup( outputTarget ) {
  9192. this._renderer.setRenderTarget( _oldTarget );
  9193. outputTarget.scissorTest = false;
  9194. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9195. }
  9196. _fromTexture( texture, renderTarget ) {
  9197. _oldTarget = this._renderer.getRenderTarget();
  9198. const cubeUVRenderTarget = renderTarget || this._allocateTargets( texture );
  9199. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9200. this._applyPMREM( cubeUVRenderTarget );
  9201. this._cleanup( cubeUVRenderTarget );
  9202. return cubeUVRenderTarget;
  9203. }
  9204. _allocateTargets( texture ) { // warning: null texture is valid
  9205. const params = {
  9206. magFilter: LinearFilter,
  9207. minFilter: LinearFilter,
  9208. generateMipmaps: false,
  9209. type: HalfFloatType,
  9210. format: RGBAFormat,
  9211. encoding: LinearEncoding,
  9212. depthBuffer: false
  9213. };
  9214. const cubeUVRenderTarget = _createRenderTarget( params );
  9215. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9216. if ( this._pingPongRenderTarget === null ) {
  9217. this._pingPongRenderTarget = _createRenderTarget( params );
  9218. }
  9219. return cubeUVRenderTarget;
  9220. }
  9221. _compileMaterial( material ) {
  9222. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  9223. this._renderer.compile( tmpMesh, _flatCamera );
  9224. }
  9225. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9226. const fov = 90;
  9227. const aspect = 1;
  9228. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9229. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9230. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9231. const renderer = this._renderer;
  9232. const originalAutoClear = renderer.autoClear;
  9233. const toneMapping = renderer.toneMapping;
  9234. renderer.getClearColor( _clearColor );
  9235. renderer.toneMapping = NoToneMapping;
  9236. renderer.autoClear = false;
  9237. const backgroundMaterial = new MeshBasicMaterial( {
  9238. name: 'PMREM.Background',
  9239. side: BackSide,
  9240. depthWrite: false,
  9241. depthTest: false,
  9242. } );
  9243. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9244. let useSolidColor = false;
  9245. const background = scene.background;
  9246. if ( background ) {
  9247. if ( background.isColor ) {
  9248. backgroundMaterial.color.copy( background );
  9249. scene.background = null;
  9250. useSolidColor = true;
  9251. }
  9252. } else {
  9253. backgroundMaterial.color.copy( _clearColor );
  9254. useSolidColor = true;
  9255. }
  9256. for ( let i = 0; i < 6; i ++ ) {
  9257. const col = i % 3;
  9258. if ( col === 0 ) {
  9259. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9260. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9261. } else if ( col === 1 ) {
  9262. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9263. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9264. } else {
  9265. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9266. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9267. }
  9268. _setViewport( cubeUVRenderTarget,
  9269. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  9270. renderer.setRenderTarget( cubeUVRenderTarget );
  9271. if ( useSolidColor ) {
  9272. renderer.render( backgroundBox, cubeCamera );
  9273. }
  9274. renderer.render( scene, cubeCamera );
  9275. }
  9276. backgroundBox.geometry.dispose();
  9277. backgroundBox.material.dispose();
  9278. renderer.toneMapping = toneMapping;
  9279. renderer.autoClear = originalAutoClear;
  9280. scene.background = background;
  9281. }
  9282. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9283. const renderer = this._renderer;
  9284. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9285. if ( isCubeTexture ) {
  9286. if ( this._cubemapShader === null ) {
  9287. this._cubemapShader = _getCubemapShader();
  9288. }
  9289. this._cubemapShader.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9290. } else {
  9291. if ( this._equirectShader === null ) {
  9292. this._equirectShader = _getEquirectShader();
  9293. }
  9294. }
  9295. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  9296. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  9297. const uniforms = material.uniforms;
  9298. uniforms[ 'envMap' ].value = texture;
  9299. if ( ! isCubeTexture ) {
  9300. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  9301. }
  9302. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  9303. renderer.setRenderTarget( cubeUVRenderTarget );
  9304. renderer.render( mesh, _flatCamera );
  9305. }
  9306. _applyPMREM( cubeUVRenderTarget ) {
  9307. const renderer = this._renderer;
  9308. const autoClear = renderer.autoClear;
  9309. renderer.autoClear = false;
  9310. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  9311. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  9312. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9313. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9314. }
  9315. renderer.autoClear = autoClear;
  9316. }
  9317. /**
  9318. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9319. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9320. * the blur latitudinally (around the poles), and then longitudinally (towards
  9321. * the poles) to approximate the orthogonally-separable blur. It is least
  9322. * accurate at the poles, but still does a decent job.
  9323. */
  9324. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9325. const pingPongRenderTarget = this._pingPongRenderTarget;
  9326. this._halfBlur(
  9327. cubeUVRenderTarget,
  9328. pingPongRenderTarget,
  9329. lodIn,
  9330. lodOut,
  9331. sigma,
  9332. 'latitudinal',
  9333. poleAxis );
  9334. this._halfBlur(
  9335. pingPongRenderTarget,
  9336. cubeUVRenderTarget,
  9337. lodOut,
  9338. lodOut,
  9339. sigma,
  9340. 'longitudinal',
  9341. poleAxis );
  9342. }
  9343. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9344. const renderer = this._renderer;
  9345. const blurMaterial = this._blurMaterial;
  9346. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9347. console.error(
  9348. 'blur direction must be either latitudinal or longitudinal!' );
  9349. }
  9350. // Number of standard deviations at which to cut off the discrete approximation.
  9351. const STANDARD_DEVIATIONS = 3;
  9352. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  9353. const blurUniforms = blurMaterial.uniforms;
  9354. const pixels = _sizeLods[ lodIn ] - 1;
  9355. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9356. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9357. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9358. if ( samples > MAX_SAMPLES ) {
  9359. console.warn( `sigmaRadians, ${
  9360. sigmaRadians}, is too large and will clip, as it requested ${
  9361. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9362. }
  9363. const weights = [];
  9364. let sum = 0;
  9365. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9366. const x = i / sigmaPixels;
  9367. const weight = Math.exp( - x * x / 2 );
  9368. weights.push( weight );
  9369. if ( i === 0 ) {
  9370. sum += weight;
  9371. } else if ( i < samples ) {
  9372. sum += 2 * weight;
  9373. }
  9374. }
  9375. for ( let i = 0; i < weights.length; i ++ ) {
  9376. weights[ i ] = weights[ i ] / sum;
  9377. }
  9378. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9379. blurUniforms[ 'samples' ].value = samples;
  9380. blurUniforms[ 'weights' ].value = weights;
  9381. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9382. if ( poleAxis ) {
  9383. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9384. }
  9385. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9386. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  9387. const outputSize = _sizeLods[ lodOut ];
  9388. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  9389. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  9390. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9391. renderer.setRenderTarget( targetOut );
  9392. renderer.render( blurMesh, _flatCamera );
  9393. }
  9394. }
  9395. function _createPlanes() {
  9396. const _lodPlanes = [];
  9397. const _sizeLods = [];
  9398. const _sigmas = [];
  9399. let lod = LOD_MAX;
  9400. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  9401. const sizeLod = Math.pow( 2, lod );
  9402. _sizeLods.push( sizeLod );
  9403. let sigma = 1.0 / sizeLod;
  9404. if ( i > LOD_MAX - LOD_MIN ) {
  9405. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  9406. } else if ( i === 0 ) {
  9407. sigma = 0;
  9408. }
  9409. _sigmas.push( sigma );
  9410. const texelSize = 1.0 / ( sizeLod - 1 );
  9411. const min = - texelSize / 2;
  9412. const max = 1 + texelSize / 2;
  9413. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9414. const cubeFaces = 6;
  9415. const vertices = 6;
  9416. const positionSize = 3;
  9417. const uvSize = 2;
  9418. const faceIndexSize = 1;
  9419. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9420. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9421. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9422. for ( let face = 0; face < cubeFaces; face ++ ) {
  9423. const x = ( face % 3 ) * 2 / 3 - 1;
  9424. const y = face > 2 ? 0 : - 1;
  9425. const coordinates = [
  9426. x, y, 0,
  9427. x + 2 / 3, y, 0,
  9428. x + 2 / 3, y + 1, 0,
  9429. x, y, 0,
  9430. x + 2 / 3, y + 1, 0,
  9431. x, y + 1, 0
  9432. ];
  9433. position.set( coordinates, positionSize * vertices * face );
  9434. uv.set( uv1, uvSize * vertices * face );
  9435. const fill = [ face, face, face, face, face, face ];
  9436. faceIndex.set( fill, faceIndexSize * vertices * face );
  9437. }
  9438. const planes = new BufferGeometry();
  9439. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9440. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9441. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9442. _lodPlanes.push( planes );
  9443. if ( lod > LOD_MIN ) {
  9444. lod --;
  9445. }
  9446. }
  9447. return { _lodPlanes, _sizeLods, _sigmas };
  9448. }
  9449. function _createRenderTarget( params ) {
  9450. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  9451. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9452. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9453. cubeUVRenderTarget.scissorTest = true;
  9454. return cubeUVRenderTarget;
  9455. }
  9456. function _setViewport( target, x, y, width, height ) {
  9457. target.viewport.set( x, y, width, height );
  9458. target.scissor.set( x, y, width, height );
  9459. }
  9460. function _getBlurShader( maxSamples ) {
  9461. const weights = new Float32Array( maxSamples );
  9462. const poleAxis = new Vector3( 0, 1, 0 );
  9463. const shaderMaterial = new RawShaderMaterial( {
  9464. name: 'SphericalGaussianBlur',
  9465. defines: { 'n': maxSamples },
  9466. uniforms: {
  9467. 'envMap': { value: null },
  9468. 'samples': { value: 1 },
  9469. 'weights': { value: weights },
  9470. 'latitudinal': { value: false },
  9471. 'dTheta': { value: 0 },
  9472. 'mipInt': { value: 0 },
  9473. 'poleAxis': { value: poleAxis }
  9474. },
  9475. vertexShader: _getCommonVertexShader(),
  9476. fragmentShader: /* glsl */`
  9477. precision mediump float;
  9478. precision mediump int;
  9479. varying vec3 vOutputDirection;
  9480. uniform sampler2D envMap;
  9481. uniform int samples;
  9482. uniform float weights[ n ];
  9483. uniform bool latitudinal;
  9484. uniform float dTheta;
  9485. uniform float mipInt;
  9486. uniform vec3 poleAxis;
  9487. #define ENVMAP_TYPE_CUBE_UV
  9488. #include <cube_uv_reflection_fragment>
  9489. vec3 getSample( float theta, vec3 axis ) {
  9490. float cosTheta = cos( theta );
  9491. // Rodrigues' axis-angle rotation
  9492. vec3 sampleDirection = vOutputDirection * cosTheta
  9493. + cross( axis, vOutputDirection ) * sin( theta )
  9494. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9495. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9496. }
  9497. void main() {
  9498. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9499. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9500. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9501. }
  9502. axis = normalize( axis );
  9503. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9504. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9505. for ( int i = 1; i < n; i++ ) {
  9506. if ( i >= samples ) {
  9507. break;
  9508. }
  9509. float theta = dTheta * float( i );
  9510. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9511. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9512. }
  9513. }
  9514. `,
  9515. blending: NoBlending,
  9516. depthTest: false,
  9517. depthWrite: false
  9518. } );
  9519. return shaderMaterial;
  9520. }
  9521. function _getEquirectShader() {
  9522. const texelSize = new Vector2( 1, 1 );
  9523. const shaderMaterial = new RawShaderMaterial( {
  9524. name: 'EquirectangularToCubeUV',
  9525. uniforms: {
  9526. 'envMap': { value: null },
  9527. 'texelSize': { value: texelSize }
  9528. },
  9529. vertexShader: _getCommonVertexShader(),
  9530. fragmentShader: /* glsl */`
  9531. precision mediump float;
  9532. precision mediump int;
  9533. varying vec3 vOutputDirection;
  9534. uniform sampler2D envMap;
  9535. uniform vec2 texelSize;
  9536. #include <common>
  9537. void main() {
  9538. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9539. vec3 outputDirection = normalize( vOutputDirection );
  9540. vec2 uv = equirectUv( outputDirection );
  9541. vec2 f = fract( uv / texelSize - 0.5 );
  9542. uv -= f * texelSize;
  9543. vec3 tl = texture2D ( envMap, uv ).rgb;
  9544. uv.x += texelSize.x;
  9545. vec3 tr = texture2D ( envMap, uv ).rgb;
  9546. uv.y += texelSize.y;
  9547. vec3 br = texture2D ( envMap, uv ).rgb;
  9548. uv.x -= texelSize.x;
  9549. vec3 bl = texture2D ( envMap, uv ).rgb;
  9550. vec3 tm = mix( tl, tr, f.x );
  9551. vec3 bm = mix( bl, br, f.x );
  9552. gl_FragColor.rgb = mix( tm, bm, f.y );
  9553. }
  9554. `,
  9555. blending: NoBlending,
  9556. depthTest: false,
  9557. depthWrite: false
  9558. } );
  9559. return shaderMaterial;
  9560. }
  9561. function _getCubemapShader() {
  9562. const shaderMaterial = new RawShaderMaterial( {
  9563. name: 'CubemapToCubeUV',
  9564. uniforms: {
  9565. 'envMap': { value: null },
  9566. 'flipEnvMap': { value: - 1 }
  9567. },
  9568. vertexShader: _getCommonVertexShader(),
  9569. fragmentShader: /* glsl */`
  9570. precision mediump float;
  9571. precision mediump int;
  9572. uniform float flipEnvMap;
  9573. varying vec3 vOutputDirection;
  9574. uniform samplerCube envMap;
  9575. void main() {
  9576. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9577. }
  9578. `,
  9579. blending: NoBlending,
  9580. depthTest: false,
  9581. depthWrite: false
  9582. } );
  9583. return shaderMaterial;
  9584. }
  9585. function _getCommonVertexShader() {
  9586. return /* glsl */`
  9587. precision mediump float;
  9588. precision mediump int;
  9589. attribute vec3 position;
  9590. attribute vec2 uv;
  9591. attribute float faceIndex;
  9592. varying vec3 vOutputDirection;
  9593. // RH coordinate system; PMREM face-indexing convention
  9594. vec3 getDirection( vec2 uv, float face ) {
  9595. uv = 2.0 * uv - 1.0;
  9596. vec3 direction = vec3( uv, 1.0 );
  9597. if ( face == 0.0 ) {
  9598. direction = direction.zyx; // ( 1, v, u ) pos x
  9599. } else if ( face == 1.0 ) {
  9600. direction = direction.xzy;
  9601. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9602. } else if ( face == 2.0 ) {
  9603. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9604. } else if ( face == 3.0 ) {
  9605. direction = direction.zyx;
  9606. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9607. } else if ( face == 4.0 ) {
  9608. direction = direction.xzy;
  9609. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9610. } else if ( face == 5.0 ) {
  9611. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9612. }
  9613. return direction;
  9614. }
  9615. void main() {
  9616. vOutputDirection = getDirection( uv, faceIndex );
  9617. gl_Position = vec4( position, 1.0 );
  9618. }
  9619. `;
  9620. }
  9621. function WebGLCubeUVMaps( renderer ) {
  9622. let cubeUVmaps = new WeakMap();
  9623. let pmremGenerator = null;
  9624. function get( texture ) {
  9625. if ( texture && texture.isTexture ) {
  9626. const mapping = texture.mapping;
  9627. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9628. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9629. // equirect/cube map to cubeUV conversion
  9630. if ( isEquirectMap || isCubeMap ) {
  9631. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9632. texture.needsPMREMUpdate = false;
  9633. let renderTarget = cubeUVmaps.get( texture );
  9634. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9635. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9636. cubeUVmaps.set( texture, renderTarget );
  9637. return renderTarget.texture;
  9638. } else {
  9639. if ( cubeUVmaps.has( texture ) ) {
  9640. return cubeUVmaps.get( texture ).texture;
  9641. } else {
  9642. const image = texture.image;
  9643. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9644. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9645. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9646. cubeUVmaps.set( texture, renderTarget );
  9647. texture.addEventListener( 'dispose', onTextureDispose );
  9648. return renderTarget.texture;
  9649. } else {
  9650. // image not yet ready. try the conversion next frame
  9651. return null;
  9652. }
  9653. }
  9654. }
  9655. }
  9656. }
  9657. return texture;
  9658. }
  9659. function isCubeTextureComplete( image ) {
  9660. let count = 0;
  9661. const length = 6;
  9662. for ( let i = 0; i < length; i ++ ) {
  9663. if ( image[ i ] !== undefined ) count ++;
  9664. }
  9665. return count === length;
  9666. }
  9667. function onTextureDispose( event ) {
  9668. const texture = event.target;
  9669. texture.removeEventListener( 'dispose', onTextureDispose );
  9670. const cubemapUV = cubeUVmaps.get( texture );
  9671. if ( cubemapUV !== undefined ) {
  9672. cubeUVmaps.delete( texture );
  9673. cubemapUV.dispose();
  9674. }
  9675. }
  9676. function dispose() {
  9677. cubeUVmaps = new WeakMap();
  9678. if ( pmremGenerator !== null ) {
  9679. pmremGenerator.dispose();
  9680. pmremGenerator = null;
  9681. }
  9682. }
  9683. return {
  9684. get: get,
  9685. dispose: dispose
  9686. };
  9687. }
  9688. function WebGLExtensions( gl ) {
  9689. const extensions = {};
  9690. function getExtension( name ) {
  9691. if ( extensions[ name ] !== undefined ) {
  9692. return extensions[ name ];
  9693. }
  9694. let extension;
  9695. switch ( name ) {
  9696. case 'WEBGL_depth_texture':
  9697. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9698. break;
  9699. case 'EXT_texture_filter_anisotropic':
  9700. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9701. break;
  9702. case 'WEBGL_compressed_texture_s3tc':
  9703. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9704. break;
  9705. case 'WEBGL_compressed_texture_pvrtc':
  9706. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9707. break;
  9708. default:
  9709. extension = gl.getExtension( name );
  9710. }
  9711. extensions[ name ] = extension;
  9712. return extension;
  9713. }
  9714. return {
  9715. has: function ( name ) {
  9716. return getExtension( name ) !== null;
  9717. },
  9718. init: function ( capabilities ) {
  9719. if ( capabilities.isWebGL2 ) {
  9720. getExtension( 'EXT_color_buffer_float' );
  9721. } else {
  9722. getExtension( 'WEBGL_depth_texture' );
  9723. getExtension( 'OES_texture_float' );
  9724. getExtension( 'OES_texture_half_float' );
  9725. getExtension( 'OES_texture_half_float_linear' );
  9726. getExtension( 'OES_standard_derivatives' );
  9727. getExtension( 'OES_element_index_uint' );
  9728. getExtension( 'OES_vertex_array_object' );
  9729. getExtension( 'ANGLE_instanced_arrays' );
  9730. }
  9731. getExtension( 'OES_texture_float_linear' );
  9732. getExtension( 'EXT_color_buffer_half_float' );
  9733. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9734. },
  9735. get: function ( name ) {
  9736. const extension = getExtension( name );
  9737. if ( extension === null ) {
  9738. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9739. }
  9740. return extension;
  9741. }
  9742. };
  9743. }
  9744. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9745. const geometries = {};
  9746. const wireframeAttributes = new WeakMap();
  9747. function onGeometryDispose( event ) {
  9748. const geometry = event.target;
  9749. if ( geometry.index !== null ) {
  9750. attributes.remove( geometry.index );
  9751. }
  9752. for ( const name in geometry.attributes ) {
  9753. attributes.remove( geometry.attributes[ name ] );
  9754. }
  9755. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9756. delete geometries[ geometry.id ];
  9757. const attribute = wireframeAttributes.get( geometry );
  9758. if ( attribute ) {
  9759. attributes.remove( attribute );
  9760. wireframeAttributes.delete( geometry );
  9761. }
  9762. bindingStates.releaseStatesOfGeometry( geometry );
  9763. if ( geometry.isInstancedBufferGeometry === true ) {
  9764. delete geometry._maxInstanceCount;
  9765. }
  9766. //
  9767. info.memory.geometries --;
  9768. }
  9769. function get( object, geometry ) {
  9770. if ( geometries[ geometry.id ] === true ) return geometry;
  9771. geometry.addEventListener( 'dispose', onGeometryDispose );
  9772. geometries[ geometry.id ] = true;
  9773. info.memory.geometries ++;
  9774. return geometry;
  9775. }
  9776. function update( geometry ) {
  9777. const geometryAttributes = geometry.attributes;
  9778. // Updating index buffer in VAO now. See WebGLBindingStates.
  9779. for ( const name in geometryAttributes ) {
  9780. attributes.update( geometryAttributes[ name ], 34962 );
  9781. }
  9782. // morph targets
  9783. const morphAttributes = geometry.morphAttributes;
  9784. for ( const name in morphAttributes ) {
  9785. const array = morphAttributes[ name ];
  9786. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9787. attributes.update( array[ i ], 34962 );
  9788. }
  9789. }
  9790. }
  9791. function updateWireframeAttribute( geometry ) {
  9792. const indices = [];
  9793. const geometryIndex = geometry.index;
  9794. const geometryPosition = geometry.attributes.position;
  9795. let version = 0;
  9796. if ( geometryIndex !== null ) {
  9797. const array = geometryIndex.array;
  9798. version = geometryIndex.version;
  9799. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9800. const a = array[ i + 0 ];
  9801. const b = array[ i + 1 ];
  9802. const c = array[ i + 2 ];
  9803. indices.push( a, b, b, c, c, a );
  9804. }
  9805. } else {
  9806. const array = geometryPosition.array;
  9807. version = geometryPosition.version;
  9808. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9809. const a = i + 0;
  9810. const b = i + 1;
  9811. const c = i + 2;
  9812. indices.push( a, b, b, c, c, a );
  9813. }
  9814. }
  9815. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9816. attribute.version = version;
  9817. // Updating index buffer in VAO now. See WebGLBindingStates
  9818. //
  9819. const previousAttribute = wireframeAttributes.get( geometry );
  9820. if ( previousAttribute ) attributes.remove( previousAttribute );
  9821. //
  9822. wireframeAttributes.set( geometry, attribute );
  9823. }
  9824. function getWireframeAttribute( geometry ) {
  9825. const currentAttribute = wireframeAttributes.get( geometry );
  9826. if ( currentAttribute ) {
  9827. const geometryIndex = geometry.index;
  9828. if ( geometryIndex !== null ) {
  9829. // if the attribute is obsolete, create a new one
  9830. if ( currentAttribute.version < geometryIndex.version ) {
  9831. updateWireframeAttribute( geometry );
  9832. }
  9833. }
  9834. } else {
  9835. updateWireframeAttribute( geometry );
  9836. }
  9837. return wireframeAttributes.get( geometry );
  9838. }
  9839. return {
  9840. get: get,
  9841. update: update,
  9842. getWireframeAttribute: getWireframeAttribute
  9843. };
  9844. }
  9845. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9846. const isWebGL2 = capabilities.isWebGL2;
  9847. let mode;
  9848. function setMode( value ) {
  9849. mode = value;
  9850. }
  9851. let type, bytesPerElement;
  9852. function setIndex( value ) {
  9853. type = value.type;
  9854. bytesPerElement = value.bytesPerElement;
  9855. }
  9856. function render( start, count ) {
  9857. gl.drawElements( mode, count, type, start * bytesPerElement );
  9858. info.update( count, mode, 1 );
  9859. }
  9860. function renderInstances( start, count, primcount ) {
  9861. if ( primcount === 0 ) return;
  9862. let extension, methodName;
  9863. if ( isWebGL2 ) {
  9864. extension = gl;
  9865. methodName = 'drawElementsInstanced';
  9866. } else {
  9867. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9868. methodName = 'drawElementsInstancedANGLE';
  9869. if ( extension === null ) {
  9870. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9871. return;
  9872. }
  9873. }
  9874. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9875. info.update( count, mode, primcount );
  9876. }
  9877. //
  9878. this.setMode = setMode;
  9879. this.setIndex = setIndex;
  9880. this.render = render;
  9881. this.renderInstances = renderInstances;
  9882. }
  9883. function WebGLInfo( gl ) {
  9884. const memory = {
  9885. geometries: 0,
  9886. textures: 0
  9887. };
  9888. const render = {
  9889. frame: 0,
  9890. calls: 0,
  9891. triangles: 0,
  9892. points: 0,
  9893. lines: 0
  9894. };
  9895. function update( count, mode, instanceCount ) {
  9896. render.calls ++;
  9897. switch ( mode ) {
  9898. case 4:
  9899. render.triangles += instanceCount * ( count / 3 );
  9900. break;
  9901. case 1:
  9902. render.lines += instanceCount * ( count / 2 );
  9903. break;
  9904. case 3:
  9905. render.lines += instanceCount * ( count - 1 );
  9906. break;
  9907. case 2:
  9908. render.lines += instanceCount * count;
  9909. break;
  9910. case 0:
  9911. render.points += instanceCount * count;
  9912. break;
  9913. default:
  9914. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9915. break;
  9916. }
  9917. }
  9918. function reset() {
  9919. render.frame ++;
  9920. render.calls = 0;
  9921. render.triangles = 0;
  9922. render.points = 0;
  9923. render.lines = 0;
  9924. }
  9925. return {
  9926. memory: memory,
  9927. render: render,
  9928. programs: null,
  9929. autoReset: true,
  9930. reset: reset,
  9931. update: update
  9932. };
  9933. }
  9934. class DataTexture2DArray extends Texture {
  9935. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9936. super( null );
  9937. this.image = { data, width, height, depth };
  9938. this.magFilter = NearestFilter;
  9939. this.minFilter = NearestFilter;
  9940. this.wrapR = ClampToEdgeWrapping;
  9941. this.generateMipmaps = false;
  9942. this.flipY = false;
  9943. this.unpackAlignment = 1;
  9944. }
  9945. }
  9946. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9947. function numericalSort( a, b ) {
  9948. return a[ 0 ] - b[ 0 ];
  9949. }
  9950. function absNumericalSort( a, b ) {
  9951. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9952. }
  9953. function denormalize( morph, attribute ) {
  9954. let denominator = 1;
  9955. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  9956. if ( array instanceof Int8Array ) denominator = 127;
  9957. else if ( array instanceof Int16Array ) denominator = 32767;
  9958. else if ( array instanceof Int32Array ) denominator = 2147483647;
  9959. else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array );
  9960. morph.divideScalar( denominator );
  9961. }
  9962. function WebGLMorphtargets( gl, capabilities, textures ) {
  9963. const influencesList = {};
  9964. const morphInfluences = new Float32Array( 8 );
  9965. const morphTextures = new WeakMap();
  9966. const morph = new Vector3();
  9967. const workInfluences = [];
  9968. for ( let i = 0; i < 8; i ++ ) {
  9969. workInfluences[ i ] = [ i, 0 ];
  9970. }
  9971. function update( object, geometry, material, program ) {
  9972. const objectInfluences = object.morphTargetInfluences;
  9973. if ( capabilities.isWebGL2 === true ) {
  9974. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9975. // into an array of data textures. Each layer represents a single morph target.
  9976. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  9977. let entry = morphTextures.get( geometry );
  9978. if ( entry === undefined || entry.count !== numberOfMorphTargets ) {
  9979. if ( entry !== undefined ) entry.texture.dispose();
  9980. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9981. const morphTargets = geometry.morphAttributes.position;
  9982. const morphNormals = geometry.morphAttributes.normal || [];
  9983. const numberOfVertices = geometry.attributes.position.count;
  9984. const numberOfVertexData = ( hasMorphNormals === true ) ? 2 : 1; // (v,n) vs. (v)
  9985. let width = numberOfVertices * numberOfVertexData;
  9986. let height = 1;
  9987. if ( width > capabilities.maxTextureSize ) {
  9988. height = Math.ceil( width / capabilities.maxTextureSize );
  9989. width = capabilities.maxTextureSize;
  9990. }
  9991. const buffer = new Float32Array( width * height * 4 * numberOfMorphTargets );
  9992. const texture = new DataTexture2DArray( buffer, width, height, numberOfMorphTargets );
  9993. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  9994. texture.type = FloatType;
  9995. texture.needsUpdate = true;
  9996. // fill buffer
  9997. const vertexDataStride = numberOfVertexData * 4;
  9998. for ( let i = 0; i < numberOfMorphTargets; i ++ ) {
  9999. const morphTarget = morphTargets[ i ];
  10000. const morphNormal = morphNormals[ i ];
  10001. const offset = width * height * 4 * i;
  10002. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10003. morph.fromBufferAttribute( morphTarget, j );
  10004. if ( morphTarget.normalized === true ) denormalize( morph, morphTarget );
  10005. const stride = j * vertexDataStride;
  10006. buffer[ offset + stride + 0 ] = morph.x;
  10007. buffer[ offset + stride + 1 ] = morph.y;
  10008. buffer[ offset + stride + 2 ] = morph.z;
  10009. buffer[ offset + stride + 3 ] = 0;
  10010. if ( hasMorphNormals === true ) {
  10011. morph.fromBufferAttribute( morphNormal, j );
  10012. if ( morphNormal.normalized === true ) denormalize( morph, morphNormal );
  10013. buffer[ offset + stride + 4 ] = morph.x;
  10014. buffer[ offset + stride + 5 ] = morph.y;
  10015. buffer[ offset + stride + 6 ] = morph.z;
  10016. buffer[ offset + stride + 7 ] = 0;
  10017. }
  10018. }
  10019. }
  10020. entry = {
  10021. count: numberOfMorphTargets,
  10022. texture: texture,
  10023. size: new Vector2( width, height )
  10024. };
  10025. morphTextures.set( geometry, entry );
  10026. function disposeTexture() {
  10027. texture.dispose();
  10028. morphTextures.delete( geometry );
  10029. geometry.removeEventListener( 'dispose', disposeTexture );
  10030. }
  10031. geometry.addEventListener( 'dispose', disposeTexture );
  10032. }
  10033. //
  10034. let morphInfluencesSum = 0;
  10035. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10036. morphInfluencesSum += objectInfluences[ i ];
  10037. }
  10038. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10039. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10040. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10041. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10042. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10043. } else {
  10044. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10045. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10046. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10047. let influences = influencesList[ geometry.id ];
  10048. if ( influences === undefined || influences.length !== length ) {
  10049. // initialise list
  10050. influences = [];
  10051. for ( let i = 0; i < length; i ++ ) {
  10052. influences[ i ] = [ i, 0 ];
  10053. }
  10054. influencesList[ geometry.id ] = influences;
  10055. }
  10056. // Collect influences
  10057. for ( let i = 0; i < length; i ++ ) {
  10058. const influence = influences[ i ];
  10059. influence[ 0 ] = i;
  10060. influence[ 1 ] = objectInfluences[ i ];
  10061. }
  10062. influences.sort( absNumericalSort );
  10063. for ( let i = 0; i < 8; i ++ ) {
  10064. if ( i < length && influences[ i ][ 1 ] ) {
  10065. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10066. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10067. } else {
  10068. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10069. workInfluences[ i ][ 1 ] = 0;
  10070. }
  10071. }
  10072. workInfluences.sort( numericalSort );
  10073. const morphTargets = geometry.morphAttributes.position;
  10074. const morphNormals = geometry.morphAttributes.normal;
  10075. let morphInfluencesSum = 0;
  10076. for ( let i = 0; i < 8; i ++ ) {
  10077. const influence = workInfluences[ i ];
  10078. const index = influence[ 0 ];
  10079. const value = influence[ 1 ];
  10080. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10081. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10082. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10083. }
  10084. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10085. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10086. }
  10087. morphInfluences[ i ] = value;
  10088. morphInfluencesSum += value;
  10089. } else {
  10090. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10091. geometry.deleteAttribute( 'morphTarget' + i );
  10092. }
  10093. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10094. geometry.deleteAttribute( 'morphNormal' + i );
  10095. }
  10096. morphInfluences[ i ] = 0;
  10097. }
  10098. }
  10099. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10100. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10101. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10102. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10103. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10104. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10105. }
  10106. }
  10107. return {
  10108. update: update
  10109. };
  10110. }
  10111. function WebGLObjects( gl, geometries, attributes, info ) {
  10112. let updateMap = new WeakMap();
  10113. function update( object ) {
  10114. const frame = info.render.frame;
  10115. const geometry = object.geometry;
  10116. const buffergeometry = geometries.get( object, geometry );
  10117. // Update once per frame
  10118. if ( updateMap.get( buffergeometry ) !== frame ) {
  10119. geometries.update( buffergeometry );
  10120. updateMap.set( buffergeometry, frame );
  10121. }
  10122. if ( object.isInstancedMesh ) {
  10123. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10124. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10125. }
  10126. attributes.update( object.instanceMatrix, 34962 );
  10127. if ( object.instanceColor !== null ) {
  10128. attributes.update( object.instanceColor, 34962 );
  10129. }
  10130. }
  10131. return buffergeometry;
  10132. }
  10133. function dispose() {
  10134. updateMap = new WeakMap();
  10135. }
  10136. function onInstancedMeshDispose( event ) {
  10137. const instancedMesh = event.target;
  10138. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10139. attributes.remove( instancedMesh.instanceMatrix );
  10140. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10141. }
  10142. return {
  10143. update: update,
  10144. dispose: dispose
  10145. };
  10146. }
  10147. class DataTexture3D extends Texture {
  10148. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10149. // We're going to add .setXXX() methods for setting properties later.
  10150. // Users can still set in DataTexture3D directly.
  10151. //
  10152. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10153. // texture.anisotropy = 16;
  10154. //
  10155. // See #14839
  10156. super( null );
  10157. this.image = { data, width, height, depth };
  10158. this.magFilter = NearestFilter;
  10159. this.minFilter = NearestFilter;
  10160. this.wrapR = ClampToEdgeWrapping;
  10161. this.generateMipmaps = false;
  10162. this.flipY = false;
  10163. this.unpackAlignment = 1;
  10164. }
  10165. }
  10166. DataTexture3D.prototype.isDataTexture3D = true;
  10167. /**
  10168. * Uniforms of a program.
  10169. * Those form a tree structure with a special top-level container for the root,
  10170. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10171. *
  10172. *
  10173. * Properties of inner nodes including the top-level container:
  10174. *
  10175. * .seq - array of nested uniforms
  10176. * .map - nested uniforms by name
  10177. *
  10178. *
  10179. * Methods of all nodes except the top-level container:
  10180. *
  10181. * .setValue( gl, value, [textures] )
  10182. *
  10183. * uploads a uniform value(s)
  10184. * the 'textures' parameter is needed for sampler uniforms
  10185. *
  10186. *
  10187. * Static methods of the top-level container (textures factorizations):
  10188. *
  10189. * .upload( gl, seq, values, textures )
  10190. *
  10191. * sets uniforms in 'seq' to 'values[id].value'
  10192. *
  10193. * .seqWithValue( seq, values ) : filteredSeq
  10194. *
  10195. * filters 'seq' entries with corresponding entry in values
  10196. *
  10197. *
  10198. * Methods of the top-level container (textures factorizations):
  10199. *
  10200. * .setValue( gl, name, value, textures )
  10201. *
  10202. * sets uniform with name 'name' to 'value'
  10203. *
  10204. * .setOptional( gl, obj, prop )
  10205. *
  10206. * like .set for an optional property of the object
  10207. *
  10208. */
  10209. const emptyTexture = new Texture();
  10210. const emptyTexture2dArray = new DataTexture2DArray();
  10211. const emptyTexture3d = new DataTexture3D();
  10212. const emptyCubeTexture = new CubeTexture();
  10213. // --- Utilities ---
  10214. // Array Caches (provide typed arrays for temporary by size)
  10215. const arrayCacheF32 = [];
  10216. const arrayCacheI32 = [];
  10217. // Float32Array caches used for uploading Matrix uniforms
  10218. const mat4array = new Float32Array( 16 );
  10219. const mat3array = new Float32Array( 9 );
  10220. const mat2array = new Float32Array( 4 );
  10221. // Flattening for arrays of vectors and matrices
  10222. function flatten( array, nBlocks, blockSize ) {
  10223. const firstElem = array[ 0 ];
  10224. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10225. // unoptimized: ! isNaN( firstElem )
  10226. // see http://jacksondunstan.com/articles/983
  10227. const n = nBlocks * blockSize;
  10228. let r = arrayCacheF32[ n ];
  10229. if ( r === undefined ) {
  10230. r = new Float32Array( n );
  10231. arrayCacheF32[ n ] = r;
  10232. }
  10233. if ( nBlocks !== 0 ) {
  10234. firstElem.toArray( r, 0 );
  10235. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10236. offset += blockSize;
  10237. array[ i ].toArray( r, offset );
  10238. }
  10239. }
  10240. return r;
  10241. }
  10242. function arraysEqual( a, b ) {
  10243. if ( a.length !== b.length ) return false;
  10244. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10245. if ( a[ i ] !== b[ i ] ) return false;
  10246. }
  10247. return true;
  10248. }
  10249. function copyArray( a, b ) {
  10250. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10251. a[ i ] = b[ i ];
  10252. }
  10253. }
  10254. // Texture unit allocation
  10255. function allocTexUnits( textures, n ) {
  10256. let r = arrayCacheI32[ n ];
  10257. if ( r === undefined ) {
  10258. r = new Int32Array( n );
  10259. arrayCacheI32[ n ] = r;
  10260. }
  10261. for ( let i = 0; i !== n; ++ i ) {
  10262. r[ i ] = textures.allocateTextureUnit();
  10263. }
  10264. return r;
  10265. }
  10266. // --- Setters ---
  10267. // Note: Defining these methods externally, because they come in a bunch
  10268. // and this way their names minify.
  10269. // Single scalar
  10270. function setValueV1f( gl, v ) {
  10271. const cache = this.cache;
  10272. if ( cache[ 0 ] === v ) return;
  10273. gl.uniform1f( this.addr, v );
  10274. cache[ 0 ] = v;
  10275. }
  10276. // Single float vector (from flat array or THREE.VectorN)
  10277. function setValueV2f( gl, v ) {
  10278. const cache = this.cache;
  10279. if ( v.x !== undefined ) {
  10280. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10281. gl.uniform2f( this.addr, v.x, v.y );
  10282. cache[ 0 ] = v.x;
  10283. cache[ 1 ] = v.y;
  10284. }
  10285. } else {
  10286. if ( arraysEqual( cache, v ) ) return;
  10287. gl.uniform2fv( this.addr, v );
  10288. copyArray( cache, v );
  10289. }
  10290. }
  10291. function setValueV3f( gl, v ) {
  10292. const cache = this.cache;
  10293. if ( v.x !== undefined ) {
  10294. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10295. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10296. cache[ 0 ] = v.x;
  10297. cache[ 1 ] = v.y;
  10298. cache[ 2 ] = v.z;
  10299. }
  10300. } else if ( v.r !== undefined ) {
  10301. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10302. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10303. cache[ 0 ] = v.r;
  10304. cache[ 1 ] = v.g;
  10305. cache[ 2 ] = v.b;
  10306. }
  10307. } else {
  10308. if ( arraysEqual( cache, v ) ) return;
  10309. gl.uniform3fv( this.addr, v );
  10310. copyArray( cache, v );
  10311. }
  10312. }
  10313. function setValueV4f( gl, v ) {
  10314. const cache = this.cache;
  10315. if ( v.x !== undefined ) {
  10316. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10317. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10318. cache[ 0 ] = v.x;
  10319. cache[ 1 ] = v.y;
  10320. cache[ 2 ] = v.z;
  10321. cache[ 3 ] = v.w;
  10322. }
  10323. } else {
  10324. if ( arraysEqual( cache, v ) ) return;
  10325. gl.uniform4fv( this.addr, v );
  10326. copyArray( cache, v );
  10327. }
  10328. }
  10329. // Single matrix (from flat array or THREE.MatrixN)
  10330. function setValueM2( gl, v ) {
  10331. const cache = this.cache;
  10332. const elements = v.elements;
  10333. if ( elements === undefined ) {
  10334. if ( arraysEqual( cache, v ) ) return;
  10335. gl.uniformMatrix2fv( this.addr, false, v );
  10336. copyArray( cache, v );
  10337. } else {
  10338. if ( arraysEqual( cache, elements ) ) return;
  10339. mat2array.set( elements );
  10340. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10341. copyArray( cache, elements );
  10342. }
  10343. }
  10344. function setValueM3( gl, v ) {
  10345. const cache = this.cache;
  10346. const elements = v.elements;
  10347. if ( elements === undefined ) {
  10348. if ( arraysEqual( cache, v ) ) return;
  10349. gl.uniformMatrix3fv( this.addr, false, v );
  10350. copyArray( cache, v );
  10351. } else {
  10352. if ( arraysEqual( cache, elements ) ) return;
  10353. mat3array.set( elements );
  10354. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10355. copyArray( cache, elements );
  10356. }
  10357. }
  10358. function setValueM4( gl, v ) {
  10359. const cache = this.cache;
  10360. const elements = v.elements;
  10361. if ( elements === undefined ) {
  10362. if ( arraysEqual( cache, v ) ) return;
  10363. gl.uniformMatrix4fv( this.addr, false, v );
  10364. copyArray( cache, v );
  10365. } else {
  10366. if ( arraysEqual( cache, elements ) ) return;
  10367. mat4array.set( elements );
  10368. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10369. copyArray( cache, elements );
  10370. }
  10371. }
  10372. // Single integer / boolean
  10373. function setValueV1i( gl, v ) {
  10374. const cache = this.cache;
  10375. if ( cache[ 0 ] === v ) return;
  10376. gl.uniform1i( this.addr, v );
  10377. cache[ 0 ] = v;
  10378. }
  10379. // Single integer / boolean vector (from flat array)
  10380. function setValueV2i( gl, v ) {
  10381. const cache = this.cache;
  10382. if ( arraysEqual( cache, v ) ) return;
  10383. gl.uniform2iv( this.addr, v );
  10384. copyArray( cache, v );
  10385. }
  10386. function setValueV3i( gl, v ) {
  10387. const cache = this.cache;
  10388. if ( arraysEqual( cache, v ) ) return;
  10389. gl.uniform3iv( this.addr, v );
  10390. copyArray( cache, v );
  10391. }
  10392. function setValueV4i( gl, v ) {
  10393. const cache = this.cache;
  10394. if ( arraysEqual( cache, v ) ) return;
  10395. gl.uniform4iv( this.addr, v );
  10396. copyArray( cache, v );
  10397. }
  10398. // Single unsigned integer
  10399. function setValueV1ui( gl, v ) {
  10400. const cache = this.cache;
  10401. if ( cache[ 0 ] === v ) return;
  10402. gl.uniform1ui( this.addr, v );
  10403. cache[ 0 ] = v;
  10404. }
  10405. // Single unsigned integer vector (from flat array)
  10406. function setValueV2ui( gl, v ) {
  10407. const cache = this.cache;
  10408. if ( arraysEqual( cache, v ) ) return;
  10409. gl.uniform2uiv( this.addr, v );
  10410. copyArray( cache, v );
  10411. }
  10412. function setValueV3ui( gl, v ) {
  10413. const cache = this.cache;
  10414. if ( arraysEqual( cache, v ) ) return;
  10415. gl.uniform3uiv( this.addr, v );
  10416. copyArray( cache, v );
  10417. }
  10418. function setValueV4ui( gl, v ) {
  10419. const cache = this.cache;
  10420. if ( arraysEqual( cache, v ) ) return;
  10421. gl.uniform4uiv( this.addr, v );
  10422. copyArray( cache, v );
  10423. }
  10424. // Single texture (2D / Cube)
  10425. function setValueT1( gl, v, textures ) {
  10426. const cache = this.cache;
  10427. const unit = textures.allocateTextureUnit();
  10428. if ( cache[ 0 ] !== unit ) {
  10429. gl.uniform1i( this.addr, unit );
  10430. cache[ 0 ] = unit;
  10431. }
  10432. textures.safeSetTexture2D( v || emptyTexture, unit );
  10433. }
  10434. function setValueT3D1( gl, v, textures ) {
  10435. const cache = this.cache;
  10436. const unit = textures.allocateTextureUnit();
  10437. if ( cache[ 0 ] !== unit ) {
  10438. gl.uniform1i( this.addr, unit );
  10439. cache[ 0 ] = unit;
  10440. }
  10441. textures.setTexture3D( v || emptyTexture3d, unit );
  10442. }
  10443. function setValueT6( gl, v, textures ) {
  10444. const cache = this.cache;
  10445. const unit = textures.allocateTextureUnit();
  10446. if ( cache[ 0 ] !== unit ) {
  10447. gl.uniform1i( this.addr, unit );
  10448. cache[ 0 ] = unit;
  10449. }
  10450. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10451. }
  10452. function setValueT2DArray1( gl, v, textures ) {
  10453. const cache = this.cache;
  10454. const unit = textures.allocateTextureUnit();
  10455. if ( cache[ 0 ] !== unit ) {
  10456. gl.uniform1i( this.addr, unit );
  10457. cache[ 0 ] = unit;
  10458. }
  10459. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10460. }
  10461. // Helper to pick the right setter for the singular case
  10462. function getSingularSetter( type ) {
  10463. switch ( type ) {
  10464. case 0x1406: return setValueV1f; // FLOAT
  10465. case 0x8b50: return setValueV2f; // _VEC2
  10466. case 0x8b51: return setValueV3f; // _VEC3
  10467. case 0x8b52: return setValueV4f; // _VEC4
  10468. case 0x8b5a: return setValueM2; // _MAT2
  10469. case 0x8b5b: return setValueM3; // _MAT3
  10470. case 0x8b5c: return setValueM4; // _MAT4
  10471. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10472. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10473. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10474. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10475. case 0x1405: return setValueV1ui; // UINT
  10476. case 0x8dc6: return setValueV2ui; // _VEC2
  10477. case 0x8dc7: return setValueV3ui; // _VEC3
  10478. case 0x8dc8: return setValueV4ui; // _VEC4
  10479. case 0x8b5e: // SAMPLER_2D
  10480. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10481. case 0x8dca: // INT_SAMPLER_2D
  10482. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10483. case 0x8b62: // SAMPLER_2D_SHADOW
  10484. return setValueT1;
  10485. case 0x8b5f: // SAMPLER_3D
  10486. case 0x8dcb: // INT_SAMPLER_3D
  10487. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10488. return setValueT3D1;
  10489. case 0x8b60: // SAMPLER_CUBE
  10490. case 0x8dcc: // INT_SAMPLER_CUBE
  10491. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10492. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10493. return setValueT6;
  10494. case 0x8dc1: // SAMPLER_2D_ARRAY
  10495. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10496. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10497. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10498. return setValueT2DArray1;
  10499. }
  10500. }
  10501. // Array of scalars
  10502. function setValueV1fArray( gl, v ) {
  10503. gl.uniform1fv( this.addr, v );
  10504. }
  10505. // Array of vectors (from flat array or array of THREE.VectorN)
  10506. function setValueV2fArray( gl, v ) {
  10507. const data = flatten( v, this.size, 2 );
  10508. gl.uniform2fv( this.addr, data );
  10509. }
  10510. function setValueV3fArray( gl, v ) {
  10511. const data = flatten( v, this.size, 3 );
  10512. gl.uniform3fv( this.addr, data );
  10513. }
  10514. function setValueV4fArray( gl, v ) {
  10515. const data = flatten( v, this.size, 4 );
  10516. gl.uniform4fv( this.addr, data );
  10517. }
  10518. // Array of matrices (from flat array or array of THREE.MatrixN)
  10519. function setValueM2Array( gl, v ) {
  10520. const data = flatten( v, this.size, 4 );
  10521. gl.uniformMatrix2fv( this.addr, false, data );
  10522. }
  10523. function setValueM3Array( gl, v ) {
  10524. const data = flatten( v, this.size, 9 );
  10525. gl.uniformMatrix3fv( this.addr, false, data );
  10526. }
  10527. function setValueM4Array( gl, v ) {
  10528. const data = flatten( v, this.size, 16 );
  10529. gl.uniformMatrix4fv( this.addr, false, data );
  10530. }
  10531. // Array of integer / boolean
  10532. function setValueV1iArray( gl, v ) {
  10533. gl.uniform1iv( this.addr, v );
  10534. }
  10535. // Array of integer / boolean vectors (from flat array)
  10536. function setValueV2iArray( gl, v ) {
  10537. gl.uniform2iv( this.addr, v );
  10538. }
  10539. function setValueV3iArray( gl, v ) {
  10540. gl.uniform3iv( this.addr, v );
  10541. }
  10542. function setValueV4iArray( gl, v ) {
  10543. gl.uniform4iv( this.addr, v );
  10544. }
  10545. // Array of unsigned integer
  10546. function setValueV1uiArray( gl, v ) {
  10547. gl.uniform1uiv( this.addr, v );
  10548. }
  10549. // Array of unsigned integer vectors (from flat array)
  10550. function setValueV2uiArray( gl, v ) {
  10551. gl.uniform2uiv( this.addr, v );
  10552. }
  10553. function setValueV3uiArray( gl, v ) {
  10554. gl.uniform3uiv( this.addr, v );
  10555. }
  10556. function setValueV4uiArray( gl, v ) {
  10557. gl.uniform4uiv( this.addr, v );
  10558. }
  10559. // Array of textures (2D / 3D / Cube / 2DArray)
  10560. function setValueT1Array( gl, v, textures ) {
  10561. const n = v.length;
  10562. const units = allocTexUnits( textures, n );
  10563. gl.uniform1iv( this.addr, units );
  10564. for ( let i = 0; i !== n; ++ i ) {
  10565. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10566. }
  10567. }
  10568. function setValueT3DArray( gl, v, textures ) {
  10569. const n = v.length;
  10570. const units = allocTexUnits( textures, n );
  10571. gl.uniform1iv( this.addr, units );
  10572. for ( let i = 0; i !== n; ++ i ) {
  10573. textures.setTexture3D( v[ i ] || emptyTexture3d, units[ i ] );
  10574. }
  10575. }
  10576. function setValueT6Array( gl, v, textures ) {
  10577. const n = v.length;
  10578. const units = allocTexUnits( textures, n );
  10579. gl.uniform1iv( this.addr, units );
  10580. for ( let i = 0; i !== n; ++ i ) {
  10581. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10582. }
  10583. }
  10584. function setValueT2DArrayArray( gl, v, textures ) {
  10585. const n = v.length;
  10586. const units = allocTexUnits( textures, n );
  10587. gl.uniform1iv( this.addr, units );
  10588. for ( let i = 0; i !== n; ++ i ) {
  10589. textures.setTexture2DArray( v[ i ] || emptyTexture2dArray, units[ i ] );
  10590. }
  10591. }
  10592. // Helper to pick the right setter for a pure (bottom-level) array
  10593. function getPureArraySetter( type ) {
  10594. switch ( type ) {
  10595. case 0x1406: return setValueV1fArray; // FLOAT
  10596. case 0x8b50: return setValueV2fArray; // _VEC2
  10597. case 0x8b51: return setValueV3fArray; // _VEC3
  10598. case 0x8b52: return setValueV4fArray; // _VEC4
  10599. case 0x8b5a: return setValueM2Array; // _MAT2
  10600. case 0x8b5b: return setValueM3Array; // _MAT3
  10601. case 0x8b5c: return setValueM4Array; // _MAT4
  10602. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10603. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10604. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10605. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10606. case 0x1405: return setValueV1uiArray; // UINT
  10607. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10608. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10609. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10610. case 0x8b5e: // SAMPLER_2D
  10611. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10612. case 0x8dca: // INT_SAMPLER_2D
  10613. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10614. case 0x8b62: // SAMPLER_2D_SHADOW
  10615. return setValueT1Array;
  10616. case 0x8b5f: // SAMPLER_3D
  10617. case 0x8dcb: // INT_SAMPLER_3D
  10618. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10619. return setValueT3DArray;
  10620. case 0x8b60: // SAMPLER_CUBE
  10621. case 0x8dcc: // INT_SAMPLER_CUBE
  10622. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10623. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10624. return setValueT6Array;
  10625. case 0x8dc1: // SAMPLER_2D_ARRAY
  10626. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10627. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10628. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10629. return setValueT2DArrayArray;
  10630. }
  10631. }
  10632. // --- Uniform Classes ---
  10633. function SingleUniform( id, activeInfo, addr ) {
  10634. this.id = id;
  10635. this.addr = addr;
  10636. this.cache = [];
  10637. this.setValue = getSingularSetter( activeInfo.type );
  10638. // this.path = activeInfo.name; // DEBUG
  10639. }
  10640. function PureArrayUniform( id, activeInfo, addr ) {
  10641. this.id = id;
  10642. this.addr = addr;
  10643. this.cache = [];
  10644. this.size = activeInfo.size;
  10645. this.setValue = getPureArraySetter( activeInfo.type );
  10646. // this.path = activeInfo.name; // DEBUG
  10647. }
  10648. PureArrayUniform.prototype.updateCache = function ( data ) {
  10649. const cache = this.cache;
  10650. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10651. this.cache = new Float32Array( data.length );
  10652. }
  10653. copyArray( cache, data );
  10654. };
  10655. function StructuredUniform( id ) {
  10656. this.id = id;
  10657. this.seq = [];
  10658. this.map = {};
  10659. }
  10660. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10661. const seq = this.seq;
  10662. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10663. const u = seq[ i ];
  10664. u.setValue( gl, value[ u.id ], textures );
  10665. }
  10666. };
  10667. // --- Top-level ---
  10668. // Parser - builds up the property tree from the path strings
  10669. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10670. // extracts
  10671. // - the identifier (member name or array index)
  10672. // - followed by an optional right bracket (found when array index)
  10673. // - followed by an optional left bracket or dot (type of subscript)
  10674. //
  10675. // Note: These portions can be read in a non-overlapping fashion and
  10676. // allow straightforward parsing of the hierarchy that WebGL encodes
  10677. // in the uniform names.
  10678. function addUniform( container, uniformObject ) {
  10679. container.seq.push( uniformObject );
  10680. container.map[ uniformObject.id ] = uniformObject;
  10681. }
  10682. function parseUniform( activeInfo, addr, container ) {
  10683. const path = activeInfo.name,
  10684. pathLength = path.length;
  10685. // reset RegExp object, because of the early exit of a previous run
  10686. RePathPart.lastIndex = 0;
  10687. while ( true ) {
  10688. const match = RePathPart.exec( path ),
  10689. matchEnd = RePathPart.lastIndex;
  10690. let id = match[ 1 ];
  10691. const idIsIndex = match[ 2 ] === ']',
  10692. subscript = match[ 3 ];
  10693. if ( idIsIndex ) id = id | 0; // convert to integer
  10694. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10695. // bare name or "pure" bottom-level array "[0]" suffix
  10696. addUniform( container, subscript === undefined ?
  10697. new SingleUniform( id, activeInfo, addr ) :
  10698. new PureArrayUniform( id, activeInfo, addr ) );
  10699. break;
  10700. } else {
  10701. // step into inner node / create it in case it doesn't exist
  10702. const map = container.map;
  10703. let next = map[ id ];
  10704. if ( next === undefined ) {
  10705. next = new StructuredUniform( id );
  10706. addUniform( container, next );
  10707. }
  10708. container = next;
  10709. }
  10710. }
  10711. }
  10712. // Root Container
  10713. function WebGLUniforms( gl, program ) {
  10714. this.seq = [];
  10715. this.map = {};
  10716. const n = gl.getProgramParameter( program, 35718 );
  10717. for ( let i = 0; i < n; ++ i ) {
  10718. const info = gl.getActiveUniform( program, i ),
  10719. addr = gl.getUniformLocation( program, info.name );
  10720. parseUniform( info, addr, this );
  10721. }
  10722. }
  10723. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10724. const u = this.map[ name ];
  10725. if ( u !== undefined ) u.setValue( gl, value, textures );
  10726. };
  10727. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10728. const v = object[ name ];
  10729. if ( v !== undefined ) this.setValue( gl, name, v );
  10730. };
  10731. // Static interface
  10732. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10733. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10734. const u = seq[ i ],
  10735. v = values[ u.id ];
  10736. if ( v.needsUpdate !== false ) {
  10737. // note: always updating when .needsUpdate is undefined
  10738. u.setValue( gl, v.value, textures );
  10739. }
  10740. }
  10741. };
  10742. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10743. const r = [];
  10744. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10745. const u = seq[ i ];
  10746. if ( u.id in values ) r.push( u );
  10747. }
  10748. return r;
  10749. };
  10750. function WebGLShader( gl, type, string ) {
  10751. const shader = gl.createShader( type );
  10752. gl.shaderSource( shader, string );
  10753. gl.compileShader( shader );
  10754. return shader;
  10755. }
  10756. let programIdCount = 0;
  10757. function addLineNumbers( string ) {
  10758. const lines = string.split( '\n' );
  10759. for ( let i = 0; i < lines.length; i ++ ) {
  10760. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10761. }
  10762. return lines.join( '\n' );
  10763. }
  10764. function getEncodingComponents( encoding ) {
  10765. switch ( encoding ) {
  10766. case LinearEncoding:
  10767. return [ 'Linear', '( value )' ];
  10768. case sRGBEncoding:
  10769. return [ 'sRGB', '( value )' ];
  10770. default:
  10771. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10772. return [ 'Linear', '( value )' ];
  10773. }
  10774. }
  10775. function getShaderErrors( gl, shader, type ) {
  10776. const status = gl.getShaderParameter( shader, 35713 );
  10777. const errors = gl.getShaderInfoLog( shader ).trim();
  10778. if ( status && errors === '' ) return '';
  10779. // --enable-privileged-webgl-extension
  10780. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10781. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers( gl.getShaderSource( shader ) );
  10782. }
  10783. function getTexelEncodingFunction( functionName, encoding ) {
  10784. const components = getEncodingComponents( encoding );
  10785. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10786. }
  10787. function getToneMappingFunction( functionName, toneMapping ) {
  10788. let toneMappingName;
  10789. switch ( toneMapping ) {
  10790. case LinearToneMapping:
  10791. toneMappingName = 'Linear';
  10792. break;
  10793. case ReinhardToneMapping:
  10794. toneMappingName = 'Reinhard';
  10795. break;
  10796. case CineonToneMapping:
  10797. toneMappingName = 'OptimizedCineon';
  10798. break;
  10799. case ACESFilmicToneMapping:
  10800. toneMappingName = 'ACESFilmic';
  10801. break;
  10802. case CustomToneMapping:
  10803. toneMappingName = 'Custom';
  10804. break;
  10805. default:
  10806. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10807. toneMappingName = 'Linear';
  10808. }
  10809. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10810. }
  10811. function generateExtensions( parameters ) {
  10812. const chunks = [
  10813. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10814. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10815. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10816. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10817. ];
  10818. return chunks.filter( filterEmptyLine ).join( '\n' );
  10819. }
  10820. function generateDefines( defines ) {
  10821. const chunks = [];
  10822. for ( const name in defines ) {
  10823. const value = defines[ name ];
  10824. if ( value === false ) continue;
  10825. chunks.push( '#define ' + name + ' ' + value );
  10826. }
  10827. return chunks.join( '\n' );
  10828. }
  10829. function fetchAttributeLocations( gl, program ) {
  10830. const attributes = {};
  10831. const n = gl.getProgramParameter( program, 35721 );
  10832. for ( let i = 0; i < n; i ++ ) {
  10833. const info = gl.getActiveAttrib( program, i );
  10834. const name = info.name;
  10835. let locationSize = 1;
  10836. if ( info.type === 35674 ) locationSize = 2;
  10837. if ( info.type === 35675 ) locationSize = 3;
  10838. if ( info.type === 35676 ) locationSize = 4;
  10839. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10840. attributes[ name ] = {
  10841. type: info.type,
  10842. location: gl.getAttribLocation( program, name ),
  10843. locationSize: locationSize
  10844. };
  10845. }
  10846. return attributes;
  10847. }
  10848. function filterEmptyLine( string ) {
  10849. return string !== '';
  10850. }
  10851. function replaceLightNums( string, parameters ) {
  10852. return string
  10853. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10854. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10855. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10856. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10857. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10858. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10859. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10860. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10861. }
  10862. function replaceClippingPlaneNums( string, parameters ) {
  10863. return string
  10864. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10865. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10866. }
  10867. // Resolve Includes
  10868. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10869. function resolveIncludes( string ) {
  10870. return string.replace( includePattern, includeReplacer );
  10871. }
  10872. function includeReplacer( match, include ) {
  10873. const string = ShaderChunk[ include ];
  10874. if ( string === undefined ) {
  10875. throw new Error( 'Can not resolve #include <' + include + '>' );
  10876. }
  10877. return resolveIncludes( string );
  10878. }
  10879. // Unroll Loops
  10880. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10881. 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;
  10882. function unrollLoops( string ) {
  10883. return string
  10884. .replace( unrollLoopPattern, loopReplacer )
  10885. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10886. }
  10887. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10888. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10889. return loopReplacer( match, start, end, snippet );
  10890. }
  10891. function loopReplacer( match, start, end, snippet ) {
  10892. let string = '';
  10893. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10894. string += snippet
  10895. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10896. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10897. }
  10898. return string;
  10899. }
  10900. //
  10901. function generatePrecision( parameters ) {
  10902. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10903. if ( parameters.precision === 'highp' ) {
  10904. precisionstring += '\n#define HIGH_PRECISION';
  10905. } else if ( parameters.precision === 'mediump' ) {
  10906. precisionstring += '\n#define MEDIUM_PRECISION';
  10907. } else if ( parameters.precision === 'lowp' ) {
  10908. precisionstring += '\n#define LOW_PRECISION';
  10909. }
  10910. return precisionstring;
  10911. }
  10912. function generateShadowMapTypeDefine( parameters ) {
  10913. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10914. if ( parameters.shadowMapType === PCFShadowMap ) {
  10915. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10916. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10917. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10918. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10919. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10920. }
  10921. return shadowMapTypeDefine;
  10922. }
  10923. function generateEnvMapTypeDefine( parameters ) {
  10924. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10925. if ( parameters.envMap ) {
  10926. switch ( parameters.envMapMode ) {
  10927. case CubeReflectionMapping:
  10928. case CubeRefractionMapping:
  10929. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10930. break;
  10931. case CubeUVReflectionMapping:
  10932. case CubeUVRefractionMapping:
  10933. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10934. break;
  10935. }
  10936. }
  10937. return envMapTypeDefine;
  10938. }
  10939. function generateEnvMapModeDefine( parameters ) {
  10940. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10941. if ( parameters.envMap ) {
  10942. switch ( parameters.envMapMode ) {
  10943. case CubeRefractionMapping:
  10944. case CubeUVRefractionMapping:
  10945. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10946. break;
  10947. }
  10948. }
  10949. return envMapModeDefine;
  10950. }
  10951. function generateEnvMapBlendingDefine( parameters ) {
  10952. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10953. if ( parameters.envMap ) {
  10954. switch ( parameters.combine ) {
  10955. case MultiplyOperation:
  10956. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10957. break;
  10958. case MixOperation:
  10959. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10960. break;
  10961. case AddOperation:
  10962. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10963. break;
  10964. }
  10965. }
  10966. return envMapBlendingDefine;
  10967. }
  10968. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10969. // TODO Send this event to Three.js DevTools
  10970. // console.log( 'WebGLProgram', cacheKey );
  10971. const gl = renderer.getContext();
  10972. const defines = parameters.defines;
  10973. let vertexShader = parameters.vertexShader;
  10974. let fragmentShader = parameters.fragmentShader;
  10975. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10976. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10977. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10978. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10979. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10980. const customDefines = generateDefines( defines );
  10981. const program = gl.createProgram();
  10982. let prefixVertex, prefixFragment;
  10983. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10984. if ( parameters.isRawShaderMaterial ) {
  10985. prefixVertex = [
  10986. customDefines
  10987. ].filter( filterEmptyLine ).join( '\n' );
  10988. if ( prefixVertex.length > 0 ) {
  10989. prefixVertex += '\n';
  10990. }
  10991. prefixFragment = [
  10992. customExtensions,
  10993. customDefines
  10994. ].filter( filterEmptyLine ).join( '\n' );
  10995. if ( prefixFragment.length > 0 ) {
  10996. prefixFragment += '\n';
  10997. }
  10998. } else {
  10999. prefixVertex = [
  11000. generatePrecision( parameters ),
  11001. '#define SHADER_NAME ' + parameters.shaderName,
  11002. customDefines,
  11003. parameters.instancing ? '#define USE_INSTANCING' : '',
  11004. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11005. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11006. '#define MAX_BONES ' + parameters.maxBones,
  11007. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11008. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11009. parameters.map ? '#define USE_MAP' : '',
  11010. parameters.envMap ? '#define USE_ENVMAP' : '',
  11011. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11012. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11013. parameters.aoMap ? '#define USE_AOMAP' : '',
  11014. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11015. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11016. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11017. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11018. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11019. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11020. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11021. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11022. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11023. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11024. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11025. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11026. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11027. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11028. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11029. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11030. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11031. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11032. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11033. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11034. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11035. parameters.vertexColors ? '#define USE_COLOR' : '',
  11036. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11037. parameters.vertexUvs ? '#define USE_UV' : '',
  11038. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11039. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11040. parameters.skinning ? '#define USE_SKINNING' : '',
  11041. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  11042. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11043. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11044. ( parameters.morphTargets && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11045. ( parameters.morphTargets && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11046. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11047. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11048. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11049. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11050. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11051. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11052. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11053. 'uniform mat4 modelMatrix;',
  11054. 'uniform mat4 modelViewMatrix;',
  11055. 'uniform mat4 projectionMatrix;',
  11056. 'uniform mat4 viewMatrix;',
  11057. 'uniform mat3 normalMatrix;',
  11058. 'uniform vec3 cameraPosition;',
  11059. 'uniform bool isOrthographic;',
  11060. '#ifdef USE_INSTANCING',
  11061. ' attribute mat4 instanceMatrix;',
  11062. '#endif',
  11063. '#ifdef USE_INSTANCING_COLOR',
  11064. ' attribute vec3 instanceColor;',
  11065. '#endif',
  11066. 'attribute vec3 position;',
  11067. 'attribute vec3 normal;',
  11068. 'attribute vec2 uv;',
  11069. '#ifdef USE_TANGENT',
  11070. ' attribute vec4 tangent;',
  11071. '#endif',
  11072. '#if defined( USE_COLOR_ALPHA )',
  11073. ' attribute vec4 color;',
  11074. '#elif defined( USE_COLOR )',
  11075. ' attribute vec3 color;',
  11076. '#endif',
  11077. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11078. ' attribute vec3 morphTarget0;',
  11079. ' attribute vec3 morphTarget1;',
  11080. ' attribute vec3 morphTarget2;',
  11081. ' attribute vec3 morphTarget3;',
  11082. ' #ifdef USE_MORPHNORMALS',
  11083. ' attribute vec3 morphNormal0;',
  11084. ' attribute vec3 morphNormal1;',
  11085. ' attribute vec3 morphNormal2;',
  11086. ' attribute vec3 morphNormal3;',
  11087. ' #else',
  11088. ' attribute vec3 morphTarget4;',
  11089. ' attribute vec3 morphTarget5;',
  11090. ' attribute vec3 morphTarget6;',
  11091. ' attribute vec3 morphTarget7;',
  11092. ' #endif',
  11093. '#endif',
  11094. '#ifdef USE_SKINNING',
  11095. ' attribute vec4 skinIndex;',
  11096. ' attribute vec4 skinWeight;',
  11097. '#endif',
  11098. '\n'
  11099. ].filter( filterEmptyLine ).join( '\n' );
  11100. prefixFragment = [
  11101. customExtensions,
  11102. generatePrecision( parameters ),
  11103. '#define SHADER_NAME ' + parameters.shaderName,
  11104. customDefines,
  11105. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11106. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11107. parameters.map ? '#define USE_MAP' : '',
  11108. parameters.matcap ? '#define USE_MATCAP' : '',
  11109. parameters.envMap ? '#define USE_ENVMAP' : '',
  11110. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11111. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11112. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11113. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11114. parameters.aoMap ? '#define USE_AOMAP' : '',
  11115. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11116. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11117. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11118. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11119. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11120. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11121. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11122. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11123. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11124. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11125. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11126. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11127. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11128. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11129. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11130. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11131. parameters.sheen ? '#define USE_SHEEN' : '',
  11132. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11133. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11134. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11135. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11136. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11137. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11138. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11139. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11140. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11141. parameters.vertexUvs ? '#define USE_UV' : '',
  11142. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11143. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11144. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11145. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11146. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11147. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11148. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11149. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11150. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11151. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11152. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11153. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11154. 'uniform mat4 viewMatrix;',
  11155. 'uniform vec3 cameraPosition;',
  11156. 'uniform bool isOrthographic;',
  11157. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11158. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11159. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11160. parameters.dithering ? '#define DITHERING' : '',
  11161. parameters.transparent ? '' : '#define OPAQUE',
  11162. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11163. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11164. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11165. '\n'
  11166. ].filter( filterEmptyLine ).join( '\n' );
  11167. }
  11168. vertexShader = resolveIncludes( vertexShader );
  11169. vertexShader = replaceLightNums( vertexShader, parameters );
  11170. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11171. fragmentShader = resolveIncludes( fragmentShader );
  11172. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11173. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11174. vertexShader = unrollLoops( vertexShader );
  11175. fragmentShader = unrollLoops( fragmentShader );
  11176. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11177. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11178. versionString = '#version 300 es\n';
  11179. prefixVertex = [
  11180. 'precision mediump sampler2DArray;',
  11181. '#define attribute in',
  11182. '#define varying out',
  11183. '#define texture2D texture'
  11184. ].join( '\n' ) + '\n' + prefixVertex;
  11185. prefixFragment = [
  11186. '#define varying in',
  11187. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11188. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11189. '#define gl_FragDepthEXT gl_FragDepth',
  11190. '#define texture2D texture',
  11191. '#define textureCube texture',
  11192. '#define texture2DProj textureProj',
  11193. '#define texture2DLodEXT textureLod',
  11194. '#define texture2DProjLodEXT textureProjLod',
  11195. '#define textureCubeLodEXT textureLod',
  11196. '#define texture2DGradEXT textureGrad',
  11197. '#define texture2DProjGradEXT textureProjGrad',
  11198. '#define textureCubeGradEXT textureGrad'
  11199. ].join( '\n' ) + '\n' + prefixFragment;
  11200. }
  11201. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11202. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11203. // console.log( '*VERTEX*', vertexGlsl );
  11204. // console.log( '*FRAGMENT*', fragmentGlsl );
  11205. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11206. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11207. gl.attachShader( program, glVertexShader );
  11208. gl.attachShader( program, glFragmentShader );
  11209. // Force a particular attribute to index 0.
  11210. if ( parameters.index0AttributeName !== undefined ) {
  11211. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11212. } else if ( parameters.morphTargets === true ) {
  11213. // programs with morphTargets displace position out of attribute 0
  11214. gl.bindAttribLocation( program, 0, 'position' );
  11215. }
  11216. gl.linkProgram( program );
  11217. // check for link errors
  11218. if ( renderer.debug.checkShaderErrors ) {
  11219. const programLog = gl.getProgramInfoLog( program ).trim();
  11220. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11221. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11222. let runnable = true;
  11223. let haveDiagnostics = true;
  11224. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11225. runnable = false;
  11226. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11227. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11228. console.error(
  11229. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11230. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11231. 'Program Info Log: ' + programLog + '\n' +
  11232. vertexErrors + '\n' +
  11233. fragmentErrors
  11234. );
  11235. } else if ( programLog !== '' ) {
  11236. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11237. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11238. haveDiagnostics = false;
  11239. }
  11240. if ( haveDiagnostics ) {
  11241. this.diagnostics = {
  11242. runnable: runnable,
  11243. programLog: programLog,
  11244. vertexShader: {
  11245. log: vertexLog,
  11246. prefix: prefixVertex
  11247. },
  11248. fragmentShader: {
  11249. log: fragmentLog,
  11250. prefix: prefixFragment
  11251. }
  11252. };
  11253. }
  11254. }
  11255. // Clean up
  11256. // Crashes in iOS9 and iOS10. #18402
  11257. // gl.detachShader( program, glVertexShader );
  11258. // gl.detachShader( program, glFragmentShader );
  11259. gl.deleteShader( glVertexShader );
  11260. gl.deleteShader( glFragmentShader );
  11261. // set up caching for uniform locations
  11262. let cachedUniforms;
  11263. this.getUniforms = function () {
  11264. if ( cachedUniforms === undefined ) {
  11265. cachedUniforms = new WebGLUniforms( gl, program );
  11266. }
  11267. return cachedUniforms;
  11268. };
  11269. // set up caching for attribute locations
  11270. let cachedAttributes;
  11271. this.getAttributes = function () {
  11272. if ( cachedAttributes === undefined ) {
  11273. cachedAttributes = fetchAttributeLocations( gl, program );
  11274. }
  11275. return cachedAttributes;
  11276. };
  11277. // free resource
  11278. this.destroy = function () {
  11279. bindingStates.releaseStatesOfProgram( this );
  11280. gl.deleteProgram( program );
  11281. this.program = undefined;
  11282. };
  11283. //
  11284. this.name = parameters.shaderName;
  11285. this.id = programIdCount ++;
  11286. this.cacheKey = cacheKey;
  11287. this.usedTimes = 1;
  11288. this.program = program;
  11289. this.vertexShader = glVertexShader;
  11290. this.fragmentShader = glFragmentShader;
  11291. return this;
  11292. }
  11293. let _id = 0;
  11294. class WebGLShaderCache {
  11295. constructor() {
  11296. this.shaderCache = new Map();
  11297. this.materialCache = new Map();
  11298. }
  11299. update( material ) {
  11300. const vertexShader = material.vertexShader;
  11301. const fragmentShader = material.fragmentShader;
  11302. const vertexShaderStage = this._getShaderStage( vertexShader );
  11303. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11304. const materialShaders = this._getShaderCacheForMaterial( material );
  11305. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11306. materialShaders.add( vertexShaderStage );
  11307. vertexShaderStage.usedTimes ++;
  11308. }
  11309. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11310. materialShaders.add( fragmentShaderStage );
  11311. fragmentShaderStage.usedTimes ++;
  11312. }
  11313. return this;
  11314. }
  11315. remove( material ) {
  11316. const materialShaders = this.materialCache.get( material );
  11317. for ( const shaderStage of materialShaders ) {
  11318. shaderStage.usedTimes --;
  11319. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage );
  11320. }
  11321. this.materialCache.delete( material );
  11322. return this;
  11323. }
  11324. getVertexShaderID( material ) {
  11325. return this._getShaderStage( material.vertexShader ).id;
  11326. }
  11327. getFragmentShaderID( material ) {
  11328. return this._getShaderStage( material.fragmentShader ).id;
  11329. }
  11330. dispose() {
  11331. this.shaderCache.clear();
  11332. this.materialCache.clear();
  11333. }
  11334. _getShaderCacheForMaterial( material ) {
  11335. const cache = this.materialCache;
  11336. if ( cache.has( material ) === false ) {
  11337. cache.set( material, new Set() );
  11338. }
  11339. return cache.get( material );
  11340. }
  11341. _getShaderStage( code ) {
  11342. const cache = this.shaderCache;
  11343. if ( cache.has( code ) === false ) {
  11344. const stage = new WebGLShaderStage();
  11345. cache.set( code, stage );
  11346. }
  11347. return cache.get( code );
  11348. }
  11349. }
  11350. class WebGLShaderStage {
  11351. constructor() {
  11352. this.id = _id ++;
  11353. this.usedTimes = 0;
  11354. }
  11355. }
  11356. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11357. const _programLayers = new Layers();
  11358. const _customShaders = new WebGLShaderCache();
  11359. const programs = [];
  11360. const isWebGL2 = capabilities.isWebGL2;
  11361. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11362. const floatVertexTextures = capabilities.floatVertexTextures;
  11363. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11364. const vertexTextures = capabilities.vertexTextures;
  11365. let precision = capabilities.precision;
  11366. const shaderIDs = {
  11367. MeshDepthMaterial: 'depth',
  11368. MeshDistanceMaterial: 'distanceRGBA',
  11369. MeshNormalMaterial: 'normal',
  11370. MeshBasicMaterial: 'basic',
  11371. MeshLambertMaterial: 'lambert',
  11372. MeshPhongMaterial: 'phong',
  11373. MeshToonMaterial: 'toon',
  11374. MeshStandardMaterial: 'physical',
  11375. MeshPhysicalMaterial: 'physical',
  11376. MeshMatcapMaterial: 'matcap',
  11377. LineBasicMaterial: 'basic',
  11378. LineDashedMaterial: 'dashed',
  11379. PointsMaterial: 'points',
  11380. ShadowMaterial: 'shadow',
  11381. SpriteMaterial: 'sprite'
  11382. };
  11383. function getMaxBones( object ) {
  11384. const skeleton = object.skeleton;
  11385. const bones = skeleton.bones;
  11386. if ( floatVertexTextures ) {
  11387. return 1024;
  11388. } else {
  11389. // default for when object is not specified
  11390. // ( for example when prebuilding shader to be used with multiple objects )
  11391. //
  11392. // - leave some extra space for other uniforms
  11393. // - limit here is ANGLE's 254 max uniform vectors
  11394. // (up to 54 should be safe)
  11395. const nVertexUniforms = maxVertexUniforms;
  11396. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11397. const maxBones = Math.min( nVertexMatrices, bones.length );
  11398. if ( maxBones < bones.length ) {
  11399. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11400. return 0;
  11401. }
  11402. return maxBones;
  11403. }
  11404. }
  11405. function getParameters( material, lights, shadows, scene, object ) {
  11406. const fog = scene.fog;
  11407. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11408. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11409. const shaderID = shaderIDs[ material.type ];
  11410. // heuristics to create shader parameters according to lights in the scene
  11411. // (not to blow over maxLights budget)
  11412. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11413. if ( material.precision !== null ) {
  11414. precision = capabilities.getMaxPrecision( material.precision );
  11415. if ( precision !== material.precision ) {
  11416. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11417. }
  11418. }
  11419. let vertexShader, fragmentShader;
  11420. let customVertexShaderID, customFragmentShaderID;
  11421. if ( shaderID ) {
  11422. const shader = ShaderLib[ shaderID ];
  11423. vertexShader = shader.vertexShader;
  11424. fragmentShader = shader.fragmentShader;
  11425. } else {
  11426. vertexShader = material.vertexShader;
  11427. fragmentShader = material.fragmentShader;
  11428. _customShaders.update( material );
  11429. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11430. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11431. }
  11432. const currentRenderTarget = renderer.getRenderTarget();
  11433. const useAlphaTest = material.alphaTest > 0;
  11434. const useClearcoat = material.clearcoat > 0;
  11435. const parameters = {
  11436. isWebGL2: isWebGL2,
  11437. shaderID: shaderID,
  11438. shaderName: material.type,
  11439. vertexShader: vertexShader,
  11440. fragmentShader: fragmentShader,
  11441. defines: material.defines,
  11442. customVertexShaderID: customVertexShaderID,
  11443. customFragmentShaderID: customFragmentShaderID,
  11444. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11445. glslVersion: material.glslVersion,
  11446. precision: precision,
  11447. instancing: object.isInstancedMesh === true,
  11448. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11449. supportsVertexTextures: vertexTextures,
  11450. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11451. map: !! material.map,
  11452. matcap: !! material.matcap,
  11453. envMap: !! envMap,
  11454. envMapMode: envMap && envMap.mapping,
  11455. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11456. lightMap: !! material.lightMap,
  11457. aoMap: !! material.aoMap,
  11458. emissiveMap: !! material.emissiveMap,
  11459. bumpMap: !! material.bumpMap,
  11460. normalMap: !! material.normalMap,
  11461. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11462. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11463. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11464. clearcoat: useClearcoat,
  11465. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11466. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11467. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11468. displacementMap: !! material.displacementMap,
  11469. roughnessMap: !! material.roughnessMap,
  11470. metalnessMap: !! material.metalnessMap,
  11471. specularMap: !! material.specularMap,
  11472. specularIntensityMap: !! material.specularIntensityMap,
  11473. specularColorMap: !! material.specularColorMap,
  11474. transparent: material.transparent,
  11475. alphaMap: !! material.alphaMap,
  11476. alphaTest: useAlphaTest,
  11477. gradientMap: !! material.gradientMap,
  11478. sheen: material.sheen > 0,
  11479. sheenColorMap: !! material.sheenColorMap,
  11480. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11481. transmission: material.transmission > 0,
  11482. transmissionMap: !! material.transmissionMap,
  11483. thicknessMap: !! material.thicknessMap,
  11484. combine: material.combine,
  11485. vertexTangents: ( !! material.normalMap && !! object.geometry && !! object.geometry.attributes.tangent ),
  11486. vertexColors: material.vertexColors,
  11487. vertexAlphas: material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11488. 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,
  11489. 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,
  11490. fog: !! fog,
  11491. useFog: material.fog,
  11492. fogExp2: ( fog && fog.isFogExp2 ),
  11493. flatShading: !! material.flatShading,
  11494. sizeAttenuation: material.sizeAttenuation,
  11495. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11496. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11497. maxBones: maxBones,
  11498. useVertexTexture: floatVertexTextures,
  11499. morphTargets: !! object.geometry && !! object.geometry.morphAttributes.position,
  11500. morphNormals: !! object.geometry && !! object.geometry.morphAttributes.normal,
  11501. morphTargetsCount: ( !! object.geometry && !! object.geometry.morphAttributes.position ) ? object.geometry.morphAttributes.position.length : 0,
  11502. numDirLights: lights.directional.length,
  11503. numPointLights: lights.point.length,
  11504. numSpotLights: lights.spot.length,
  11505. numRectAreaLights: lights.rectArea.length,
  11506. numHemiLights: lights.hemi.length,
  11507. numDirLightShadows: lights.directionalShadowMap.length,
  11508. numPointLightShadows: lights.pointShadowMap.length,
  11509. numSpotLightShadows: lights.spotShadowMap.length,
  11510. numClippingPlanes: clipping.numPlanes,
  11511. numClipIntersection: clipping.numIntersection,
  11512. dithering: material.dithering,
  11513. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11514. shadowMapType: renderer.shadowMap.type,
  11515. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11516. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11517. premultipliedAlpha: material.premultipliedAlpha,
  11518. doubleSided: material.side === DoubleSide,
  11519. flipSided: material.side === BackSide,
  11520. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11521. index0AttributeName: material.index0AttributeName,
  11522. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11523. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11524. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11525. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11526. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11527. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11528. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11529. customProgramCacheKey: material.customProgramCacheKey()
  11530. };
  11531. return parameters;
  11532. }
  11533. function getProgramCacheKey( parameters ) {
  11534. const array = [];
  11535. if ( parameters.shaderID ) {
  11536. array.push( parameters.shaderID );
  11537. } else {
  11538. array.push( parameters.customVertexShaderID );
  11539. array.push( parameters.customFragmentShaderID );
  11540. }
  11541. if ( parameters.defines !== undefined ) {
  11542. for ( const name in parameters.defines ) {
  11543. array.push( name );
  11544. array.push( parameters.defines[ name ] );
  11545. }
  11546. }
  11547. if ( parameters.isRawShaderMaterial === false ) {
  11548. getProgramCacheKeyParameters( array, parameters );
  11549. getProgramCacheKeyBooleans( array, parameters );
  11550. array.push( renderer.outputEncoding );
  11551. }
  11552. array.push( parameters.customProgramCacheKey );
  11553. return array.join();
  11554. }
  11555. function getProgramCacheKeyParameters( array, parameters ) {
  11556. array.push( parameters.precision );
  11557. array.push( parameters.outputEncoding );
  11558. array.push( parameters.envMapMode );
  11559. array.push( parameters.combine );
  11560. array.push( parameters.vertexUvs );
  11561. array.push( parameters.fogExp2 );
  11562. array.push( parameters.sizeAttenuation );
  11563. array.push( parameters.maxBones );
  11564. array.push( parameters.morphTargetsCount );
  11565. array.push( parameters.numDirLights );
  11566. array.push( parameters.numPointLights );
  11567. array.push( parameters.numSpotLights );
  11568. array.push( parameters.numHemiLights );
  11569. array.push( parameters.numRectAreaLights );
  11570. array.push( parameters.numDirLightShadows );
  11571. array.push( parameters.numPointLightShadows );
  11572. array.push( parameters.numSpotLightShadows );
  11573. array.push( parameters.shadowMapType );
  11574. array.push( parameters.toneMapping );
  11575. array.push( parameters.numClippingPlanes );
  11576. array.push( parameters.numClipIntersection );
  11577. }
  11578. function getProgramCacheKeyBooleans( array, parameters ) {
  11579. _programLayers.disableAll();
  11580. if ( parameters.isWebGL2 )
  11581. _programLayers.enable( 0 );
  11582. if ( parameters.supportsVertexTextures )
  11583. _programLayers.enable( 1 );
  11584. if ( parameters.instancing )
  11585. _programLayers.enable( 2 );
  11586. if ( parameters.instancingColor )
  11587. _programLayers.enable( 3 );
  11588. if ( parameters.map )
  11589. _programLayers.enable( 4 );
  11590. if ( parameters.matcap )
  11591. _programLayers.enable( 5 );
  11592. if ( parameters.envMap )
  11593. _programLayers.enable( 6 );
  11594. if ( parameters.envMapCubeUV )
  11595. _programLayers.enable( 7 );
  11596. if ( parameters.lightMap )
  11597. _programLayers.enable( 8 );
  11598. if ( parameters.aoMap )
  11599. _programLayers.enable( 9 );
  11600. if ( parameters.emissiveMap )
  11601. _programLayers.enable( 10 );
  11602. if ( parameters.bumpMap )
  11603. _programLayers.enable( 11 );
  11604. if ( parameters.normalMap )
  11605. _programLayers.enable( 12 );
  11606. if ( parameters.objectSpaceNormalMap )
  11607. _programLayers.enable( 13 );
  11608. if ( parameters.tangentSpaceNormalMap )
  11609. _programLayers.enable( 14 );
  11610. if ( parameters.clearcoat )
  11611. _programLayers.enable( 15 );
  11612. if ( parameters.clearcoatMap )
  11613. _programLayers.enable( 16 );
  11614. if ( parameters.clearcoatRoughnessMap )
  11615. _programLayers.enable( 17 );
  11616. if ( parameters.clearcoatNormalMap )
  11617. _programLayers.enable( 18 );
  11618. if ( parameters.displacementMap )
  11619. _programLayers.enable( 19 );
  11620. if ( parameters.specularMap )
  11621. _programLayers.enable( 20 );
  11622. if ( parameters.roughnessMap )
  11623. _programLayers.enable( 21 );
  11624. if ( parameters.metalnessMap )
  11625. _programLayers.enable( 22 );
  11626. if ( parameters.gradientMap )
  11627. _programLayers.enable( 23 );
  11628. if ( parameters.alphaMap )
  11629. _programLayers.enable( 24 );
  11630. if ( parameters.alphaTest )
  11631. _programLayers.enable( 25 );
  11632. if ( parameters.vertexColors )
  11633. _programLayers.enable( 26 );
  11634. if ( parameters.vertexAlphas )
  11635. _programLayers.enable( 27 );
  11636. if ( parameters.vertexUvs )
  11637. _programLayers.enable( 28 );
  11638. if ( parameters.vertexTangents )
  11639. _programLayers.enable( 29 );
  11640. if ( parameters.uvsVertexOnly )
  11641. _programLayers.enable( 30 );
  11642. if ( parameters.fog )
  11643. _programLayers.enable( 31 );
  11644. array.push( _programLayers.mask );
  11645. _programLayers.disableAll();
  11646. if ( parameters.useFog )
  11647. _programLayers.enable( 0 );
  11648. if ( parameters.flatShading )
  11649. _programLayers.enable( 1 );
  11650. if ( parameters.logarithmicDepthBuffer )
  11651. _programLayers.enable( 2 );
  11652. if ( parameters.skinning )
  11653. _programLayers.enable( 3 );
  11654. if ( parameters.useVertexTexture )
  11655. _programLayers.enable( 4 );
  11656. if ( parameters.morphTargets )
  11657. _programLayers.enable( 5 );
  11658. if ( parameters.morphNormals )
  11659. _programLayers.enable( 6 );
  11660. if ( parameters.premultipliedAlpha )
  11661. _programLayers.enable( 7 );
  11662. if ( parameters.shadowMapEnabled )
  11663. _programLayers.enable( 8 );
  11664. if ( parameters.physicallyCorrectLights )
  11665. _programLayers.enable( 9 );
  11666. if ( parameters.doubleSided )
  11667. _programLayers.enable( 10 );
  11668. if ( parameters.flipSided )
  11669. _programLayers.enable( 11 );
  11670. if ( parameters.depthPacking )
  11671. _programLayers.enable( 12 );
  11672. if ( parameters.dithering )
  11673. _programLayers.enable( 13 );
  11674. if ( parameters.specularIntensityMap )
  11675. _programLayers.enable( 14 );
  11676. if ( parameters.specularColorMap )
  11677. _programLayers.enable( 15 );
  11678. if ( parameters.transmission )
  11679. _programLayers.enable( 16 );
  11680. if ( parameters.transmissionMap )
  11681. _programLayers.enable( 17 );
  11682. if ( parameters.thicknessMap )
  11683. _programLayers.enable( 18 );
  11684. if ( parameters.sheen )
  11685. _programLayers.enable( 19 );
  11686. if ( parameters.sheenColorMap )
  11687. _programLayers.enable( 20 );
  11688. if ( parameters.sheenRoughnessMap )
  11689. _programLayers.enable( 21 );
  11690. if ( parameters.decodeVideoTexture )
  11691. _programLayers.enable( 22 );
  11692. if ( parameters.transparent )
  11693. _programLayers.enable( 23 );
  11694. array.push( _programLayers.mask );
  11695. }
  11696. function getUniforms( material ) {
  11697. const shaderID = shaderIDs[ material.type ];
  11698. let uniforms;
  11699. if ( shaderID ) {
  11700. const shader = ShaderLib[ shaderID ];
  11701. uniforms = UniformsUtils.clone( shader.uniforms );
  11702. } else {
  11703. uniforms = material.uniforms;
  11704. }
  11705. return uniforms;
  11706. }
  11707. function acquireProgram( parameters, cacheKey ) {
  11708. let program;
  11709. // Check if code has been already compiled
  11710. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11711. const preexistingProgram = programs[ p ];
  11712. if ( preexistingProgram.cacheKey === cacheKey ) {
  11713. program = preexistingProgram;
  11714. ++ program.usedTimes;
  11715. break;
  11716. }
  11717. }
  11718. if ( program === undefined ) {
  11719. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11720. programs.push( program );
  11721. }
  11722. return program;
  11723. }
  11724. function releaseProgram( program ) {
  11725. if ( -- program.usedTimes === 0 ) {
  11726. // Remove from unordered set
  11727. const i = programs.indexOf( program );
  11728. programs[ i ] = programs[ programs.length - 1 ];
  11729. programs.pop();
  11730. // Free WebGL resources
  11731. program.destroy();
  11732. }
  11733. }
  11734. function releaseShaderCache( material ) {
  11735. _customShaders.remove( material );
  11736. }
  11737. function dispose() {
  11738. _customShaders.dispose();
  11739. }
  11740. return {
  11741. getParameters: getParameters,
  11742. getProgramCacheKey: getProgramCacheKey,
  11743. getUniforms: getUniforms,
  11744. acquireProgram: acquireProgram,
  11745. releaseProgram: releaseProgram,
  11746. releaseShaderCache: releaseShaderCache,
  11747. // Exposed for resource monitoring & error feedback via renderer.info:
  11748. programs: programs,
  11749. dispose: dispose
  11750. };
  11751. }
  11752. function WebGLProperties() {
  11753. let properties = new WeakMap();
  11754. function get( object ) {
  11755. let map = properties.get( object );
  11756. if ( map === undefined ) {
  11757. map = {};
  11758. properties.set( object, map );
  11759. }
  11760. return map;
  11761. }
  11762. function remove( object ) {
  11763. properties.delete( object );
  11764. }
  11765. function update( object, key, value ) {
  11766. properties.get( object )[ key ] = value;
  11767. }
  11768. function dispose() {
  11769. properties = new WeakMap();
  11770. }
  11771. return {
  11772. get: get,
  11773. remove: remove,
  11774. update: update,
  11775. dispose: dispose
  11776. };
  11777. }
  11778. function painterSortStable( a, b ) {
  11779. if ( a.groupOrder !== b.groupOrder ) {
  11780. return a.groupOrder - b.groupOrder;
  11781. } else if ( a.renderOrder !== b.renderOrder ) {
  11782. return a.renderOrder - b.renderOrder;
  11783. } else if ( a.material.id !== b.material.id ) {
  11784. return a.material.id - b.material.id;
  11785. } else if ( a.z !== b.z ) {
  11786. return a.z - b.z;
  11787. } else {
  11788. return a.id - b.id;
  11789. }
  11790. }
  11791. function reversePainterSortStable( a, b ) {
  11792. if ( a.groupOrder !== b.groupOrder ) {
  11793. return a.groupOrder - b.groupOrder;
  11794. } else if ( a.renderOrder !== b.renderOrder ) {
  11795. return a.renderOrder - b.renderOrder;
  11796. } else if ( a.z !== b.z ) {
  11797. return b.z - a.z;
  11798. } else {
  11799. return a.id - b.id;
  11800. }
  11801. }
  11802. function WebGLRenderList() {
  11803. const renderItems = [];
  11804. let renderItemsIndex = 0;
  11805. const opaque = [];
  11806. const transmissive = [];
  11807. const transparent = [];
  11808. function init() {
  11809. renderItemsIndex = 0;
  11810. opaque.length = 0;
  11811. transmissive.length = 0;
  11812. transparent.length = 0;
  11813. }
  11814. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11815. let renderItem = renderItems[ renderItemsIndex ];
  11816. if ( renderItem === undefined ) {
  11817. renderItem = {
  11818. id: object.id,
  11819. object: object,
  11820. geometry: geometry,
  11821. material: material,
  11822. groupOrder: groupOrder,
  11823. renderOrder: object.renderOrder,
  11824. z: z,
  11825. group: group
  11826. };
  11827. renderItems[ renderItemsIndex ] = renderItem;
  11828. } else {
  11829. renderItem.id = object.id;
  11830. renderItem.object = object;
  11831. renderItem.geometry = geometry;
  11832. renderItem.material = material;
  11833. renderItem.groupOrder = groupOrder;
  11834. renderItem.renderOrder = object.renderOrder;
  11835. renderItem.z = z;
  11836. renderItem.group = group;
  11837. }
  11838. renderItemsIndex ++;
  11839. return renderItem;
  11840. }
  11841. function push( object, geometry, material, groupOrder, z, group ) {
  11842. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11843. if ( material.transmission > 0.0 ) {
  11844. transmissive.push( renderItem );
  11845. } else if ( material.transparent === true ) {
  11846. transparent.push( renderItem );
  11847. } else {
  11848. opaque.push( renderItem );
  11849. }
  11850. }
  11851. function unshift( object, geometry, material, groupOrder, z, group ) {
  11852. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11853. if ( material.transmission > 0.0 ) {
  11854. transmissive.unshift( renderItem );
  11855. } else if ( material.transparent === true ) {
  11856. transparent.unshift( renderItem );
  11857. } else {
  11858. opaque.unshift( renderItem );
  11859. }
  11860. }
  11861. function sort( customOpaqueSort, customTransparentSort ) {
  11862. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11863. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  11864. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11865. }
  11866. function finish() {
  11867. // Clear references from inactive renderItems in the list
  11868. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11869. const renderItem = renderItems[ i ];
  11870. if ( renderItem.id === null ) break;
  11871. renderItem.id = null;
  11872. renderItem.object = null;
  11873. renderItem.geometry = null;
  11874. renderItem.material = null;
  11875. renderItem.group = null;
  11876. }
  11877. }
  11878. return {
  11879. opaque: opaque,
  11880. transmissive: transmissive,
  11881. transparent: transparent,
  11882. init: init,
  11883. push: push,
  11884. unshift: unshift,
  11885. finish: finish,
  11886. sort: sort
  11887. };
  11888. }
  11889. function WebGLRenderLists() {
  11890. let lists = new WeakMap();
  11891. function get( scene, renderCallDepth ) {
  11892. let list;
  11893. if ( lists.has( scene ) === false ) {
  11894. list = new WebGLRenderList();
  11895. lists.set( scene, [ list ] );
  11896. } else {
  11897. if ( renderCallDepth >= lists.get( scene ).length ) {
  11898. list = new WebGLRenderList();
  11899. lists.get( scene ).push( list );
  11900. } else {
  11901. list = lists.get( scene )[ renderCallDepth ];
  11902. }
  11903. }
  11904. return list;
  11905. }
  11906. function dispose() {
  11907. lists = new WeakMap();
  11908. }
  11909. return {
  11910. get: get,
  11911. dispose: dispose
  11912. };
  11913. }
  11914. function UniformsCache() {
  11915. const lights = {};
  11916. return {
  11917. get: function ( light ) {
  11918. if ( lights[ light.id ] !== undefined ) {
  11919. return lights[ light.id ];
  11920. }
  11921. let uniforms;
  11922. switch ( light.type ) {
  11923. case 'DirectionalLight':
  11924. uniforms = {
  11925. direction: new Vector3(),
  11926. color: new Color()
  11927. };
  11928. break;
  11929. case 'SpotLight':
  11930. uniforms = {
  11931. position: new Vector3(),
  11932. direction: new Vector3(),
  11933. color: new Color(),
  11934. distance: 0,
  11935. coneCos: 0,
  11936. penumbraCos: 0,
  11937. decay: 0
  11938. };
  11939. break;
  11940. case 'PointLight':
  11941. uniforms = {
  11942. position: new Vector3(),
  11943. color: new Color(),
  11944. distance: 0,
  11945. decay: 0
  11946. };
  11947. break;
  11948. case 'HemisphereLight':
  11949. uniforms = {
  11950. direction: new Vector3(),
  11951. skyColor: new Color(),
  11952. groundColor: new Color()
  11953. };
  11954. break;
  11955. case 'RectAreaLight':
  11956. uniforms = {
  11957. color: new Color(),
  11958. position: new Vector3(),
  11959. halfWidth: new Vector3(),
  11960. halfHeight: new Vector3()
  11961. };
  11962. break;
  11963. }
  11964. lights[ light.id ] = uniforms;
  11965. return uniforms;
  11966. }
  11967. };
  11968. }
  11969. function ShadowUniformsCache() {
  11970. const lights = {};
  11971. return {
  11972. get: function ( light ) {
  11973. if ( lights[ light.id ] !== undefined ) {
  11974. return lights[ light.id ];
  11975. }
  11976. let uniforms;
  11977. switch ( light.type ) {
  11978. case 'DirectionalLight':
  11979. uniforms = {
  11980. shadowBias: 0,
  11981. shadowNormalBias: 0,
  11982. shadowRadius: 1,
  11983. shadowMapSize: new Vector2()
  11984. };
  11985. break;
  11986. case 'SpotLight':
  11987. uniforms = {
  11988. shadowBias: 0,
  11989. shadowNormalBias: 0,
  11990. shadowRadius: 1,
  11991. shadowMapSize: new Vector2()
  11992. };
  11993. break;
  11994. case 'PointLight':
  11995. uniforms = {
  11996. shadowBias: 0,
  11997. shadowNormalBias: 0,
  11998. shadowRadius: 1,
  11999. shadowMapSize: new Vector2(),
  12000. shadowCameraNear: 1,
  12001. shadowCameraFar: 1000
  12002. };
  12003. break;
  12004. // TODO (abelnation): set RectAreaLight shadow uniforms
  12005. }
  12006. lights[ light.id ] = uniforms;
  12007. return uniforms;
  12008. }
  12009. };
  12010. }
  12011. let nextVersion = 0;
  12012. function shadowCastingLightsFirst( lightA, lightB ) {
  12013. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  12014. }
  12015. function WebGLLights( extensions, capabilities ) {
  12016. const cache = new UniformsCache();
  12017. const shadowCache = ShadowUniformsCache();
  12018. const state = {
  12019. version: 0,
  12020. hash: {
  12021. directionalLength: - 1,
  12022. pointLength: - 1,
  12023. spotLength: - 1,
  12024. rectAreaLength: - 1,
  12025. hemiLength: - 1,
  12026. numDirectionalShadows: - 1,
  12027. numPointShadows: - 1,
  12028. numSpotShadows: - 1
  12029. },
  12030. ambient: [ 0, 0, 0 ],
  12031. probe: [],
  12032. directional: [],
  12033. directionalShadow: [],
  12034. directionalShadowMap: [],
  12035. directionalShadowMatrix: [],
  12036. spot: [],
  12037. spotShadow: [],
  12038. spotShadowMap: [],
  12039. spotShadowMatrix: [],
  12040. rectArea: [],
  12041. rectAreaLTC1: null,
  12042. rectAreaLTC2: null,
  12043. point: [],
  12044. pointShadow: [],
  12045. pointShadowMap: [],
  12046. pointShadowMatrix: [],
  12047. hemi: []
  12048. };
  12049. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12050. const vector3 = new Vector3();
  12051. const matrix4 = new Matrix4();
  12052. const matrix42 = new Matrix4();
  12053. function setup( lights, physicallyCorrectLights ) {
  12054. let r = 0, g = 0, b = 0;
  12055. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12056. let directionalLength = 0;
  12057. let pointLength = 0;
  12058. let spotLength = 0;
  12059. let rectAreaLength = 0;
  12060. let hemiLength = 0;
  12061. let numDirectionalShadows = 0;
  12062. let numPointShadows = 0;
  12063. let numSpotShadows = 0;
  12064. lights.sort( shadowCastingLightsFirst );
  12065. // artist-friendly light intensity scaling factor
  12066. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12067. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12068. const light = lights[ i ];
  12069. const color = light.color;
  12070. const intensity = light.intensity;
  12071. const distance = light.distance;
  12072. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12073. if ( light.isAmbientLight ) {
  12074. r += color.r * intensity * scaleFactor;
  12075. g += color.g * intensity * scaleFactor;
  12076. b += color.b * intensity * scaleFactor;
  12077. } else if ( light.isLightProbe ) {
  12078. for ( let j = 0; j < 9; j ++ ) {
  12079. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12080. }
  12081. } else if ( light.isDirectionalLight ) {
  12082. const uniforms = cache.get( light );
  12083. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12084. if ( light.castShadow ) {
  12085. const shadow = light.shadow;
  12086. const shadowUniforms = shadowCache.get( light );
  12087. shadowUniforms.shadowBias = shadow.bias;
  12088. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12089. shadowUniforms.shadowRadius = shadow.radius;
  12090. shadowUniforms.shadowMapSize = shadow.mapSize;
  12091. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12092. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12093. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12094. numDirectionalShadows ++;
  12095. }
  12096. state.directional[ directionalLength ] = uniforms;
  12097. directionalLength ++;
  12098. } else if ( light.isSpotLight ) {
  12099. const uniforms = cache.get( light );
  12100. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12101. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12102. uniforms.distance = distance;
  12103. uniforms.coneCos = Math.cos( light.angle );
  12104. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12105. uniforms.decay = light.decay;
  12106. if ( light.castShadow ) {
  12107. const shadow = light.shadow;
  12108. const shadowUniforms = shadowCache.get( light );
  12109. shadowUniforms.shadowBias = shadow.bias;
  12110. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12111. shadowUniforms.shadowRadius = shadow.radius;
  12112. shadowUniforms.shadowMapSize = shadow.mapSize;
  12113. state.spotShadow[ spotLength ] = shadowUniforms;
  12114. state.spotShadowMap[ spotLength ] = shadowMap;
  12115. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12116. numSpotShadows ++;
  12117. }
  12118. state.spot[ spotLength ] = uniforms;
  12119. spotLength ++;
  12120. } else if ( light.isRectAreaLight ) {
  12121. const uniforms = cache.get( light );
  12122. // (a) intensity is the total visible light emitted
  12123. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12124. // (b) intensity is the brightness of the light
  12125. uniforms.color.copy( color ).multiplyScalar( intensity );
  12126. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12127. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12128. state.rectArea[ rectAreaLength ] = uniforms;
  12129. rectAreaLength ++;
  12130. } else if ( light.isPointLight ) {
  12131. const uniforms = cache.get( light );
  12132. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12133. uniforms.distance = light.distance;
  12134. uniforms.decay = light.decay;
  12135. if ( light.castShadow ) {
  12136. const shadow = light.shadow;
  12137. const shadowUniforms = shadowCache.get( light );
  12138. shadowUniforms.shadowBias = shadow.bias;
  12139. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12140. shadowUniforms.shadowRadius = shadow.radius;
  12141. shadowUniforms.shadowMapSize = shadow.mapSize;
  12142. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12143. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12144. state.pointShadow[ pointLength ] = shadowUniforms;
  12145. state.pointShadowMap[ pointLength ] = shadowMap;
  12146. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12147. numPointShadows ++;
  12148. }
  12149. state.point[ pointLength ] = uniforms;
  12150. pointLength ++;
  12151. } else if ( light.isHemisphereLight ) {
  12152. const uniforms = cache.get( light );
  12153. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12154. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12155. state.hemi[ hemiLength ] = uniforms;
  12156. hemiLength ++;
  12157. }
  12158. }
  12159. if ( rectAreaLength > 0 ) {
  12160. if ( capabilities.isWebGL2 ) {
  12161. // WebGL 2
  12162. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12163. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12164. } else {
  12165. // WebGL 1
  12166. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12167. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12168. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12169. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12170. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12171. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12172. } else {
  12173. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12174. }
  12175. }
  12176. }
  12177. state.ambient[ 0 ] = r;
  12178. state.ambient[ 1 ] = g;
  12179. state.ambient[ 2 ] = b;
  12180. const hash = state.hash;
  12181. if ( hash.directionalLength !== directionalLength ||
  12182. hash.pointLength !== pointLength ||
  12183. hash.spotLength !== spotLength ||
  12184. hash.rectAreaLength !== rectAreaLength ||
  12185. hash.hemiLength !== hemiLength ||
  12186. hash.numDirectionalShadows !== numDirectionalShadows ||
  12187. hash.numPointShadows !== numPointShadows ||
  12188. hash.numSpotShadows !== numSpotShadows ) {
  12189. state.directional.length = directionalLength;
  12190. state.spot.length = spotLength;
  12191. state.rectArea.length = rectAreaLength;
  12192. state.point.length = pointLength;
  12193. state.hemi.length = hemiLength;
  12194. state.directionalShadow.length = numDirectionalShadows;
  12195. state.directionalShadowMap.length = numDirectionalShadows;
  12196. state.pointShadow.length = numPointShadows;
  12197. state.pointShadowMap.length = numPointShadows;
  12198. state.spotShadow.length = numSpotShadows;
  12199. state.spotShadowMap.length = numSpotShadows;
  12200. state.directionalShadowMatrix.length = numDirectionalShadows;
  12201. state.pointShadowMatrix.length = numPointShadows;
  12202. state.spotShadowMatrix.length = numSpotShadows;
  12203. hash.directionalLength = directionalLength;
  12204. hash.pointLength = pointLength;
  12205. hash.spotLength = spotLength;
  12206. hash.rectAreaLength = rectAreaLength;
  12207. hash.hemiLength = hemiLength;
  12208. hash.numDirectionalShadows = numDirectionalShadows;
  12209. hash.numPointShadows = numPointShadows;
  12210. hash.numSpotShadows = numSpotShadows;
  12211. state.version = nextVersion ++;
  12212. }
  12213. }
  12214. function setupView( lights, camera ) {
  12215. let directionalLength = 0;
  12216. let pointLength = 0;
  12217. let spotLength = 0;
  12218. let rectAreaLength = 0;
  12219. let hemiLength = 0;
  12220. const viewMatrix = camera.matrixWorldInverse;
  12221. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12222. const light = lights[ i ];
  12223. if ( light.isDirectionalLight ) {
  12224. const uniforms = state.directional[ directionalLength ];
  12225. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12226. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12227. uniforms.direction.sub( vector3 );
  12228. uniforms.direction.transformDirection( viewMatrix );
  12229. directionalLength ++;
  12230. } else if ( light.isSpotLight ) {
  12231. const uniforms = state.spot[ spotLength ];
  12232. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12233. uniforms.position.applyMatrix4( viewMatrix );
  12234. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12235. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12236. uniforms.direction.sub( vector3 );
  12237. uniforms.direction.transformDirection( viewMatrix );
  12238. spotLength ++;
  12239. } else if ( light.isRectAreaLight ) {
  12240. const uniforms = state.rectArea[ rectAreaLength ];
  12241. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12242. uniforms.position.applyMatrix4( viewMatrix );
  12243. // extract local rotation of light to derive width/height half vectors
  12244. matrix42.identity();
  12245. matrix4.copy( light.matrixWorld );
  12246. matrix4.premultiply( viewMatrix );
  12247. matrix42.extractRotation( matrix4 );
  12248. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12249. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12250. uniforms.halfWidth.applyMatrix4( matrix42 );
  12251. uniforms.halfHeight.applyMatrix4( matrix42 );
  12252. rectAreaLength ++;
  12253. } else if ( light.isPointLight ) {
  12254. const uniforms = state.point[ pointLength ];
  12255. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12256. uniforms.position.applyMatrix4( viewMatrix );
  12257. pointLength ++;
  12258. } else if ( light.isHemisphereLight ) {
  12259. const uniforms = state.hemi[ hemiLength ];
  12260. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12261. uniforms.direction.transformDirection( viewMatrix );
  12262. uniforms.direction.normalize();
  12263. hemiLength ++;
  12264. }
  12265. }
  12266. }
  12267. return {
  12268. setup: setup,
  12269. setupView: setupView,
  12270. state: state
  12271. };
  12272. }
  12273. function WebGLRenderState( extensions, capabilities ) {
  12274. const lights = new WebGLLights( extensions, capabilities );
  12275. const lightsArray = [];
  12276. const shadowsArray = [];
  12277. function init() {
  12278. lightsArray.length = 0;
  12279. shadowsArray.length = 0;
  12280. }
  12281. function pushLight( light ) {
  12282. lightsArray.push( light );
  12283. }
  12284. function pushShadow( shadowLight ) {
  12285. shadowsArray.push( shadowLight );
  12286. }
  12287. function setupLights( physicallyCorrectLights ) {
  12288. lights.setup( lightsArray, physicallyCorrectLights );
  12289. }
  12290. function setupLightsView( camera ) {
  12291. lights.setupView( lightsArray, camera );
  12292. }
  12293. const state = {
  12294. lightsArray: lightsArray,
  12295. shadowsArray: shadowsArray,
  12296. lights: lights
  12297. };
  12298. return {
  12299. init: init,
  12300. state: state,
  12301. setupLights: setupLights,
  12302. setupLightsView: setupLightsView,
  12303. pushLight: pushLight,
  12304. pushShadow: pushShadow
  12305. };
  12306. }
  12307. function WebGLRenderStates( extensions, capabilities ) {
  12308. let renderStates = new WeakMap();
  12309. function get( scene, renderCallDepth = 0 ) {
  12310. let renderState;
  12311. if ( renderStates.has( scene ) === false ) {
  12312. renderState = new WebGLRenderState( extensions, capabilities );
  12313. renderStates.set( scene, [ renderState ] );
  12314. } else {
  12315. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12316. renderState = new WebGLRenderState( extensions, capabilities );
  12317. renderStates.get( scene ).push( renderState );
  12318. } else {
  12319. renderState = renderStates.get( scene )[ renderCallDepth ];
  12320. }
  12321. }
  12322. return renderState;
  12323. }
  12324. function dispose() {
  12325. renderStates = new WeakMap();
  12326. }
  12327. return {
  12328. get: get,
  12329. dispose: dispose
  12330. };
  12331. }
  12332. /**
  12333. * parameters = {
  12334. *
  12335. * opacity: <float>,
  12336. *
  12337. * map: new THREE.Texture( <Image> ),
  12338. *
  12339. * alphaMap: new THREE.Texture( <Image> ),
  12340. *
  12341. * displacementMap: new THREE.Texture( <Image> ),
  12342. * displacementScale: <float>,
  12343. * displacementBias: <float>,
  12344. *
  12345. * wireframe: <boolean>,
  12346. * wireframeLinewidth: <float>
  12347. * }
  12348. */
  12349. class MeshDepthMaterial extends Material {
  12350. constructor( parameters ) {
  12351. super();
  12352. this.type = 'MeshDepthMaterial';
  12353. this.depthPacking = BasicDepthPacking;
  12354. this.map = null;
  12355. this.alphaMap = null;
  12356. this.displacementMap = null;
  12357. this.displacementScale = 1;
  12358. this.displacementBias = 0;
  12359. this.wireframe = false;
  12360. this.wireframeLinewidth = 1;
  12361. this.fog = false;
  12362. this.setValues( parameters );
  12363. }
  12364. copy( source ) {
  12365. super.copy( source );
  12366. this.depthPacking = source.depthPacking;
  12367. this.map = source.map;
  12368. this.alphaMap = source.alphaMap;
  12369. this.displacementMap = source.displacementMap;
  12370. this.displacementScale = source.displacementScale;
  12371. this.displacementBias = source.displacementBias;
  12372. this.wireframe = source.wireframe;
  12373. this.wireframeLinewidth = source.wireframeLinewidth;
  12374. return this;
  12375. }
  12376. }
  12377. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12378. /**
  12379. * parameters = {
  12380. *
  12381. * referencePosition: <float>,
  12382. * nearDistance: <float>,
  12383. * farDistance: <float>,
  12384. *
  12385. * map: new THREE.Texture( <Image> ),
  12386. *
  12387. * alphaMap: new THREE.Texture( <Image> ),
  12388. *
  12389. * displacementMap: new THREE.Texture( <Image> ),
  12390. * displacementScale: <float>,
  12391. * displacementBias: <float>
  12392. *
  12393. * }
  12394. */
  12395. class MeshDistanceMaterial extends Material {
  12396. constructor( parameters ) {
  12397. super();
  12398. this.type = 'MeshDistanceMaterial';
  12399. this.referencePosition = new Vector3();
  12400. this.nearDistance = 1;
  12401. this.farDistance = 1000;
  12402. this.map = null;
  12403. this.alphaMap = null;
  12404. this.displacementMap = null;
  12405. this.displacementScale = 1;
  12406. this.displacementBias = 0;
  12407. this.fog = false;
  12408. this.setValues( parameters );
  12409. }
  12410. copy( source ) {
  12411. super.copy( source );
  12412. this.referencePosition.copy( source.referencePosition );
  12413. this.nearDistance = source.nearDistance;
  12414. this.farDistance = source.farDistance;
  12415. this.map = source.map;
  12416. this.alphaMap = source.alphaMap;
  12417. this.displacementMap = source.displacementMap;
  12418. this.displacementScale = source.displacementScale;
  12419. this.displacementBias = source.displacementBias;
  12420. return this;
  12421. }
  12422. }
  12423. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12424. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12425. 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}";
  12426. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12427. let _frustum = new Frustum();
  12428. const _shadowMapSize = new Vector2(),
  12429. _viewportSize = new Vector2(),
  12430. _viewport = new Vector4(),
  12431. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12432. _distanceMaterial = new MeshDistanceMaterial(),
  12433. _materialCache = {},
  12434. _maxTextureSize = _capabilities.maxTextureSize;
  12435. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12436. const shadowMaterialVertical = new ShaderMaterial( {
  12437. defines: {
  12438. VSM_SAMPLES: 8
  12439. },
  12440. uniforms: {
  12441. shadow_pass: { value: null },
  12442. resolution: { value: new Vector2() },
  12443. radius: { value: 4.0 }
  12444. },
  12445. vertexShader: vertex,
  12446. fragmentShader: fragment
  12447. } );
  12448. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12449. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12450. const fullScreenTri = new BufferGeometry();
  12451. fullScreenTri.setAttribute(
  12452. 'position',
  12453. new BufferAttribute(
  12454. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12455. 3
  12456. )
  12457. );
  12458. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12459. const scope = this;
  12460. this.enabled = false;
  12461. this.autoUpdate = true;
  12462. this.needsUpdate = false;
  12463. this.type = PCFShadowMap;
  12464. this.render = function ( lights, scene, camera ) {
  12465. if ( scope.enabled === false ) return;
  12466. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12467. if ( lights.length === 0 ) return;
  12468. const currentRenderTarget = _renderer.getRenderTarget();
  12469. const activeCubeFace = _renderer.getActiveCubeFace();
  12470. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12471. const _state = _renderer.state;
  12472. // Set GL state for depth map.
  12473. _state.setBlending( NoBlending );
  12474. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12475. _state.buffers.depth.setTest( true );
  12476. _state.setScissorTest( false );
  12477. // render depth map
  12478. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12479. const light = lights[ i ];
  12480. const shadow = light.shadow;
  12481. if ( shadow === undefined ) {
  12482. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12483. continue;
  12484. }
  12485. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12486. _shadowMapSize.copy( shadow.mapSize );
  12487. const shadowFrameExtents = shadow.getFrameExtents();
  12488. _shadowMapSize.multiply( shadowFrameExtents );
  12489. _viewportSize.copy( shadow.mapSize );
  12490. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12491. if ( _shadowMapSize.x > _maxTextureSize ) {
  12492. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12493. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12494. shadow.mapSize.x = _viewportSize.x;
  12495. }
  12496. if ( _shadowMapSize.y > _maxTextureSize ) {
  12497. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12498. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12499. shadow.mapSize.y = _viewportSize.y;
  12500. }
  12501. }
  12502. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12503. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12504. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12505. shadow.map.texture.name = light.name + '.shadowMap';
  12506. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12507. shadow.camera.updateProjectionMatrix();
  12508. }
  12509. if ( shadow.map === null ) {
  12510. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12511. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12512. shadow.map.texture.name = light.name + '.shadowMap';
  12513. shadow.camera.updateProjectionMatrix();
  12514. }
  12515. _renderer.setRenderTarget( shadow.map );
  12516. _renderer.clear();
  12517. const viewportCount = shadow.getViewportCount();
  12518. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12519. const viewport = shadow.getViewport( vp );
  12520. _viewport.set(
  12521. _viewportSize.x * viewport.x,
  12522. _viewportSize.y * viewport.y,
  12523. _viewportSize.x * viewport.z,
  12524. _viewportSize.y * viewport.w
  12525. );
  12526. _state.viewport( _viewport );
  12527. shadow.updateMatrices( light, vp );
  12528. _frustum = shadow.getFrustum();
  12529. renderObject( scene, camera, shadow.camera, light, this.type );
  12530. }
  12531. // do blur pass for VSM
  12532. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12533. VSMPass( shadow, camera );
  12534. }
  12535. shadow.needsUpdate = false;
  12536. }
  12537. scope.needsUpdate = false;
  12538. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12539. };
  12540. function VSMPass( shadow, camera ) {
  12541. const geometry = _objects.update( fullScreenMesh );
  12542. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12543. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12544. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12545. shadowMaterialVertical.needsUpdate = true;
  12546. shadowMaterialHorizontal.needsUpdate = true;
  12547. }
  12548. // vertical pass
  12549. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12550. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12551. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12552. _renderer.setRenderTarget( shadow.mapPass );
  12553. _renderer.clear();
  12554. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12555. // horizontal pass
  12556. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12557. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12558. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12559. _renderer.setRenderTarget( shadow.map );
  12560. _renderer.clear();
  12561. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12562. }
  12563. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12564. let result = null;
  12565. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12566. if ( customMaterial !== undefined ) {
  12567. result = customMaterial;
  12568. } else {
  12569. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12570. }
  12571. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  12572. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12573. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12574. // in this case we need a unique material instance reflecting the
  12575. // appropriate state
  12576. const keyA = result.uuid, keyB = material.uuid;
  12577. let materialsForVariant = _materialCache[ keyA ];
  12578. if ( materialsForVariant === undefined ) {
  12579. materialsForVariant = {};
  12580. _materialCache[ keyA ] = materialsForVariant;
  12581. }
  12582. let cachedMaterial = materialsForVariant[ keyB ];
  12583. if ( cachedMaterial === undefined ) {
  12584. cachedMaterial = result.clone();
  12585. materialsForVariant[ keyB ] = cachedMaterial;
  12586. }
  12587. result = cachedMaterial;
  12588. }
  12589. result.visible = material.visible;
  12590. result.wireframe = material.wireframe;
  12591. if ( type === VSMShadowMap ) {
  12592. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12593. } else {
  12594. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12595. }
  12596. result.alphaMap = material.alphaMap;
  12597. result.alphaTest = material.alphaTest;
  12598. result.clipShadows = material.clipShadows;
  12599. result.clippingPlanes = material.clippingPlanes;
  12600. result.clipIntersection = material.clipIntersection;
  12601. result.displacementMap = material.displacementMap;
  12602. result.displacementScale = material.displacementScale;
  12603. result.displacementBias = material.displacementBias;
  12604. result.wireframeLinewidth = material.wireframeLinewidth;
  12605. result.linewidth = material.linewidth;
  12606. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12607. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12608. result.nearDistance = shadowCameraNear;
  12609. result.farDistance = shadowCameraFar;
  12610. }
  12611. return result;
  12612. }
  12613. function renderObject( object, camera, shadowCamera, light, type ) {
  12614. if ( object.visible === false ) return;
  12615. const visible = object.layers.test( camera.layers );
  12616. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12617. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12618. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12619. const geometry = _objects.update( object );
  12620. const material = object.material;
  12621. if ( Array.isArray( material ) ) {
  12622. const groups = geometry.groups;
  12623. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12624. const group = groups[ k ];
  12625. const groupMaterial = material[ group.materialIndex ];
  12626. if ( groupMaterial && groupMaterial.visible ) {
  12627. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12628. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12629. }
  12630. }
  12631. } else if ( material.visible ) {
  12632. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12633. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12634. }
  12635. }
  12636. }
  12637. const children = object.children;
  12638. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12639. renderObject( children[ i ], camera, shadowCamera, light, type );
  12640. }
  12641. }
  12642. }
  12643. function WebGLState( gl, extensions, capabilities ) {
  12644. const isWebGL2 = capabilities.isWebGL2;
  12645. function ColorBuffer() {
  12646. let locked = false;
  12647. const color = new Vector4();
  12648. let currentColorMask = null;
  12649. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12650. return {
  12651. setMask: function ( colorMask ) {
  12652. if ( currentColorMask !== colorMask && ! locked ) {
  12653. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12654. currentColorMask = colorMask;
  12655. }
  12656. },
  12657. setLocked: function ( lock ) {
  12658. locked = lock;
  12659. },
  12660. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12661. if ( premultipliedAlpha === true ) {
  12662. r *= a; g *= a; b *= a;
  12663. }
  12664. color.set( r, g, b, a );
  12665. if ( currentColorClear.equals( color ) === false ) {
  12666. gl.clearColor( r, g, b, a );
  12667. currentColorClear.copy( color );
  12668. }
  12669. },
  12670. reset: function () {
  12671. locked = false;
  12672. currentColorMask = null;
  12673. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12674. }
  12675. };
  12676. }
  12677. function DepthBuffer() {
  12678. let locked = false;
  12679. let currentDepthMask = null;
  12680. let currentDepthFunc = null;
  12681. let currentDepthClear = null;
  12682. return {
  12683. setTest: function ( depthTest ) {
  12684. if ( depthTest ) {
  12685. enable( 2929 );
  12686. } else {
  12687. disable( 2929 );
  12688. }
  12689. },
  12690. setMask: function ( depthMask ) {
  12691. if ( currentDepthMask !== depthMask && ! locked ) {
  12692. gl.depthMask( depthMask );
  12693. currentDepthMask = depthMask;
  12694. }
  12695. },
  12696. setFunc: function ( depthFunc ) {
  12697. if ( currentDepthFunc !== depthFunc ) {
  12698. if ( depthFunc ) {
  12699. switch ( depthFunc ) {
  12700. case NeverDepth:
  12701. gl.depthFunc( 512 );
  12702. break;
  12703. case AlwaysDepth:
  12704. gl.depthFunc( 519 );
  12705. break;
  12706. case LessDepth:
  12707. gl.depthFunc( 513 );
  12708. break;
  12709. case LessEqualDepth:
  12710. gl.depthFunc( 515 );
  12711. break;
  12712. case EqualDepth:
  12713. gl.depthFunc( 514 );
  12714. break;
  12715. case GreaterEqualDepth:
  12716. gl.depthFunc( 518 );
  12717. break;
  12718. case GreaterDepth:
  12719. gl.depthFunc( 516 );
  12720. break;
  12721. case NotEqualDepth:
  12722. gl.depthFunc( 517 );
  12723. break;
  12724. default:
  12725. gl.depthFunc( 515 );
  12726. }
  12727. } else {
  12728. gl.depthFunc( 515 );
  12729. }
  12730. currentDepthFunc = depthFunc;
  12731. }
  12732. },
  12733. setLocked: function ( lock ) {
  12734. locked = lock;
  12735. },
  12736. setClear: function ( depth ) {
  12737. if ( currentDepthClear !== depth ) {
  12738. gl.clearDepth( depth );
  12739. currentDepthClear = depth;
  12740. }
  12741. },
  12742. reset: function () {
  12743. locked = false;
  12744. currentDepthMask = null;
  12745. currentDepthFunc = null;
  12746. currentDepthClear = null;
  12747. }
  12748. };
  12749. }
  12750. function StencilBuffer() {
  12751. let locked = false;
  12752. let currentStencilMask = null;
  12753. let currentStencilFunc = null;
  12754. let currentStencilRef = null;
  12755. let currentStencilFuncMask = null;
  12756. let currentStencilFail = null;
  12757. let currentStencilZFail = null;
  12758. let currentStencilZPass = null;
  12759. let currentStencilClear = null;
  12760. return {
  12761. setTest: function ( stencilTest ) {
  12762. if ( ! locked ) {
  12763. if ( stencilTest ) {
  12764. enable( 2960 );
  12765. } else {
  12766. disable( 2960 );
  12767. }
  12768. }
  12769. },
  12770. setMask: function ( stencilMask ) {
  12771. if ( currentStencilMask !== stencilMask && ! locked ) {
  12772. gl.stencilMask( stencilMask );
  12773. currentStencilMask = stencilMask;
  12774. }
  12775. },
  12776. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12777. if ( currentStencilFunc !== stencilFunc ||
  12778. currentStencilRef !== stencilRef ||
  12779. currentStencilFuncMask !== stencilMask ) {
  12780. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12781. currentStencilFunc = stencilFunc;
  12782. currentStencilRef = stencilRef;
  12783. currentStencilFuncMask = stencilMask;
  12784. }
  12785. },
  12786. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12787. if ( currentStencilFail !== stencilFail ||
  12788. currentStencilZFail !== stencilZFail ||
  12789. currentStencilZPass !== stencilZPass ) {
  12790. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12791. currentStencilFail = stencilFail;
  12792. currentStencilZFail = stencilZFail;
  12793. currentStencilZPass = stencilZPass;
  12794. }
  12795. },
  12796. setLocked: function ( lock ) {
  12797. locked = lock;
  12798. },
  12799. setClear: function ( stencil ) {
  12800. if ( currentStencilClear !== stencil ) {
  12801. gl.clearStencil( stencil );
  12802. currentStencilClear = stencil;
  12803. }
  12804. },
  12805. reset: function () {
  12806. locked = false;
  12807. currentStencilMask = null;
  12808. currentStencilFunc = null;
  12809. currentStencilRef = null;
  12810. currentStencilFuncMask = null;
  12811. currentStencilFail = null;
  12812. currentStencilZFail = null;
  12813. currentStencilZPass = null;
  12814. currentStencilClear = null;
  12815. }
  12816. };
  12817. }
  12818. //
  12819. const colorBuffer = new ColorBuffer();
  12820. const depthBuffer = new DepthBuffer();
  12821. const stencilBuffer = new StencilBuffer();
  12822. let enabledCapabilities = {};
  12823. let currentBoundFramebuffers = {};
  12824. let currentDrawbuffers = new WeakMap();
  12825. let defaultDrawbuffers = [];
  12826. let currentProgram = null;
  12827. let currentBlendingEnabled = false;
  12828. let currentBlending = null;
  12829. let currentBlendEquation = null;
  12830. let currentBlendSrc = null;
  12831. let currentBlendDst = null;
  12832. let currentBlendEquationAlpha = null;
  12833. let currentBlendSrcAlpha = null;
  12834. let currentBlendDstAlpha = null;
  12835. let currentPremultipledAlpha = false;
  12836. let currentFlipSided = null;
  12837. let currentCullFace = null;
  12838. let currentLineWidth = null;
  12839. let currentPolygonOffsetFactor = null;
  12840. let currentPolygonOffsetUnits = null;
  12841. const maxTextures = gl.getParameter( 35661 );
  12842. let lineWidthAvailable = false;
  12843. let version = 0;
  12844. const glVersion = gl.getParameter( 7938 );
  12845. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12846. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12847. lineWidthAvailable = ( version >= 1.0 );
  12848. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12849. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12850. lineWidthAvailable = ( version >= 2.0 );
  12851. }
  12852. let currentTextureSlot = null;
  12853. let currentBoundTextures = {};
  12854. const scissorParam = gl.getParameter( 3088 );
  12855. const viewportParam = gl.getParameter( 2978 );
  12856. const currentScissor = new Vector4().fromArray( scissorParam );
  12857. const currentViewport = new Vector4().fromArray( viewportParam );
  12858. function createTexture( type, target, count ) {
  12859. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12860. const texture = gl.createTexture();
  12861. gl.bindTexture( type, texture );
  12862. gl.texParameteri( type, 10241, 9728 );
  12863. gl.texParameteri( type, 10240, 9728 );
  12864. for ( let i = 0; i < count; i ++ ) {
  12865. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12866. }
  12867. return texture;
  12868. }
  12869. const emptyTextures = {};
  12870. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12871. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12872. // init
  12873. colorBuffer.setClear( 0, 0, 0, 1 );
  12874. depthBuffer.setClear( 1 );
  12875. stencilBuffer.setClear( 0 );
  12876. enable( 2929 );
  12877. depthBuffer.setFunc( LessEqualDepth );
  12878. setFlipSided( false );
  12879. setCullFace( CullFaceBack );
  12880. enable( 2884 );
  12881. setBlending( NoBlending );
  12882. //
  12883. function enable( id ) {
  12884. if ( enabledCapabilities[ id ] !== true ) {
  12885. gl.enable( id );
  12886. enabledCapabilities[ id ] = true;
  12887. }
  12888. }
  12889. function disable( id ) {
  12890. if ( enabledCapabilities[ id ] !== false ) {
  12891. gl.disable( id );
  12892. enabledCapabilities[ id ] = false;
  12893. }
  12894. }
  12895. function bindFramebuffer( target, framebuffer ) {
  12896. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12897. gl.bindFramebuffer( target, framebuffer );
  12898. currentBoundFramebuffers[ target ] = framebuffer;
  12899. if ( isWebGL2 ) {
  12900. // 36009 is equivalent to 36160
  12901. if ( target === 36009 ) {
  12902. currentBoundFramebuffers[ 36160 ] = framebuffer;
  12903. }
  12904. if ( target === 36160 ) {
  12905. currentBoundFramebuffers[ 36009 ] = framebuffer;
  12906. }
  12907. }
  12908. return true;
  12909. }
  12910. return false;
  12911. }
  12912. function drawBuffers( renderTarget, framebuffer ) {
  12913. let drawBuffers = defaultDrawbuffers;
  12914. let needsUpdate = false;
  12915. if ( renderTarget ) {
  12916. drawBuffers = currentDrawbuffers.get( framebuffer );
  12917. if ( drawBuffers === undefined ) {
  12918. drawBuffers = [];
  12919. currentDrawbuffers.set( framebuffer, drawBuffers );
  12920. }
  12921. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  12922. const textures = renderTarget.texture;
  12923. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  12924. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12925. drawBuffers[ i ] = 36064 + i;
  12926. }
  12927. drawBuffers.length = textures.length;
  12928. needsUpdate = true;
  12929. }
  12930. } else {
  12931. if ( drawBuffers[ 0 ] !== 36064 ) {
  12932. drawBuffers[ 0 ] = 36064;
  12933. needsUpdate = true;
  12934. }
  12935. }
  12936. } else {
  12937. if ( drawBuffers[ 0 ] !== 1029 ) {
  12938. drawBuffers[ 0 ] = 1029;
  12939. needsUpdate = true;
  12940. }
  12941. }
  12942. if ( needsUpdate ) {
  12943. if ( capabilities.isWebGL2 ) {
  12944. gl.drawBuffers( drawBuffers );
  12945. } else {
  12946. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  12947. }
  12948. }
  12949. }
  12950. function useProgram( program ) {
  12951. if ( currentProgram !== program ) {
  12952. gl.useProgram( program );
  12953. currentProgram = program;
  12954. return true;
  12955. }
  12956. return false;
  12957. }
  12958. const equationToGL = {
  12959. [ AddEquation ]: 32774,
  12960. [ SubtractEquation ]: 32778,
  12961. [ ReverseSubtractEquation ]: 32779
  12962. };
  12963. if ( isWebGL2 ) {
  12964. equationToGL[ MinEquation ] = 32775;
  12965. equationToGL[ MaxEquation ] = 32776;
  12966. } else {
  12967. const extension = extensions.get( 'EXT_blend_minmax' );
  12968. if ( extension !== null ) {
  12969. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12970. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12971. }
  12972. }
  12973. const factorToGL = {
  12974. [ ZeroFactor ]: 0,
  12975. [ OneFactor ]: 1,
  12976. [ SrcColorFactor ]: 768,
  12977. [ SrcAlphaFactor ]: 770,
  12978. [ SrcAlphaSaturateFactor ]: 776,
  12979. [ DstColorFactor ]: 774,
  12980. [ DstAlphaFactor ]: 772,
  12981. [ OneMinusSrcColorFactor ]: 769,
  12982. [ OneMinusSrcAlphaFactor ]: 771,
  12983. [ OneMinusDstColorFactor ]: 775,
  12984. [ OneMinusDstAlphaFactor ]: 773
  12985. };
  12986. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12987. if ( blending === NoBlending ) {
  12988. if ( currentBlendingEnabled === true ) {
  12989. disable( 3042 );
  12990. currentBlendingEnabled = false;
  12991. }
  12992. return;
  12993. }
  12994. if ( currentBlendingEnabled === false ) {
  12995. enable( 3042 );
  12996. currentBlendingEnabled = true;
  12997. }
  12998. if ( blending !== CustomBlending ) {
  12999. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13000. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13001. gl.blendEquation( 32774 );
  13002. currentBlendEquation = AddEquation;
  13003. currentBlendEquationAlpha = AddEquation;
  13004. }
  13005. if ( premultipliedAlpha ) {
  13006. switch ( blending ) {
  13007. case NormalBlending:
  13008. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13009. break;
  13010. case AdditiveBlending:
  13011. gl.blendFunc( 1, 1 );
  13012. break;
  13013. case SubtractiveBlending:
  13014. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13015. break;
  13016. case MultiplyBlending:
  13017. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13018. break;
  13019. default:
  13020. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13021. break;
  13022. }
  13023. } else {
  13024. switch ( blending ) {
  13025. case NormalBlending:
  13026. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13027. break;
  13028. case AdditiveBlending:
  13029. gl.blendFunc( 770, 1 );
  13030. break;
  13031. case SubtractiveBlending:
  13032. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13033. break;
  13034. case MultiplyBlending:
  13035. gl.blendFunc( 0, 768 );
  13036. break;
  13037. default:
  13038. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13039. break;
  13040. }
  13041. }
  13042. currentBlendSrc = null;
  13043. currentBlendDst = null;
  13044. currentBlendSrcAlpha = null;
  13045. currentBlendDstAlpha = null;
  13046. currentBlending = blending;
  13047. currentPremultipledAlpha = premultipliedAlpha;
  13048. }
  13049. return;
  13050. }
  13051. // custom blending
  13052. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13053. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13054. blendDstAlpha = blendDstAlpha || blendDst;
  13055. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13056. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13057. currentBlendEquation = blendEquation;
  13058. currentBlendEquationAlpha = blendEquationAlpha;
  13059. }
  13060. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13061. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13062. currentBlendSrc = blendSrc;
  13063. currentBlendDst = blendDst;
  13064. currentBlendSrcAlpha = blendSrcAlpha;
  13065. currentBlendDstAlpha = blendDstAlpha;
  13066. }
  13067. currentBlending = blending;
  13068. currentPremultipledAlpha = null;
  13069. }
  13070. function setMaterial( material, frontFaceCW ) {
  13071. material.side === DoubleSide
  13072. ? disable( 2884 )
  13073. : enable( 2884 );
  13074. let flipSided = ( material.side === BackSide );
  13075. if ( frontFaceCW ) flipSided = ! flipSided;
  13076. setFlipSided( flipSided );
  13077. ( material.blending === NormalBlending && material.transparent === false )
  13078. ? setBlending( NoBlending )
  13079. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13080. depthBuffer.setFunc( material.depthFunc );
  13081. depthBuffer.setTest( material.depthTest );
  13082. depthBuffer.setMask( material.depthWrite );
  13083. colorBuffer.setMask( material.colorWrite );
  13084. const stencilWrite = material.stencilWrite;
  13085. stencilBuffer.setTest( stencilWrite );
  13086. if ( stencilWrite ) {
  13087. stencilBuffer.setMask( material.stencilWriteMask );
  13088. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13089. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13090. }
  13091. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13092. material.alphaToCoverage === true
  13093. ? enable( 32926 )
  13094. : disable( 32926 );
  13095. }
  13096. //
  13097. function setFlipSided( flipSided ) {
  13098. if ( currentFlipSided !== flipSided ) {
  13099. if ( flipSided ) {
  13100. gl.frontFace( 2304 );
  13101. } else {
  13102. gl.frontFace( 2305 );
  13103. }
  13104. currentFlipSided = flipSided;
  13105. }
  13106. }
  13107. function setCullFace( cullFace ) {
  13108. if ( cullFace !== CullFaceNone ) {
  13109. enable( 2884 );
  13110. if ( cullFace !== currentCullFace ) {
  13111. if ( cullFace === CullFaceBack ) {
  13112. gl.cullFace( 1029 );
  13113. } else if ( cullFace === CullFaceFront ) {
  13114. gl.cullFace( 1028 );
  13115. } else {
  13116. gl.cullFace( 1032 );
  13117. }
  13118. }
  13119. } else {
  13120. disable( 2884 );
  13121. }
  13122. currentCullFace = cullFace;
  13123. }
  13124. function setLineWidth( width ) {
  13125. if ( width !== currentLineWidth ) {
  13126. if ( lineWidthAvailable ) gl.lineWidth( width );
  13127. currentLineWidth = width;
  13128. }
  13129. }
  13130. function setPolygonOffset( polygonOffset, factor, units ) {
  13131. if ( polygonOffset ) {
  13132. enable( 32823 );
  13133. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13134. gl.polygonOffset( factor, units );
  13135. currentPolygonOffsetFactor = factor;
  13136. currentPolygonOffsetUnits = units;
  13137. }
  13138. } else {
  13139. disable( 32823 );
  13140. }
  13141. }
  13142. function setScissorTest( scissorTest ) {
  13143. if ( scissorTest ) {
  13144. enable( 3089 );
  13145. } else {
  13146. disable( 3089 );
  13147. }
  13148. }
  13149. // texture
  13150. function activeTexture( webglSlot ) {
  13151. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13152. if ( currentTextureSlot !== webglSlot ) {
  13153. gl.activeTexture( webglSlot );
  13154. currentTextureSlot = webglSlot;
  13155. }
  13156. }
  13157. function bindTexture( webglType, webglTexture ) {
  13158. if ( currentTextureSlot === null ) {
  13159. activeTexture();
  13160. }
  13161. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  13162. if ( boundTexture === undefined ) {
  13163. boundTexture = { type: undefined, texture: undefined };
  13164. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  13165. }
  13166. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13167. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13168. boundTexture.type = webglType;
  13169. boundTexture.texture = webglTexture;
  13170. }
  13171. }
  13172. function unbindTexture() {
  13173. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13174. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13175. gl.bindTexture( boundTexture.type, null );
  13176. boundTexture.type = undefined;
  13177. boundTexture.texture = undefined;
  13178. }
  13179. }
  13180. function compressedTexImage2D() {
  13181. try {
  13182. gl.compressedTexImage2D.apply( gl, arguments );
  13183. } catch ( error ) {
  13184. console.error( 'THREE.WebGLState:', error );
  13185. }
  13186. }
  13187. function texSubImage2D() {
  13188. try {
  13189. gl.texSubImage2D.apply( gl, arguments );
  13190. } catch ( error ) {
  13191. console.error( 'THREE.WebGLState:', error );
  13192. }
  13193. }
  13194. function texSubImage3D() {
  13195. try {
  13196. gl.texSubImage3D.apply( gl, arguments );
  13197. } catch ( error ) {
  13198. console.error( 'THREE.WebGLState:', error );
  13199. }
  13200. }
  13201. function compressedTexSubImage2D() {
  13202. try {
  13203. gl.compressedTexSubImage2D.apply( gl, arguments );
  13204. } catch ( error ) {
  13205. console.error( 'THREE.WebGLState:', error );
  13206. }
  13207. }
  13208. function texStorage2D() {
  13209. try {
  13210. gl.texStorage2D.apply( gl, arguments );
  13211. } catch ( error ) {
  13212. console.error( 'THREE.WebGLState:', error );
  13213. }
  13214. }
  13215. function texStorage3D() {
  13216. try {
  13217. gl.texStorage3D.apply( gl, arguments );
  13218. } catch ( error ) {
  13219. console.error( 'THREE.WebGLState:', error );
  13220. }
  13221. }
  13222. function texImage2D() {
  13223. try {
  13224. gl.texImage2D.apply( gl, arguments );
  13225. } catch ( error ) {
  13226. console.error( 'THREE.WebGLState:', error );
  13227. }
  13228. }
  13229. function texImage3D() {
  13230. try {
  13231. gl.texImage3D.apply( gl, arguments );
  13232. } catch ( error ) {
  13233. console.error( 'THREE.WebGLState:', error );
  13234. }
  13235. }
  13236. //
  13237. function scissor( scissor ) {
  13238. if ( currentScissor.equals( scissor ) === false ) {
  13239. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13240. currentScissor.copy( scissor );
  13241. }
  13242. }
  13243. function viewport( viewport ) {
  13244. if ( currentViewport.equals( viewport ) === false ) {
  13245. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13246. currentViewport.copy( viewport );
  13247. }
  13248. }
  13249. //
  13250. function reset() {
  13251. // reset state
  13252. gl.disable( 3042 );
  13253. gl.disable( 2884 );
  13254. gl.disable( 2929 );
  13255. gl.disable( 32823 );
  13256. gl.disable( 3089 );
  13257. gl.disable( 2960 );
  13258. gl.disable( 32926 );
  13259. gl.blendEquation( 32774 );
  13260. gl.blendFunc( 1, 0 );
  13261. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13262. gl.colorMask( true, true, true, true );
  13263. gl.clearColor( 0, 0, 0, 0 );
  13264. gl.depthMask( true );
  13265. gl.depthFunc( 513 );
  13266. gl.clearDepth( 1 );
  13267. gl.stencilMask( 0xffffffff );
  13268. gl.stencilFunc( 519, 0, 0xffffffff );
  13269. gl.stencilOp( 7680, 7680, 7680 );
  13270. gl.clearStencil( 0 );
  13271. gl.cullFace( 1029 );
  13272. gl.frontFace( 2305 );
  13273. gl.polygonOffset( 0, 0 );
  13274. gl.activeTexture( 33984 );
  13275. gl.bindFramebuffer( 36160, null );
  13276. if ( isWebGL2 === true ) {
  13277. gl.bindFramebuffer( 36009, null );
  13278. gl.bindFramebuffer( 36008, null );
  13279. }
  13280. gl.useProgram( null );
  13281. gl.lineWidth( 1 );
  13282. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13283. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13284. // reset internals
  13285. enabledCapabilities = {};
  13286. currentTextureSlot = null;
  13287. currentBoundTextures = {};
  13288. currentBoundFramebuffers = {};
  13289. currentDrawbuffers = new WeakMap();
  13290. defaultDrawbuffers = [];
  13291. currentProgram = null;
  13292. currentBlendingEnabled = false;
  13293. currentBlending = null;
  13294. currentBlendEquation = null;
  13295. currentBlendSrc = null;
  13296. currentBlendDst = null;
  13297. currentBlendEquationAlpha = null;
  13298. currentBlendSrcAlpha = null;
  13299. currentBlendDstAlpha = null;
  13300. currentPremultipledAlpha = false;
  13301. currentFlipSided = null;
  13302. currentCullFace = null;
  13303. currentLineWidth = null;
  13304. currentPolygonOffsetFactor = null;
  13305. currentPolygonOffsetUnits = null;
  13306. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13307. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13308. colorBuffer.reset();
  13309. depthBuffer.reset();
  13310. stencilBuffer.reset();
  13311. }
  13312. return {
  13313. buffers: {
  13314. color: colorBuffer,
  13315. depth: depthBuffer,
  13316. stencil: stencilBuffer
  13317. },
  13318. enable: enable,
  13319. disable: disable,
  13320. bindFramebuffer: bindFramebuffer,
  13321. drawBuffers: drawBuffers,
  13322. useProgram: useProgram,
  13323. setBlending: setBlending,
  13324. setMaterial: setMaterial,
  13325. setFlipSided: setFlipSided,
  13326. setCullFace: setCullFace,
  13327. setLineWidth: setLineWidth,
  13328. setPolygonOffset: setPolygonOffset,
  13329. setScissorTest: setScissorTest,
  13330. activeTexture: activeTexture,
  13331. bindTexture: bindTexture,
  13332. unbindTexture: unbindTexture,
  13333. compressedTexImage2D: compressedTexImage2D,
  13334. texImage2D: texImage2D,
  13335. texImage3D: texImage3D,
  13336. texStorage2D: texStorage2D,
  13337. texStorage3D: texStorage3D,
  13338. texSubImage2D: texSubImage2D,
  13339. texSubImage3D: texSubImage3D,
  13340. compressedTexSubImage2D: compressedTexSubImage2D,
  13341. scissor: scissor,
  13342. viewport: viewport,
  13343. reset: reset
  13344. };
  13345. }
  13346. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13347. const isWebGL2 = capabilities.isWebGL2;
  13348. const maxTextures = capabilities.maxTextures;
  13349. const maxCubemapSize = capabilities.maxCubemapSize;
  13350. const maxTextureSize = capabilities.maxTextureSize;
  13351. const maxSamples = capabilities.maxSamples;
  13352. const hasMultisampledRenderToTexture = extensions.has( 'WEBGL_multisampled_render_to_texture' );
  13353. const MultisampledRenderToTextureExtension = hasMultisampledRenderToTexture ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : undefined;
  13354. const _videoTextures = new WeakMap();
  13355. let _canvas;
  13356. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13357. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13358. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13359. let useOffscreenCanvas = false;
  13360. try {
  13361. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13362. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13363. } catch ( err ) {
  13364. // Ignore any errors
  13365. }
  13366. function createCanvas( width, height ) {
  13367. // Use OffscreenCanvas when available. Specially needed in web workers
  13368. return useOffscreenCanvas ?
  13369. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13370. }
  13371. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13372. let scale = 1;
  13373. // handle case if texture exceeds max size
  13374. if ( image.width > maxSize || image.height > maxSize ) {
  13375. scale = maxSize / Math.max( image.width, image.height );
  13376. }
  13377. // only perform resize if necessary
  13378. if ( scale < 1 || needsPowerOfTwo === true ) {
  13379. // only perform resize for certain image types
  13380. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13381. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13382. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13383. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13384. const width = floor( scale * image.width );
  13385. const height = floor( scale * image.height );
  13386. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13387. // cube textures can't reuse the same canvas
  13388. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13389. canvas.width = width;
  13390. canvas.height = height;
  13391. const context = canvas.getContext( '2d' );
  13392. context.drawImage( image, 0, 0, width, height );
  13393. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13394. return canvas;
  13395. } else {
  13396. if ( 'data' in image ) {
  13397. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13398. }
  13399. return image;
  13400. }
  13401. }
  13402. return image;
  13403. }
  13404. function isPowerOfTwo$1( image ) {
  13405. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13406. }
  13407. function textureNeedsPowerOfTwo( texture ) {
  13408. if ( isWebGL2 ) return false;
  13409. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13410. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13411. }
  13412. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13413. return texture.generateMipmaps && supportsMips &&
  13414. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13415. }
  13416. function generateMipmap( target ) {
  13417. _gl.generateMipmap( target );
  13418. }
  13419. function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) {
  13420. if ( isWebGL2 === false ) return glFormat;
  13421. if ( internalFormatName !== null ) {
  13422. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13423. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13424. }
  13425. let internalFormat = glFormat;
  13426. if ( glFormat === 6403 ) {
  13427. if ( glType === 5126 ) internalFormat = 33326;
  13428. if ( glType === 5131 ) internalFormat = 33325;
  13429. if ( glType === 5121 ) internalFormat = 33321;
  13430. }
  13431. if ( glFormat === 33319 ) {
  13432. if ( glType === 5126 ) internalFormat = 33328;
  13433. if ( glType === 5131 ) internalFormat = 33327;
  13434. if ( glType === 5121 ) internalFormat = 33323;
  13435. }
  13436. if ( glFormat === 6408 ) {
  13437. if ( glType === 5126 ) internalFormat = 34836;
  13438. if ( glType === 5131 ) internalFormat = 34842;
  13439. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856;
  13440. if ( glType === 32819 ) internalFormat = 32854;
  13441. if ( glType === 32820 ) internalFormat = 32855;
  13442. }
  13443. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13444. internalFormat === 33327 || internalFormat === 33328 ||
  13445. internalFormat === 34842 || internalFormat === 34836 ) {
  13446. extensions.get( 'EXT_color_buffer_float' );
  13447. }
  13448. return internalFormat;
  13449. }
  13450. function getMipLevels( texture, image, supportsMips ) {
  13451. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13452. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13453. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13454. // user-defined mipmaps
  13455. return texture.mipmaps.length;
  13456. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13457. return image.mipmaps.length;
  13458. } else {
  13459. // texture without mipmaps (only base level)
  13460. return 1;
  13461. }
  13462. }
  13463. // Fallback filters for non-power-of-2 textures
  13464. function filterFallback( f ) {
  13465. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13466. return 9728;
  13467. }
  13468. return 9729;
  13469. }
  13470. //
  13471. function onTextureDispose( event ) {
  13472. const texture = event.target;
  13473. texture.removeEventListener( 'dispose', onTextureDispose );
  13474. deallocateTexture( texture );
  13475. if ( texture.isVideoTexture ) {
  13476. _videoTextures.delete( texture );
  13477. }
  13478. info.memory.textures --;
  13479. }
  13480. function onRenderTargetDispose( event ) {
  13481. const renderTarget = event.target;
  13482. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13483. deallocateRenderTarget( renderTarget );
  13484. }
  13485. //
  13486. function deallocateTexture( texture ) {
  13487. const textureProperties = properties.get( texture );
  13488. if ( textureProperties.__webglInit === undefined ) return;
  13489. _gl.deleteTexture( textureProperties.__webglTexture );
  13490. properties.remove( texture );
  13491. }
  13492. function deallocateRenderTarget( renderTarget ) {
  13493. const texture = renderTarget.texture;
  13494. const renderTargetProperties = properties.get( renderTarget );
  13495. const textureProperties = properties.get( texture );
  13496. if ( ! renderTarget ) return;
  13497. if ( textureProperties.__webglTexture !== undefined ) {
  13498. _gl.deleteTexture( textureProperties.__webglTexture );
  13499. info.memory.textures --;
  13500. }
  13501. if ( renderTarget.depthTexture ) {
  13502. renderTarget.depthTexture.dispose();
  13503. }
  13504. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13505. for ( let i = 0; i < 6; i ++ ) {
  13506. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13507. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13508. }
  13509. } else {
  13510. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13511. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13512. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13513. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13514. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13515. }
  13516. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13517. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13518. const attachmentProperties = properties.get( texture[ i ] );
  13519. if ( attachmentProperties.__webglTexture ) {
  13520. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13521. info.memory.textures --;
  13522. }
  13523. properties.remove( texture[ i ] );
  13524. }
  13525. }
  13526. properties.remove( texture );
  13527. properties.remove( renderTarget );
  13528. }
  13529. //
  13530. let textureUnits = 0;
  13531. function resetTextureUnits() {
  13532. textureUnits = 0;
  13533. }
  13534. function allocateTextureUnit() {
  13535. const textureUnit = textureUnits;
  13536. if ( textureUnit >= maxTextures ) {
  13537. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13538. }
  13539. textureUnits += 1;
  13540. return textureUnit;
  13541. }
  13542. //
  13543. function setTexture2D( texture, slot ) {
  13544. const textureProperties = properties.get( texture );
  13545. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13546. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13547. const image = texture.image;
  13548. if ( image === undefined ) {
  13549. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13550. } else if ( image.complete === false ) {
  13551. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13552. } else {
  13553. uploadTexture( textureProperties, texture, slot );
  13554. return;
  13555. }
  13556. }
  13557. state.activeTexture( 33984 + slot );
  13558. state.bindTexture( 3553, textureProperties.__webglTexture );
  13559. }
  13560. function setTexture2DArray( texture, slot ) {
  13561. const textureProperties = properties.get( texture );
  13562. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13563. uploadTexture( textureProperties, texture, slot );
  13564. return;
  13565. }
  13566. state.activeTexture( 33984 + slot );
  13567. state.bindTexture( 35866, textureProperties.__webglTexture );
  13568. }
  13569. function setTexture3D( texture, slot ) {
  13570. const textureProperties = properties.get( texture );
  13571. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13572. uploadTexture( textureProperties, texture, slot );
  13573. return;
  13574. }
  13575. state.activeTexture( 33984 + slot );
  13576. state.bindTexture( 32879, textureProperties.__webglTexture );
  13577. }
  13578. function setTextureCube( texture, slot ) {
  13579. const textureProperties = properties.get( texture );
  13580. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13581. uploadCubeTexture( textureProperties, texture, slot );
  13582. return;
  13583. }
  13584. state.activeTexture( 33984 + slot );
  13585. state.bindTexture( 34067, textureProperties.__webglTexture );
  13586. }
  13587. const wrappingToGL = {
  13588. [ RepeatWrapping ]: 10497,
  13589. [ ClampToEdgeWrapping ]: 33071,
  13590. [ MirroredRepeatWrapping ]: 33648
  13591. };
  13592. const filterToGL = {
  13593. [ NearestFilter ]: 9728,
  13594. [ NearestMipmapNearestFilter ]: 9984,
  13595. [ NearestMipmapLinearFilter ]: 9986,
  13596. [ LinearFilter ]: 9729,
  13597. [ LinearMipmapNearestFilter ]: 9985,
  13598. [ LinearMipmapLinearFilter ]: 9987
  13599. };
  13600. function setTextureParameters( textureType, texture, supportsMips ) {
  13601. if ( supportsMips ) {
  13602. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13603. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13604. if ( textureType === 32879 || textureType === 35866 ) {
  13605. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13606. }
  13607. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13608. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13609. } else {
  13610. _gl.texParameteri( textureType, 10242, 33071 );
  13611. _gl.texParameteri( textureType, 10243, 33071 );
  13612. if ( textureType === 32879 || textureType === 35866 ) {
  13613. _gl.texParameteri( textureType, 32882, 33071 );
  13614. }
  13615. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13616. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13617. }
  13618. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13619. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13620. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13621. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13622. }
  13623. }
  13624. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13625. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13626. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13627. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13628. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13629. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13630. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13631. }
  13632. }
  13633. }
  13634. function initTexture( textureProperties, texture ) {
  13635. if ( textureProperties.__webglInit === undefined ) {
  13636. textureProperties.__webglInit = true;
  13637. texture.addEventListener( 'dispose', onTextureDispose );
  13638. textureProperties.__webglTexture = _gl.createTexture();
  13639. info.memory.textures ++;
  13640. }
  13641. }
  13642. function uploadTexture( textureProperties, texture, slot ) {
  13643. let textureType = 3553;
  13644. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13645. if ( texture.isDataTexture3D ) textureType = 32879;
  13646. initTexture( textureProperties, texture );
  13647. state.activeTexture( 33984 + slot );
  13648. state.bindTexture( textureType, textureProperties.__webglTexture );
  13649. _gl.pixelStorei( 37440, texture.flipY );
  13650. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13651. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13652. _gl.pixelStorei( 37443, 0 );
  13653. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13654. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13655. image = verifyColorSpace( texture, image );
  13656. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13657. glFormat = utils.convert( texture.format, texture.encoding );
  13658. let glType = utils.convert( texture.type ),
  13659. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13660. setTextureParameters( textureType, texture, supportsMips );
  13661. let mipmap;
  13662. const mipmaps = texture.mipmaps;
  13663. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13664. const allocateMemory = ( textureProperties.__version === undefined );
  13665. const levels = getMipLevels( texture, image, supportsMips );
  13666. if ( texture.isDepthTexture ) {
  13667. // populate depth texture with dummy data
  13668. glInternalFormat = 6402;
  13669. if ( isWebGL2 ) {
  13670. if ( texture.type === FloatType ) {
  13671. glInternalFormat = 36012;
  13672. } else if ( texture.type === UnsignedIntType ) {
  13673. glInternalFormat = 33190;
  13674. } else if ( texture.type === UnsignedInt248Type ) {
  13675. glInternalFormat = 35056;
  13676. } else {
  13677. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13678. }
  13679. } else {
  13680. if ( texture.type === FloatType ) {
  13681. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13682. }
  13683. }
  13684. // validation checks for WebGL 1
  13685. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13686. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13687. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13688. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13689. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13690. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13691. texture.type = UnsignedShortType;
  13692. glType = utils.convert( texture.type );
  13693. }
  13694. }
  13695. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13696. // Depth stencil textures need the DEPTH_STENCIL internal format
  13697. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13698. glInternalFormat = 34041;
  13699. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13700. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13701. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13702. if ( texture.type !== UnsignedInt248Type ) {
  13703. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13704. texture.type = UnsignedInt248Type;
  13705. glType = utils.convert( texture.type );
  13706. }
  13707. }
  13708. //
  13709. if ( useTexStorage && allocateMemory ) {
  13710. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  13711. } else {
  13712. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13713. }
  13714. } else if ( texture.isDataTexture ) {
  13715. // use manually created mipmaps if available
  13716. // if there are no manual mipmaps
  13717. // set 0 level mipmap and then use GL to generate other mipmap levels
  13718. if ( mipmaps.length > 0 && supportsMips ) {
  13719. if ( useTexStorage && allocateMemory ) {
  13720. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13721. }
  13722. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13723. mipmap = mipmaps[ i ];
  13724. if ( useTexStorage ) {
  13725. state.texSubImage2D( 3553, 0, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13726. } else {
  13727. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13728. }
  13729. }
  13730. texture.generateMipmaps = false;
  13731. } else {
  13732. if ( useTexStorage ) {
  13733. if ( allocateMemory ) {
  13734. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13735. }
  13736. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  13737. } else {
  13738. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13739. }
  13740. }
  13741. } else if ( texture.isCompressedTexture ) {
  13742. if ( useTexStorage && allocateMemory ) {
  13743. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13744. }
  13745. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13746. mipmap = mipmaps[ i ];
  13747. if ( texture.format !== RGBAFormat ) {
  13748. if ( glFormat !== null ) {
  13749. if ( useTexStorage ) {
  13750. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  13751. } else {
  13752. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13753. }
  13754. } else {
  13755. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13756. }
  13757. } else {
  13758. if ( useTexStorage ) {
  13759. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13760. } else {
  13761. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13762. }
  13763. }
  13764. }
  13765. } else if ( texture.isDataTexture2DArray ) {
  13766. if ( useTexStorage ) {
  13767. if ( allocateMemory ) {
  13768. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  13769. }
  13770. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13771. } else {
  13772. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13773. }
  13774. } else if ( texture.isDataTexture3D ) {
  13775. if ( useTexStorage ) {
  13776. if ( allocateMemory ) {
  13777. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  13778. }
  13779. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13780. } else {
  13781. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13782. }
  13783. } else if ( texture.isFramebufferTexture ) {
  13784. if ( useTexStorage && allocateMemory ) {
  13785. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13786. } else {
  13787. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13788. }
  13789. } else {
  13790. // regular Texture (image, video, canvas)
  13791. // use manually created mipmaps if available
  13792. // if there are no manual mipmaps
  13793. // set 0 level mipmap and then use GL to generate other mipmap levels
  13794. if ( mipmaps.length > 0 && supportsMips ) {
  13795. if ( useTexStorage && allocateMemory ) {
  13796. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13797. }
  13798. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13799. mipmap = mipmaps[ i ];
  13800. if ( useTexStorage ) {
  13801. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  13802. } else {
  13803. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13804. }
  13805. }
  13806. texture.generateMipmaps = false;
  13807. } else {
  13808. if ( useTexStorage ) {
  13809. if ( allocateMemory ) {
  13810. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13811. }
  13812. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  13813. } else {
  13814. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13815. }
  13816. }
  13817. }
  13818. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13819. generateMipmap( textureType );
  13820. }
  13821. textureProperties.__version = texture.version;
  13822. if ( texture.onUpdate ) texture.onUpdate( texture );
  13823. }
  13824. function uploadCubeTexture( textureProperties, texture, slot ) {
  13825. if ( texture.image.length !== 6 ) return;
  13826. initTexture( textureProperties, texture );
  13827. state.activeTexture( 33984 + slot );
  13828. state.bindTexture( 34067, textureProperties.__webglTexture );
  13829. _gl.pixelStorei( 37440, texture.flipY );
  13830. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13831. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13832. _gl.pixelStorei( 37443, 0 );
  13833. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13834. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13835. const cubeImage = [];
  13836. for ( let i = 0; i < 6; i ++ ) {
  13837. if ( ! isCompressed && ! isDataTexture ) {
  13838. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13839. } else {
  13840. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13841. }
  13842. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  13843. }
  13844. const image = cubeImage[ 0 ],
  13845. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13846. glFormat = utils.convert( texture.format, texture.encoding ),
  13847. glType = utils.convert( texture.type ),
  13848. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13849. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13850. const allocateMemory = ( textureProperties.__version === undefined );
  13851. let levels = getMipLevels( texture, image, supportsMips );
  13852. setTextureParameters( 34067, texture, supportsMips );
  13853. let mipmaps;
  13854. if ( isCompressed ) {
  13855. if ( useTexStorage && allocateMemory ) {
  13856. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  13857. }
  13858. for ( let i = 0; i < 6; i ++ ) {
  13859. mipmaps = cubeImage[ i ].mipmaps;
  13860. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13861. const mipmap = mipmaps[ j ];
  13862. if ( texture.format !== RGBAFormat ) {
  13863. if ( glFormat !== null ) {
  13864. if ( useTexStorage ) {
  13865. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  13866. } else {
  13867. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13868. }
  13869. } else {
  13870. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13871. }
  13872. } else {
  13873. if ( useTexStorage ) {
  13874. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13875. } else {
  13876. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13877. }
  13878. }
  13879. }
  13880. }
  13881. } else {
  13882. mipmaps = texture.mipmaps;
  13883. if ( useTexStorage && allocateMemory ) {
  13884. // TODO: Uniformly handle mipmap definitions
  13885. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  13886. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  13887. if ( mipmaps.length > 0 ) levels ++;
  13888. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  13889. }
  13890. for ( let i = 0; i < 6; i ++ ) {
  13891. if ( isDataTexture ) {
  13892. if ( useTexStorage ) {
  13893. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  13894. } else {
  13895. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13896. }
  13897. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13898. const mipmap = mipmaps[ j ];
  13899. const mipmapImage = mipmap.image[ i ].image;
  13900. if ( useTexStorage ) {
  13901. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  13902. } else {
  13903. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13904. }
  13905. }
  13906. } else {
  13907. if ( useTexStorage ) {
  13908. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  13909. } else {
  13910. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13911. }
  13912. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13913. const mipmap = mipmaps[ j ];
  13914. if ( useTexStorage ) {
  13915. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  13916. } else {
  13917. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13918. }
  13919. }
  13920. }
  13921. }
  13922. }
  13923. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13924. // We assume images for cube map have the same size.
  13925. generateMipmap( 34067 );
  13926. }
  13927. textureProperties.__version = texture.version;
  13928. if ( texture.onUpdate ) texture.onUpdate( texture );
  13929. }
  13930. // Render targets
  13931. // Setup storage for target texture and bind it to correct framebuffer
  13932. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  13933. const glFormat = utils.convert( texture.format, texture.encoding );
  13934. const glType = utils.convert( texture.type );
  13935. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13936. const renderTargetProperties = properties.get( renderTarget );
  13937. if ( ! renderTargetProperties.__hasExternalTextures ) {
  13938. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  13939. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  13940. } else {
  13941. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13942. }
  13943. }
  13944. state.bindFramebuffer( 36160, framebuffer );
  13945. if ( renderTarget.useRenderToTexture ) {
  13946. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  13947. } else {
  13948. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  13949. }
  13950. state.bindFramebuffer( 36160, null );
  13951. }
  13952. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13953. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13954. _gl.bindRenderbuffer( 36161, renderbuffer );
  13955. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13956. let glInternalFormat = 33189;
  13957. if ( isMultisample || renderTarget.useRenderToTexture ) {
  13958. const depthTexture = renderTarget.depthTexture;
  13959. if ( depthTexture && depthTexture.isDepthTexture ) {
  13960. if ( depthTexture.type === FloatType ) {
  13961. glInternalFormat = 36012;
  13962. } else if ( depthTexture.type === UnsignedIntType ) {
  13963. glInternalFormat = 33190;
  13964. }
  13965. }
  13966. const samples = getRenderTargetSamples( renderTarget );
  13967. if ( renderTarget.useRenderToTexture ) {
  13968. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13969. } else {
  13970. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13971. }
  13972. } else {
  13973. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13974. }
  13975. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13976. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13977. const samples = getRenderTargetSamples( renderTarget );
  13978. if ( isMultisample && renderTarget.useRenderbuffer ) {
  13979. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13980. } else if ( renderTarget.useRenderToTexture ) {
  13981. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13982. } else {
  13983. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13984. }
  13985. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13986. } else {
  13987. // Use the first texture for MRT so far
  13988. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  13989. const glFormat = utils.convert( texture.format, texture.encoding );
  13990. const glType = utils.convert( texture.type );
  13991. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13992. const samples = getRenderTargetSamples( renderTarget );
  13993. if ( isMultisample && renderTarget.useRenderbuffer ) {
  13994. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13995. } else if ( renderTarget.useRenderToTexture ) {
  13996. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13997. } else {
  13998. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13999. }
  14000. }
  14001. _gl.bindRenderbuffer( 36161, null );
  14002. }
  14003. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14004. function setupDepthTexture( framebuffer, renderTarget ) {
  14005. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14006. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14007. state.bindFramebuffer( 36160, framebuffer );
  14008. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14009. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14010. }
  14011. // upload an empty depth texture with framebuffer size
  14012. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14013. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14014. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14015. renderTarget.depthTexture.image.width = renderTarget.width;
  14016. renderTarget.depthTexture.image.height = renderTarget.height;
  14017. renderTarget.depthTexture.needsUpdate = true;
  14018. }
  14019. setTexture2D( renderTarget.depthTexture, 0 );
  14020. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14021. const samples = getRenderTargetSamples( renderTarget );
  14022. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14023. if ( renderTarget.useRenderToTexture ) {
  14024. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14025. } else {
  14026. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14027. }
  14028. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14029. if ( renderTarget.useRenderToTexture ) {
  14030. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14031. } else {
  14032. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14033. }
  14034. } else {
  14035. throw new Error( 'Unknown depthTexture format' );
  14036. }
  14037. }
  14038. // Setup GL resources for a non-texture depth buffer
  14039. function setupDepthRenderbuffer( renderTarget ) {
  14040. const renderTargetProperties = properties.get( renderTarget );
  14041. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14042. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14043. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14044. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14045. } else {
  14046. if ( isCube ) {
  14047. renderTargetProperties.__webglDepthbuffer = [];
  14048. for ( let i = 0; i < 6; i ++ ) {
  14049. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14050. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14051. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14052. }
  14053. } else {
  14054. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14055. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14056. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14057. }
  14058. }
  14059. state.bindFramebuffer( 36160, null );
  14060. }
  14061. // rebind framebuffer with external textures
  14062. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14063. const renderTargetProperties = properties.get( renderTarget );
  14064. if ( colorTexture !== undefined ) {
  14065. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14066. }
  14067. if ( depthTexture !== undefined ) {
  14068. setupDepthRenderbuffer( renderTarget );
  14069. }
  14070. }
  14071. // Set up GL resources for the render target
  14072. function setupRenderTarget( renderTarget ) {
  14073. const texture = renderTarget.texture;
  14074. const renderTargetProperties = properties.get( renderTarget );
  14075. const textureProperties = properties.get( texture );
  14076. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14077. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14078. if ( textureProperties.__webglTexture === undefined ) {
  14079. textureProperties.__webglTexture = _gl.createTexture();
  14080. }
  14081. textureProperties.__version = texture.version;
  14082. info.memory.textures ++;
  14083. }
  14084. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14085. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14086. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  14087. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14088. // Setup framebuffer
  14089. if ( isCube ) {
  14090. renderTargetProperties.__webglFramebuffer = [];
  14091. for ( let i = 0; i < 6; i ++ ) {
  14092. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14093. }
  14094. } else {
  14095. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14096. if ( isMultipleRenderTargets ) {
  14097. if ( capabilities.drawBuffers ) {
  14098. const textures = renderTarget.texture;
  14099. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14100. const attachmentProperties = properties.get( textures[ i ] );
  14101. if ( attachmentProperties.__webglTexture === undefined ) {
  14102. attachmentProperties.__webglTexture = _gl.createTexture();
  14103. info.memory.textures ++;
  14104. }
  14105. }
  14106. } else {
  14107. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14108. }
  14109. } else if ( renderTarget.useRenderbuffer ) {
  14110. if ( isWebGL2 ) {
  14111. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14112. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14113. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  14114. const glFormat = utils.convert( texture.format, texture.encoding );
  14115. const glType = utils.convert( texture.type );
  14116. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14117. const samples = getRenderTargetSamples( renderTarget );
  14118. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14119. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14120. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  14121. _gl.bindRenderbuffer( 36161, null );
  14122. if ( renderTarget.depthBuffer ) {
  14123. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14124. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14125. }
  14126. state.bindFramebuffer( 36160, null );
  14127. } else {
  14128. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  14129. }
  14130. }
  14131. }
  14132. // Setup color buffer
  14133. if ( isCube ) {
  14134. state.bindTexture( 34067, textureProperties.__webglTexture );
  14135. setTextureParameters( 34067, texture, supportsMips );
  14136. for ( let i = 0; i < 6; i ++ ) {
  14137. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14138. }
  14139. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14140. generateMipmap( 34067 );
  14141. }
  14142. state.unbindTexture();
  14143. } else if ( isMultipleRenderTargets ) {
  14144. const textures = renderTarget.texture;
  14145. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14146. const attachment = textures[ i ];
  14147. const attachmentProperties = properties.get( attachment );
  14148. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14149. setTextureParameters( 3553, attachment, supportsMips );
  14150. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14151. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14152. generateMipmap( 3553 );
  14153. }
  14154. }
  14155. state.unbindTexture();
  14156. } else {
  14157. let glTextureType = 3553;
  14158. if ( isRenderTarget3D ) {
  14159. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  14160. if ( isWebGL2 ) {
  14161. const isTexture3D = texture.isDataTexture3D;
  14162. glTextureType = isTexture3D ? 32879 : 35866;
  14163. } else {
  14164. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  14165. }
  14166. }
  14167. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14168. setTextureParameters( glTextureType, texture, supportsMips );
  14169. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14170. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14171. generateMipmap( glTextureType );
  14172. }
  14173. state.unbindTexture();
  14174. }
  14175. // Setup depth and stencil buffers
  14176. if ( renderTarget.depthBuffer ) {
  14177. setupDepthRenderbuffer( renderTarget );
  14178. }
  14179. }
  14180. function updateRenderTargetMipmap( renderTarget ) {
  14181. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14182. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14183. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14184. const texture = textures[ i ];
  14185. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14186. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14187. const webglTexture = properties.get( texture ).__webglTexture;
  14188. state.bindTexture( target, webglTexture );
  14189. generateMipmap( target );
  14190. state.unbindTexture();
  14191. }
  14192. }
  14193. }
  14194. function updateMultisampleRenderTarget( renderTarget ) {
  14195. if ( renderTarget.useRenderbuffer ) {
  14196. if ( isWebGL2 ) {
  14197. const width = renderTarget.width;
  14198. const height = renderTarget.height;
  14199. let mask = 16384;
  14200. const invalidationArray = [ 36064 ];
  14201. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14202. if ( renderTarget.depthBuffer ) {
  14203. invalidationArray.push( depthStyle );
  14204. }
  14205. if ( ! renderTarget.ignoreDepthForMultisampleCopy ) {
  14206. if ( renderTarget.depthBuffer ) mask |= 256;
  14207. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14208. }
  14209. const renderTargetProperties = properties.get( renderTarget );
  14210. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14211. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14212. if ( renderTarget.ignoreDepthForMultisampleCopy ) {
  14213. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14214. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14215. }
  14216. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14217. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14218. state.bindFramebuffer( 36008, null );
  14219. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14220. } else {
  14221. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  14222. }
  14223. }
  14224. }
  14225. function getRenderTargetSamples( renderTarget ) {
  14226. return ( isWebGL2 && ( renderTarget.useRenderbuffer || renderTarget.useRenderToTexture ) ) ?
  14227. Math.min( maxSamples, renderTarget.samples ) : 0;
  14228. }
  14229. function updateVideoTexture( texture ) {
  14230. const frame = info.render.frame;
  14231. // Check the last frame we updated the VideoTexture
  14232. if ( _videoTextures.get( texture ) !== frame ) {
  14233. _videoTextures.set( texture, frame );
  14234. texture.update();
  14235. }
  14236. }
  14237. function verifyColorSpace( texture, image ) {
  14238. const encoding = texture.encoding;
  14239. const format = texture.format;
  14240. const type = texture.type;
  14241. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14242. if ( encoding !== LinearEncoding ) {
  14243. // sRGB
  14244. if ( encoding === sRGBEncoding ) {
  14245. if ( isWebGL2 === false ) {
  14246. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14247. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14248. texture.format = _SRGBAFormat;
  14249. // it's not possible to generate mips in WebGL 1 with this extension
  14250. texture.minFilter = LinearFilter;
  14251. texture.generateMipmaps = false;
  14252. } else {
  14253. // slow fallback (CPU decode)
  14254. image = ImageUtils.sRGBToLinear( image );
  14255. }
  14256. } else {
  14257. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14258. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14259. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14260. }
  14261. }
  14262. } else {
  14263. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14264. }
  14265. }
  14266. return image;
  14267. }
  14268. // backwards compatibility
  14269. let warnedTexture2D = false;
  14270. let warnedTextureCube = false;
  14271. function safeSetTexture2D( texture, slot ) {
  14272. if ( texture && texture.isWebGLRenderTarget ) {
  14273. if ( warnedTexture2D === false ) {
  14274. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  14275. warnedTexture2D = true;
  14276. }
  14277. texture = texture.texture;
  14278. }
  14279. setTexture2D( texture, slot );
  14280. }
  14281. function safeSetTextureCube( texture, slot ) {
  14282. if ( texture && texture.isWebGLCubeRenderTarget ) {
  14283. if ( warnedTextureCube === false ) {
  14284. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  14285. warnedTextureCube = true;
  14286. }
  14287. texture = texture.texture;
  14288. }
  14289. setTextureCube( texture, slot );
  14290. }
  14291. //
  14292. this.allocateTextureUnit = allocateTextureUnit;
  14293. this.resetTextureUnits = resetTextureUnits;
  14294. this.setTexture2D = setTexture2D;
  14295. this.setTexture2DArray = setTexture2DArray;
  14296. this.setTexture3D = setTexture3D;
  14297. this.setTextureCube = setTextureCube;
  14298. this.rebindTextures = rebindTextures;
  14299. this.setupRenderTarget = setupRenderTarget;
  14300. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14301. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14302. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14303. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14304. this.safeSetTexture2D = safeSetTexture2D;
  14305. this.safeSetTextureCube = safeSetTextureCube;
  14306. }
  14307. function WebGLUtils( gl, extensions, capabilities ) {
  14308. const isWebGL2 = capabilities.isWebGL2;
  14309. function convert( p, encoding = null ) {
  14310. let extension;
  14311. if ( p === UnsignedByteType ) return 5121;
  14312. if ( p === UnsignedShort4444Type ) return 32819;
  14313. if ( p === UnsignedShort5551Type ) return 32820;
  14314. if ( p === ByteType ) return 5120;
  14315. if ( p === ShortType ) return 5122;
  14316. if ( p === UnsignedShortType ) return 5123;
  14317. if ( p === IntType ) return 5124;
  14318. if ( p === UnsignedIntType ) return 5125;
  14319. if ( p === FloatType ) return 5126;
  14320. if ( p === HalfFloatType ) {
  14321. if ( isWebGL2 ) return 5131;
  14322. extension = extensions.get( 'OES_texture_half_float' );
  14323. if ( extension !== null ) {
  14324. return extension.HALF_FLOAT_OES;
  14325. } else {
  14326. return null;
  14327. }
  14328. }
  14329. if ( p === AlphaFormat ) return 6406;
  14330. if ( p === RGBAFormat ) return 6408;
  14331. if ( p === LuminanceFormat ) return 6409;
  14332. if ( p === LuminanceAlphaFormat ) return 6410;
  14333. if ( p === DepthFormat ) return 6402;
  14334. if ( p === DepthStencilFormat ) return 34041;
  14335. if ( p === RedFormat ) return 6403;
  14336. if ( p === RGBFormat ) {
  14337. console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' );
  14338. return 6408;
  14339. }
  14340. // WebGL 1 sRGB fallback
  14341. if ( p === _SRGBAFormat ) {
  14342. extension = extensions.get( 'EXT_sRGB' );
  14343. if ( extension !== null ) {
  14344. return extension.SRGB_ALPHA_EXT;
  14345. } else {
  14346. return null;
  14347. }
  14348. }
  14349. // WebGL2 formats.
  14350. if ( p === RedIntegerFormat ) return 36244;
  14351. if ( p === RGFormat ) return 33319;
  14352. if ( p === RGIntegerFormat ) return 33320;
  14353. if ( p === RGBAIntegerFormat ) return 36249;
  14354. // S3TC
  14355. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14356. if ( encoding === sRGBEncoding ) {
  14357. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14358. if ( extension !== null ) {
  14359. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14360. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14361. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14362. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14363. } else {
  14364. return null;
  14365. }
  14366. } else {
  14367. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14368. if ( extension !== null ) {
  14369. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14370. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14371. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14372. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14373. } else {
  14374. return null;
  14375. }
  14376. }
  14377. }
  14378. // PVRTC
  14379. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14380. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14381. if ( extension !== null ) {
  14382. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14383. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14384. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14385. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14386. } else {
  14387. return null;
  14388. }
  14389. }
  14390. // ETC1
  14391. if ( p === RGB_ETC1_Format ) {
  14392. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14393. if ( extension !== null ) {
  14394. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14395. } else {
  14396. return null;
  14397. }
  14398. }
  14399. // ETC2
  14400. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14401. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14402. if ( extension !== null ) {
  14403. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14404. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14405. } else {
  14406. return null;
  14407. }
  14408. }
  14409. // ASTC
  14410. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14411. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14412. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14413. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14414. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14415. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14416. if ( extension !== null ) {
  14417. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14418. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14419. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14420. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14421. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14422. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14423. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14424. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14425. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14426. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14427. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14428. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14429. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14430. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14431. } else {
  14432. return null;
  14433. }
  14434. }
  14435. // BPTC
  14436. if ( p === RGBA_BPTC_Format ) {
  14437. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14438. if ( extension !== null ) {
  14439. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14440. } else {
  14441. return null;
  14442. }
  14443. }
  14444. //
  14445. if ( p === UnsignedInt248Type ) {
  14446. if ( isWebGL2 ) return 34042;
  14447. extension = extensions.get( 'WEBGL_depth_texture' );
  14448. if ( extension !== null ) {
  14449. return extension.UNSIGNED_INT_24_8_WEBGL;
  14450. } else {
  14451. return null;
  14452. }
  14453. }
  14454. }
  14455. return { convert: convert };
  14456. }
  14457. class ArrayCamera extends PerspectiveCamera {
  14458. constructor( array = [] ) {
  14459. super();
  14460. this.cameras = array;
  14461. }
  14462. }
  14463. ArrayCamera.prototype.isArrayCamera = true;
  14464. class Group extends Object3D {
  14465. constructor() {
  14466. super();
  14467. this.type = 'Group';
  14468. }
  14469. }
  14470. Group.prototype.isGroup = true;
  14471. const _moveEvent = { type: 'move' };
  14472. class WebXRController {
  14473. constructor() {
  14474. this._targetRay = null;
  14475. this._grip = null;
  14476. this._hand = null;
  14477. }
  14478. getHandSpace() {
  14479. if ( this._hand === null ) {
  14480. this._hand = new Group();
  14481. this._hand.matrixAutoUpdate = false;
  14482. this._hand.visible = false;
  14483. this._hand.joints = {};
  14484. this._hand.inputState = { pinching: false };
  14485. }
  14486. return this._hand;
  14487. }
  14488. getTargetRaySpace() {
  14489. if ( this._targetRay === null ) {
  14490. this._targetRay = new Group();
  14491. this._targetRay.matrixAutoUpdate = false;
  14492. this._targetRay.visible = false;
  14493. this._targetRay.hasLinearVelocity = false;
  14494. this._targetRay.linearVelocity = new Vector3();
  14495. this._targetRay.hasAngularVelocity = false;
  14496. this._targetRay.angularVelocity = new Vector3();
  14497. }
  14498. return this._targetRay;
  14499. }
  14500. getGripSpace() {
  14501. if ( this._grip === null ) {
  14502. this._grip = new Group();
  14503. this._grip.matrixAutoUpdate = false;
  14504. this._grip.visible = false;
  14505. this._grip.hasLinearVelocity = false;
  14506. this._grip.linearVelocity = new Vector3();
  14507. this._grip.hasAngularVelocity = false;
  14508. this._grip.angularVelocity = new Vector3();
  14509. }
  14510. return this._grip;
  14511. }
  14512. dispatchEvent( event ) {
  14513. if ( this._targetRay !== null ) {
  14514. this._targetRay.dispatchEvent( event );
  14515. }
  14516. if ( this._grip !== null ) {
  14517. this._grip.dispatchEvent( event );
  14518. }
  14519. if ( this._hand !== null ) {
  14520. this._hand.dispatchEvent( event );
  14521. }
  14522. return this;
  14523. }
  14524. disconnect( inputSource ) {
  14525. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14526. if ( this._targetRay !== null ) {
  14527. this._targetRay.visible = false;
  14528. }
  14529. if ( this._grip !== null ) {
  14530. this._grip.visible = false;
  14531. }
  14532. if ( this._hand !== null ) {
  14533. this._hand.visible = false;
  14534. }
  14535. return this;
  14536. }
  14537. update( inputSource, frame, referenceSpace ) {
  14538. let inputPose = null;
  14539. let gripPose = null;
  14540. let handPose = null;
  14541. const targetRay = this._targetRay;
  14542. const grip = this._grip;
  14543. const hand = this._hand;
  14544. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14545. if ( targetRay !== null ) {
  14546. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14547. if ( inputPose !== null ) {
  14548. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14549. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14550. if ( inputPose.linearVelocity ) {
  14551. targetRay.hasLinearVelocity = true;
  14552. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14553. } else {
  14554. targetRay.hasLinearVelocity = false;
  14555. }
  14556. if ( inputPose.angularVelocity ) {
  14557. targetRay.hasAngularVelocity = true;
  14558. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14559. } else {
  14560. targetRay.hasAngularVelocity = false;
  14561. }
  14562. this.dispatchEvent( _moveEvent );
  14563. }
  14564. }
  14565. if ( hand && inputSource.hand ) {
  14566. handPose = true;
  14567. for ( const inputjoint of inputSource.hand.values() ) {
  14568. // Update the joints groups with the XRJoint poses
  14569. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14570. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14571. // The transform of this joint will be updated with the joint pose on each frame
  14572. const joint = new Group();
  14573. joint.matrixAutoUpdate = false;
  14574. joint.visible = false;
  14575. hand.joints[ inputjoint.jointName ] = joint;
  14576. // ??
  14577. hand.add( joint );
  14578. }
  14579. const joint = hand.joints[ inputjoint.jointName ];
  14580. if ( jointPose !== null ) {
  14581. joint.matrix.fromArray( jointPose.transform.matrix );
  14582. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14583. joint.jointRadius = jointPose.radius;
  14584. }
  14585. joint.visible = jointPose !== null;
  14586. }
  14587. // Custom events
  14588. // Check pinchz
  14589. const indexTip = hand.joints[ 'index-finger-tip' ];
  14590. const thumbTip = hand.joints[ 'thumb-tip' ];
  14591. const distance = indexTip.position.distanceTo( thumbTip.position );
  14592. const distanceToPinch = 0.02;
  14593. const threshold = 0.005;
  14594. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14595. hand.inputState.pinching = false;
  14596. this.dispatchEvent( {
  14597. type: 'pinchend',
  14598. handedness: inputSource.handedness,
  14599. target: this
  14600. } );
  14601. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14602. hand.inputState.pinching = true;
  14603. this.dispatchEvent( {
  14604. type: 'pinchstart',
  14605. handedness: inputSource.handedness,
  14606. target: this
  14607. } );
  14608. }
  14609. } else {
  14610. if ( grip !== null && inputSource.gripSpace ) {
  14611. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14612. if ( gripPose !== null ) {
  14613. grip.matrix.fromArray( gripPose.transform.matrix );
  14614. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14615. if ( gripPose.linearVelocity ) {
  14616. grip.hasLinearVelocity = true;
  14617. grip.linearVelocity.copy( gripPose.linearVelocity );
  14618. } else {
  14619. grip.hasLinearVelocity = false;
  14620. }
  14621. if ( gripPose.angularVelocity ) {
  14622. grip.hasAngularVelocity = true;
  14623. grip.angularVelocity.copy( gripPose.angularVelocity );
  14624. } else {
  14625. grip.hasAngularVelocity = false;
  14626. }
  14627. }
  14628. }
  14629. }
  14630. }
  14631. if ( targetRay !== null ) {
  14632. targetRay.visible = ( inputPose !== null );
  14633. }
  14634. if ( grip !== null ) {
  14635. grip.visible = ( gripPose !== null );
  14636. }
  14637. if ( hand !== null ) {
  14638. hand.visible = ( handPose !== null );
  14639. }
  14640. return this;
  14641. }
  14642. }
  14643. class DepthTexture extends Texture {
  14644. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14645. format = format !== undefined ? format : DepthFormat;
  14646. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14647. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14648. }
  14649. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14650. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14651. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14652. this.image = { width: width, height: height };
  14653. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14654. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14655. this.flipY = false;
  14656. this.generateMipmaps = false;
  14657. }
  14658. }
  14659. DepthTexture.prototype.isDepthTexture = true;
  14660. class WebXRManager extends EventDispatcher {
  14661. constructor( renderer, gl ) {
  14662. super();
  14663. const scope = this;
  14664. let session = null;
  14665. let framebufferScaleFactor = 1.0;
  14666. let referenceSpace = null;
  14667. let referenceSpaceType = 'local-floor';
  14668. const hasMultisampledRenderToTexture = renderer.extensions.has( 'WEBGL_multisampled_render_to_texture' );
  14669. let pose = null;
  14670. let glBinding = null;
  14671. let glProjLayer = null;
  14672. let glBaseLayer = null;
  14673. let isMultisample = false;
  14674. let xrFrame = null;
  14675. const attributes = gl.getContextAttributes();
  14676. let initialRenderTarget = null;
  14677. let newRenderTarget = null;
  14678. const controllers = [];
  14679. const inputSourcesMap = new Map();
  14680. //
  14681. const cameraL = new PerspectiveCamera();
  14682. cameraL.layers.enable( 1 );
  14683. cameraL.viewport = new Vector4();
  14684. const cameraR = new PerspectiveCamera();
  14685. cameraR.layers.enable( 2 );
  14686. cameraR.viewport = new Vector4();
  14687. const cameras = [ cameraL, cameraR ];
  14688. const cameraVR = new ArrayCamera();
  14689. cameraVR.layers.enable( 1 );
  14690. cameraVR.layers.enable( 2 );
  14691. let _currentDepthNear = null;
  14692. let _currentDepthFar = null;
  14693. //
  14694. this.cameraAutoUpdate = true;
  14695. this.enabled = false;
  14696. this.isPresenting = false;
  14697. this.getController = function ( index ) {
  14698. let controller = controllers[ index ];
  14699. if ( controller === undefined ) {
  14700. controller = new WebXRController();
  14701. controllers[ index ] = controller;
  14702. }
  14703. return controller.getTargetRaySpace();
  14704. };
  14705. this.getControllerGrip = function ( index ) {
  14706. let controller = controllers[ index ];
  14707. if ( controller === undefined ) {
  14708. controller = new WebXRController();
  14709. controllers[ index ] = controller;
  14710. }
  14711. return controller.getGripSpace();
  14712. };
  14713. this.getHand = function ( index ) {
  14714. let controller = controllers[ index ];
  14715. if ( controller === undefined ) {
  14716. controller = new WebXRController();
  14717. controllers[ index ] = controller;
  14718. }
  14719. return controller.getHandSpace();
  14720. };
  14721. //
  14722. function onSessionEvent( event ) {
  14723. const controller = inputSourcesMap.get( event.inputSource );
  14724. if ( controller ) {
  14725. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14726. }
  14727. }
  14728. function onSessionEnd() {
  14729. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14730. controller.disconnect( inputSource );
  14731. } );
  14732. inputSourcesMap.clear();
  14733. _currentDepthNear = null;
  14734. _currentDepthFar = null;
  14735. // restore framebuffer/rendering state
  14736. renderer.setRenderTarget( initialRenderTarget );
  14737. glBaseLayer = null;
  14738. glProjLayer = null;
  14739. glBinding = null;
  14740. session = null;
  14741. newRenderTarget = null;
  14742. //
  14743. animation.stop();
  14744. scope.isPresenting = false;
  14745. scope.dispatchEvent( { type: 'sessionend' } );
  14746. }
  14747. this.setFramebufferScaleFactor = function ( value ) {
  14748. framebufferScaleFactor = value;
  14749. if ( scope.isPresenting === true ) {
  14750. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14751. }
  14752. };
  14753. this.setReferenceSpaceType = function ( value ) {
  14754. referenceSpaceType = value;
  14755. if ( scope.isPresenting === true ) {
  14756. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14757. }
  14758. };
  14759. this.getReferenceSpace = function () {
  14760. return referenceSpace;
  14761. };
  14762. this.getBaseLayer = function () {
  14763. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14764. };
  14765. this.getBinding = function () {
  14766. return glBinding;
  14767. };
  14768. this.getFrame = function () {
  14769. return xrFrame;
  14770. };
  14771. this.getSession = function () {
  14772. return session;
  14773. };
  14774. this.setSession = async function ( value ) {
  14775. session = value;
  14776. if ( session !== null ) {
  14777. initialRenderTarget = renderer.getRenderTarget();
  14778. session.addEventListener( 'select', onSessionEvent );
  14779. session.addEventListener( 'selectstart', onSessionEvent );
  14780. session.addEventListener( 'selectend', onSessionEvent );
  14781. session.addEventListener( 'squeeze', onSessionEvent );
  14782. session.addEventListener( 'squeezestart', onSessionEvent );
  14783. session.addEventListener( 'squeezeend', onSessionEvent );
  14784. session.addEventListener( 'end', onSessionEnd );
  14785. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14786. if ( attributes.xrCompatible !== true ) {
  14787. await gl.makeXRCompatible();
  14788. }
  14789. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  14790. const layerInit = {
  14791. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  14792. alpha: attributes.alpha,
  14793. depth: attributes.depth,
  14794. stencil: attributes.stencil,
  14795. framebufferScaleFactor: framebufferScaleFactor
  14796. };
  14797. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14798. session.updateRenderState( { baseLayer: glBaseLayer } );
  14799. newRenderTarget = new WebGLRenderTarget(
  14800. glBaseLayer.framebufferWidth,
  14801. glBaseLayer.framebufferHeight,
  14802. {
  14803. format: RGBAFormat,
  14804. type: UnsignedByteType,
  14805. encoding: renderer.outputEncoding
  14806. }
  14807. );
  14808. } else {
  14809. isMultisample = attributes.antialias;
  14810. let depthFormat = null;
  14811. let depthType = null;
  14812. let glDepthFormat = null;
  14813. if ( attributes.depth ) {
  14814. glDepthFormat = attributes.stencil ? 35056 : 33190;
  14815. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14816. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  14817. }
  14818. const projectionlayerInit = {
  14819. colorFormat: ( renderer.outputEncoding === sRGBEncoding ) ? 35907 : 32856,
  14820. depthFormat: glDepthFormat,
  14821. scaleFactor: framebufferScaleFactor
  14822. };
  14823. glBinding = new XRWebGLBinding( session, gl );
  14824. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  14825. session.updateRenderState( { layers: [ glProjLayer ] } );
  14826. if ( isMultisample ) {
  14827. newRenderTarget = new WebGLMultisampleRenderTarget(
  14828. glProjLayer.textureWidth,
  14829. glProjLayer.textureHeight,
  14830. {
  14831. format: RGBAFormat,
  14832. type: UnsignedByteType,
  14833. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  14834. stencilBuffer: attributes.stencil,
  14835. ignoreDepth: glProjLayer.ignoreDepthValues,
  14836. useRenderToTexture: hasMultisampledRenderToTexture,
  14837. encoding: renderer.outputEncoding
  14838. } );
  14839. } else {
  14840. newRenderTarget = new WebGLRenderTarget(
  14841. glProjLayer.textureWidth,
  14842. glProjLayer.textureHeight,
  14843. {
  14844. format: RGBAFormat,
  14845. type: UnsignedByteType,
  14846. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  14847. stencilBuffer: attributes.stencil,
  14848. ignoreDepth: glProjLayer.ignoreDepthValues,
  14849. encoding: renderer.outputEncoding
  14850. } );
  14851. }
  14852. }
  14853. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  14854. // Set foveation to maximum.
  14855. this.setFoveation( 1.0 );
  14856. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  14857. animation.setContext( session );
  14858. animation.start();
  14859. scope.isPresenting = true;
  14860. scope.dispatchEvent( { type: 'sessionstart' } );
  14861. }
  14862. };
  14863. function onInputSourcesChange( event ) {
  14864. const inputSources = session.inputSources;
  14865. // Assign inputSources to available controllers
  14866. for ( let i = 0; i < controllers.length; i ++ ) {
  14867. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14868. }
  14869. // Notify disconnected
  14870. for ( let i = 0; i < event.removed.length; i ++ ) {
  14871. const inputSource = event.removed[ i ];
  14872. const controller = inputSourcesMap.get( inputSource );
  14873. if ( controller ) {
  14874. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14875. inputSourcesMap.delete( inputSource );
  14876. }
  14877. }
  14878. // Notify connected
  14879. for ( let i = 0; i < event.added.length; i ++ ) {
  14880. const inputSource = event.added[ i ];
  14881. const controller = inputSourcesMap.get( inputSource );
  14882. if ( controller ) {
  14883. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14884. }
  14885. }
  14886. }
  14887. //
  14888. const cameraLPos = new Vector3();
  14889. const cameraRPos = new Vector3();
  14890. /**
  14891. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14892. * the cameras' projection and world matrices have already been set.
  14893. * And that near and far planes are identical for both cameras.
  14894. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14895. */
  14896. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14897. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14898. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14899. const ipd = cameraLPos.distanceTo( cameraRPos );
  14900. const projL = cameraL.projectionMatrix.elements;
  14901. const projR = cameraR.projectionMatrix.elements;
  14902. // VR systems will have identical far and near planes, and
  14903. // most likely identical top and bottom frustum extents.
  14904. // Use the left camera for these values.
  14905. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14906. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14907. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14908. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14909. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14910. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14911. const left = near * leftFov;
  14912. const right = near * rightFov;
  14913. // Calculate the new camera's position offset from the
  14914. // left camera. xOffset should be roughly half `ipd`.
  14915. const zOffset = ipd / ( - leftFov + rightFov );
  14916. const xOffset = zOffset * - leftFov;
  14917. // TODO: Better way to apply this offset?
  14918. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14919. camera.translateX( xOffset );
  14920. camera.translateZ( zOffset );
  14921. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14922. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14923. // Find the union of the frustum values of the cameras and scale
  14924. // the values so that the near plane's position does not change in world space,
  14925. // although must now be relative to the new union camera.
  14926. const near2 = near + zOffset;
  14927. const far2 = far + zOffset;
  14928. const left2 = left - xOffset;
  14929. const right2 = right + ( ipd - xOffset );
  14930. const top2 = topFov * far / far2 * near2;
  14931. const bottom2 = bottomFov * far / far2 * near2;
  14932. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14933. }
  14934. function updateCamera( camera, parent ) {
  14935. if ( parent === null ) {
  14936. camera.matrixWorld.copy( camera.matrix );
  14937. } else {
  14938. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14939. }
  14940. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14941. }
  14942. this.updateCamera = function ( camera ) {
  14943. if ( session === null ) return;
  14944. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14945. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14946. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14947. // Note that the new renderState won't apply until the next frame. See #18320
  14948. session.updateRenderState( {
  14949. depthNear: cameraVR.near,
  14950. depthFar: cameraVR.far
  14951. } );
  14952. _currentDepthNear = cameraVR.near;
  14953. _currentDepthFar = cameraVR.far;
  14954. }
  14955. const parent = camera.parent;
  14956. const cameras = cameraVR.cameras;
  14957. updateCamera( cameraVR, parent );
  14958. for ( let i = 0; i < cameras.length; i ++ ) {
  14959. updateCamera( cameras[ i ], parent );
  14960. }
  14961. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  14962. // update user camera and its children
  14963. camera.position.copy( cameraVR.position );
  14964. camera.quaternion.copy( cameraVR.quaternion );
  14965. camera.scale.copy( cameraVR.scale );
  14966. camera.matrix.copy( cameraVR.matrix );
  14967. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14968. const children = camera.children;
  14969. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14970. children[ i ].updateMatrixWorld( true );
  14971. }
  14972. // update projection matrix for proper view frustum culling
  14973. if ( cameras.length === 2 ) {
  14974. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14975. } else {
  14976. // assume single camera setup (AR)
  14977. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14978. }
  14979. };
  14980. this.getCamera = function () {
  14981. return cameraVR;
  14982. };
  14983. this.getFoveation = function () {
  14984. if ( glProjLayer !== null ) {
  14985. return glProjLayer.fixedFoveation;
  14986. }
  14987. if ( glBaseLayer !== null ) {
  14988. return glBaseLayer.fixedFoveation;
  14989. }
  14990. return undefined;
  14991. };
  14992. this.setFoveation = function ( foveation ) {
  14993. // 0 = no foveation = full resolution
  14994. // 1 = maximum foveation = the edges render at lower resolution
  14995. if ( glProjLayer !== null ) {
  14996. glProjLayer.fixedFoveation = foveation;
  14997. }
  14998. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  14999. glBaseLayer.fixedFoveation = foveation;
  15000. }
  15001. };
  15002. // Animation Loop
  15003. let onAnimationFrameCallback = null;
  15004. function onAnimationFrame( time, frame ) {
  15005. pose = frame.getViewerPose( referenceSpace );
  15006. xrFrame = frame;
  15007. if ( pose !== null ) {
  15008. const views = pose.views;
  15009. if ( glBaseLayer !== null ) {
  15010. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15011. renderer.setRenderTarget( newRenderTarget );
  15012. }
  15013. let cameraVRNeedsUpdate = false;
  15014. // check if it's necessary to rebuild cameraVR's camera list
  15015. if ( views.length !== cameraVR.cameras.length ) {
  15016. cameraVR.cameras.length = 0;
  15017. cameraVRNeedsUpdate = true;
  15018. }
  15019. for ( let i = 0; i < views.length; i ++ ) {
  15020. const view = views[ i ];
  15021. let viewport = null;
  15022. if ( glBaseLayer !== null ) {
  15023. viewport = glBaseLayer.getViewport( view );
  15024. } else {
  15025. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15026. viewport = glSubImage.viewport;
  15027. // For side-by-side projection, we only produce a single texture for both eyes.
  15028. if ( i === 0 ) {
  15029. renderer.setRenderTargetTextures(
  15030. newRenderTarget,
  15031. glSubImage.colorTexture,
  15032. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15033. renderer.setRenderTarget( newRenderTarget );
  15034. }
  15035. }
  15036. const camera = cameras[ i ];
  15037. camera.matrix.fromArray( view.transform.matrix );
  15038. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15039. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15040. if ( i === 0 ) {
  15041. cameraVR.matrix.copy( camera.matrix );
  15042. }
  15043. if ( cameraVRNeedsUpdate === true ) {
  15044. cameraVR.cameras.push( camera );
  15045. }
  15046. }
  15047. }
  15048. //
  15049. const inputSources = session.inputSources;
  15050. for ( let i = 0; i < controllers.length; i ++ ) {
  15051. const controller = controllers[ i ];
  15052. const inputSource = inputSources[ i ];
  15053. controller.update( inputSource, frame, referenceSpace );
  15054. }
  15055. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15056. xrFrame = null;
  15057. }
  15058. const animation = new WebGLAnimation();
  15059. animation.setAnimationLoop( onAnimationFrame );
  15060. this.setAnimationLoop = function ( callback ) {
  15061. onAnimationFrameCallback = callback;
  15062. };
  15063. this.dispose = function () {};
  15064. }
  15065. }
  15066. function WebGLMaterials( properties ) {
  15067. function refreshFogUniforms( uniforms, fog ) {
  15068. uniforms.fogColor.value.copy( fog.color );
  15069. if ( fog.isFog ) {
  15070. uniforms.fogNear.value = fog.near;
  15071. uniforms.fogFar.value = fog.far;
  15072. } else if ( fog.isFogExp2 ) {
  15073. uniforms.fogDensity.value = fog.density;
  15074. }
  15075. }
  15076. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15077. if ( material.isMeshBasicMaterial ) {
  15078. refreshUniformsCommon( uniforms, material );
  15079. } else if ( material.isMeshLambertMaterial ) {
  15080. refreshUniformsCommon( uniforms, material );
  15081. refreshUniformsLambert( uniforms, material );
  15082. } else if ( material.isMeshToonMaterial ) {
  15083. refreshUniformsCommon( uniforms, material );
  15084. refreshUniformsToon( uniforms, material );
  15085. } else if ( material.isMeshPhongMaterial ) {
  15086. refreshUniformsCommon( uniforms, material );
  15087. refreshUniformsPhong( uniforms, material );
  15088. } else if ( material.isMeshStandardMaterial ) {
  15089. refreshUniformsCommon( uniforms, material );
  15090. if ( material.isMeshPhysicalMaterial ) {
  15091. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15092. } else {
  15093. refreshUniformsStandard( uniforms, material );
  15094. }
  15095. } else if ( material.isMeshMatcapMaterial ) {
  15096. refreshUniformsCommon( uniforms, material );
  15097. refreshUniformsMatcap( uniforms, material );
  15098. } else if ( material.isMeshDepthMaterial ) {
  15099. refreshUniformsCommon( uniforms, material );
  15100. refreshUniformsDepth( uniforms, material );
  15101. } else if ( material.isMeshDistanceMaterial ) {
  15102. refreshUniformsCommon( uniforms, material );
  15103. refreshUniformsDistance( uniforms, material );
  15104. } else if ( material.isMeshNormalMaterial ) {
  15105. refreshUniformsCommon( uniforms, material );
  15106. refreshUniformsNormal( uniforms, material );
  15107. } else if ( material.isLineBasicMaterial ) {
  15108. refreshUniformsLine( uniforms, material );
  15109. if ( material.isLineDashedMaterial ) {
  15110. refreshUniformsDash( uniforms, material );
  15111. }
  15112. } else if ( material.isPointsMaterial ) {
  15113. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15114. } else if ( material.isSpriteMaterial ) {
  15115. refreshUniformsSprites( uniforms, material );
  15116. } else if ( material.isShadowMaterial ) {
  15117. uniforms.color.value.copy( material.color );
  15118. uniforms.opacity.value = material.opacity;
  15119. } else if ( material.isShaderMaterial ) {
  15120. material.uniformsNeedUpdate = false; // #15581
  15121. }
  15122. }
  15123. function refreshUniformsCommon( uniforms, material ) {
  15124. uniforms.opacity.value = material.opacity;
  15125. if ( material.color ) {
  15126. uniforms.diffuse.value.copy( material.color );
  15127. }
  15128. if ( material.emissive ) {
  15129. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15130. }
  15131. if ( material.map ) {
  15132. uniforms.map.value = material.map;
  15133. }
  15134. if ( material.alphaMap ) {
  15135. uniforms.alphaMap.value = material.alphaMap;
  15136. }
  15137. if ( material.specularMap ) {
  15138. uniforms.specularMap.value = material.specularMap;
  15139. }
  15140. if ( material.alphaTest > 0 ) {
  15141. uniforms.alphaTest.value = material.alphaTest;
  15142. }
  15143. const envMap = properties.get( material ).envMap;
  15144. if ( envMap ) {
  15145. uniforms.envMap.value = envMap;
  15146. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15147. uniforms.reflectivity.value = material.reflectivity;
  15148. uniforms.ior.value = material.ior;
  15149. uniforms.refractionRatio.value = material.refractionRatio;
  15150. }
  15151. if ( material.lightMap ) {
  15152. uniforms.lightMap.value = material.lightMap;
  15153. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15154. }
  15155. if ( material.aoMap ) {
  15156. uniforms.aoMap.value = material.aoMap;
  15157. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15158. }
  15159. // uv repeat and offset setting priorities
  15160. // 1. color map
  15161. // 2. specular map
  15162. // 3. displacementMap map
  15163. // 4. normal map
  15164. // 5. bump map
  15165. // 6. roughnessMap map
  15166. // 7. metalnessMap map
  15167. // 8. alphaMap map
  15168. // 9. emissiveMap map
  15169. // 10. clearcoat map
  15170. // 11. clearcoat normal map
  15171. // 12. clearcoat roughnessMap map
  15172. // 13. specular intensity map
  15173. // 14. specular tint map
  15174. // 15. transmission map
  15175. // 16. thickness map
  15176. let uvScaleMap;
  15177. if ( material.map ) {
  15178. uvScaleMap = material.map;
  15179. } else if ( material.specularMap ) {
  15180. uvScaleMap = material.specularMap;
  15181. } else if ( material.displacementMap ) {
  15182. uvScaleMap = material.displacementMap;
  15183. } else if ( material.normalMap ) {
  15184. uvScaleMap = material.normalMap;
  15185. } else if ( material.bumpMap ) {
  15186. uvScaleMap = material.bumpMap;
  15187. } else if ( material.roughnessMap ) {
  15188. uvScaleMap = material.roughnessMap;
  15189. } else if ( material.metalnessMap ) {
  15190. uvScaleMap = material.metalnessMap;
  15191. } else if ( material.alphaMap ) {
  15192. uvScaleMap = material.alphaMap;
  15193. } else if ( material.emissiveMap ) {
  15194. uvScaleMap = material.emissiveMap;
  15195. } else if ( material.clearcoatMap ) {
  15196. uvScaleMap = material.clearcoatMap;
  15197. } else if ( material.clearcoatNormalMap ) {
  15198. uvScaleMap = material.clearcoatNormalMap;
  15199. } else if ( material.clearcoatRoughnessMap ) {
  15200. uvScaleMap = material.clearcoatRoughnessMap;
  15201. } else if ( material.specularIntensityMap ) {
  15202. uvScaleMap = material.specularIntensityMap;
  15203. } else if ( material.specularColorMap ) {
  15204. uvScaleMap = material.specularColorMap;
  15205. } else if ( material.transmissionMap ) {
  15206. uvScaleMap = material.transmissionMap;
  15207. } else if ( material.thicknessMap ) {
  15208. uvScaleMap = material.thicknessMap;
  15209. } else if ( material.sheenColorMap ) {
  15210. uvScaleMap = material.sheenColorMap;
  15211. } else if ( material.sheenRoughnessMap ) {
  15212. uvScaleMap = material.sheenRoughnessMap;
  15213. }
  15214. if ( uvScaleMap !== undefined ) {
  15215. // backwards compatibility
  15216. if ( uvScaleMap.isWebGLRenderTarget ) {
  15217. uvScaleMap = uvScaleMap.texture;
  15218. }
  15219. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15220. uvScaleMap.updateMatrix();
  15221. }
  15222. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15223. }
  15224. // uv repeat and offset setting priorities for uv2
  15225. // 1. ao map
  15226. // 2. light map
  15227. let uv2ScaleMap;
  15228. if ( material.aoMap ) {
  15229. uv2ScaleMap = material.aoMap;
  15230. } else if ( material.lightMap ) {
  15231. uv2ScaleMap = material.lightMap;
  15232. }
  15233. if ( uv2ScaleMap !== undefined ) {
  15234. // backwards compatibility
  15235. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15236. uv2ScaleMap = uv2ScaleMap.texture;
  15237. }
  15238. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15239. uv2ScaleMap.updateMatrix();
  15240. }
  15241. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15242. }
  15243. }
  15244. function refreshUniformsLine( uniforms, material ) {
  15245. uniforms.diffuse.value.copy( material.color );
  15246. uniforms.opacity.value = material.opacity;
  15247. }
  15248. function refreshUniformsDash( uniforms, material ) {
  15249. uniforms.dashSize.value = material.dashSize;
  15250. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15251. uniforms.scale.value = material.scale;
  15252. }
  15253. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15254. uniforms.diffuse.value.copy( material.color );
  15255. uniforms.opacity.value = material.opacity;
  15256. uniforms.size.value = material.size * pixelRatio;
  15257. uniforms.scale.value = height * 0.5;
  15258. if ( material.map ) {
  15259. uniforms.map.value = material.map;
  15260. }
  15261. if ( material.alphaMap ) {
  15262. uniforms.alphaMap.value = material.alphaMap;
  15263. }
  15264. if ( material.alphaTest > 0 ) {
  15265. uniforms.alphaTest.value = material.alphaTest;
  15266. }
  15267. // uv repeat and offset setting priorities
  15268. // 1. color map
  15269. // 2. alpha map
  15270. let uvScaleMap;
  15271. if ( material.map ) {
  15272. uvScaleMap = material.map;
  15273. } else if ( material.alphaMap ) {
  15274. uvScaleMap = material.alphaMap;
  15275. }
  15276. if ( uvScaleMap !== undefined ) {
  15277. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15278. uvScaleMap.updateMatrix();
  15279. }
  15280. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15281. }
  15282. }
  15283. function refreshUniformsSprites( uniforms, material ) {
  15284. uniforms.diffuse.value.copy( material.color );
  15285. uniforms.opacity.value = material.opacity;
  15286. uniforms.rotation.value = material.rotation;
  15287. if ( material.map ) {
  15288. uniforms.map.value = material.map;
  15289. }
  15290. if ( material.alphaMap ) {
  15291. uniforms.alphaMap.value = material.alphaMap;
  15292. }
  15293. if ( material.alphaTest > 0 ) {
  15294. uniforms.alphaTest.value = material.alphaTest;
  15295. }
  15296. // uv repeat and offset setting priorities
  15297. // 1. color map
  15298. // 2. alpha map
  15299. let uvScaleMap;
  15300. if ( material.map ) {
  15301. uvScaleMap = material.map;
  15302. } else if ( material.alphaMap ) {
  15303. uvScaleMap = material.alphaMap;
  15304. }
  15305. if ( uvScaleMap !== undefined ) {
  15306. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15307. uvScaleMap.updateMatrix();
  15308. }
  15309. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15310. }
  15311. }
  15312. function refreshUniformsLambert( uniforms, material ) {
  15313. if ( material.emissiveMap ) {
  15314. uniforms.emissiveMap.value = material.emissiveMap;
  15315. }
  15316. }
  15317. function refreshUniformsPhong( uniforms, material ) {
  15318. uniforms.specular.value.copy( material.specular );
  15319. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15320. if ( material.emissiveMap ) {
  15321. uniforms.emissiveMap.value = material.emissiveMap;
  15322. }
  15323. if ( material.bumpMap ) {
  15324. uniforms.bumpMap.value = material.bumpMap;
  15325. uniforms.bumpScale.value = material.bumpScale;
  15326. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15327. }
  15328. if ( material.normalMap ) {
  15329. uniforms.normalMap.value = material.normalMap;
  15330. uniforms.normalScale.value.copy( material.normalScale );
  15331. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15332. }
  15333. if ( material.displacementMap ) {
  15334. uniforms.displacementMap.value = material.displacementMap;
  15335. uniforms.displacementScale.value = material.displacementScale;
  15336. uniforms.displacementBias.value = material.displacementBias;
  15337. }
  15338. }
  15339. function refreshUniformsToon( uniforms, material ) {
  15340. if ( material.gradientMap ) {
  15341. uniforms.gradientMap.value = material.gradientMap;
  15342. }
  15343. if ( material.emissiveMap ) {
  15344. uniforms.emissiveMap.value = material.emissiveMap;
  15345. }
  15346. if ( material.bumpMap ) {
  15347. uniforms.bumpMap.value = material.bumpMap;
  15348. uniforms.bumpScale.value = material.bumpScale;
  15349. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15350. }
  15351. if ( material.normalMap ) {
  15352. uniforms.normalMap.value = material.normalMap;
  15353. uniforms.normalScale.value.copy( material.normalScale );
  15354. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15355. }
  15356. if ( material.displacementMap ) {
  15357. uniforms.displacementMap.value = material.displacementMap;
  15358. uniforms.displacementScale.value = material.displacementScale;
  15359. uniforms.displacementBias.value = material.displacementBias;
  15360. }
  15361. }
  15362. function refreshUniformsStandard( uniforms, material ) {
  15363. uniforms.roughness.value = material.roughness;
  15364. uniforms.metalness.value = material.metalness;
  15365. if ( material.roughnessMap ) {
  15366. uniforms.roughnessMap.value = material.roughnessMap;
  15367. }
  15368. if ( material.metalnessMap ) {
  15369. uniforms.metalnessMap.value = material.metalnessMap;
  15370. }
  15371. if ( material.emissiveMap ) {
  15372. uniforms.emissiveMap.value = material.emissiveMap;
  15373. }
  15374. if ( material.bumpMap ) {
  15375. uniforms.bumpMap.value = material.bumpMap;
  15376. uniforms.bumpScale.value = material.bumpScale;
  15377. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15378. }
  15379. if ( material.normalMap ) {
  15380. uniforms.normalMap.value = material.normalMap;
  15381. uniforms.normalScale.value.copy( material.normalScale );
  15382. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15383. }
  15384. if ( material.displacementMap ) {
  15385. uniforms.displacementMap.value = material.displacementMap;
  15386. uniforms.displacementScale.value = material.displacementScale;
  15387. uniforms.displacementBias.value = material.displacementBias;
  15388. }
  15389. const envMap = properties.get( material ).envMap;
  15390. if ( envMap ) {
  15391. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15392. uniforms.envMapIntensity.value = material.envMapIntensity;
  15393. }
  15394. }
  15395. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15396. refreshUniformsStandard( uniforms, material );
  15397. uniforms.ior.value = material.ior; // also part of uniforms common
  15398. if ( material.sheen > 0 ) {
  15399. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15400. uniforms.sheenRoughness.value = material.sheenRoughness;
  15401. if ( material.sheenColorMap ) {
  15402. uniforms.sheenColorMap.value = material.sheenColorMap;
  15403. }
  15404. if ( material.sheenRoughnessMap ) {
  15405. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15406. }
  15407. }
  15408. if ( material.clearcoat > 0 ) {
  15409. uniforms.clearcoat.value = material.clearcoat;
  15410. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15411. if ( material.clearcoatMap ) {
  15412. uniforms.clearcoatMap.value = material.clearcoatMap;
  15413. }
  15414. if ( material.clearcoatRoughnessMap ) {
  15415. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15416. }
  15417. if ( material.clearcoatNormalMap ) {
  15418. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15419. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15420. if ( material.side === BackSide ) {
  15421. uniforms.clearcoatNormalScale.value.negate();
  15422. }
  15423. }
  15424. }
  15425. if ( material.transmission > 0 ) {
  15426. uniforms.transmission.value = material.transmission;
  15427. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15428. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15429. if ( material.transmissionMap ) {
  15430. uniforms.transmissionMap.value = material.transmissionMap;
  15431. }
  15432. uniforms.thickness.value = material.thickness;
  15433. if ( material.thicknessMap ) {
  15434. uniforms.thicknessMap.value = material.thicknessMap;
  15435. }
  15436. uniforms.attenuationDistance.value = material.attenuationDistance;
  15437. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15438. }
  15439. uniforms.specularIntensity.value = material.specularIntensity;
  15440. uniforms.specularColor.value.copy( material.specularColor );
  15441. if ( material.specularIntensityMap ) {
  15442. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15443. }
  15444. if ( material.specularColorMap ) {
  15445. uniforms.specularColorMap.value = material.specularColorMap;
  15446. }
  15447. }
  15448. function refreshUniformsMatcap( uniforms, material ) {
  15449. if ( material.matcap ) {
  15450. uniforms.matcap.value = material.matcap;
  15451. }
  15452. if ( material.bumpMap ) {
  15453. uniforms.bumpMap.value = material.bumpMap;
  15454. uniforms.bumpScale.value = material.bumpScale;
  15455. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15456. }
  15457. if ( material.normalMap ) {
  15458. uniforms.normalMap.value = material.normalMap;
  15459. uniforms.normalScale.value.copy( material.normalScale );
  15460. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15461. }
  15462. if ( material.displacementMap ) {
  15463. uniforms.displacementMap.value = material.displacementMap;
  15464. uniforms.displacementScale.value = material.displacementScale;
  15465. uniforms.displacementBias.value = material.displacementBias;
  15466. }
  15467. }
  15468. function refreshUniformsDepth( uniforms, material ) {
  15469. if ( material.displacementMap ) {
  15470. uniforms.displacementMap.value = material.displacementMap;
  15471. uniforms.displacementScale.value = material.displacementScale;
  15472. uniforms.displacementBias.value = material.displacementBias;
  15473. }
  15474. }
  15475. function refreshUniformsDistance( uniforms, material ) {
  15476. if ( material.displacementMap ) {
  15477. uniforms.displacementMap.value = material.displacementMap;
  15478. uniforms.displacementScale.value = material.displacementScale;
  15479. uniforms.displacementBias.value = material.displacementBias;
  15480. }
  15481. uniforms.referencePosition.value.copy( material.referencePosition );
  15482. uniforms.nearDistance.value = material.nearDistance;
  15483. uniforms.farDistance.value = material.farDistance;
  15484. }
  15485. function refreshUniformsNormal( uniforms, material ) {
  15486. if ( material.bumpMap ) {
  15487. uniforms.bumpMap.value = material.bumpMap;
  15488. uniforms.bumpScale.value = material.bumpScale;
  15489. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15490. }
  15491. if ( material.normalMap ) {
  15492. uniforms.normalMap.value = material.normalMap;
  15493. uniforms.normalScale.value.copy( material.normalScale );
  15494. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15495. }
  15496. if ( material.displacementMap ) {
  15497. uniforms.displacementMap.value = material.displacementMap;
  15498. uniforms.displacementScale.value = material.displacementScale;
  15499. uniforms.displacementBias.value = material.displacementBias;
  15500. }
  15501. }
  15502. return {
  15503. refreshFogUniforms: refreshFogUniforms,
  15504. refreshMaterialUniforms: refreshMaterialUniforms
  15505. };
  15506. }
  15507. function createCanvasElement() {
  15508. const canvas = createElementNS( 'canvas' );
  15509. canvas.style.display = 'block';
  15510. return canvas;
  15511. }
  15512. function WebGLRenderer( parameters = {} ) {
  15513. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15514. _context = parameters.context !== undefined ? parameters.context : null,
  15515. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15516. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15517. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15518. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15519. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15520. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15521. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15522. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15523. let currentRenderList = null;
  15524. let currentRenderState = null;
  15525. // render() can be called from within a callback triggered by another render.
  15526. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15527. const renderListStack = [];
  15528. const renderStateStack = [];
  15529. // public properties
  15530. this.domElement = _canvas;
  15531. // Debug configuration container
  15532. this.debug = {
  15533. /**
  15534. * Enables error checking and reporting when shader programs are being compiled
  15535. * @type {boolean}
  15536. */
  15537. checkShaderErrors: true
  15538. };
  15539. // clearing
  15540. this.autoClear = true;
  15541. this.autoClearColor = true;
  15542. this.autoClearDepth = true;
  15543. this.autoClearStencil = true;
  15544. // scene graph
  15545. this.sortObjects = true;
  15546. // user-defined clipping
  15547. this.clippingPlanes = [];
  15548. this.localClippingEnabled = false;
  15549. // physically based shading
  15550. this.outputEncoding = LinearEncoding;
  15551. // physical lights
  15552. this.physicallyCorrectLights = false;
  15553. // tone mapping
  15554. this.toneMapping = NoToneMapping;
  15555. this.toneMappingExposure = 1.0;
  15556. // internal properties
  15557. const _this = this;
  15558. let _isContextLost = false;
  15559. // internal state cache
  15560. let _currentActiveCubeFace = 0;
  15561. let _currentActiveMipmapLevel = 0;
  15562. let _currentRenderTarget = null;
  15563. let _currentMaterialId = - 1;
  15564. let _currentCamera = null;
  15565. const _currentViewport = new Vector4();
  15566. const _currentScissor = new Vector4();
  15567. let _currentScissorTest = null;
  15568. //
  15569. let _width = _canvas.width;
  15570. let _height = _canvas.height;
  15571. let _pixelRatio = 1;
  15572. let _opaqueSort = null;
  15573. let _transparentSort = null;
  15574. const _viewport = new Vector4( 0, 0, _width, _height );
  15575. const _scissor = new Vector4( 0, 0, _width, _height );
  15576. let _scissorTest = false;
  15577. // frustum
  15578. const _frustum = new Frustum();
  15579. // clipping
  15580. let _clippingEnabled = false;
  15581. let _localClippingEnabled = false;
  15582. // transmission
  15583. let _transmissionRenderTarget = null;
  15584. // camera matrices cache
  15585. const _projScreenMatrix = new Matrix4();
  15586. const _vector3 = new Vector3();
  15587. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15588. function getTargetPixelRatio() {
  15589. return _currentRenderTarget === null ? _pixelRatio : 1;
  15590. }
  15591. // initialize
  15592. let _gl = _context;
  15593. function getContext( contextNames, contextAttributes ) {
  15594. for ( let i = 0; i < contextNames.length; i ++ ) {
  15595. const contextName = contextNames[ i ];
  15596. const context = _canvas.getContext( contextName, contextAttributes );
  15597. if ( context !== null ) return context;
  15598. }
  15599. return null;
  15600. }
  15601. try {
  15602. const contextAttributes = {
  15603. alpha: true,
  15604. depth: _depth,
  15605. stencil: _stencil,
  15606. antialias: _antialias,
  15607. premultipliedAlpha: _premultipliedAlpha,
  15608. preserveDrawingBuffer: _preserveDrawingBuffer,
  15609. powerPreference: _powerPreference,
  15610. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15611. };
  15612. // OffscreenCanvas does not have setAttribute, see #22811
  15613. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  15614. // event listeners must be registered before WebGL context is created, see #12753
  15615. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15616. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15617. if ( _gl === null ) {
  15618. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15619. if ( _this.isWebGL1Renderer === true ) {
  15620. contextNames.shift();
  15621. }
  15622. _gl = getContext( contextNames, contextAttributes );
  15623. if ( _gl === null ) {
  15624. if ( getContext( contextNames ) ) {
  15625. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  15626. } else {
  15627. throw new Error( 'Error creating WebGL context.' );
  15628. }
  15629. }
  15630. }
  15631. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15632. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15633. _gl.getShaderPrecisionFormat = function () {
  15634. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15635. };
  15636. }
  15637. } catch ( error ) {
  15638. console.error( 'THREE.WebGLRenderer: ' + error.message );
  15639. throw error;
  15640. }
  15641. let extensions, capabilities, state, info;
  15642. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15643. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15644. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15645. let utils, bindingStates;
  15646. function initGLContext() {
  15647. extensions = new WebGLExtensions( _gl );
  15648. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15649. extensions.init( capabilities );
  15650. utils = new WebGLUtils( _gl, extensions, capabilities );
  15651. state = new WebGLState( _gl, extensions, capabilities );
  15652. info = new WebGLInfo( _gl );
  15653. properties = new WebGLProperties();
  15654. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  15655. cubemaps = new WebGLCubeMaps( _this );
  15656. cubeuvmaps = new WebGLCubeUVMaps( _this );
  15657. attributes = new WebGLAttributes( _gl, capabilities );
  15658. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  15659. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  15660. objects = new WebGLObjects( _gl, geometries, attributes, info );
  15661. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  15662. clipping = new WebGLClipping( properties );
  15663. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  15664. materials = new WebGLMaterials( properties );
  15665. renderLists = new WebGLRenderLists();
  15666. renderStates = new WebGLRenderStates( extensions, capabilities );
  15667. background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
  15668. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  15669. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  15670. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  15671. info.programs = programCache.programs;
  15672. _this.capabilities = capabilities;
  15673. _this.extensions = extensions;
  15674. _this.properties = properties;
  15675. _this.renderLists = renderLists;
  15676. _this.shadowMap = shadowMap;
  15677. _this.state = state;
  15678. _this.info = info;
  15679. }
  15680. initGLContext();
  15681. // xr
  15682. const xr = new WebXRManager( _this, _gl );
  15683. this.xr = xr;
  15684. // API
  15685. this.getContext = function () {
  15686. return _gl;
  15687. };
  15688. this.getContextAttributes = function () {
  15689. return _gl.getContextAttributes();
  15690. };
  15691. this.forceContextLoss = function () {
  15692. const extension = extensions.get( 'WEBGL_lose_context' );
  15693. if ( extension ) extension.loseContext();
  15694. };
  15695. this.forceContextRestore = function () {
  15696. const extension = extensions.get( 'WEBGL_lose_context' );
  15697. if ( extension ) extension.restoreContext();
  15698. };
  15699. this.getPixelRatio = function () {
  15700. return _pixelRatio;
  15701. };
  15702. this.setPixelRatio = function ( value ) {
  15703. if ( value === undefined ) return;
  15704. _pixelRatio = value;
  15705. this.setSize( _width, _height, false );
  15706. };
  15707. this.getSize = function ( target ) {
  15708. return target.set( _width, _height );
  15709. };
  15710. this.setSize = function ( width, height, updateStyle ) {
  15711. if ( xr.isPresenting ) {
  15712. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  15713. return;
  15714. }
  15715. _width = width;
  15716. _height = height;
  15717. _canvas.width = Math.floor( width * _pixelRatio );
  15718. _canvas.height = Math.floor( height * _pixelRatio );
  15719. if ( updateStyle !== false ) {
  15720. _canvas.style.width = width + 'px';
  15721. _canvas.style.height = height + 'px';
  15722. }
  15723. this.setViewport( 0, 0, width, height );
  15724. };
  15725. this.getDrawingBufferSize = function ( target ) {
  15726. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  15727. };
  15728. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  15729. _width = width;
  15730. _height = height;
  15731. _pixelRatio = pixelRatio;
  15732. _canvas.width = Math.floor( width * pixelRatio );
  15733. _canvas.height = Math.floor( height * pixelRatio );
  15734. this.setViewport( 0, 0, width, height );
  15735. };
  15736. this.getCurrentViewport = function ( target ) {
  15737. return target.copy( _currentViewport );
  15738. };
  15739. this.getViewport = function ( target ) {
  15740. return target.copy( _viewport );
  15741. };
  15742. this.setViewport = function ( x, y, width, height ) {
  15743. if ( x.isVector4 ) {
  15744. _viewport.set( x.x, x.y, x.z, x.w );
  15745. } else {
  15746. _viewport.set( x, y, width, height );
  15747. }
  15748. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  15749. };
  15750. this.getScissor = function ( target ) {
  15751. return target.copy( _scissor );
  15752. };
  15753. this.setScissor = function ( x, y, width, height ) {
  15754. if ( x.isVector4 ) {
  15755. _scissor.set( x.x, x.y, x.z, x.w );
  15756. } else {
  15757. _scissor.set( x, y, width, height );
  15758. }
  15759. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  15760. };
  15761. this.getScissorTest = function () {
  15762. return _scissorTest;
  15763. };
  15764. this.setScissorTest = function ( boolean ) {
  15765. state.setScissorTest( _scissorTest = boolean );
  15766. };
  15767. this.setOpaqueSort = function ( method ) {
  15768. _opaqueSort = method;
  15769. };
  15770. this.setTransparentSort = function ( method ) {
  15771. _transparentSort = method;
  15772. };
  15773. // Clearing
  15774. this.getClearColor = function ( target ) {
  15775. return target.copy( background.getClearColor() );
  15776. };
  15777. this.setClearColor = function () {
  15778. background.setClearColor.apply( background, arguments );
  15779. };
  15780. this.getClearAlpha = function () {
  15781. return background.getClearAlpha();
  15782. };
  15783. this.setClearAlpha = function () {
  15784. background.setClearAlpha.apply( background, arguments );
  15785. };
  15786. this.clear = function ( color, depth, stencil ) {
  15787. let bits = 0;
  15788. if ( color === undefined || color ) bits |= 16384;
  15789. if ( depth === undefined || depth ) bits |= 256;
  15790. if ( stencil === undefined || stencil ) bits |= 1024;
  15791. _gl.clear( bits );
  15792. };
  15793. this.clearColor = function () {
  15794. this.clear( true, false, false );
  15795. };
  15796. this.clearDepth = function () {
  15797. this.clear( false, true, false );
  15798. };
  15799. this.clearStencil = function () {
  15800. this.clear( false, false, true );
  15801. };
  15802. //
  15803. this.dispose = function () {
  15804. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  15805. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  15806. renderLists.dispose();
  15807. renderStates.dispose();
  15808. properties.dispose();
  15809. cubemaps.dispose();
  15810. cubeuvmaps.dispose();
  15811. objects.dispose();
  15812. bindingStates.dispose();
  15813. programCache.dispose();
  15814. xr.dispose();
  15815. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  15816. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  15817. if ( _transmissionRenderTarget ) {
  15818. _transmissionRenderTarget.dispose();
  15819. _transmissionRenderTarget = null;
  15820. }
  15821. animation.stop();
  15822. };
  15823. // Events
  15824. function onContextLost( event ) {
  15825. event.preventDefault();
  15826. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  15827. _isContextLost = true;
  15828. }
  15829. function onContextRestore( /* event */ ) {
  15830. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  15831. _isContextLost = false;
  15832. const infoAutoReset = info.autoReset;
  15833. const shadowMapEnabled = shadowMap.enabled;
  15834. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15835. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15836. const shadowMapType = shadowMap.type;
  15837. initGLContext();
  15838. info.autoReset = infoAutoReset;
  15839. shadowMap.enabled = shadowMapEnabled;
  15840. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15841. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15842. shadowMap.type = shadowMapType;
  15843. }
  15844. function onMaterialDispose( event ) {
  15845. const material = event.target;
  15846. material.removeEventListener( 'dispose', onMaterialDispose );
  15847. deallocateMaterial( material );
  15848. }
  15849. // Buffer deallocation
  15850. function deallocateMaterial( material ) {
  15851. releaseMaterialProgramReferences( material );
  15852. properties.remove( material );
  15853. }
  15854. function releaseMaterialProgramReferences( material ) {
  15855. const programs = properties.get( material ).programs;
  15856. if ( programs !== undefined ) {
  15857. programs.forEach( function ( program ) {
  15858. programCache.releaseProgram( program );
  15859. } );
  15860. if ( material.isShaderMaterial ) {
  15861. programCache.releaseShaderCache( material );
  15862. }
  15863. }
  15864. }
  15865. // Buffer rendering
  15866. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15867. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15868. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15869. const program = setProgram( camera, scene, geometry, material, object );
  15870. state.setMaterial( material, frontFaceCW );
  15871. //
  15872. let index = geometry.index;
  15873. const position = geometry.attributes.position;
  15874. //
  15875. if ( index === null ) {
  15876. if ( position === undefined || position.count === 0 ) return;
  15877. } else if ( index.count === 0 ) {
  15878. return;
  15879. }
  15880. //
  15881. let rangeFactor = 1;
  15882. if ( material.wireframe === true ) {
  15883. index = geometries.getWireframeAttribute( geometry );
  15884. rangeFactor = 2;
  15885. }
  15886. bindingStates.setup( object, material, program, geometry, index );
  15887. let attribute;
  15888. let renderer = bufferRenderer;
  15889. if ( index !== null ) {
  15890. attribute = attributes.get( index );
  15891. renderer = indexedBufferRenderer;
  15892. renderer.setIndex( attribute );
  15893. }
  15894. //
  15895. const dataCount = ( index !== null ) ? index.count : position.count;
  15896. const rangeStart = geometry.drawRange.start * rangeFactor;
  15897. const rangeCount = geometry.drawRange.count * rangeFactor;
  15898. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15899. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15900. const drawStart = Math.max( rangeStart, groupStart );
  15901. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15902. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15903. if ( drawCount === 0 ) return;
  15904. //
  15905. if ( object.isMesh ) {
  15906. if ( material.wireframe === true ) {
  15907. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15908. renderer.setMode( 1 );
  15909. } else {
  15910. renderer.setMode( 4 );
  15911. }
  15912. } else if ( object.isLine ) {
  15913. let lineWidth = material.linewidth;
  15914. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15915. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15916. if ( object.isLineSegments ) {
  15917. renderer.setMode( 1 );
  15918. } else if ( object.isLineLoop ) {
  15919. renderer.setMode( 2 );
  15920. } else {
  15921. renderer.setMode( 3 );
  15922. }
  15923. } else if ( object.isPoints ) {
  15924. renderer.setMode( 0 );
  15925. } else if ( object.isSprite ) {
  15926. renderer.setMode( 4 );
  15927. }
  15928. if ( object.isInstancedMesh ) {
  15929. renderer.renderInstances( drawStart, drawCount, object.count );
  15930. } else if ( geometry.isInstancedBufferGeometry ) {
  15931. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15932. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15933. } else {
  15934. renderer.render( drawStart, drawCount );
  15935. }
  15936. };
  15937. // Compile
  15938. this.compile = function ( scene, camera ) {
  15939. currentRenderState = renderStates.get( scene );
  15940. currentRenderState.init();
  15941. renderStateStack.push( currentRenderState );
  15942. scene.traverseVisible( function ( object ) {
  15943. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15944. currentRenderState.pushLight( object );
  15945. if ( object.castShadow ) {
  15946. currentRenderState.pushShadow( object );
  15947. }
  15948. }
  15949. } );
  15950. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15951. scene.traverse( function ( object ) {
  15952. const material = object.material;
  15953. if ( material ) {
  15954. if ( Array.isArray( material ) ) {
  15955. for ( let i = 0; i < material.length; i ++ ) {
  15956. const material2 = material[ i ];
  15957. getProgram( material2, scene, object );
  15958. }
  15959. } else {
  15960. getProgram( material, scene, object );
  15961. }
  15962. }
  15963. } );
  15964. renderStateStack.pop();
  15965. currentRenderState = null;
  15966. };
  15967. // Animation Loop
  15968. let onAnimationFrameCallback = null;
  15969. function onAnimationFrame( time ) {
  15970. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15971. }
  15972. function onXRSessionStart() {
  15973. animation.stop();
  15974. }
  15975. function onXRSessionEnd() {
  15976. animation.start();
  15977. }
  15978. const animation = new WebGLAnimation();
  15979. animation.setAnimationLoop( onAnimationFrame );
  15980. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15981. this.setAnimationLoop = function ( callback ) {
  15982. onAnimationFrameCallback = callback;
  15983. xr.setAnimationLoop( callback );
  15984. ( callback === null ) ? animation.stop() : animation.start();
  15985. };
  15986. xr.addEventListener( 'sessionstart', onXRSessionStart );
  15987. xr.addEventListener( 'sessionend', onXRSessionEnd );
  15988. // Rendering
  15989. this.render = function ( scene, camera ) {
  15990. if ( camera !== undefined && camera.isCamera !== true ) {
  15991. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15992. return;
  15993. }
  15994. if ( _isContextLost === true ) return;
  15995. // update scene graph
  15996. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15997. // update camera matrices and frustum
  15998. if ( camera.parent === null ) camera.updateMatrixWorld();
  15999. if ( xr.enabled === true && xr.isPresenting === true ) {
  16000. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16001. camera = xr.getCamera(); // use XR camera for rendering
  16002. }
  16003. //
  16004. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16005. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16006. currentRenderState.init();
  16007. renderStateStack.push( currentRenderState );
  16008. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16009. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16010. _localClippingEnabled = this.localClippingEnabled;
  16011. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16012. currentRenderList = renderLists.get( scene, renderListStack.length );
  16013. currentRenderList.init();
  16014. renderListStack.push( currentRenderList );
  16015. projectObject( scene, camera, 0, _this.sortObjects );
  16016. currentRenderList.finish();
  16017. if ( _this.sortObjects === true ) {
  16018. currentRenderList.sort( _opaqueSort, _transparentSort );
  16019. }
  16020. //
  16021. if ( _clippingEnabled === true ) clipping.beginShadows();
  16022. const shadowsArray = currentRenderState.state.shadowsArray;
  16023. shadowMap.render( shadowsArray, scene, camera );
  16024. if ( _clippingEnabled === true ) clipping.endShadows();
  16025. //
  16026. if ( this.info.autoReset === true ) this.info.reset();
  16027. //
  16028. background.render( currentRenderList, scene );
  16029. // render scene
  16030. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16031. if ( camera.isArrayCamera ) {
  16032. const cameras = camera.cameras;
  16033. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16034. const camera2 = cameras[ i ];
  16035. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16036. }
  16037. } else {
  16038. renderScene( currentRenderList, scene, camera );
  16039. }
  16040. //
  16041. if ( _currentRenderTarget !== null ) {
  16042. // resolve multisample renderbuffers to a single-sample texture if necessary
  16043. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16044. // Generate mipmap if we're using any kind of mipmap filtering
  16045. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16046. }
  16047. //
  16048. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16049. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16050. state.buffers.depth.setTest( true );
  16051. state.buffers.depth.setMask( true );
  16052. state.buffers.color.setMask( true );
  16053. state.setPolygonOffset( false );
  16054. // _gl.finish();
  16055. bindingStates.resetDefaultState();
  16056. _currentMaterialId = - 1;
  16057. _currentCamera = null;
  16058. renderStateStack.pop();
  16059. if ( renderStateStack.length > 0 ) {
  16060. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16061. } else {
  16062. currentRenderState = null;
  16063. }
  16064. renderListStack.pop();
  16065. if ( renderListStack.length > 0 ) {
  16066. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16067. } else {
  16068. currentRenderList = null;
  16069. }
  16070. };
  16071. function projectObject( object, camera, groupOrder, sortObjects ) {
  16072. if ( object.visible === false ) return;
  16073. const visible = object.layers.test( camera.layers );
  16074. if ( visible ) {
  16075. if ( object.isGroup ) {
  16076. groupOrder = object.renderOrder;
  16077. } else if ( object.isLOD ) {
  16078. if ( object.autoUpdate === true ) object.update( camera );
  16079. } else if ( object.isLight ) {
  16080. currentRenderState.pushLight( object );
  16081. if ( object.castShadow ) {
  16082. currentRenderState.pushShadow( object );
  16083. }
  16084. } else if ( object.isSprite ) {
  16085. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16086. if ( sortObjects ) {
  16087. _vector3.setFromMatrixPosition( object.matrixWorld )
  16088. .applyMatrix4( _projScreenMatrix );
  16089. }
  16090. const geometry = objects.update( object );
  16091. const material = object.material;
  16092. if ( material.visible ) {
  16093. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16094. }
  16095. }
  16096. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16097. if ( object.isSkinnedMesh ) {
  16098. // update skeleton only once in a frame
  16099. if ( object.skeleton.frame !== info.render.frame ) {
  16100. object.skeleton.update();
  16101. object.skeleton.frame = info.render.frame;
  16102. }
  16103. }
  16104. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16105. if ( sortObjects ) {
  16106. _vector3.setFromMatrixPosition( object.matrixWorld )
  16107. .applyMatrix4( _projScreenMatrix );
  16108. }
  16109. const geometry = objects.update( object );
  16110. const material = object.material;
  16111. if ( Array.isArray( material ) ) {
  16112. const groups = geometry.groups;
  16113. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16114. const group = groups[ i ];
  16115. const groupMaterial = material[ group.materialIndex ];
  16116. if ( groupMaterial && groupMaterial.visible ) {
  16117. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16118. }
  16119. }
  16120. } else if ( material.visible ) {
  16121. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16122. }
  16123. }
  16124. }
  16125. }
  16126. const children = object.children;
  16127. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16128. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16129. }
  16130. }
  16131. function renderScene( currentRenderList, scene, camera, viewport ) {
  16132. const opaqueObjects = currentRenderList.opaque;
  16133. const transmissiveObjects = currentRenderList.transmissive;
  16134. const transparentObjects = currentRenderList.transparent;
  16135. currentRenderState.setupLightsView( camera );
  16136. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16137. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16138. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16139. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16140. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16141. }
  16142. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16143. if ( _transmissionRenderTarget === null ) {
  16144. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  16145. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  16146. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  16147. generateMipmaps: true,
  16148. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  16149. minFilter: LinearMipmapLinearFilter,
  16150. magFilter: NearestFilter,
  16151. wrapS: ClampToEdgeWrapping,
  16152. wrapT: ClampToEdgeWrapping,
  16153. useRenderToTexture: extensions.has( 'WEBGL_multisampled_render_to_texture' )
  16154. } );
  16155. }
  16156. const currentRenderTarget = _this.getRenderTarget();
  16157. _this.setRenderTarget( _transmissionRenderTarget );
  16158. _this.clear();
  16159. // Turn off the features which can affect the frag color for opaque objects pass.
  16160. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16161. const currentToneMapping = _this.toneMapping;
  16162. _this.toneMapping = NoToneMapping;
  16163. renderObjects( opaqueObjects, scene, camera );
  16164. _this.toneMapping = currentToneMapping;
  16165. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16166. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16167. _this.setRenderTarget( currentRenderTarget );
  16168. }
  16169. function renderObjects( renderList, scene, camera ) {
  16170. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16171. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16172. const renderItem = renderList[ i ];
  16173. const object = renderItem.object;
  16174. const geometry = renderItem.geometry;
  16175. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16176. const group = renderItem.group;
  16177. if ( object.layers.test( camera.layers ) ) {
  16178. renderObject( object, scene, camera, geometry, material, group );
  16179. }
  16180. }
  16181. }
  16182. function renderObject( object, scene, camera, geometry, material, group ) {
  16183. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16184. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16185. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16186. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16187. if ( material.transparent === true && material.side === DoubleSide ) {
  16188. material.side = BackSide;
  16189. material.needsUpdate = true;
  16190. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16191. material.side = FrontSide;
  16192. material.needsUpdate = true;
  16193. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16194. material.side = DoubleSide;
  16195. } else {
  16196. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16197. }
  16198. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16199. }
  16200. function getProgram( material, scene, object ) {
  16201. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16202. const materialProperties = properties.get( material );
  16203. const lights = currentRenderState.state.lights;
  16204. const shadowsArray = currentRenderState.state.shadowsArray;
  16205. const lightsStateVersion = lights.state.version;
  16206. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16207. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16208. let programs = materialProperties.programs;
  16209. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16210. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16211. materialProperties.fog = scene.fog;
  16212. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16213. if ( programs === undefined ) {
  16214. // new material
  16215. material.addEventListener( 'dispose', onMaterialDispose );
  16216. programs = new Map();
  16217. materialProperties.programs = programs;
  16218. }
  16219. let program = programs.get( programCacheKey );
  16220. if ( program !== undefined ) {
  16221. // early out if program and light state is identical
  16222. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16223. updateCommonMaterialProperties( material, parameters );
  16224. return program;
  16225. }
  16226. } else {
  16227. parameters.uniforms = programCache.getUniforms( material );
  16228. material.onBuild( object, parameters, _this );
  16229. material.onBeforeCompile( parameters, _this );
  16230. program = programCache.acquireProgram( parameters, programCacheKey );
  16231. programs.set( programCacheKey, program );
  16232. materialProperties.uniforms = parameters.uniforms;
  16233. }
  16234. const uniforms = materialProperties.uniforms;
  16235. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16236. uniforms.clippingPlanes = clipping.uniform;
  16237. }
  16238. updateCommonMaterialProperties( material, parameters );
  16239. // store the light setup it was created for
  16240. materialProperties.needsLights = materialNeedsLights( material );
  16241. materialProperties.lightsStateVersion = lightsStateVersion;
  16242. if ( materialProperties.needsLights ) {
  16243. // wire up the material to this renderer's lighting state
  16244. uniforms.ambientLightColor.value = lights.state.ambient;
  16245. uniforms.lightProbe.value = lights.state.probe;
  16246. uniforms.directionalLights.value = lights.state.directional;
  16247. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16248. uniforms.spotLights.value = lights.state.spot;
  16249. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16250. uniforms.rectAreaLights.value = lights.state.rectArea;
  16251. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16252. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16253. uniforms.pointLights.value = lights.state.point;
  16254. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16255. uniforms.hemisphereLights.value = lights.state.hemi;
  16256. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16257. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16258. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16259. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16260. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16261. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16262. // TODO (abelnation): add area lights shadow info to uniforms
  16263. }
  16264. const progUniforms = program.getUniforms();
  16265. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16266. materialProperties.currentProgram = program;
  16267. materialProperties.uniformsList = uniformsList;
  16268. return program;
  16269. }
  16270. function updateCommonMaterialProperties( material, parameters ) {
  16271. const materialProperties = properties.get( material );
  16272. materialProperties.outputEncoding = parameters.outputEncoding;
  16273. materialProperties.instancing = parameters.instancing;
  16274. materialProperties.skinning = parameters.skinning;
  16275. materialProperties.morphTargets = parameters.morphTargets;
  16276. materialProperties.morphNormals = parameters.morphNormals;
  16277. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16278. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16279. materialProperties.numIntersection = parameters.numClipIntersection;
  16280. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16281. materialProperties.vertexTangents = parameters.vertexTangents;
  16282. materialProperties.toneMapping = parameters.toneMapping;
  16283. }
  16284. function setProgram( camera, scene, geometry, material, object ) {
  16285. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16286. textures.resetTextureUnits();
  16287. const fog = scene.fog;
  16288. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16289. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16290. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16291. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16292. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16293. const morphTargets = !! geometry.morphAttributes.position;
  16294. const morphNormals = !! geometry.morphAttributes.normal;
  16295. const morphTargetsCount = !! geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  16296. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16297. const materialProperties = properties.get( material );
  16298. const lights = currentRenderState.state.lights;
  16299. if ( _clippingEnabled === true ) {
  16300. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16301. const useCache =
  16302. camera === _currentCamera &&
  16303. material.id === _currentMaterialId;
  16304. // we might want to call this function with some ClippingGroup
  16305. // object instead of the material, once it becomes feasible
  16306. // (#8465, #8379)
  16307. clipping.setState( material, camera, useCache );
  16308. }
  16309. }
  16310. //
  16311. let needsProgramChange = false;
  16312. if ( material.version === materialProperties.__version ) {
  16313. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16314. needsProgramChange = true;
  16315. } else if ( materialProperties.outputEncoding !== encoding ) {
  16316. needsProgramChange = true;
  16317. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16318. needsProgramChange = true;
  16319. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16320. needsProgramChange = true;
  16321. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16322. needsProgramChange = true;
  16323. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16324. needsProgramChange = true;
  16325. } else if ( materialProperties.envMap !== envMap ) {
  16326. needsProgramChange = true;
  16327. } else if ( material.fog && materialProperties.fog !== fog ) {
  16328. needsProgramChange = true;
  16329. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16330. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16331. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16332. needsProgramChange = true;
  16333. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16334. needsProgramChange = true;
  16335. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16336. needsProgramChange = true;
  16337. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16338. needsProgramChange = true;
  16339. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16340. needsProgramChange = true;
  16341. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16342. needsProgramChange = true;
  16343. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16344. needsProgramChange = true;
  16345. }
  16346. } else {
  16347. needsProgramChange = true;
  16348. materialProperties.__version = material.version;
  16349. }
  16350. //
  16351. let program = materialProperties.currentProgram;
  16352. if ( needsProgramChange === true ) {
  16353. program = getProgram( material, scene, object );
  16354. }
  16355. let refreshProgram = false;
  16356. let refreshMaterial = false;
  16357. let refreshLights = false;
  16358. const p_uniforms = program.getUniforms(),
  16359. m_uniforms = materialProperties.uniforms;
  16360. if ( state.useProgram( program.program ) ) {
  16361. refreshProgram = true;
  16362. refreshMaterial = true;
  16363. refreshLights = true;
  16364. }
  16365. if ( material.id !== _currentMaterialId ) {
  16366. _currentMaterialId = material.id;
  16367. refreshMaterial = true;
  16368. }
  16369. if ( refreshProgram || _currentCamera !== camera ) {
  16370. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16371. if ( capabilities.logarithmicDepthBuffer ) {
  16372. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16373. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16374. }
  16375. if ( _currentCamera !== camera ) {
  16376. _currentCamera = camera;
  16377. // lighting uniforms depend on the camera so enforce an update
  16378. // now, in case this material supports lights - or later, when
  16379. // the next material that does gets activated:
  16380. refreshMaterial = true; // set to true on material change
  16381. refreshLights = true; // remains set until update done
  16382. }
  16383. // load material specific uniforms
  16384. // (shader material also gets them for the sake of genericity)
  16385. if ( material.isShaderMaterial ||
  16386. material.isMeshPhongMaterial ||
  16387. material.isMeshToonMaterial ||
  16388. material.isMeshStandardMaterial ||
  16389. material.envMap ) {
  16390. const uCamPos = p_uniforms.map.cameraPosition;
  16391. if ( uCamPos !== undefined ) {
  16392. uCamPos.setValue( _gl,
  16393. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16394. }
  16395. }
  16396. if ( material.isMeshPhongMaterial ||
  16397. material.isMeshToonMaterial ||
  16398. material.isMeshLambertMaterial ||
  16399. material.isMeshBasicMaterial ||
  16400. material.isMeshStandardMaterial ||
  16401. material.isShaderMaterial ) {
  16402. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  16403. }
  16404. if ( material.isMeshPhongMaterial ||
  16405. material.isMeshToonMaterial ||
  16406. material.isMeshLambertMaterial ||
  16407. material.isMeshBasicMaterial ||
  16408. material.isMeshStandardMaterial ||
  16409. material.isShaderMaterial ||
  16410. material.isShadowMaterial ||
  16411. object.isSkinnedMesh ) {
  16412. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16413. }
  16414. }
  16415. // skinning and morph target uniforms must be set even if material didn't change
  16416. // auto-setting of texture unit for bone and morph texture must go before other textures
  16417. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16418. if ( object.isSkinnedMesh ) {
  16419. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16420. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16421. const skeleton = object.skeleton;
  16422. if ( skeleton ) {
  16423. if ( capabilities.floatVertexTextures ) {
  16424. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  16425. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  16426. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  16427. } else {
  16428. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  16429. }
  16430. }
  16431. }
  16432. if ( !! geometry && ( geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined ) ) {
  16433. morphtargets.update( object, geometry, material, program );
  16434. }
  16435. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  16436. materialProperties.receiveShadow = object.receiveShadow;
  16437. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  16438. }
  16439. if ( refreshMaterial ) {
  16440. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  16441. if ( materialProperties.needsLights ) {
  16442. // the current material requires lighting info
  16443. // note: all lighting uniforms are always set correctly
  16444. // they simply reference the renderer's state for their
  16445. // values
  16446. //
  16447. // use the current material's .needsUpdate flags to set
  16448. // the GL state when required
  16449. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16450. }
  16451. // refresh uniforms common to several materials
  16452. if ( fog && material.fog ) {
  16453. materials.refreshFogUniforms( m_uniforms, fog );
  16454. }
  16455. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  16456. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16457. }
  16458. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  16459. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16460. material.uniformsNeedUpdate = false;
  16461. }
  16462. if ( material.isSpriteMaterial ) {
  16463. p_uniforms.setValue( _gl, 'center', object.center );
  16464. }
  16465. // common matrices
  16466. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  16467. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  16468. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16469. return program;
  16470. }
  16471. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16472. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  16473. uniforms.ambientLightColor.needsUpdate = value;
  16474. uniforms.lightProbe.needsUpdate = value;
  16475. uniforms.directionalLights.needsUpdate = value;
  16476. uniforms.directionalLightShadows.needsUpdate = value;
  16477. uniforms.pointLights.needsUpdate = value;
  16478. uniforms.pointLightShadows.needsUpdate = value;
  16479. uniforms.spotLights.needsUpdate = value;
  16480. uniforms.spotLightShadows.needsUpdate = value;
  16481. uniforms.rectAreaLights.needsUpdate = value;
  16482. uniforms.hemisphereLights.needsUpdate = value;
  16483. }
  16484. function materialNeedsLights( material ) {
  16485. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  16486. material.isMeshStandardMaterial || material.isShadowMaterial ||
  16487. ( material.isShaderMaterial && material.lights === true );
  16488. }
  16489. this.getActiveCubeFace = function () {
  16490. return _currentActiveCubeFace;
  16491. };
  16492. this.getActiveMipmapLevel = function () {
  16493. return _currentActiveMipmapLevel;
  16494. };
  16495. this.getRenderTarget = function () {
  16496. return _currentRenderTarget;
  16497. };
  16498. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  16499. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  16500. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  16501. const renderTargetProperties = properties.get( renderTarget );
  16502. renderTargetProperties.__hasExternalTextures = true;
  16503. if ( renderTargetProperties.__hasExternalTextures ) {
  16504. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16505. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  16506. // The multisample_render_to_texture extension doesn't work properly if there
  16507. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16508. if ( renderTarget.useRenderToTexture ) {
  16509. console.warn( 'render-to-texture extension was disabled because an external texture was provided' );
  16510. renderTarget.useRenderToTexture = false;
  16511. renderTarget.useRenderbuffer = true;
  16512. }
  16513. }
  16514. }
  16515. };
  16516. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  16517. const renderTargetProperties = properties.get( renderTarget );
  16518. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16519. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16520. };
  16521. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16522. _currentRenderTarget = renderTarget;
  16523. _currentActiveCubeFace = activeCubeFace;
  16524. _currentActiveMipmapLevel = activeMipmapLevel;
  16525. let useDefaultFramebuffer = true;
  16526. if ( renderTarget ) {
  16527. const renderTargetProperties = properties.get( renderTarget );
  16528. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  16529. // We need to make sure to rebind the framebuffer.
  16530. state.bindFramebuffer( 36160, null );
  16531. useDefaultFramebuffer = false;
  16532. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  16533. textures.setupRenderTarget( renderTarget );
  16534. } else if ( renderTargetProperties.__hasExternalTextures ) {
  16535. // Color and depth texture must be rebound in order for the swapchain to update.
  16536. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  16537. }
  16538. }
  16539. let framebuffer = null;
  16540. let isCube = false;
  16541. let isRenderTarget3D = false;
  16542. if ( renderTarget ) {
  16543. const texture = renderTarget.texture;
  16544. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  16545. isRenderTarget3D = true;
  16546. }
  16547. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16548. if ( renderTarget.isWebGLCubeRenderTarget ) {
  16549. framebuffer = __webglFramebuffer[ activeCubeFace ];
  16550. isCube = true;
  16551. } else if ( renderTarget.useRenderbuffer ) {
  16552. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  16553. } else {
  16554. framebuffer = __webglFramebuffer;
  16555. }
  16556. _currentViewport.copy( renderTarget.viewport );
  16557. _currentScissor.copy( renderTarget.scissor );
  16558. _currentScissorTest = renderTarget.scissorTest;
  16559. } else {
  16560. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16561. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16562. _currentScissorTest = _scissorTest;
  16563. }
  16564. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16565. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  16566. state.drawBuffers( renderTarget, framebuffer );
  16567. }
  16568. state.viewport( _currentViewport );
  16569. state.scissor( _currentScissor );
  16570. state.setScissorTest( _currentScissorTest );
  16571. if ( isCube ) {
  16572. const textureProperties = properties.get( renderTarget.texture );
  16573. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16574. } else if ( isRenderTarget3D ) {
  16575. const textureProperties = properties.get( renderTarget.texture );
  16576. const layer = activeCubeFace || 0;
  16577. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16578. }
  16579. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  16580. };
  16581. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  16582. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  16583. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16584. return;
  16585. }
  16586. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16587. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  16588. framebuffer = framebuffer[ activeCubeFaceIndex ];
  16589. }
  16590. if ( framebuffer ) {
  16591. state.bindFramebuffer( 36160, framebuffer );
  16592. try {
  16593. const texture = renderTarget.texture;
  16594. const textureFormat = texture.format;
  16595. const textureType = texture.type;
  16596. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  16597. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16598. return;
  16599. }
  16600. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  16601. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  16602. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16603. ! halfFloatSupportedByExt ) {
  16604. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16605. return;
  16606. }
  16607. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  16608. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16609. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16610. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  16611. }
  16612. } else {
  16613. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16614. }
  16615. } finally {
  16616. // restore framebuffer of current render target if necessary
  16617. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  16618. state.bindFramebuffer( 36160, framebuffer );
  16619. }
  16620. }
  16621. };
  16622. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  16623. if ( texture.isFramebufferTexture !== true ) {
  16624. console.error( 'THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.' );
  16625. return;
  16626. }
  16627. const levelScale = Math.pow( 2, - level );
  16628. const width = Math.floor( texture.image.width * levelScale );
  16629. const height = Math.floor( texture.image.height * levelScale );
  16630. textures.setTexture2D( texture, 0 );
  16631. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  16632. state.unbindTexture();
  16633. };
  16634. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  16635. const width = srcTexture.image.width;
  16636. const height = srcTexture.image.height;
  16637. const glFormat = utils.convert( dstTexture.format );
  16638. const glType = utils.convert( dstTexture.type );
  16639. textures.setTexture2D( dstTexture, 0 );
  16640. // As another texture upload may have changed pixelStorei
  16641. // parameters, make sure they are correct for the dstTexture
  16642. _gl.pixelStorei( 37440, dstTexture.flipY );
  16643. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16644. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16645. if ( srcTexture.isDataTexture ) {
  16646. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  16647. } else {
  16648. if ( srcTexture.isCompressedTexture ) {
  16649. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  16650. } else {
  16651. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  16652. }
  16653. }
  16654. // Generate mipmaps only when copying level 0
  16655. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  16656. state.unbindTexture();
  16657. };
  16658. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  16659. if ( _this.isWebGL1Renderer ) {
  16660. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  16661. return;
  16662. }
  16663. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16664. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16665. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16666. const glFormat = utils.convert( dstTexture.format );
  16667. const glType = utils.convert( dstTexture.type );
  16668. let glTarget;
  16669. if ( dstTexture.isDataTexture3D ) {
  16670. textures.setTexture3D( dstTexture, 0 );
  16671. glTarget = 32879;
  16672. } else if ( dstTexture.isDataTexture2DArray ) {
  16673. textures.setTexture2DArray( dstTexture, 0 );
  16674. glTarget = 35866;
  16675. } else {
  16676. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  16677. return;
  16678. }
  16679. _gl.pixelStorei( 37440, dstTexture.flipY );
  16680. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16681. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16682. const unpackRowLen = _gl.getParameter( 3314 );
  16683. const unpackImageHeight = _gl.getParameter( 32878 );
  16684. const unpackSkipPixels = _gl.getParameter( 3316 );
  16685. const unpackSkipRows = _gl.getParameter( 3315 );
  16686. const unpackSkipImages = _gl.getParameter( 32877 );
  16687. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  16688. _gl.pixelStorei( 3314, image.width );
  16689. _gl.pixelStorei( 32878, image.height );
  16690. _gl.pixelStorei( 3316, sourceBox.min.x );
  16691. _gl.pixelStorei( 3315, sourceBox.min.y );
  16692. _gl.pixelStorei( 32877, sourceBox.min.z );
  16693. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  16694. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  16695. } else {
  16696. if ( srcTexture.isCompressedTexture ) {
  16697. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  16698. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  16699. } else {
  16700. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  16701. }
  16702. }
  16703. _gl.pixelStorei( 3314, unpackRowLen );
  16704. _gl.pixelStorei( 32878, unpackImageHeight );
  16705. _gl.pixelStorei( 3316, unpackSkipPixels );
  16706. _gl.pixelStorei( 3315, unpackSkipRows );
  16707. _gl.pixelStorei( 32877, unpackSkipImages );
  16708. // Generate mipmaps only when copying level 0
  16709. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  16710. state.unbindTexture();
  16711. };
  16712. this.initTexture = function ( texture ) {
  16713. textures.setTexture2D( texture, 0 );
  16714. state.unbindTexture();
  16715. };
  16716. this.resetState = function () {
  16717. _currentActiveCubeFace = 0;
  16718. _currentActiveMipmapLevel = 0;
  16719. _currentRenderTarget = null;
  16720. state.reset();
  16721. bindingStates.reset();
  16722. };
  16723. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16724. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  16725. }
  16726. }
  16727. WebGLRenderer.prototype.isWebGLRenderer = true;
  16728. class WebGL1Renderer extends WebGLRenderer {}
  16729. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16730. class FogExp2 {
  16731. constructor( color, density = 0.00025 ) {
  16732. this.name = '';
  16733. this.color = new Color( color );
  16734. this.density = density;
  16735. }
  16736. clone() {
  16737. return new FogExp2( this.color, this.density );
  16738. }
  16739. toJSON( /* meta */ ) {
  16740. return {
  16741. type: 'FogExp2',
  16742. color: this.color.getHex(),
  16743. density: this.density
  16744. };
  16745. }
  16746. }
  16747. FogExp2.prototype.isFogExp2 = true;
  16748. class Fog {
  16749. constructor( color, near = 1, far = 1000 ) {
  16750. this.name = '';
  16751. this.color = new Color( color );
  16752. this.near = near;
  16753. this.far = far;
  16754. }
  16755. clone() {
  16756. return new Fog( this.color, this.near, this.far );
  16757. }
  16758. toJSON( /* meta */ ) {
  16759. return {
  16760. type: 'Fog',
  16761. color: this.color.getHex(),
  16762. near: this.near,
  16763. far: this.far
  16764. };
  16765. }
  16766. }
  16767. Fog.prototype.isFog = true;
  16768. class Scene extends Object3D {
  16769. constructor() {
  16770. super();
  16771. this.type = 'Scene';
  16772. this.background = null;
  16773. this.environment = null;
  16774. this.fog = null;
  16775. this.overrideMaterial = null;
  16776. this.autoUpdate = true; // checked by the renderer
  16777. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16778. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  16779. }
  16780. }
  16781. copy( source, recursive ) {
  16782. super.copy( source, recursive );
  16783. if ( source.background !== null ) this.background = source.background.clone();
  16784. if ( source.environment !== null ) this.environment = source.environment.clone();
  16785. if ( source.fog !== null ) this.fog = source.fog.clone();
  16786. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16787. this.autoUpdate = source.autoUpdate;
  16788. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16789. return this;
  16790. }
  16791. toJSON( meta ) {
  16792. const data = super.toJSON( meta );
  16793. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16794. return data;
  16795. }
  16796. }
  16797. Scene.prototype.isScene = true;
  16798. class InterleavedBuffer {
  16799. constructor( array, stride ) {
  16800. this.array = array;
  16801. this.stride = stride;
  16802. this.count = array !== undefined ? array.length / stride : 0;
  16803. this.usage = StaticDrawUsage;
  16804. this.updateRange = { offset: 0, count: - 1 };
  16805. this.version = 0;
  16806. this.uuid = generateUUID();
  16807. }
  16808. onUploadCallback() {}
  16809. set needsUpdate( value ) {
  16810. if ( value === true ) this.version ++;
  16811. }
  16812. setUsage( value ) {
  16813. this.usage = value;
  16814. return this;
  16815. }
  16816. copy( source ) {
  16817. this.array = new source.array.constructor( source.array );
  16818. this.count = source.count;
  16819. this.stride = source.stride;
  16820. this.usage = source.usage;
  16821. return this;
  16822. }
  16823. copyAt( index1, attribute, index2 ) {
  16824. index1 *= this.stride;
  16825. index2 *= attribute.stride;
  16826. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  16827. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  16828. }
  16829. return this;
  16830. }
  16831. set( value, offset = 0 ) {
  16832. this.array.set( value, offset );
  16833. return this;
  16834. }
  16835. clone( data ) {
  16836. if ( data.arrayBuffers === undefined ) {
  16837. data.arrayBuffers = {};
  16838. }
  16839. if ( this.array.buffer._uuid === undefined ) {
  16840. this.array.buffer._uuid = generateUUID();
  16841. }
  16842. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16843. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  16844. }
  16845. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  16846. const ib = new this.constructor( array, this.stride );
  16847. ib.setUsage( this.usage );
  16848. return ib;
  16849. }
  16850. onUpload( callback ) {
  16851. this.onUploadCallback = callback;
  16852. return this;
  16853. }
  16854. toJSON( data ) {
  16855. if ( data.arrayBuffers === undefined ) {
  16856. data.arrayBuffers = {};
  16857. }
  16858. // generate UUID for array buffer if necessary
  16859. if ( this.array.buffer._uuid === undefined ) {
  16860. this.array.buffer._uuid = generateUUID();
  16861. }
  16862. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16863. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  16864. }
  16865. //
  16866. return {
  16867. uuid: this.uuid,
  16868. buffer: this.array.buffer._uuid,
  16869. type: this.array.constructor.name,
  16870. stride: this.stride
  16871. };
  16872. }
  16873. }
  16874. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16875. const _vector$6 = /*@__PURE__*/ new Vector3();
  16876. class InterleavedBufferAttribute {
  16877. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  16878. this.name = '';
  16879. this.data = interleavedBuffer;
  16880. this.itemSize = itemSize;
  16881. this.offset = offset;
  16882. this.normalized = normalized === true;
  16883. }
  16884. get count() {
  16885. return this.data.count;
  16886. }
  16887. get array() {
  16888. return this.data.array;
  16889. }
  16890. set needsUpdate( value ) {
  16891. this.data.needsUpdate = value;
  16892. }
  16893. applyMatrix4( m ) {
  16894. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  16895. _vector$6.x = this.getX( i );
  16896. _vector$6.y = this.getY( i );
  16897. _vector$6.z = this.getZ( i );
  16898. _vector$6.applyMatrix4( m );
  16899. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16900. }
  16901. return this;
  16902. }
  16903. applyNormalMatrix( m ) {
  16904. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16905. _vector$6.x = this.getX( i );
  16906. _vector$6.y = this.getY( i );
  16907. _vector$6.z = this.getZ( i );
  16908. _vector$6.applyNormalMatrix( m );
  16909. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16910. }
  16911. return this;
  16912. }
  16913. transformDirection( m ) {
  16914. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16915. _vector$6.x = this.getX( i );
  16916. _vector$6.y = this.getY( i );
  16917. _vector$6.z = this.getZ( i );
  16918. _vector$6.transformDirection( m );
  16919. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16920. }
  16921. return this;
  16922. }
  16923. setX( index, x ) {
  16924. this.data.array[ index * this.data.stride + this.offset ] = x;
  16925. return this;
  16926. }
  16927. setY( index, y ) {
  16928. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  16929. return this;
  16930. }
  16931. setZ( index, z ) {
  16932. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  16933. return this;
  16934. }
  16935. setW( index, w ) {
  16936. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  16937. return this;
  16938. }
  16939. getX( index ) {
  16940. return this.data.array[ index * this.data.stride + this.offset ];
  16941. }
  16942. getY( index ) {
  16943. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  16944. }
  16945. getZ( index ) {
  16946. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  16947. }
  16948. getW( index ) {
  16949. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  16950. }
  16951. setXY( index, x, y ) {
  16952. index = index * this.data.stride + this.offset;
  16953. this.data.array[ index + 0 ] = x;
  16954. this.data.array[ index + 1 ] = y;
  16955. return this;
  16956. }
  16957. setXYZ( index, x, y, z ) {
  16958. index = index * this.data.stride + this.offset;
  16959. this.data.array[ index + 0 ] = x;
  16960. this.data.array[ index + 1 ] = y;
  16961. this.data.array[ index + 2 ] = z;
  16962. return this;
  16963. }
  16964. setXYZW( index, x, y, z, w ) {
  16965. index = index * this.data.stride + this.offset;
  16966. this.data.array[ index + 0 ] = x;
  16967. this.data.array[ index + 1 ] = y;
  16968. this.data.array[ index + 2 ] = z;
  16969. this.data.array[ index + 3 ] = w;
  16970. return this;
  16971. }
  16972. clone( data ) {
  16973. if ( data === undefined ) {
  16974. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16975. const array = [];
  16976. for ( let i = 0; i < this.count; i ++ ) {
  16977. const index = i * this.data.stride + this.offset;
  16978. for ( let j = 0; j < this.itemSize; j ++ ) {
  16979. array.push( this.data.array[ index + j ] );
  16980. }
  16981. }
  16982. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16983. } else {
  16984. if ( data.interleavedBuffers === undefined ) {
  16985. data.interleavedBuffers = {};
  16986. }
  16987. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16988. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16989. }
  16990. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16991. }
  16992. }
  16993. toJSON( data ) {
  16994. if ( data === undefined ) {
  16995. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16996. const array = [];
  16997. for ( let i = 0; i < this.count; i ++ ) {
  16998. const index = i * this.data.stride + this.offset;
  16999. for ( let j = 0; j < this.itemSize; j ++ ) {
  17000. array.push( this.data.array[ index + j ] );
  17001. }
  17002. }
  17003. // deinterleave data and save it as an ordinary buffer attribute for now
  17004. return {
  17005. itemSize: this.itemSize,
  17006. type: this.array.constructor.name,
  17007. array: array,
  17008. normalized: this.normalized
  17009. };
  17010. } else {
  17011. // save as true interlaved attribtue
  17012. if ( data.interleavedBuffers === undefined ) {
  17013. data.interleavedBuffers = {};
  17014. }
  17015. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17016. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17017. }
  17018. return {
  17019. isInterleavedBufferAttribute: true,
  17020. itemSize: this.itemSize,
  17021. data: this.data.uuid,
  17022. offset: this.offset,
  17023. normalized: this.normalized
  17024. };
  17025. }
  17026. }
  17027. }
  17028. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  17029. /**
  17030. * parameters = {
  17031. * color: <hex>,
  17032. * map: new THREE.Texture( <Image> ),
  17033. * alphaMap: new THREE.Texture( <Image> ),
  17034. * rotation: <float>,
  17035. * sizeAttenuation: <bool>
  17036. * }
  17037. */
  17038. class SpriteMaterial extends Material {
  17039. constructor( parameters ) {
  17040. super();
  17041. this.type = 'SpriteMaterial';
  17042. this.color = new Color( 0xffffff );
  17043. this.map = null;
  17044. this.alphaMap = null;
  17045. this.rotation = 0;
  17046. this.sizeAttenuation = true;
  17047. this.transparent = true;
  17048. this.setValues( parameters );
  17049. }
  17050. copy( source ) {
  17051. super.copy( source );
  17052. this.color.copy( source.color );
  17053. this.map = source.map;
  17054. this.alphaMap = source.alphaMap;
  17055. this.rotation = source.rotation;
  17056. this.sizeAttenuation = source.sizeAttenuation;
  17057. return this;
  17058. }
  17059. }
  17060. SpriteMaterial.prototype.isSpriteMaterial = true;
  17061. let _geometry;
  17062. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17063. const _worldScale = /*@__PURE__*/ new Vector3();
  17064. const _mvPosition = /*@__PURE__*/ new Vector3();
  17065. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17066. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17067. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17068. const _vA = /*@__PURE__*/ new Vector3();
  17069. const _vB = /*@__PURE__*/ new Vector3();
  17070. const _vC = /*@__PURE__*/ new Vector3();
  17071. const _uvA = /*@__PURE__*/ new Vector2();
  17072. const _uvB = /*@__PURE__*/ new Vector2();
  17073. const _uvC = /*@__PURE__*/ new Vector2();
  17074. class Sprite extends Object3D {
  17075. constructor( material ) {
  17076. super();
  17077. this.type = 'Sprite';
  17078. if ( _geometry === undefined ) {
  17079. _geometry = new BufferGeometry();
  17080. const float32Array = new Float32Array( [
  17081. - 0.5, - 0.5, 0, 0, 0,
  17082. 0.5, - 0.5, 0, 1, 0,
  17083. 0.5, 0.5, 0, 1, 1,
  17084. - 0.5, 0.5, 0, 0, 1
  17085. ] );
  17086. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17087. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17088. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17089. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17090. }
  17091. this.geometry = _geometry;
  17092. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17093. this.center = new Vector2( 0.5, 0.5 );
  17094. }
  17095. raycast( raycaster, intersects ) {
  17096. if ( raycaster.camera === null ) {
  17097. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17098. }
  17099. _worldScale.setFromMatrixScale( this.matrixWorld );
  17100. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17101. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17102. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17103. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17104. _worldScale.multiplyScalar( - _mvPosition.z );
  17105. }
  17106. const rotation = this.material.rotation;
  17107. let sin, cos;
  17108. if ( rotation !== 0 ) {
  17109. cos = Math.cos( rotation );
  17110. sin = Math.sin( rotation );
  17111. }
  17112. const center = this.center;
  17113. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17114. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17115. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17116. _uvA.set( 0, 0 );
  17117. _uvB.set( 1, 0 );
  17118. _uvC.set( 1, 1 );
  17119. // check first triangle
  17120. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17121. if ( intersect === null ) {
  17122. // check second triangle
  17123. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17124. _uvB.set( 0, 1 );
  17125. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17126. if ( intersect === null ) {
  17127. return;
  17128. }
  17129. }
  17130. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17131. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17132. intersects.push( {
  17133. distance: distance,
  17134. point: _intersectPoint.clone(),
  17135. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17136. face: null,
  17137. object: this
  17138. } );
  17139. }
  17140. copy( source ) {
  17141. super.copy( source );
  17142. if ( source.center !== undefined ) this.center.copy( source.center );
  17143. this.material = source.material;
  17144. return this;
  17145. }
  17146. }
  17147. Sprite.prototype.isSprite = true;
  17148. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17149. // compute position in camera space
  17150. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17151. // to check if rotation is not zero
  17152. if ( sin !== undefined ) {
  17153. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17154. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17155. } else {
  17156. _rotatedPosition.copy( _alignedPosition );
  17157. }
  17158. vertexPosition.copy( mvPosition );
  17159. vertexPosition.x += _rotatedPosition.x;
  17160. vertexPosition.y += _rotatedPosition.y;
  17161. // transform to world space
  17162. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17163. }
  17164. const _v1$2 = /*@__PURE__*/ new Vector3();
  17165. const _v2$1 = /*@__PURE__*/ new Vector3();
  17166. class LOD extends Object3D {
  17167. constructor() {
  17168. super();
  17169. this._currentLevel = 0;
  17170. this.type = 'LOD';
  17171. Object.defineProperties( this, {
  17172. levels: {
  17173. enumerable: true,
  17174. value: []
  17175. },
  17176. isLOD: {
  17177. value: true,
  17178. }
  17179. } );
  17180. this.autoUpdate = true;
  17181. }
  17182. copy( source ) {
  17183. super.copy( source, false );
  17184. const levels = source.levels;
  17185. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17186. const level = levels[ i ];
  17187. this.addLevel( level.object.clone(), level.distance );
  17188. }
  17189. this.autoUpdate = source.autoUpdate;
  17190. return this;
  17191. }
  17192. addLevel( object, distance = 0 ) {
  17193. distance = Math.abs( distance );
  17194. const levels = this.levels;
  17195. let l;
  17196. for ( l = 0; l < levels.length; l ++ ) {
  17197. if ( distance < levels[ l ].distance ) {
  17198. break;
  17199. }
  17200. }
  17201. levels.splice( l, 0, { distance: distance, object: object } );
  17202. this.add( object );
  17203. return this;
  17204. }
  17205. getCurrentLevel() {
  17206. return this._currentLevel;
  17207. }
  17208. getObjectForDistance( distance ) {
  17209. const levels = this.levels;
  17210. if ( levels.length > 0 ) {
  17211. let i, l;
  17212. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17213. if ( distance < levels[ i ].distance ) {
  17214. break;
  17215. }
  17216. }
  17217. return levels[ i - 1 ].object;
  17218. }
  17219. return null;
  17220. }
  17221. raycast( raycaster, intersects ) {
  17222. const levels = this.levels;
  17223. if ( levels.length > 0 ) {
  17224. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17225. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17226. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17227. }
  17228. }
  17229. update( camera ) {
  17230. const levels = this.levels;
  17231. if ( levels.length > 1 ) {
  17232. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17233. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17234. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17235. levels[ 0 ].object.visible = true;
  17236. let i, l;
  17237. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17238. if ( distance >= levels[ i ].distance ) {
  17239. levels[ i - 1 ].object.visible = false;
  17240. levels[ i ].object.visible = true;
  17241. } else {
  17242. break;
  17243. }
  17244. }
  17245. this._currentLevel = i - 1;
  17246. for ( ; i < l; i ++ ) {
  17247. levels[ i ].object.visible = false;
  17248. }
  17249. }
  17250. }
  17251. toJSON( meta ) {
  17252. const data = super.toJSON( meta );
  17253. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17254. data.object.levels = [];
  17255. const levels = this.levels;
  17256. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17257. const level = levels[ i ];
  17258. data.object.levels.push( {
  17259. object: level.object.uuid,
  17260. distance: level.distance
  17261. } );
  17262. }
  17263. return data;
  17264. }
  17265. }
  17266. const _basePosition = /*@__PURE__*/ new Vector3();
  17267. const _skinIndex = /*@__PURE__*/ new Vector4();
  17268. const _skinWeight = /*@__PURE__*/ new Vector4();
  17269. const _vector$5 = /*@__PURE__*/ new Vector3();
  17270. const _matrix = /*@__PURE__*/ new Matrix4();
  17271. class SkinnedMesh extends Mesh {
  17272. constructor( geometry, material ) {
  17273. super( geometry, material );
  17274. this.type = 'SkinnedMesh';
  17275. this.bindMode = 'attached';
  17276. this.bindMatrix = new Matrix4();
  17277. this.bindMatrixInverse = new Matrix4();
  17278. }
  17279. copy( source ) {
  17280. super.copy( source );
  17281. this.bindMode = source.bindMode;
  17282. this.bindMatrix.copy( source.bindMatrix );
  17283. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17284. this.skeleton = source.skeleton;
  17285. return this;
  17286. }
  17287. bind( skeleton, bindMatrix ) {
  17288. this.skeleton = skeleton;
  17289. if ( bindMatrix === undefined ) {
  17290. this.updateMatrixWorld( true );
  17291. this.skeleton.calculateInverses();
  17292. bindMatrix = this.matrixWorld;
  17293. }
  17294. this.bindMatrix.copy( bindMatrix );
  17295. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17296. }
  17297. pose() {
  17298. this.skeleton.pose();
  17299. }
  17300. normalizeSkinWeights() {
  17301. const vector = new Vector4();
  17302. const skinWeight = this.geometry.attributes.skinWeight;
  17303. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17304. vector.x = skinWeight.getX( i );
  17305. vector.y = skinWeight.getY( i );
  17306. vector.z = skinWeight.getZ( i );
  17307. vector.w = skinWeight.getW( i );
  17308. const scale = 1.0 / vector.manhattanLength();
  17309. if ( scale !== Infinity ) {
  17310. vector.multiplyScalar( scale );
  17311. } else {
  17312. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17313. }
  17314. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17315. }
  17316. }
  17317. updateMatrixWorld( force ) {
  17318. super.updateMatrixWorld( force );
  17319. if ( this.bindMode === 'attached' ) {
  17320. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17321. } else if ( this.bindMode === 'detached' ) {
  17322. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17323. } else {
  17324. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17325. }
  17326. }
  17327. boneTransform( index, target ) {
  17328. const skeleton = this.skeleton;
  17329. const geometry = this.geometry;
  17330. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17331. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17332. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17333. target.set( 0, 0, 0 );
  17334. for ( let i = 0; i < 4; i ++ ) {
  17335. const weight = _skinWeight.getComponent( i );
  17336. if ( weight !== 0 ) {
  17337. const boneIndex = _skinIndex.getComponent( i );
  17338. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17339. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  17340. }
  17341. }
  17342. return target.applyMatrix4( this.bindMatrixInverse );
  17343. }
  17344. }
  17345. SkinnedMesh.prototype.isSkinnedMesh = true;
  17346. class Bone extends Object3D {
  17347. constructor() {
  17348. super();
  17349. this.type = 'Bone';
  17350. }
  17351. }
  17352. Bone.prototype.isBone = true;
  17353. class DataTexture extends Texture {
  17354. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  17355. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17356. this.image = { data: data, width: width, height: height };
  17357. this.magFilter = magFilter;
  17358. this.minFilter = minFilter;
  17359. this.generateMipmaps = false;
  17360. this.flipY = false;
  17361. this.unpackAlignment = 1;
  17362. }
  17363. }
  17364. DataTexture.prototype.isDataTexture = true;
  17365. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17366. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17367. class Skeleton {
  17368. constructor( bones = [], boneInverses = [] ) {
  17369. this.uuid = generateUUID();
  17370. this.bones = bones.slice( 0 );
  17371. this.boneInverses = boneInverses;
  17372. this.boneMatrices = null;
  17373. this.boneTexture = null;
  17374. this.boneTextureSize = 0;
  17375. this.frame = - 1;
  17376. this.init();
  17377. }
  17378. init() {
  17379. const bones = this.bones;
  17380. const boneInverses = this.boneInverses;
  17381. this.boneMatrices = new Float32Array( bones.length * 16 );
  17382. // calculate inverse bone matrices if necessary
  17383. if ( boneInverses.length === 0 ) {
  17384. this.calculateInverses();
  17385. } else {
  17386. // handle special case
  17387. if ( bones.length !== boneInverses.length ) {
  17388. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17389. this.boneInverses = [];
  17390. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17391. this.boneInverses.push( new Matrix4() );
  17392. }
  17393. }
  17394. }
  17395. }
  17396. calculateInverses() {
  17397. this.boneInverses.length = 0;
  17398. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17399. const inverse = new Matrix4();
  17400. if ( this.bones[ i ] ) {
  17401. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17402. }
  17403. this.boneInverses.push( inverse );
  17404. }
  17405. }
  17406. pose() {
  17407. // recover the bind-time world matrices
  17408. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17409. const bone = this.bones[ i ];
  17410. if ( bone ) {
  17411. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17412. }
  17413. }
  17414. // compute the local matrices, positions, rotations and scales
  17415. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17416. const bone = this.bones[ i ];
  17417. if ( bone ) {
  17418. if ( bone.parent && bone.parent.isBone ) {
  17419. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17420. bone.matrix.multiply( bone.matrixWorld );
  17421. } else {
  17422. bone.matrix.copy( bone.matrixWorld );
  17423. }
  17424. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17425. }
  17426. }
  17427. }
  17428. update() {
  17429. const bones = this.bones;
  17430. const boneInverses = this.boneInverses;
  17431. const boneMatrices = this.boneMatrices;
  17432. const boneTexture = this.boneTexture;
  17433. // flatten bone matrices to array
  17434. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17435. // compute the offset between the current and the original transform
  17436. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17437. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17438. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17439. }
  17440. if ( boneTexture !== null ) {
  17441. boneTexture.needsUpdate = true;
  17442. }
  17443. }
  17444. clone() {
  17445. return new Skeleton( this.bones, this.boneInverses );
  17446. }
  17447. computeBoneTexture() {
  17448. // layout (1 matrix = 4 pixels)
  17449. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17450. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17451. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17452. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17453. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17454. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17455. size = ceilPowerOfTwo( size );
  17456. size = Math.max( size, 4 );
  17457. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17458. boneMatrices.set( this.boneMatrices ); // copy current values
  17459. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17460. boneTexture.needsUpdate = true;
  17461. this.boneMatrices = boneMatrices;
  17462. this.boneTexture = boneTexture;
  17463. this.boneTextureSize = size;
  17464. return this;
  17465. }
  17466. getBoneByName( name ) {
  17467. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17468. const bone = this.bones[ i ];
  17469. if ( bone.name === name ) {
  17470. return bone;
  17471. }
  17472. }
  17473. return undefined;
  17474. }
  17475. dispose( ) {
  17476. if ( this.boneTexture !== null ) {
  17477. this.boneTexture.dispose();
  17478. this.boneTexture = null;
  17479. }
  17480. }
  17481. fromJSON( json, bones ) {
  17482. this.uuid = json.uuid;
  17483. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17484. const uuid = json.bones[ i ];
  17485. let bone = bones[ uuid ];
  17486. if ( bone === undefined ) {
  17487. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  17488. bone = new Bone();
  17489. }
  17490. this.bones.push( bone );
  17491. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17492. }
  17493. this.init();
  17494. return this;
  17495. }
  17496. toJSON() {
  17497. const data = {
  17498. metadata: {
  17499. version: 4.5,
  17500. type: 'Skeleton',
  17501. generator: 'Skeleton.toJSON'
  17502. },
  17503. bones: [],
  17504. boneInverses: []
  17505. };
  17506. data.uuid = this.uuid;
  17507. const bones = this.bones;
  17508. const boneInverses = this.boneInverses;
  17509. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17510. const bone = bones[ i ];
  17511. data.bones.push( bone.uuid );
  17512. const boneInverse = boneInverses[ i ];
  17513. data.boneInverses.push( boneInverse.toArray() );
  17514. }
  17515. return data;
  17516. }
  17517. }
  17518. class InstancedBufferAttribute extends BufferAttribute {
  17519. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17520. if ( typeof normalized === 'number' ) {
  17521. meshPerAttribute = normalized;
  17522. normalized = false;
  17523. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  17524. }
  17525. super( array, itemSize, normalized );
  17526. this.meshPerAttribute = meshPerAttribute;
  17527. }
  17528. copy( source ) {
  17529. super.copy( source );
  17530. this.meshPerAttribute = source.meshPerAttribute;
  17531. return this;
  17532. }
  17533. toJSON() {
  17534. const data = super.toJSON();
  17535. data.meshPerAttribute = this.meshPerAttribute;
  17536. data.isInstancedBufferAttribute = true;
  17537. return data;
  17538. }
  17539. }
  17540. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17541. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17542. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17543. const _instanceIntersects = [];
  17544. const _mesh = /*@__PURE__*/ new Mesh();
  17545. class InstancedMesh extends Mesh {
  17546. constructor( geometry, material, count ) {
  17547. super( geometry, material );
  17548. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17549. this.instanceColor = null;
  17550. this.count = count;
  17551. this.frustumCulled = false;
  17552. }
  17553. copy( source ) {
  17554. super.copy( source );
  17555. this.instanceMatrix.copy( source.instanceMatrix );
  17556. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17557. this.count = source.count;
  17558. return this;
  17559. }
  17560. getColorAt( index, color ) {
  17561. color.fromArray( this.instanceColor.array, index * 3 );
  17562. }
  17563. getMatrixAt( index, matrix ) {
  17564. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17565. }
  17566. raycast( raycaster, intersects ) {
  17567. const matrixWorld = this.matrixWorld;
  17568. const raycastTimes = this.count;
  17569. _mesh.geometry = this.geometry;
  17570. _mesh.material = this.material;
  17571. if ( _mesh.material === undefined ) return;
  17572. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  17573. // calculate the world matrix for each instance
  17574. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  17575. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  17576. // the mesh represents this single instance
  17577. _mesh.matrixWorld = _instanceWorldMatrix;
  17578. _mesh.raycast( raycaster, _instanceIntersects );
  17579. // process the result of raycast
  17580. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  17581. const intersect = _instanceIntersects[ i ];
  17582. intersect.instanceId = instanceId;
  17583. intersect.object = this;
  17584. intersects.push( intersect );
  17585. }
  17586. _instanceIntersects.length = 0;
  17587. }
  17588. }
  17589. setColorAt( index, color ) {
  17590. if ( this.instanceColor === null ) {
  17591. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  17592. }
  17593. color.toArray( this.instanceColor.array, index * 3 );
  17594. }
  17595. setMatrixAt( index, matrix ) {
  17596. matrix.toArray( this.instanceMatrix.array, index * 16 );
  17597. }
  17598. updateMorphTargets() {
  17599. }
  17600. dispose() {
  17601. this.dispatchEvent( { type: 'dispose' } );
  17602. }
  17603. }
  17604. InstancedMesh.prototype.isInstancedMesh = true;
  17605. /**
  17606. * parameters = {
  17607. * color: <hex>,
  17608. * opacity: <float>,
  17609. *
  17610. * linewidth: <float>,
  17611. * linecap: "round",
  17612. * linejoin: "round"
  17613. * }
  17614. */
  17615. class LineBasicMaterial extends Material {
  17616. constructor( parameters ) {
  17617. super();
  17618. this.type = 'LineBasicMaterial';
  17619. this.color = new Color( 0xffffff );
  17620. this.linewidth = 1;
  17621. this.linecap = 'round';
  17622. this.linejoin = 'round';
  17623. this.setValues( parameters );
  17624. }
  17625. copy( source ) {
  17626. super.copy( source );
  17627. this.color.copy( source.color );
  17628. this.linewidth = source.linewidth;
  17629. this.linecap = source.linecap;
  17630. this.linejoin = source.linejoin;
  17631. return this;
  17632. }
  17633. }
  17634. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17635. const _start$1 = /*@__PURE__*/ new Vector3();
  17636. const _end$1 = /*@__PURE__*/ new Vector3();
  17637. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  17638. const _ray$1 = /*@__PURE__*/ new Ray();
  17639. const _sphere$1 = /*@__PURE__*/ new Sphere();
  17640. class Line extends Object3D {
  17641. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  17642. super();
  17643. this.type = 'Line';
  17644. this.geometry = geometry;
  17645. this.material = material;
  17646. this.updateMorphTargets();
  17647. }
  17648. copy( source ) {
  17649. super.copy( source );
  17650. this.material = source.material;
  17651. this.geometry = source.geometry;
  17652. return this;
  17653. }
  17654. computeLineDistances() {
  17655. const geometry = this.geometry;
  17656. if ( geometry.isBufferGeometry ) {
  17657. // we assume non-indexed geometry
  17658. if ( geometry.index === null ) {
  17659. const positionAttribute = geometry.attributes.position;
  17660. const lineDistances = [ 0 ];
  17661. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  17662. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  17663. _end$1.fromBufferAttribute( positionAttribute, i );
  17664. lineDistances[ i ] = lineDistances[ i - 1 ];
  17665. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  17666. }
  17667. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17668. } else {
  17669. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17670. }
  17671. } else if ( geometry.isGeometry ) {
  17672. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17673. }
  17674. return this;
  17675. }
  17676. raycast( raycaster, intersects ) {
  17677. const geometry = this.geometry;
  17678. const matrixWorld = this.matrixWorld;
  17679. const threshold = raycaster.params.Line.threshold;
  17680. const drawRange = geometry.drawRange;
  17681. // Checking boundingSphere distance to ray
  17682. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17683. _sphere$1.copy( geometry.boundingSphere );
  17684. _sphere$1.applyMatrix4( matrixWorld );
  17685. _sphere$1.radius += threshold;
  17686. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  17687. //
  17688. _inverseMatrix$1.copy( matrixWorld ).invert();
  17689. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  17690. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17691. const localThresholdSq = localThreshold * localThreshold;
  17692. const vStart = new Vector3();
  17693. const vEnd = new Vector3();
  17694. const interSegment = new Vector3();
  17695. const interRay = new Vector3();
  17696. const step = this.isLineSegments ? 2 : 1;
  17697. if ( geometry.isBufferGeometry ) {
  17698. const index = geometry.index;
  17699. const attributes = geometry.attributes;
  17700. const positionAttribute = attributes.position;
  17701. if ( index !== null ) {
  17702. const start = Math.max( 0, drawRange.start );
  17703. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17704. for ( let i = start, l = end - 1; i < l; i += step ) {
  17705. const a = index.getX( i );
  17706. const b = index.getX( i + 1 );
  17707. vStart.fromBufferAttribute( positionAttribute, a );
  17708. vEnd.fromBufferAttribute( positionAttribute, b );
  17709. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17710. if ( distSq > localThresholdSq ) continue;
  17711. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17712. const distance = raycaster.ray.origin.distanceTo( interRay );
  17713. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17714. intersects.push( {
  17715. distance: distance,
  17716. // What do we want? intersection point on the ray or on the segment??
  17717. // point: raycaster.ray.at( distance ),
  17718. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17719. index: i,
  17720. face: null,
  17721. faceIndex: null,
  17722. object: this
  17723. } );
  17724. }
  17725. } else {
  17726. const start = Math.max( 0, drawRange.start );
  17727. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17728. for ( let i = start, l = end - 1; i < l; i += step ) {
  17729. vStart.fromBufferAttribute( positionAttribute, i );
  17730. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  17731. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17732. if ( distSq > localThresholdSq ) continue;
  17733. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17734. const distance = raycaster.ray.origin.distanceTo( interRay );
  17735. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17736. intersects.push( {
  17737. distance: distance,
  17738. // What do we want? intersection point on the ray or on the segment??
  17739. // point: raycaster.ray.at( distance ),
  17740. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17741. index: i,
  17742. face: null,
  17743. faceIndex: null,
  17744. object: this
  17745. } );
  17746. }
  17747. }
  17748. } else if ( geometry.isGeometry ) {
  17749. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17750. }
  17751. }
  17752. updateMorphTargets() {
  17753. const geometry = this.geometry;
  17754. if ( geometry.isBufferGeometry ) {
  17755. const morphAttributes = geometry.morphAttributes;
  17756. const keys = Object.keys( morphAttributes );
  17757. if ( keys.length > 0 ) {
  17758. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17759. if ( morphAttribute !== undefined ) {
  17760. this.morphTargetInfluences = [];
  17761. this.morphTargetDictionary = {};
  17762. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17763. const name = morphAttribute[ m ].name || String( m );
  17764. this.morphTargetInfluences.push( 0 );
  17765. this.morphTargetDictionary[ name ] = m;
  17766. }
  17767. }
  17768. }
  17769. } else {
  17770. const morphTargets = geometry.morphTargets;
  17771. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17772. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17773. }
  17774. }
  17775. }
  17776. }
  17777. Line.prototype.isLine = true;
  17778. const _start = /*@__PURE__*/ new Vector3();
  17779. const _end = /*@__PURE__*/ new Vector3();
  17780. class LineSegments extends Line {
  17781. constructor( geometry, material ) {
  17782. super( geometry, material );
  17783. this.type = 'LineSegments';
  17784. }
  17785. computeLineDistances() {
  17786. const geometry = this.geometry;
  17787. if ( geometry.isBufferGeometry ) {
  17788. // we assume non-indexed geometry
  17789. if ( geometry.index === null ) {
  17790. const positionAttribute = geometry.attributes.position;
  17791. const lineDistances = [];
  17792. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17793. _start.fromBufferAttribute( positionAttribute, i );
  17794. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17795. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17796. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17797. }
  17798. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17799. } else {
  17800. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17801. }
  17802. } else if ( geometry.isGeometry ) {
  17803. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17804. }
  17805. return this;
  17806. }
  17807. }
  17808. LineSegments.prototype.isLineSegments = true;
  17809. class LineLoop extends Line {
  17810. constructor( geometry, material ) {
  17811. super( geometry, material );
  17812. this.type = 'LineLoop';
  17813. }
  17814. }
  17815. LineLoop.prototype.isLineLoop = true;
  17816. /**
  17817. * parameters = {
  17818. * color: <hex>,
  17819. * opacity: <float>,
  17820. * map: new THREE.Texture( <Image> ),
  17821. * alphaMap: new THREE.Texture( <Image> ),
  17822. *
  17823. * size: <float>,
  17824. * sizeAttenuation: <bool>
  17825. *
  17826. * }
  17827. */
  17828. class PointsMaterial extends Material {
  17829. constructor( parameters ) {
  17830. super();
  17831. this.type = 'PointsMaterial';
  17832. this.color = new Color( 0xffffff );
  17833. this.map = null;
  17834. this.alphaMap = null;
  17835. this.size = 1;
  17836. this.sizeAttenuation = true;
  17837. this.setValues( parameters );
  17838. }
  17839. copy( source ) {
  17840. super.copy( source );
  17841. this.color.copy( source.color );
  17842. this.map = source.map;
  17843. this.alphaMap = source.alphaMap;
  17844. this.size = source.size;
  17845. this.sizeAttenuation = source.sizeAttenuation;
  17846. return this;
  17847. }
  17848. }
  17849. PointsMaterial.prototype.isPointsMaterial = true;
  17850. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17851. const _ray = /*@__PURE__*/ new Ray();
  17852. const _sphere = /*@__PURE__*/ new Sphere();
  17853. const _position$2 = /*@__PURE__*/ new Vector3();
  17854. class Points extends Object3D {
  17855. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17856. super();
  17857. this.type = 'Points';
  17858. this.geometry = geometry;
  17859. this.material = material;
  17860. this.updateMorphTargets();
  17861. }
  17862. copy( source ) {
  17863. super.copy( source );
  17864. this.material = source.material;
  17865. this.geometry = source.geometry;
  17866. return this;
  17867. }
  17868. raycast( raycaster, intersects ) {
  17869. const geometry = this.geometry;
  17870. const matrixWorld = this.matrixWorld;
  17871. const threshold = raycaster.params.Points.threshold;
  17872. const drawRange = geometry.drawRange;
  17873. // Checking boundingSphere distance to ray
  17874. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17875. _sphere.copy( geometry.boundingSphere );
  17876. _sphere.applyMatrix4( matrixWorld );
  17877. _sphere.radius += threshold;
  17878. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17879. //
  17880. _inverseMatrix.copy( matrixWorld ).invert();
  17881. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17882. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17883. const localThresholdSq = localThreshold * localThreshold;
  17884. if ( geometry.isBufferGeometry ) {
  17885. const index = geometry.index;
  17886. const attributes = geometry.attributes;
  17887. const positionAttribute = attributes.position;
  17888. if ( index !== null ) {
  17889. const start = Math.max( 0, drawRange.start );
  17890. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17891. for ( let i = start, il = end; i < il; i ++ ) {
  17892. const a = index.getX( i );
  17893. _position$2.fromBufferAttribute( positionAttribute, a );
  17894. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17895. }
  17896. } else {
  17897. const start = Math.max( 0, drawRange.start );
  17898. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17899. for ( let i = start, l = end; i < l; i ++ ) {
  17900. _position$2.fromBufferAttribute( positionAttribute, i );
  17901. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17902. }
  17903. }
  17904. } else {
  17905. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17906. }
  17907. }
  17908. updateMorphTargets() {
  17909. const geometry = this.geometry;
  17910. if ( geometry.isBufferGeometry ) {
  17911. const morphAttributes = geometry.morphAttributes;
  17912. const keys = Object.keys( morphAttributes );
  17913. if ( keys.length > 0 ) {
  17914. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17915. if ( morphAttribute !== undefined ) {
  17916. this.morphTargetInfluences = [];
  17917. this.morphTargetDictionary = {};
  17918. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17919. const name = morphAttribute[ m ].name || String( m );
  17920. this.morphTargetInfluences.push( 0 );
  17921. this.morphTargetDictionary[ name ] = m;
  17922. }
  17923. }
  17924. }
  17925. } else {
  17926. const morphTargets = geometry.morphTargets;
  17927. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17928. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17929. }
  17930. }
  17931. }
  17932. }
  17933. Points.prototype.isPoints = true;
  17934. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17935. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17936. if ( rayPointDistanceSq < localThresholdSq ) {
  17937. const intersectPoint = new Vector3();
  17938. _ray.closestPointToPoint( point, intersectPoint );
  17939. intersectPoint.applyMatrix4( matrixWorld );
  17940. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17941. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17942. intersects.push( {
  17943. distance: distance,
  17944. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17945. point: intersectPoint,
  17946. index: index,
  17947. face: null,
  17948. object: object
  17949. } );
  17950. }
  17951. }
  17952. class VideoTexture extends Texture {
  17953. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17954. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17955. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17956. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17957. this.generateMipmaps = false;
  17958. const scope = this;
  17959. function updateVideo() {
  17960. scope.needsUpdate = true;
  17961. video.requestVideoFrameCallback( updateVideo );
  17962. }
  17963. if ( 'requestVideoFrameCallback' in video ) {
  17964. video.requestVideoFrameCallback( updateVideo );
  17965. }
  17966. }
  17967. clone() {
  17968. return new this.constructor( this.image ).copy( this );
  17969. }
  17970. update() {
  17971. const video = this.image;
  17972. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  17973. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  17974. this.needsUpdate = true;
  17975. }
  17976. }
  17977. }
  17978. VideoTexture.prototype.isVideoTexture = true;
  17979. class FramebufferTexture extends Texture {
  17980. constructor( width, height, format ) {
  17981. super( { width, height } );
  17982. this.format = format;
  17983. this.magFilter = NearestFilter;
  17984. this.minFilter = NearestFilter;
  17985. this.generateMipmaps = false;
  17986. this.needsUpdate = true;
  17987. }
  17988. }
  17989. FramebufferTexture.prototype.isFramebufferTexture = true;
  17990. class CompressedTexture extends Texture {
  17991. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  17992. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17993. this.image = { width: width, height: height };
  17994. this.mipmaps = mipmaps;
  17995. // no flipping for cube textures
  17996. // (also flipping doesn't work for compressed textures )
  17997. this.flipY = false;
  17998. // can't generate mipmaps for compressed textures
  17999. // mips must be embedded in DDS files
  18000. this.generateMipmaps = false;
  18001. }
  18002. }
  18003. CompressedTexture.prototype.isCompressedTexture = true;
  18004. class CanvasTexture extends Texture {
  18005. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18006. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18007. this.needsUpdate = true;
  18008. }
  18009. }
  18010. CanvasTexture.prototype.isCanvasTexture = true;
  18011. class CircleGeometry extends BufferGeometry {
  18012. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18013. super();
  18014. this.type = 'CircleGeometry';
  18015. this.parameters = {
  18016. radius: radius,
  18017. segments: segments,
  18018. thetaStart: thetaStart,
  18019. thetaLength: thetaLength
  18020. };
  18021. segments = Math.max( 3, segments );
  18022. // buffers
  18023. const indices = [];
  18024. const vertices = [];
  18025. const normals = [];
  18026. const uvs = [];
  18027. // helper variables
  18028. const vertex = new Vector3();
  18029. const uv = new Vector2();
  18030. // center point
  18031. vertices.push( 0, 0, 0 );
  18032. normals.push( 0, 0, 1 );
  18033. uvs.push( 0.5, 0.5 );
  18034. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  18035. const segment = thetaStart + s / segments * thetaLength;
  18036. // vertex
  18037. vertex.x = radius * Math.cos( segment );
  18038. vertex.y = radius * Math.sin( segment );
  18039. vertices.push( vertex.x, vertex.y, vertex.z );
  18040. // normal
  18041. normals.push( 0, 0, 1 );
  18042. // uvs
  18043. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  18044. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  18045. uvs.push( uv.x, uv.y );
  18046. }
  18047. // indices
  18048. for ( let i = 1; i <= segments; i ++ ) {
  18049. indices.push( i, i + 1, 0 );
  18050. }
  18051. // build geometry
  18052. this.setIndex( indices );
  18053. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18054. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18055. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18056. }
  18057. static fromJSON( data ) {
  18058. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  18059. }
  18060. }
  18061. class CylinderGeometry extends BufferGeometry {
  18062. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18063. super();
  18064. this.type = 'CylinderGeometry';
  18065. this.parameters = {
  18066. radiusTop: radiusTop,
  18067. radiusBottom: radiusBottom,
  18068. height: height,
  18069. radialSegments: radialSegments,
  18070. heightSegments: heightSegments,
  18071. openEnded: openEnded,
  18072. thetaStart: thetaStart,
  18073. thetaLength: thetaLength
  18074. };
  18075. const scope = this;
  18076. radialSegments = Math.floor( radialSegments );
  18077. heightSegments = Math.floor( heightSegments );
  18078. // buffers
  18079. const indices = [];
  18080. const vertices = [];
  18081. const normals = [];
  18082. const uvs = [];
  18083. // helper variables
  18084. let index = 0;
  18085. const indexArray = [];
  18086. const halfHeight = height / 2;
  18087. let groupStart = 0;
  18088. // generate geometry
  18089. generateTorso();
  18090. if ( openEnded === false ) {
  18091. if ( radiusTop > 0 ) generateCap( true );
  18092. if ( radiusBottom > 0 ) generateCap( false );
  18093. }
  18094. // build geometry
  18095. this.setIndex( indices );
  18096. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18097. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18098. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18099. function generateTorso() {
  18100. const normal = new Vector3();
  18101. const vertex = new Vector3();
  18102. let groupCount = 0;
  18103. // this will be used to calculate the normal
  18104. const slope = ( radiusBottom - radiusTop ) / height;
  18105. // generate vertices, normals and uvs
  18106. for ( let y = 0; y <= heightSegments; y ++ ) {
  18107. const indexRow = [];
  18108. const v = y / heightSegments;
  18109. // calculate the radius of the current row
  18110. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18111. for ( let x = 0; x <= radialSegments; x ++ ) {
  18112. const u = x / radialSegments;
  18113. const theta = u * thetaLength + thetaStart;
  18114. const sinTheta = Math.sin( theta );
  18115. const cosTheta = Math.cos( theta );
  18116. // vertex
  18117. vertex.x = radius * sinTheta;
  18118. vertex.y = - v * height + halfHeight;
  18119. vertex.z = radius * cosTheta;
  18120. vertices.push( vertex.x, vertex.y, vertex.z );
  18121. // normal
  18122. normal.set( sinTheta, slope, cosTheta ).normalize();
  18123. normals.push( normal.x, normal.y, normal.z );
  18124. // uv
  18125. uvs.push( u, 1 - v );
  18126. // save index of vertex in respective row
  18127. indexRow.push( index ++ );
  18128. }
  18129. // now save vertices of the row in our index array
  18130. indexArray.push( indexRow );
  18131. }
  18132. // generate indices
  18133. for ( let x = 0; x < radialSegments; x ++ ) {
  18134. for ( let y = 0; y < heightSegments; y ++ ) {
  18135. // we use the index array to access the correct indices
  18136. const a = indexArray[ y ][ x ];
  18137. const b = indexArray[ y + 1 ][ x ];
  18138. const c = indexArray[ y + 1 ][ x + 1 ];
  18139. const d = indexArray[ y ][ x + 1 ];
  18140. // faces
  18141. indices.push( a, b, d );
  18142. indices.push( b, c, d );
  18143. // update group counter
  18144. groupCount += 6;
  18145. }
  18146. }
  18147. // add a group to the geometry. this will ensure multi material support
  18148. scope.addGroup( groupStart, groupCount, 0 );
  18149. // calculate new start value for groups
  18150. groupStart += groupCount;
  18151. }
  18152. function generateCap( top ) {
  18153. // save the index of the first center vertex
  18154. const centerIndexStart = index;
  18155. const uv = new Vector2();
  18156. const vertex = new Vector3();
  18157. let groupCount = 0;
  18158. const radius = ( top === true ) ? radiusTop : radiusBottom;
  18159. const sign = ( top === true ) ? 1 : - 1;
  18160. // first we generate the center vertex data of the cap.
  18161. // because the geometry needs one set of uvs per face,
  18162. // we must generate a center vertex per face/segment
  18163. for ( let x = 1; x <= radialSegments; x ++ ) {
  18164. // vertex
  18165. vertices.push( 0, halfHeight * sign, 0 );
  18166. // normal
  18167. normals.push( 0, sign, 0 );
  18168. // uv
  18169. uvs.push( 0.5, 0.5 );
  18170. // increase index
  18171. index ++;
  18172. }
  18173. // save the index of the last center vertex
  18174. const centerIndexEnd = index;
  18175. // now we generate the surrounding vertices, normals and uvs
  18176. for ( let x = 0; x <= radialSegments; x ++ ) {
  18177. const u = x / radialSegments;
  18178. const theta = u * thetaLength + thetaStart;
  18179. const cosTheta = Math.cos( theta );
  18180. const sinTheta = Math.sin( theta );
  18181. // vertex
  18182. vertex.x = radius * sinTheta;
  18183. vertex.y = halfHeight * sign;
  18184. vertex.z = radius * cosTheta;
  18185. vertices.push( vertex.x, vertex.y, vertex.z );
  18186. // normal
  18187. normals.push( 0, sign, 0 );
  18188. // uv
  18189. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18190. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18191. uvs.push( uv.x, uv.y );
  18192. // increase index
  18193. index ++;
  18194. }
  18195. // generate indices
  18196. for ( let x = 0; x < radialSegments; x ++ ) {
  18197. const c = centerIndexStart + x;
  18198. const i = centerIndexEnd + x;
  18199. if ( top === true ) {
  18200. // face top
  18201. indices.push( i, i + 1, c );
  18202. } else {
  18203. // face bottom
  18204. indices.push( i + 1, i, c );
  18205. }
  18206. groupCount += 3;
  18207. }
  18208. // add a group to the geometry. this will ensure multi material support
  18209. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18210. // calculate new start value for groups
  18211. groupStart += groupCount;
  18212. }
  18213. }
  18214. static fromJSON( data ) {
  18215. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18216. }
  18217. }
  18218. class ConeGeometry extends CylinderGeometry {
  18219. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18220. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18221. this.type = 'ConeGeometry';
  18222. this.parameters = {
  18223. radius: radius,
  18224. height: height,
  18225. radialSegments: radialSegments,
  18226. heightSegments: heightSegments,
  18227. openEnded: openEnded,
  18228. thetaStart: thetaStart,
  18229. thetaLength: thetaLength
  18230. };
  18231. }
  18232. static fromJSON( data ) {
  18233. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18234. }
  18235. }
  18236. class PolyhedronGeometry extends BufferGeometry {
  18237. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  18238. super();
  18239. this.type = 'PolyhedronGeometry';
  18240. this.parameters = {
  18241. vertices: vertices,
  18242. indices: indices,
  18243. radius: radius,
  18244. detail: detail
  18245. };
  18246. // default buffer data
  18247. const vertexBuffer = [];
  18248. const uvBuffer = [];
  18249. // the subdivision creates the vertex buffer data
  18250. subdivide( detail );
  18251. // all vertices should lie on a conceptual sphere with a given radius
  18252. applyRadius( radius );
  18253. // finally, create the uv data
  18254. generateUVs();
  18255. // build non-indexed geometry
  18256. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18257. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18258. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18259. if ( detail === 0 ) {
  18260. this.computeVertexNormals(); // flat normals
  18261. } else {
  18262. this.normalizeNormals(); // smooth normals
  18263. }
  18264. // helper functions
  18265. function subdivide( detail ) {
  18266. const a = new Vector3();
  18267. const b = new Vector3();
  18268. const c = new Vector3();
  18269. // iterate over all faces and apply a subdivison with the given detail value
  18270. for ( let i = 0; i < indices.length; i += 3 ) {
  18271. // get the vertices of the face
  18272. getVertexByIndex( indices[ i + 0 ], a );
  18273. getVertexByIndex( indices[ i + 1 ], b );
  18274. getVertexByIndex( indices[ i + 2 ], c );
  18275. // perform subdivision
  18276. subdivideFace( a, b, c, detail );
  18277. }
  18278. }
  18279. function subdivideFace( a, b, c, detail ) {
  18280. const cols = detail + 1;
  18281. // we use this multidimensional array as a data structure for creating the subdivision
  18282. const v = [];
  18283. // construct all of the vertices for this subdivision
  18284. for ( let i = 0; i <= cols; i ++ ) {
  18285. v[ i ] = [];
  18286. const aj = a.clone().lerp( c, i / cols );
  18287. const bj = b.clone().lerp( c, i / cols );
  18288. const rows = cols - i;
  18289. for ( let j = 0; j <= rows; j ++ ) {
  18290. if ( j === 0 && i === cols ) {
  18291. v[ i ][ j ] = aj;
  18292. } else {
  18293. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18294. }
  18295. }
  18296. }
  18297. // construct all of the faces
  18298. for ( let i = 0; i < cols; i ++ ) {
  18299. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18300. const k = Math.floor( j / 2 );
  18301. if ( j % 2 === 0 ) {
  18302. pushVertex( v[ i ][ k + 1 ] );
  18303. pushVertex( v[ i + 1 ][ k ] );
  18304. pushVertex( v[ i ][ k ] );
  18305. } else {
  18306. pushVertex( v[ i ][ k + 1 ] );
  18307. pushVertex( v[ i + 1 ][ k + 1 ] );
  18308. pushVertex( v[ i + 1 ][ k ] );
  18309. }
  18310. }
  18311. }
  18312. }
  18313. function applyRadius( radius ) {
  18314. const vertex = new Vector3();
  18315. // iterate over the entire buffer and apply the radius to each vertex
  18316. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18317. vertex.x = vertexBuffer[ i + 0 ];
  18318. vertex.y = vertexBuffer[ i + 1 ];
  18319. vertex.z = vertexBuffer[ i + 2 ];
  18320. vertex.normalize().multiplyScalar( radius );
  18321. vertexBuffer[ i + 0 ] = vertex.x;
  18322. vertexBuffer[ i + 1 ] = vertex.y;
  18323. vertexBuffer[ i + 2 ] = vertex.z;
  18324. }
  18325. }
  18326. function generateUVs() {
  18327. const vertex = new Vector3();
  18328. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18329. vertex.x = vertexBuffer[ i + 0 ];
  18330. vertex.y = vertexBuffer[ i + 1 ];
  18331. vertex.z = vertexBuffer[ i + 2 ];
  18332. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18333. const v = inclination( vertex ) / Math.PI + 0.5;
  18334. uvBuffer.push( u, 1 - v );
  18335. }
  18336. correctUVs();
  18337. correctSeam();
  18338. }
  18339. function correctSeam() {
  18340. // handle case when face straddles the seam, see #3269
  18341. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18342. // uv data of a single face
  18343. const x0 = uvBuffer[ i + 0 ];
  18344. const x1 = uvBuffer[ i + 2 ];
  18345. const x2 = uvBuffer[ i + 4 ];
  18346. const max = Math.max( x0, x1, x2 );
  18347. const min = Math.min( x0, x1, x2 );
  18348. // 0.9 is somewhat arbitrary
  18349. if ( max > 0.9 && min < 0.1 ) {
  18350. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18351. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18352. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18353. }
  18354. }
  18355. }
  18356. function pushVertex( vertex ) {
  18357. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18358. }
  18359. function getVertexByIndex( index, vertex ) {
  18360. const stride = index * 3;
  18361. vertex.x = vertices[ stride + 0 ];
  18362. vertex.y = vertices[ stride + 1 ];
  18363. vertex.z = vertices[ stride + 2 ];
  18364. }
  18365. function correctUVs() {
  18366. const a = new Vector3();
  18367. const b = new Vector3();
  18368. const c = new Vector3();
  18369. const centroid = new Vector3();
  18370. const uvA = new Vector2();
  18371. const uvB = new Vector2();
  18372. const uvC = new Vector2();
  18373. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18374. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18375. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18376. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18377. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18378. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18379. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18380. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18381. const azi = azimuth( centroid );
  18382. correctUV( uvA, j + 0, a, azi );
  18383. correctUV( uvB, j + 2, b, azi );
  18384. correctUV( uvC, j + 4, c, azi );
  18385. }
  18386. }
  18387. function correctUV( uv, stride, vector, azimuth ) {
  18388. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18389. uvBuffer[ stride ] = uv.x - 1;
  18390. }
  18391. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18392. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18393. }
  18394. }
  18395. // Angle around the Y axis, counter-clockwise when looking from above.
  18396. function azimuth( vector ) {
  18397. return Math.atan2( vector.z, - vector.x );
  18398. }
  18399. // Angle above the XZ plane.
  18400. function inclination( vector ) {
  18401. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18402. }
  18403. }
  18404. static fromJSON( data ) {
  18405. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  18406. }
  18407. }
  18408. class DodecahedronGeometry extends PolyhedronGeometry {
  18409. constructor( radius = 1, detail = 0 ) {
  18410. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18411. const r = 1 / t;
  18412. const vertices = [
  18413. // (±1, ±1, ±1)
  18414. - 1, - 1, - 1, - 1, - 1, 1,
  18415. - 1, 1, - 1, - 1, 1, 1,
  18416. 1, - 1, - 1, 1, - 1, 1,
  18417. 1, 1, - 1, 1, 1, 1,
  18418. // (0, ±1/φ, ±φ)
  18419. 0, - r, - t, 0, - r, t,
  18420. 0, r, - t, 0, r, t,
  18421. // (±1/φ, ±φ, 0)
  18422. - r, - t, 0, - r, t, 0,
  18423. r, - t, 0, r, t, 0,
  18424. // (±φ, 0, ±1/φ)
  18425. - t, 0, - r, t, 0, - r,
  18426. - t, 0, r, t, 0, r
  18427. ];
  18428. const indices = [
  18429. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18430. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18431. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18432. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18433. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18434. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18435. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18436. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18437. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18438. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18439. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18440. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18441. ];
  18442. super( vertices, indices, radius, detail );
  18443. this.type = 'DodecahedronGeometry';
  18444. this.parameters = {
  18445. radius: radius,
  18446. detail: detail
  18447. };
  18448. }
  18449. static fromJSON( data ) {
  18450. return new DodecahedronGeometry( data.radius, data.detail );
  18451. }
  18452. }
  18453. const _v0 = new Vector3();
  18454. const _v1$1 = new Vector3();
  18455. const _normal = new Vector3();
  18456. const _triangle = new Triangle();
  18457. class EdgesGeometry extends BufferGeometry {
  18458. constructor( geometry = null, thresholdAngle = 1 ) {
  18459. super();
  18460. this.type = 'EdgesGeometry';
  18461. this.parameters = {
  18462. geometry: geometry,
  18463. thresholdAngle: thresholdAngle
  18464. };
  18465. if ( geometry !== null ) {
  18466. const precisionPoints = 4;
  18467. const precision = Math.pow( 10, precisionPoints );
  18468. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  18469. const indexAttr = geometry.getIndex();
  18470. const positionAttr = geometry.getAttribute( 'position' );
  18471. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18472. const indexArr = [ 0, 0, 0 ];
  18473. const vertKeys = [ 'a', 'b', 'c' ];
  18474. const hashes = new Array( 3 );
  18475. const edgeData = {};
  18476. const vertices = [];
  18477. for ( let i = 0; i < indexCount; i += 3 ) {
  18478. if ( indexAttr ) {
  18479. indexArr[ 0 ] = indexAttr.getX( i );
  18480. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18481. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18482. } else {
  18483. indexArr[ 0 ] = i;
  18484. indexArr[ 1 ] = i + 1;
  18485. indexArr[ 2 ] = i + 2;
  18486. }
  18487. const { a, b, c } = _triangle;
  18488. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18489. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18490. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18491. _triangle.getNormal( _normal );
  18492. // create hashes for the edge from the vertices
  18493. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18494. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18495. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18496. // skip degenerate triangles
  18497. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18498. continue;
  18499. }
  18500. // iterate over every edge
  18501. for ( let j = 0; j < 3; j ++ ) {
  18502. // get the first and next vertex making up the edge
  18503. const jNext = ( j + 1 ) % 3;
  18504. const vecHash0 = hashes[ j ];
  18505. const vecHash1 = hashes[ jNext ];
  18506. const v0 = _triangle[ vertKeys[ j ] ];
  18507. const v1 = _triangle[ vertKeys[ jNext ] ];
  18508. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18509. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18510. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18511. // if we found a sibling edge add it into the vertex array if
  18512. // it meets the angle threshold and delete the edge from the map.
  18513. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18514. vertices.push( v0.x, v0.y, v0.z );
  18515. vertices.push( v1.x, v1.y, v1.z );
  18516. }
  18517. edgeData[ reverseHash ] = null;
  18518. } else if ( ! ( hash in edgeData ) ) {
  18519. // if we've already got an edge here then skip adding a new one
  18520. edgeData[ hash ] = {
  18521. index0: indexArr[ j ],
  18522. index1: indexArr[ jNext ],
  18523. normal: _normal.clone(),
  18524. };
  18525. }
  18526. }
  18527. }
  18528. // iterate over all remaining, unmatched edges and add them to the vertex array
  18529. for ( const key in edgeData ) {
  18530. if ( edgeData[ key ] ) {
  18531. const { index0, index1 } = edgeData[ key ];
  18532. _v0.fromBufferAttribute( positionAttr, index0 );
  18533. _v1$1.fromBufferAttribute( positionAttr, index1 );
  18534. vertices.push( _v0.x, _v0.y, _v0.z );
  18535. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  18536. }
  18537. }
  18538. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18539. }
  18540. }
  18541. }
  18542. /**
  18543. * Extensible curve object.
  18544. *
  18545. * Some common of curve methods:
  18546. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18547. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18548. * .getPoints(), .getSpacedPoints()
  18549. * .getLength()
  18550. * .updateArcLengths()
  18551. *
  18552. * This following curves inherit from THREE.Curve:
  18553. *
  18554. * -- 2D curves --
  18555. * THREE.ArcCurve
  18556. * THREE.CubicBezierCurve
  18557. * THREE.EllipseCurve
  18558. * THREE.LineCurve
  18559. * THREE.QuadraticBezierCurve
  18560. * THREE.SplineCurve
  18561. *
  18562. * -- 3D curves --
  18563. * THREE.CatmullRomCurve3
  18564. * THREE.CubicBezierCurve3
  18565. * THREE.LineCurve3
  18566. * THREE.QuadraticBezierCurve3
  18567. *
  18568. * A series of curves can be represented as a THREE.CurvePath.
  18569. *
  18570. **/
  18571. class Curve {
  18572. constructor() {
  18573. this.type = 'Curve';
  18574. this.arcLengthDivisions = 200;
  18575. }
  18576. // Virtual base class method to overwrite and implement in subclasses
  18577. // - t [0 .. 1]
  18578. getPoint( /* t, optionalTarget */ ) {
  18579. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18580. return null;
  18581. }
  18582. // Get point at relative position in curve according to arc length
  18583. // - u [0 .. 1]
  18584. getPointAt( u, optionalTarget ) {
  18585. const t = this.getUtoTmapping( u );
  18586. return this.getPoint( t, optionalTarget );
  18587. }
  18588. // Get sequence of points using getPoint( t )
  18589. getPoints( divisions = 5 ) {
  18590. const points = [];
  18591. for ( let d = 0; d <= divisions; d ++ ) {
  18592. points.push( this.getPoint( d / divisions ) );
  18593. }
  18594. return points;
  18595. }
  18596. // Get sequence of points using getPointAt( u )
  18597. getSpacedPoints( divisions = 5 ) {
  18598. const points = [];
  18599. for ( let d = 0; d <= divisions; d ++ ) {
  18600. points.push( this.getPointAt( d / divisions ) );
  18601. }
  18602. return points;
  18603. }
  18604. // Get total curve arc length
  18605. getLength() {
  18606. const lengths = this.getLengths();
  18607. return lengths[ lengths.length - 1 ];
  18608. }
  18609. // Get list of cumulative segment lengths
  18610. getLengths( divisions = this.arcLengthDivisions ) {
  18611. if ( this.cacheArcLengths &&
  18612. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18613. ! this.needsUpdate ) {
  18614. return this.cacheArcLengths;
  18615. }
  18616. this.needsUpdate = false;
  18617. const cache = [];
  18618. let current, last = this.getPoint( 0 );
  18619. let sum = 0;
  18620. cache.push( 0 );
  18621. for ( let p = 1; p <= divisions; p ++ ) {
  18622. current = this.getPoint( p / divisions );
  18623. sum += current.distanceTo( last );
  18624. cache.push( sum );
  18625. last = current;
  18626. }
  18627. this.cacheArcLengths = cache;
  18628. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18629. }
  18630. updateArcLengths() {
  18631. this.needsUpdate = true;
  18632. this.getLengths();
  18633. }
  18634. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18635. getUtoTmapping( u, distance ) {
  18636. const arcLengths = this.getLengths();
  18637. let i = 0;
  18638. const il = arcLengths.length;
  18639. let targetArcLength; // The targeted u distance value to get
  18640. if ( distance ) {
  18641. targetArcLength = distance;
  18642. } else {
  18643. targetArcLength = u * arcLengths[ il - 1 ];
  18644. }
  18645. // binary search for the index with largest value smaller than target u distance
  18646. let low = 0, high = il - 1, comparison;
  18647. while ( low <= high ) {
  18648. 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
  18649. comparison = arcLengths[ i ] - targetArcLength;
  18650. if ( comparison < 0 ) {
  18651. low = i + 1;
  18652. } else if ( comparison > 0 ) {
  18653. high = i - 1;
  18654. } else {
  18655. high = i;
  18656. break;
  18657. // DONE
  18658. }
  18659. }
  18660. i = high;
  18661. if ( arcLengths[ i ] === targetArcLength ) {
  18662. return i / ( il - 1 );
  18663. }
  18664. // we could get finer grain at lengths, or use simple interpolation between two points
  18665. const lengthBefore = arcLengths[ i ];
  18666. const lengthAfter = arcLengths[ i + 1 ];
  18667. const segmentLength = lengthAfter - lengthBefore;
  18668. // determine where we are between the 'before' and 'after' points
  18669. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18670. // add that fractional amount to t
  18671. const t = ( i + segmentFraction ) / ( il - 1 );
  18672. return t;
  18673. }
  18674. // Returns a unit vector tangent at t
  18675. // In case any sub curve does not implement its tangent derivation,
  18676. // 2 points a small delta apart will be used to find its gradient
  18677. // which seems to give a reasonable approximation
  18678. getTangent( t, optionalTarget ) {
  18679. const delta = 0.0001;
  18680. let t1 = t - delta;
  18681. let t2 = t + delta;
  18682. // Capping in case of danger
  18683. if ( t1 < 0 ) t1 = 0;
  18684. if ( t2 > 1 ) t2 = 1;
  18685. const pt1 = this.getPoint( t1 );
  18686. const pt2 = this.getPoint( t2 );
  18687. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18688. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18689. return tangent;
  18690. }
  18691. getTangentAt( u, optionalTarget ) {
  18692. const t = this.getUtoTmapping( u );
  18693. return this.getTangent( t, optionalTarget );
  18694. }
  18695. computeFrenetFrames( segments, closed ) {
  18696. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18697. const normal = new Vector3();
  18698. const tangents = [];
  18699. const normals = [];
  18700. const binormals = [];
  18701. const vec = new Vector3();
  18702. const mat = new Matrix4();
  18703. // compute the tangent vectors for each segment on the curve
  18704. for ( let i = 0; i <= segments; i ++ ) {
  18705. const u = i / segments;
  18706. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18707. }
  18708. // select an initial normal vector perpendicular to the first tangent vector,
  18709. // and in the direction of the minimum tangent xyz component
  18710. normals[ 0 ] = new Vector3();
  18711. binormals[ 0 ] = new Vector3();
  18712. let min = Number.MAX_VALUE;
  18713. const tx = Math.abs( tangents[ 0 ].x );
  18714. const ty = Math.abs( tangents[ 0 ].y );
  18715. const tz = Math.abs( tangents[ 0 ].z );
  18716. if ( tx <= min ) {
  18717. min = tx;
  18718. normal.set( 1, 0, 0 );
  18719. }
  18720. if ( ty <= min ) {
  18721. min = ty;
  18722. normal.set( 0, 1, 0 );
  18723. }
  18724. if ( tz <= min ) {
  18725. normal.set( 0, 0, 1 );
  18726. }
  18727. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18728. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18729. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18730. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18731. for ( let i = 1; i <= segments; i ++ ) {
  18732. normals[ i ] = normals[ i - 1 ].clone();
  18733. binormals[ i ] = binormals[ i - 1 ].clone();
  18734. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18735. if ( vec.length() > Number.EPSILON ) {
  18736. vec.normalize();
  18737. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18738. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18739. }
  18740. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18741. }
  18742. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18743. if ( closed === true ) {
  18744. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18745. theta /= segments;
  18746. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18747. theta = - theta;
  18748. }
  18749. for ( let i = 1; i <= segments; i ++ ) {
  18750. // twist a little...
  18751. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18752. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18753. }
  18754. }
  18755. return {
  18756. tangents: tangents,
  18757. normals: normals,
  18758. binormals: binormals
  18759. };
  18760. }
  18761. clone() {
  18762. return new this.constructor().copy( this );
  18763. }
  18764. copy( source ) {
  18765. this.arcLengthDivisions = source.arcLengthDivisions;
  18766. return this;
  18767. }
  18768. toJSON() {
  18769. const data = {
  18770. metadata: {
  18771. version: 4.5,
  18772. type: 'Curve',
  18773. generator: 'Curve.toJSON'
  18774. }
  18775. };
  18776. data.arcLengthDivisions = this.arcLengthDivisions;
  18777. data.type = this.type;
  18778. return data;
  18779. }
  18780. fromJSON( json ) {
  18781. this.arcLengthDivisions = json.arcLengthDivisions;
  18782. return this;
  18783. }
  18784. }
  18785. class EllipseCurve extends Curve {
  18786. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18787. super();
  18788. this.type = 'EllipseCurve';
  18789. this.aX = aX;
  18790. this.aY = aY;
  18791. this.xRadius = xRadius;
  18792. this.yRadius = yRadius;
  18793. this.aStartAngle = aStartAngle;
  18794. this.aEndAngle = aEndAngle;
  18795. this.aClockwise = aClockwise;
  18796. this.aRotation = aRotation;
  18797. }
  18798. getPoint( t, optionalTarget ) {
  18799. const point = optionalTarget || new Vector2();
  18800. const twoPi = Math.PI * 2;
  18801. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18802. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18803. // ensures that deltaAngle is 0 .. 2 PI
  18804. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18805. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18806. if ( deltaAngle < Number.EPSILON ) {
  18807. if ( samePoints ) {
  18808. deltaAngle = 0;
  18809. } else {
  18810. deltaAngle = twoPi;
  18811. }
  18812. }
  18813. if ( this.aClockwise === true && ! samePoints ) {
  18814. if ( deltaAngle === twoPi ) {
  18815. deltaAngle = - twoPi;
  18816. } else {
  18817. deltaAngle = deltaAngle - twoPi;
  18818. }
  18819. }
  18820. const angle = this.aStartAngle + t * deltaAngle;
  18821. let x = this.aX + this.xRadius * Math.cos( angle );
  18822. let y = this.aY + this.yRadius * Math.sin( angle );
  18823. if ( this.aRotation !== 0 ) {
  18824. const cos = Math.cos( this.aRotation );
  18825. const sin = Math.sin( this.aRotation );
  18826. const tx = x - this.aX;
  18827. const ty = y - this.aY;
  18828. // Rotate the point about the center of the ellipse.
  18829. x = tx * cos - ty * sin + this.aX;
  18830. y = tx * sin + ty * cos + this.aY;
  18831. }
  18832. return point.set( x, y );
  18833. }
  18834. copy( source ) {
  18835. super.copy( source );
  18836. this.aX = source.aX;
  18837. this.aY = source.aY;
  18838. this.xRadius = source.xRadius;
  18839. this.yRadius = source.yRadius;
  18840. this.aStartAngle = source.aStartAngle;
  18841. this.aEndAngle = source.aEndAngle;
  18842. this.aClockwise = source.aClockwise;
  18843. this.aRotation = source.aRotation;
  18844. return this;
  18845. }
  18846. toJSON() {
  18847. const data = super.toJSON();
  18848. data.aX = this.aX;
  18849. data.aY = this.aY;
  18850. data.xRadius = this.xRadius;
  18851. data.yRadius = this.yRadius;
  18852. data.aStartAngle = this.aStartAngle;
  18853. data.aEndAngle = this.aEndAngle;
  18854. data.aClockwise = this.aClockwise;
  18855. data.aRotation = this.aRotation;
  18856. return data;
  18857. }
  18858. fromJSON( json ) {
  18859. super.fromJSON( json );
  18860. this.aX = json.aX;
  18861. this.aY = json.aY;
  18862. this.xRadius = json.xRadius;
  18863. this.yRadius = json.yRadius;
  18864. this.aStartAngle = json.aStartAngle;
  18865. this.aEndAngle = json.aEndAngle;
  18866. this.aClockwise = json.aClockwise;
  18867. this.aRotation = json.aRotation;
  18868. return this;
  18869. }
  18870. }
  18871. EllipseCurve.prototype.isEllipseCurve = true;
  18872. class ArcCurve extends EllipseCurve {
  18873. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18874. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18875. this.type = 'ArcCurve';
  18876. }
  18877. }
  18878. ArcCurve.prototype.isArcCurve = true;
  18879. /**
  18880. * Centripetal CatmullRom Curve - which is useful for avoiding
  18881. * cusps and self-intersections in non-uniform catmull rom curves.
  18882. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18883. *
  18884. * curve.type accepts centripetal(default), chordal and catmullrom
  18885. * curve.tension is used for catmullrom which defaults to 0.5
  18886. */
  18887. /*
  18888. Based on an optimized c++ solution in
  18889. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18890. - http://ideone.com/NoEbVM
  18891. This CubicPoly class could be used for reusing some variables and calculations,
  18892. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18893. which can be placed in CurveUtils.
  18894. */
  18895. function CubicPoly() {
  18896. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18897. /*
  18898. * Compute coefficients for a cubic polynomial
  18899. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18900. * such that
  18901. * p(0) = x0, p(1) = x1
  18902. * and
  18903. * p'(0) = t0, p'(1) = t1.
  18904. */
  18905. function init( x0, x1, t0, t1 ) {
  18906. c0 = x0;
  18907. c1 = t0;
  18908. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18909. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18910. }
  18911. return {
  18912. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18913. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18914. },
  18915. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18916. // compute tangents when parameterized in [t1,t2]
  18917. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18918. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18919. // rescale tangents for parametrization in [0,1]
  18920. t1 *= dt1;
  18921. t2 *= dt1;
  18922. init( x1, x2, t1, t2 );
  18923. },
  18924. calc: function ( t ) {
  18925. const t2 = t * t;
  18926. const t3 = t2 * t;
  18927. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18928. }
  18929. };
  18930. }
  18931. //
  18932. const tmp = new Vector3();
  18933. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  18934. class CatmullRomCurve3 extends Curve {
  18935. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18936. super();
  18937. this.type = 'CatmullRomCurve3';
  18938. this.points = points;
  18939. this.closed = closed;
  18940. this.curveType = curveType;
  18941. this.tension = tension;
  18942. }
  18943. getPoint( t, optionalTarget = new Vector3() ) {
  18944. const point = optionalTarget;
  18945. const points = this.points;
  18946. const l = points.length;
  18947. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18948. let intPoint = Math.floor( p );
  18949. let weight = p - intPoint;
  18950. if ( this.closed ) {
  18951. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18952. } else if ( weight === 0 && intPoint === l - 1 ) {
  18953. intPoint = l - 2;
  18954. weight = 1;
  18955. }
  18956. let p0, p3; // 4 points (p1 & p2 defined below)
  18957. if ( this.closed || intPoint > 0 ) {
  18958. p0 = points[ ( intPoint - 1 ) % l ];
  18959. } else {
  18960. // extrapolate first point
  18961. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18962. p0 = tmp;
  18963. }
  18964. const p1 = points[ intPoint % l ];
  18965. const p2 = points[ ( intPoint + 1 ) % l ];
  18966. if ( this.closed || intPoint + 2 < l ) {
  18967. p3 = points[ ( intPoint + 2 ) % l ];
  18968. } else {
  18969. // extrapolate last point
  18970. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18971. p3 = tmp;
  18972. }
  18973. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18974. // init Centripetal / Chordal Catmull-Rom
  18975. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18976. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18977. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18978. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18979. // safety check for repeated points
  18980. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18981. if ( dt0 < 1e-4 ) dt0 = dt1;
  18982. if ( dt2 < 1e-4 ) dt2 = dt1;
  18983. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18984. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18985. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18986. } else if ( this.curveType === 'catmullrom' ) {
  18987. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18988. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18989. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18990. }
  18991. point.set(
  18992. px.calc( weight ),
  18993. py.calc( weight ),
  18994. pz.calc( weight )
  18995. );
  18996. return point;
  18997. }
  18998. copy( source ) {
  18999. super.copy( source );
  19000. this.points = [];
  19001. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19002. const point = source.points[ i ];
  19003. this.points.push( point.clone() );
  19004. }
  19005. this.closed = source.closed;
  19006. this.curveType = source.curveType;
  19007. this.tension = source.tension;
  19008. return this;
  19009. }
  19010. toJSON() {
  19011. const data = super.toJSON();
  19012. data.points = [];
  19013. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19014. const point = this.points[ i ];
  19015. data.points.push( point.toArray() );
  19016. }
  19017. data.closed = this.closed;
  19018. data.curveType = this.curveType;
  19019. data.tension = this.tension;
  19020. return data;
  19021. }
  19022. fromJSON( json ) {
  19023. super.fromJSON( json );
  19024. this.points = [];
  19025. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19026. const point = json.points[ i ];
  19027. this.points.push( new Vector3().fromArray( point ) );
  19028. }
  19029. this.closed = json.closed;
  19030. this.curveType = json.curveType;
  19031. this.tension = json.tension;
  19032. return this;
  19033. }
  19034. }
  19035. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  19036. /**
  19037. * Bezier Curves formulas obtained from
  19038. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19039. */
  19040. function CatmullRom( t, p0, p1, p2, p3 ) {
  19041. const v0 = ( p2 - p0 ) * 0.5;
  19042. const v1 = ( p3 - p1 ) * 0.5;
  19043. const t2 = t * t;
  19044. const t3 = t * t2;
  19045. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19046. }
  19047. //
  19048. function QuadraticBezierP0( t, p ) {
  19049. const k = 1 - t;
  19050. return k * k * p;
  19051. }
  19052. function QuadraticBezierP1( t, p ) {
  19053. return 2 * ( 1 - t ) * t * p;
  19054. }
  19055. function QuadraticBezierP2( t, p ) {
  19056. return t * t * p;
  19057. }
  19058. function QuadraticBezier( t, p0, p1, p2 ) {
  19059. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19060. QuadraticBezierP2( t, p2 );
  19061. }
  19062. //
  19063. function CubicBezierP0( t, p ) {
  19064. const k = 1 - t;
  19065. return k * k * k * p;
  19066. }
  19067. function CubicBezierP1( t, p ) {
  19068. const k = 1 - t;
  19069. return 3 * k * k * t * p;
  19070. }
  19071. function CubicBezierP2( t, p ) {
  19072. return 3 * ( 1 - t ) * t * t * p;
  19073. }
  19074. function CubicBezierP3( t, p ) {
  19075. return t * t * t * p;
  19076. }
  19077. function CubicBezier( t, p0, p1, p2, p3 ) {
  19078. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19079. CubicBezierP3( t, p3 );
  19080. }
  19081. class CubicBezierCurve extends Curve {
  19082. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19083. super();
  19084. this.type = 'CubicBezierCurve';
  19085. this.v0 = v0;
  19086. this.v1 = v1;
  19087. this.v2 = v2;
  19088. this.v3 = v3;
  19089. }
  19090. getPoint( t, optionalTarget = new Vector2() ) {
  19091. const point = optionalTarget;
  19092. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19093. point.set(
  19094. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19095. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19096. );
  19097. return point;
  19098. }
  19099. copy( source ) {
  19100. super.copy( source );
  19101. this.v0.copy( source.v0 );
  19102. this.v1.copy( source.v1 );
  19103. this.v2.copy( source.v2 );
  19104. this.v3.copy( source.v3 );
  19105. return this;
  19106. }
  19107. toJSON() {
  19108. const data = super.toJSON();
  19109. data.v0 = this.v0.toArray();
  19110. data.v1 = this.v1.toArray();
  19111. data.v2 = this.v2.toArray();
  19112. data.v3 = this.v3.toArray();
  19113. return data;
  19114. }
  19115. fromJSON( json ) {
  19116. super.fromJSON( json );
  19117. this.v0.fromArray( json.v0 );
  19118. this.v1.fromArray( json.v1 );
  19119. this.v2.fromArray( json.v2 );
  19120. this.v3.fromArray( json.v3 );
  19121. return this;
  19122. }
  19123. }
  19124. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  19125. class CubicBezierCurve3 extends Curve {
  19126. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19127. super();
  19128. this.type = 'CubicBezierCurve3';
  19129. this.v0 = v0;
  19130. this.v1 = v1;
  19131. this.v2 = v2;
  19132. this.v3 = v3;
  19133. }
  19134. getPoint( t, optionalTarget = new Vector3() ) {
  19135. const point = optionalTarget;
  19136. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19137. point.set(
  19138. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19139. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19140. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19141. );
  19142. return point;
  19143. }
  19144. copy( source ) {
  19145. super.copy( source );
  19146. this.v0.copy( source.v0 );
  19147. this.v1.copy( source.v1 );
  19148. this.v2.copy( source.v2 );
  19149. this.v3.copy( source.v3 );
  19150. return this;
  19151. }
  19152. toJSON() {
  19153. const data = super.toJSON();
  19154. data.v0 = this.v0.toArray();
  19155. data.v1 = this.v1.toArray();
  19156. data.v2 = this.v2.toArray();
  19157. data.v3 = this.v3.toArray();
  19158. return data;
  19159. }
  19160. fromJSON( json ) {
  19161. super.fromJSON( json );
  19162. this.v0.fromArray( json.v0 );
  19163. this.v1.fromArray( json.v1 );
  19164. this.v2.fromArray( json.v2 );
  19165. this.v3.fromArray( json.v3 );
  19166. return this;
  19167. }
  19168. }
  19169. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  19170. class LineCurve extends Curve {
  19171. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19172. super();
  19173. this.type = 'LineCurve';
  19174. this.v1 = v1;
  19175. this.v2 = v2;
  19176. }
  19177. getPoint( t, optionalTarget = new Vector2() ) {
  19178. const point = optionalTarget;
  19179. if ( t === 1 ) {
  19180. point.copy( this.v2 );
  19181. } else {
  19182. point.copy( this.v2 ).sub( this.v1 );
  19183. point.multiplyScalar( t ).add( this.v1 );
  19184. }
  19185. return point;
  19186. }
  19187. // Line curve is linear, so we can overwrite default getPointAt
  19188. getPointAt( u, optionalTarget ) {
  19189. return this.getPoint( u, optionalTarget );
  19190. }
  19191. getTangent( t, optionalTarget ) {
  19192. const tangent = optionalTarget || new Vector2();
  19193. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19194. return tangent;
  19195. }
  19196. copy( source ) {
  19197. super.copy( source );
  19198. this.v1.copy( source.v1 );
  19199. this.v2.copy( source.v2 );
  19200. return this;
  19201. }
  19202. toJSON() {
  19203. const data = super.toJSON();
  19204. data.v1 = this.v1.toArray();
  19205. data.v2 = this.v2.toArray();
  19206. return data;
  19207. }
  19208. fromJSON( json ) {
  19209. super.fromJSON( json );
  19210. this.v1.fromArray( json.v1 );
  19211. this.v2.fromArray( json.v2 );
  19212. return this;
  19213. }
  19214. }
  19215. LineCurve.prototype.isLineCurve = true;
  19216. class LineCurve3 extends Curve {
  19217. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19218. super();
  19219. this.type = 'LineCurve3';
  19220. this.isLineCurve3 = true;
  19221. this.v1 = v1;
  19222. this.v2 = v2;
  19223. }
  19224. getPoint( t, optionalTarget = new Vector3() ) {
  19225. const point = optionalTarget;
  19226. if ( t === 1 ) {
  19227. point.copy( this.v2 );
  19228. } else {
  19229. point.copy( this.v2 ).sub( this.v1 );
  19230. point.multiplyScalar( t ).add( this.v1 );
  19231. }
  19232. return point;
  19233. }
  19234. // Line curve is linear, so we can overwrite default getPointAt
  19235. getPointAt( u, optionalTarget ) {
  19236. return this.getPoint( u, optionalTarget );
  19237. }
  19238. copy( source ) {
  19239. super.copy( source );
  19240. this.v1.copy( source.v1 );
  19241. this.v2.copy( source.v2 );
  19242. return this;
  19243. }
  19244. toJSON() {
  19245. const data = super.toJSON();
  19246. data.v1 = this.v1.toArray();
  19247. data.v2 = this.v2.toArray();
  19248. return data;
  19249. }
  19250. fromJSON( json ) {
  19251. super.fromJSON( json );
  19252. this.v1.fromArray( json.v1 );
  19253. this.v2.fromArray( json.v2 );
  19254. return this;
  19255. }
  19256. }
  19257. class QuadraticBezierCurve extends Curve {
  19258. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19259. super();
  19260. this.type = 'QuadraticBezierCurve';
  19261. this.v0 = v0;
  19262. this.v1 = v1;
  19263. this.v2 = v2;
  19264. }
  19265. getPoint( t, optionalTarget = new Vector2() ) {
  19266. const point = optionalTarget;
  19267. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19268. point.set(
  19269. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19270. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19271. );
  19272. return point;
  19273. }
  19274. copy( source ) {
  19275. super.copy( source );
  19276. this.v0.copy( source.v0 );
  19277. this.v1.copy( source.v1 );
  19278. this.v2.copy( source.v2 );
  19279. return this;
  19280. }
  19281. toJSON() {
  19282. const data = super.toJSON();
  19283. data.v0 = this.v0.toArray();
  19284. data.v1 = this.v1.toArray();
  19285. data.v2 = this.v2.toArray();
  19286. return data;
  19287. }
  19288. fromJSON( json ) {
  19289. super.fromJSON( json );
  19290. this.v0.fromArray( json.v0 );
  19291. this.v1.fromArray( json.v1 );
  19292. this.v2.fromArray( json.v2 );
  19293. return this;
  19294. }
  19295. }
  19296. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  19297. class QuadraticBezierCurve3 extends Curve {
  19298. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19299. super();
  19300. this.type = 'QuadraticBezierCurve3';
  19301. this.v0 = v0;
  19302. this.v1 = v1;
  19303. this.v2 = v2;
  19304. }
  19305. getPoint( t, optionalTarget = new Vector3() ) {
  19306. const point = optionalTarget;
  19307. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19308. point.set(
  19309. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19310. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19311. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19312. );
  19313. return point;
  19314. }
  19315. copy( source ) {
  19316. super.copy( source );
  19317. this.v0.copy( source.v0 );
  19318. this.v1.copy( source.v1 );
  19319. this.v2.copy( source.v2 );
  19320. return this;
  19321. }
  19322. toJSON() {
  19323. const data = super.toJSON();
  19324. data.v0 = this.v0.toArray();
  19325. data.v1 = this.v1.toArray();
  19326. data.v2 = this.v2.toArray();
  19327. return data;
  19328. }
  19329. fromJSON( json ) {
  19330. super.fromJSON( json );
  19331. this.v0.fromArray( json.v0 );
  19332. this.v1.fromArray( json.v1 );
  19333. this.v2.fromArray( json.v2 );
  19334. return this;
  19335. }
  19336. }
  19337. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  19338. class SplineCurve extends Curve {
  19339. constructor( points = [] ) {
  19340. super();
  19341. this.type = 'SplineCurve';
  19342. this.points = points;
  19343. }
  19344. getPoint( t, optionalTarget = new Vector2() ) {
  19345. const point = optionalTarget;
  19346. const points = this.points;
  19347. const p = ( points.length - 1 ) * t;
  19348. const intPoint = Math.floor( p );
  19349. const weight = p - intPoint;
  19350. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19351. const p1 = points[ intPoint ];
  19352. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19353. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19354. point.set(
  19355. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19356. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19357. );
  19358. return point;
  19359. }
  19360. copy( source ) {
  19361. super.copy( source );
  19362. this.points = [];
  19363. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19364. const point = source.points[ i ];
  19365. this.points.push( point.clone() );
  19366. }
  19367. return this;
  19368. }
  19369. toJSON() {
  19370. const data = super.toJSON();
  19371. data.points = [];
  19372. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19373. const point = this.points[ i ];
  19374. data.points.push( point.toArray() );
  19375. }
  19376. return data;
  19377. }
  19378. fromJSON( json ) {
  19379. super.fromJSON( json );
  19380. this.points = [];
  19381. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19382. const point = json.points[ i ];
  19383. this.points.push( new Vector2().fromArray( point ) );
  19384. }
  19385. return this;
  19386. }
  19387. }
  19388. SplineCurve.prototype.isSplineCurve = true;
  19389. var Curves = /*#__PURE__*/Object.freeze({
  19390. __proto__: null,
  19391. ArcCurve: ArcCurve,
  19392. CatmullRomCurve3: CatmullRomCurve3,
  19393. CubicBezierCurve: CubicBezierCurve,
  19394. CubicBezierCurve3: CubicBezierCurve3,
  19395. EllipseCurve: EllipseCurve,
  19396. LineCurve: LineCurve,
  19397. LineCurve3: LineCurve3,
  19398. QuadraticBezierCurve: QuadraticBezierCurve,
  19399. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19400. SplineCurve: SplineCurve
  19401. });
  19402. /**************************************************************
  19403. * Curved Path - a curve path is simply a array of connected
  19404. * curves, but retains the api of a curve
  19405. **************************************************************/
  19406. class CurvePath extends Curve {
  19407. constructor() {
  19408. super();
  19409. this.type = 'CurvePath';
  19410. this.curves = [];
  19411. this.autoClose = false; // Automatically closes the path
  19412. }
  19413. add( curve ) {
  19414. this.curves.push( curve );
  19415. }
  19416. closePath() {
  19417. // Add a line curve if start and end of lines are not connected
  19418. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19419. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19420. if ( ! startPoint.equals( endPoint ) ) {
  19421. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19422. }
  19423. }
  19424. // To get accurate point with reference to
  19425. // entire path distance at time t,
  19426. // following has to be done:
  19427. // 1. Length of each sub path have to be known
  19428. // 2. Locate and identify type of curve
  19429. // 3. Get t for the curve
  19430. // 4. Return curve.getPointAt(t')
  19431. getPoint( t, optionalTarget ) {
  19432. const d = t * this.getLength();
  19433. const curveLengths = this.getCurveLengths();
  19434. let i = 0;
  19435. // To think about boundaries points.
  19436. while ( i < curveLengths.length ) {
  19437. if ( curveLengths[ i ] >= d ) {
  19438. const diff = curveLengths[ i ] - d;
  19439. const curve = this.curves[ i ];
  19440. const segmentLength = curve.getLength();
  19441. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19442. return curve.getPointAt( u, optionalTarget );
  19443. }
  19444. i ++;
  19445. }
  19446. return null;
  19447. // loop where sum != 0, sum > d , sum+1 <d
  19448. }
  19449. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19450. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19451. // getPoint() depends on getLength
  19452. getLength() {
  19453. const lens = this.getCurveLengths();
  19454. return lens[ lens.length - 1 ];
  19455. }
  19456. // cacheLengths must be recalculated.
  19457. updateArcLengths() {
  19458. this.needsUpdate = true;
  19459. this.cacheLengths = null;
  19460. this.getCurveLengths();
  19461. }
  19462. // Compute lengths and cache them
  19463. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19464. getCurveLengths() {
  19465. // We use cache values if curves and cache array are same length
  19466. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19467. return this.cacheLengths;
  19468. }
  19469. // Get length of sub-curve
  19470. // Push sums into cached array
  19471. const lengths = [];
  19472. let sums = 0;
  19473. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19474. sums += this.curves[ i ].getLength();
  19475. lengths.push( sums );
  19476. }
  19477. this.cacheLengths = lengths;
  19478. return lengths;
  19479. }
  19480. getSpacedPoints( divisions = 40 ) {
  19481. const points = [];
  19482. for ( let i = 0; i <= divisions; i ++ ) {
  19483. points.push( this.getPoint( i / divisions ) );
  19484. }
  19485. if ( this.autoClose ) {
  19486. points.push( points[ 0 ] );
  19487. }
  19488. return points;
  19489. }
  19490. getPoints( divisions = 12 ) {
  19491. const points = [];
  19492. let last;
  19493. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19494. const curve = curves[ i ];
  19495. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  19496. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  19497. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  19498. : divisions;
  19499. const pts = curve.getPoints( resolution );
  19500. for ( let j = 0; j < pts.length; j ++ ) {
  19501. const point = pts[ j ];
  19502. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19503. points.push( point );
  19504. last = point;
  19505. }
  19506. }
  19507. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19508. points.push( points[ 0 ] );
  19509. }
  19510. return points;
  19511. }
  19512. copy( source ) {
  19513. super.copy( source );
  19514. this.curves = [];
  19515. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19516. const curve = source.curves[ i ];
  19517. this.curves.push( curve.clone() );
  19518. }
  19519. this.autoClose = source.autoClose;
  19520. return this;
  19521. }
  19522. toJSON() {
  19523. const data = super.toJSON();
  19524. data.autoClose = this.autoClose;
  19525. data.curves = [];
  19526. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19527. const curve = this.curves[ i ];
  19528. data.curves.push( curve.toJSON() );
  19529. }
  19530. return data;
  19531. }
  19532. fromJSON( json ) {
  19533. super.fromJSON( json );
  19534. this.autoClose = json.autoClose;
  19535. this.curves = [];
  19536. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19537. const curve = json.curves[ i ];
  19538. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19539. }
  19540. return this;
  19541. }
  19542. }
  19543. class Path extends CurvePath {
  19544. constructor( points ) {
  19545. super();
  19546. this.type = 'Path';
  19547. this.currentPoint = new Vector2();
  19548. if ( points ) {
  19549. this.setFromPoints( points );
  19550. }
  19551. }
  19552. setFromPoints( points ) {
  19553. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19554. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19555. this.lineTo( points[ i ].x, points[ i ].y );
  19556. }
  19557. return this;
  19558. }
  19559. moveTo( x, y ) {
  19560. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19561. return this;
  19562. }
  19563. lineTo( x, y ) {
  19564. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19565. this.curves.push( curve );
  19566. this.currentPoint.set( x, y );
  19567. return this;
  19568. }
  19569. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19570. const curve = new QuadraticBezierCurve(
  19571. this.currentPoint.clone(),
  19572. new Vector2( aCPx, aCPy ),
  19573. new Vector2( aX, aY )
  19574. );
  19575. this.curves.push( curve );
  19576. this.currentPoint.set( aX, aY );
  19577. return this;
  19578. }
  19579. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19580. const curve = new CubicBezierCurve(
  19581. this.currentPoint.clone(),
  19582. new Vector2( aCP1x, aCP1y ),
  19583. new Vector2( aCP2x, aCP2y ),
  19584. new Vector2( aX, aY )
  19585. );
  19586. this.curves.push( curve );
  19587. this.currentPoint.set( aX, aY );
  19588. return this;
  19589. }
  19590. splineThru( pts /*Array of Vector*/ ) {
  19591. const npts = [ this.currentPoint.clone() ].concat( pts );
  19592. const curve = new SplineCurve( npts );
  19593. this.curves.push( curve );
  19594. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19595. return this;
  19596. }
  19597. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19598. const x0 = this.currentPoint.x;
  19599. const y0 = this.currentPoint.y;
  19600. this.absarc( aX + x0, aY + y0, aRadius,
  19601. aStartAngle, aEndAngle, aClockwise );
  19602. return this;
  19603. }
  19604. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19605. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19606. return this;
  19607. }
  19608. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19609. const x0 = this.currentPoint.x;
  19610. const y0 = this.currentPoint.y;
  19611. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19612. return this;
  19613. }
  19614. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19615. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19616. if ( this.curves.length > 0 ) {
  19617. // if a previous curve is present, attempt to join
  19618. const firstPoint = curve.getPoint( 0 );
  19619. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19620. this.lineTo( firstPoint.x, firstPoint.y );
  19621. }
  19622. }
  19623. this.curves.push( curve );
  19624. const lastPoint = curve.getPoint( 1 );
  19625. this.currentPoint.copy( lastPoint );
  19626. return this;
  19627. }
  19628. copy( source ) {
  19629. super.copy( source );
  19630. this.currentPoint.copy( source.currentPoint );
  19631. return this;
  19632. }
  19633. toJSON() {
  19634. const data = super.toJSON();
  19635. data.currentPoint = this.currentPoint.toArray();
  19636. return data;
  19637. }
  19638. fromJSON( json ) {
  19639. super.fromJSON( json );
  19640. this.currentPoint.fromArray( json.currentPoint );
  19641. return this;
  19642. }
  19643. }
  19644. class Shape extends Path {
  19645. constructor( points ) {
  19646. super( points );
  19647. this.uuid = generateUUID();
  19648. this.type = 'Shape';
  19649. this.holes = [];
  19650. }
  19651. getPointsHoles( divisions ) {
  19652. const holesPts = [];
  19653. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19654. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  19655. }
  19656. return holesPts;
  19657. }
  19658. // get points of shape and holes (keypoints based on segments parameter)
  19659. extractPoints( divisions ) {
  19660. return {
  19661. shape: this.getPoints( divisions ),
  19662. holes: this.getPointsHoles( divisions )
  19663. };
  19664. }
  19665. copy( source ) {
  19666. super.copy( source );
  19667. this.holes = [];
  19668. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  19669. const hole = source.holes[ i ];
  19670. this.holes.push( hole.clone() );
  19671. }
  19672. return this;
  19673. }
  19674. toJSON() {
  19675. const data = super.toJSON();
  19676. data.uuid = this.uuid;
  19677. data.holes = [];
  19678. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19679. const hole = this.holes[ i ];
  19680. data.holes.push( hole.toJSON() );
  19681. }
  19682. return data;
  19683. }
  19684. fromJSON( json ) {
  19685. super.fromJSON( json );
  19686. this.uuid = json.uuid;
  19687. this.holes = [];
  19688. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  19689. const hole = json.holes[ i ];
  19690. this.holes.push( new Path().fromJSON( hole ) );
  19691. }
  19692. return this;
  19693. }
  19694. }
  19695. /**
  19696. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19697. */
  19698. const Earcut = {
  19699. triangulate: function ( data, holeIndices, dim = 2 ) {
  19700. const hasHoles = holeIndices && holeIndices.length;
  19701. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  19702. let outerNode = linkedList( data, 0, outerLen, dim, true );
  19703. const triangles = [];
  19704. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  19705. let minX, minY, maxX, maxY, x, y, invSize;
  19706. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  19707. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19708. if ( data.length > 80 * dim ) {
  19709. minX = maxX = data[ 0 ];
  19710. minY = maxY = data[ 1 ];
  19711. for ( let i = dim; i < outerLen; i += dim ) {
  19712. x = data[ i ];
  19713. y = data[ i + 1 ];
  19714. if ( x < minX ) minX = x;
  19715. if ( y < minY ) minY = y;
  19716. if ( x > maxX ) maxX = x;
  19717. if ( y > maxY ) maxY = y;
  19718. }
  19719. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19720. invSize = Math.max( maxX - minX, maxY - minY );
  19721. invSize = invSize !== 0 ? 1 / invSize : 0;
  19722. }
  19723. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  19724. return triangles;
  19725. }
  19726. };
  19727. // create a circular doubly linked list from polygon points in the specified winding order
  19728. function linkedList( data, start, end, dim, clockwise ) {
  19729. let i, last;
  19730. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  19731. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19732. } else {
  19733. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19734. }
  19735. if ( last && equals( last, last.next ) ) {
  19736. removeNode( last );
  19737. last = last.next;
  19738. }
  19739. return last;
  19740. }
  19741. // eliminate colinear or duplicate points
  19742. function filterPoints( start, end ) {
  19743. if ( ! start ) return start;
  19744. if ( ! end ) end = start;
  19745. let p = start,
  19746. again;
  19747. do {
  19748. again = false;
  19749. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  19750. removeNode( p );
  19751. p = end = p.prev;
  19752. if ( p === p.next ) break;
  19753. again = true;
  19754. } else {
  19755. p = p.next;
  19756. }
  19757. } while ( again || p !== end );
  19758. return end;
  19759. }
  19760. // main ear slicing loop which triangulates a polygon (given as a linked list)
  19761. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  19762. if ( ! ear ) return;
  19763. // interlink polygon nodes in z-order
  19764. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  19765. let stop = ear,
  19766. prev, next;
  19767. // iterate through ears, slicing them one by one
  19768. while ( ear.prev !== ear.next ) {
  19769. prev = ear.prev;
  19770. next = ear.next;
  19771. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  19772. // cut off the triangle
  19773. triangles.push( prev.i / dim );
  19774. triangles.push( ear.i / dim );
  19775. triangles.push( next.i / dim );
  19776. removeNode( ear );
  19777. // skipping the next vertex leads to less sliver triangles
  19778. ear = next.next;
  19779. stop = next.next;
  19780. continue;
  19781. }
  19782. ear = next;
  19783. // if we looped through the whole remaining polygon and can't find any more ears
  19784. if ( ear === stop ) {
  19785. // try filtering points and slicing again
  19786. if ( ! pass ) {
  19787. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  19788. // if this didn't work, try curing all small self-intersections locally
  19789. } else if ( pass === 1 ) {
  19790. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  19791. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  19792. // as a last resort, try splitting the remaining polygon into two
  19793. } else if ( pass === 2 ) {
  19794. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  19795. }
  19796. break;
  19797. }
  19798. }
  19799. }
  19800. // check whether a polygon node forms a valid ear with adjacent nodes
  19801. function isEar( ear ) {
  19802. const a = ear.prev,
  19803. b = ear,
  19804. c = ear.next;
  19805. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19806. // now make sure we don't have other points inside the potential ear
  19807. let p = ear.next.next;
  19808. while ( p !== ear.prev ) {
  19809. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19810. area( p.prev, p, p.next ) >= 0 ) return false;
  19811. p = p.next;
  19812. }
  19813. return true;
  19814. }
  19815. function isEarHashed( ear, minX, minY, invSize ) {
  19816. const a = ear.prev,
  19817. b = ear,
  19818. c = ear.next;
  19819. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19820. // triangle bbox; min & max are calculated like this for speed
  19821. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  19822. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  19823. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  19824. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  19825. // z-order range for the current triangle bbox;
  19826. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  19827. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  19828. let p = ear.prevZ,
  19829. n = ear.nextZ;
  19830. // look for points inside the triangle in both directions
  19831. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19832. if ( p !== ear.prev && p !== ear.next &&
  19833. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19834. area( p.prev, p, p.next ) >= 0 ) return false;
  19835. p = p.prevZ;
  19836. if ( n !== ear.prev && n !== ear.next &&
  19837. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19838. area( n.prev, n, n.next ) >= 0 ) return false;
  19839. n = n.nextZ;
  19840. }
  19841. // look for remaining points in decreasing z-order
  19842. while ( p && p.z >= minZ ) {
  19843. if ( p !== ear.prev && p !== ear.next &&
  19844. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19845. area( p.prev, p, p.next ) >= 0 ) return false;
  19846. p = p.prevZ;
  19847. }
  19848. // look for remaining points in increasing z-order
  19849. while ( n && n.z <= maxZ ) {
  19850. if ( n !== ear.prev && n !== ear.next &&
  19851. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19852. area( n.prev, n, n.next ) >= 0 ) return false;
  19853. n = n.nextZ;
  19854. }
  19855. return true;
  19856. }
  19857. // go through all polygon nodes and cure small local self-intersections
  19858. function cureLocalIntersections( start, triangles, dim ) {
  19859. let p = start;
  19860. do {
  19861. const a = p.prev,
  19862. b = p.next.next;
  19863. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  19864. triangles.push( a.i / dim );
  19865. triangles.push( p.i / dim );
  19866. triangles.push( b.i / dim );
  19867. // remove two nodes involved
  19868. removeNode( p );
  19869. removeNode( p.next );
  19870. p = start = b;
  19871. }
  19872. p = p.next;
  19873. } while ( p !== start );
  19874. return filterPoints( p );
  19875. }
  19876. // try splitting polygon into two and triangulate them independently
  19877. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  19878. // look for a valid diagonal that divides the polygon into two
  19879. let a = start;
  19880. do {
  19881. let b = a.next.next;
  19882. while ( b !== a.prev ) {
  19883. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  19884. // split the polygon in two by the diagonal
  19885. let c = splitPolygon( a, b );
  19886. // filter colinear points around the cuts
  19887. a = filterPoints( a, a.next );
  19888. c = filterPoints( c, c.next );
  19889. // run earcut on each half
  19890. earcutLinked( a, triangles, dim, minX, minY, invSize );
  19891. earcutLinked( c, triangles, dim, minX, minY, invSize );
  19892. return;
  19893. }
  19894. b = b.next;
  19895. }
  19896. a = a.next;
  19897. } while ( a !== start );
  19898. }
  19899. // link every hole into the outer loop, producing a single-ring polygon without holes
  19900. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  19901. const queue = [];
  19902. let i, len, start, end, list;
  19903. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  19904. start = holeIndices[ i ] * dim;
  19905. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  19906. list = linkedList( data, start, end, dim, false );
  19907. if ( list === list.next ) list.steiner = true;
  19908. queue.push( getLeftmost( list ) );
  19909. }
  19910. queue.sort( compareX );
  19911. // process holes from left to right
  19912. for ( i = 0; i < queue.length; i ++ ) {
  19913. eliminateHole( queue[ i ], outerNode );
  19914. outerNode = filterPoints( outerNode, outerNode.next );
  19915. }
  19916. return outerNode;
  19917. }
  19918. function compareX( a, b ) {
  19919. return a.x - b.x;
  19920. }
  19921. // find a bridge between vertices that connects hole with an outer ring and and link it
  19922. function eliminateHole( hole, outerNode ) {
  19923. outerNode = findHoleBridge( hole, outerNode );
  19924. if ( outerNode ) {
  19925. const b = splitPolygon( outerNode, hole );
  19926. // filter collinear points around the cuts
  19927. filterPoints( outerNode, outerNode.next );
  19928. filterPoints( b, b.next );
  19929. }
  19930. }
  19931. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19932. function findHoleBridge( hole, outerNode ) {
  19933. let p = outerNode;
  19934. const hx = hole.x;
  19935. const hy = hole.y;
  19936. let qx = - Infinity, m;
  19937. // find a segment intersected by a ray from the hole's leftmost point to the left;
  19938. // segment's endpoint with lesser x will be potential connection point
  19939. do {
  19940. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  19941. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  19942. if ( x <= hx && x > qx ) {
  19943. qx = x;
  19944. if ( x === hx ) {
  19945. if ( hy === p.y ) return p;
  19946. if ( hy === p.next.y ) return p.next;
  19947. }
  19948. m = p.x < p.next.x ? p : p.next;
  19949. }
  19950. }
  19951. p = p.next;
  19952. } while ( p !== outerNode );
  19953. if ( ! m ) return null;
  19954. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  19955. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19956. // if there are no points found, we have a valid connection;
  19957. // otherwise choose the point of the minimum angle with the ray as connection point
  19958. const stop = m,
  19959. mx = m.x,
  19960. my = m.y;
  19961. let tanMin = Infinity, tan;
  19962. p = m;
  19963. do {
  19964. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  19965. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  19966. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  19967. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  19968. m = p;
  19969. tanMin = tan;
  19970. }
  19971. }
  19972. p = p.next;
  19973. } while ( p !== stop );
  19974. return m;
  19975. }
  19976. // whether sector in vertex m contains sector in vertex p in the same coordinates
  19977. function sectorContainsSector( m, p ) {
  19978. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  19979. }
  19980. // interlink polygon nodes in z-order
  19981. function indexCurve( start, minX, minY, invSize ) {
  19982. let p = start;
  19983. do {
  19984. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  19985. p.prevZ = p.prev;
  19986. p.nextZ = p.next;
  19987. p = p.next;
  19988. } while ( p !== start );
  19989. p.prevZ.nextZ = null;
  19990. p.prevZ = null;
  19991. sortLinked( p );
  19992. }
  19993. // Simon Tatham's linked list merge sort algorithm
  19994. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19995. function sortLinked( list ) {
  19996. let i, p, q, e, tail, numMerges, pSize, qSize,
  19997. inSize = 1;
  19998. do {
  19999. p = list;
  20000. list = null;
  20001. tail = null;
  20002. numMerges = 0;
  20003. while ( p ) {
  20004. numMerges ++;
  20005. q = p;
  20006. pSize = 0;
  20007. for ( i = 0; i < inSize; i ++ ) {
  20008. pSize ++;
  20009. q = q.nextZ;
  20010. if ( ! q ) break;
  20011. }
  20012. qSize = inSize;
  20013. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20014. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20015. e = p;
  20016. p = p.nextZ;
  20017. pSize --;
  20018. } else {
  20019. e = q;
  20020. q = q.nextZ;
  20021. qSize --;
  20022. }
  20023. if ( tail ) tail.nextZ = e;
  20024. else list = e;
  20025. e.prevZ = tail;
  20026. tail = e;
  20027. }
  20028. p = q;
  20029. }
  20030. tail.nextZ = null;
  20031. inSize *= 2;
  20032. } while ( numMerges > 1 );
  20033. return list;
  20034. }
  20035. // z-order of a point given coords and inverse of the longer side of data bbox
  20036. function zOrder( x, y, minX, minY, invSize ) {
  20037. // coords are transformed into non-negative 15-bit integer range
  20038. x = 32767 * ( x - minX ) * invSize;
  20039. y = 32767 * ( y - minY ) * invSize;
  20040. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20041. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20042. x = ( x | ( x << 2 ) ) & 0x33333333;
  20043. x = ( x | ( x << 1 ) ) & 0x55555555;
  20044. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20045. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20046. y = ( y | ( y << 2 ) ) & 0x33333333;
  20047. y = ( y | ( y << 1 ) ) & 0x55555555;
  20048. return x | ( y << 1 );
  20049. }
  20050. // find the leftmost node of a polygon ring
  20051. function getLeftmost( start ) {
  20052. let p = start,
  20053. leftmost = start;
  20054. do {
  20055. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20056. p = p.next;
  20057. } while ( p !== start );
  20058. return leftmost;
  20059. }
  20060. // check if a point lies within a convex triangle
  20061. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20062. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20063. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20064. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20065. }
  20066. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20067. function isValidDiagonal( a, b ) {
  20068. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20069. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20070. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20071. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20072. }
  20073. // signed area of a triangle
  20074. function area( p, q, r ) {
  20075. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20076. }
  20077. // check if two points are equal
  20078. function equals( p1, p2 ) {
  20079. return p1.x === p2.x && p1.y === p2.y;
  20080. }
  20081. // check if two segments intersect
  20082. function intersects( p1, q1, p2, q2 ) {
  20083. const o1 = sign( area( p1, q1, p2 ) );
  20084. const o2 = sign( area( p1, q1, q2 ) );
  20085. const o3 = sign( area( p2, q2, p1 ) );
  20086. const o4 = sign( area( p2, q2, q1 ) );
  20087. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20088. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20089. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20090. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20091. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20092. return false;
  20093. }
  20094. // for collinear points p, q, r, check if point q lies on segment pr
  20095. function onSegment( p, q, r ) {
  20096. 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 );
  20097. }
  20098. function sign( num ) {
  20099. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20100. }
  20101. // check if a polygon diagonal intersects any polygon segments
  20102. function intersectsPolygon( a, b ) {
  20103. let p = a;
  20104. do {
  20105. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20106. intersects( p, p.next, a, b ) ) return true;
  20107. p = p.next;
  20108. } while ( p !== a );
  20109. return false;
  20110. }
  20111. // check if a polygon diagonal is locally inside the polygon
  20112. function locallyInside( a, b ) {
  20113. return area( a.prev, a, a.next ) < 0 ?
  20114. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20115. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20116. }
  20117. // check if the middle point of a polygon diagonal is inside the polygon
  20118. function middleInside( a, b ) {
  20119. let p = a,
  20120. inside = false;
  20121. const px = ( a.x + b.x ) / 2,
  20122. py = ( a.y + b.y ) / 2;
  20123. do {
  20124. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20125. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20126. inside = ! inside;
  20127. p = p.next;
  20128. } while ( p !== a );
  20129. return inside;
  20130. }
  20131. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20132. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20133. function splitPolygon( a, b ) {
  20134. const a2 = new Node( a.i, a.x, a.y ),
  20135. b2 = new Node( b.i, b.x, b.y ),
  20136. an = a.next,
  20137. bp = b.prev;
  20138. a.next = b;
  20139. b.prev = a;
  20140. a2.next = an;
  20141. an.prev = a2;
  20142. b2.next = a2;
  20143. a2.prev = b2;
  20144. bp.next = b2;
  20145. b2.prev = bp;
  20146. return b2;
  20147. }
  20148. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20149. function insertNode( i, x, y, last ) {
  20150. const p = new Node( i, x, y );
  20151. if ( ! last ) {
  20152. p.prev = p;
  20153. p.next = p;
  20154. } else {
  20155. p.next = last.next;
  20156. p.prev = last;
  20157. last.next.prev = p;
  20158. last.next = p;
  20159. }
  20160. return p;
  20161. }
  20162. function removeNode( p ) {
  20163. p.next.prev = p.prev;
  20164. p.prev.next = p.next;
  20165. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20166. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20167. }
  20168. function Node( i, x, y ) {
  20169. // vertex index in coordinates array
  20170. this.i = i;
  20171. // vertex coordinates
  20172. this.x = x;
  20173. this.y = y;
  20174. // previous and next vertex nodes in a polygon ring
  20175. this.prev = null;
  20176. this.next = null;
  20177. // z-order curve value
  20178. this.z = null;
  20179. // previous and next nodes in z-order
  20180. this.prevZ = null;
  20181. this.nextZ = null;
  20182. // indicates whether this is a steiner point
  20183. this.steiner = false;
  20184. }
  20185. function signedArea( data, start, end, dim ) {
  20186. let sum = 0;
  20187. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20188. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20189. j = i;
  20190. }
  20191. return sum;
  20192. }
  20193. class ShapeUtils {
  20194. // calculate area of the contour polygon
  20195. static area( contour ) {
  20196. const n = contour.length;
  20197. let a = 0.0;
  20198. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20199. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20200. }
  20201. return a * 0.5;
  20202. }
  20203. static isClockWise( pts ) {
  20204. return ShapeUtils.area( pts ) < 0;
  20205. }
  20206. static triangulateShape( contour, holes ) {
  20207. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20208. const holeIndices = []; // array of hole indices
  20209. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20210. removeDupEndPts( contour );
  20211. addContour( vertices, contour );
  20212. //
  20213. let holeIndex = contour.length;
  20214. holes.forEach( removeDupEndPts );
  20215. for ( let i = 0; i < holes.length; i ++ ) {
  20216. holeIndices.push( holeIndex );
  20217. holeIndex += holes[ i ].length;
  20218. addContour( vertices, holes[ i ] );
  20219. }
  20220. //
  20221. const triangles = Earcut.triangulate( vertices, holeIndices );
  20222. //
  20223. for ( let i = 0; i < triangles.length; i += 3 ) {
  20224. faces.push( triangles.slice( i, i + 3 ) );
  20225. }
  20226. return faces;
  20227. }
  20228. }
  20229. function removeDupEndPts( points ) {
  20230. const l = points.length;
  20231. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20232. points.pop();
  20233. }
  20234. }
  20235. function addContour( vertices, contour ) {
  20236. for ( let i = 0; i < contour.length; i ++ ) {
  20237. vertices.push( contour[ i ].x );
  20238. vertices.push( contour[ i ].y );
  20239. }
  20240. }
  20241. /**
  20242. * Creates extruded geometry from a path shape.
  20243. *
  20244. * parameters = {
  20245. *
  20246. * curveSegments: <int>, // number of points on the curves
  20247. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20248. * depth: <float>, // Depth to extrude the shape
  20249. *
  20250. * bevelEnabled: <bool>, // turn on bevel
  20251. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20252. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20253. * bevelOffset: <float>, // how far from shape outline does bevel start
  20254. * bevelSegments: <int>, // number of bevel layers
  20255. *
  20256. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20257. *
  20258. * UVGenerator: <Object> // object that provides UV generator functions
  20259. *
  20260. * }
  20261. */
  20262. class ExtrudeGeometry extends BufferGeometry {
  20263. 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 = {} ) {
  20264. super();
  20265. this.type = 'ExtrudeGeometry';
  20266. this.parameters = {
  20267. shapes: shapes,
  20268. options: options
  20269. };
  20270. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20271. const scope = this;
  20272. const verticesArray = [];
  20273. const uvArray = [];
  20274. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20275. const shape = shapes[ i ];
  20276. addShape( shape );
  20277. }
  20278. // build geometry
  20279. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20280. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20281. this.computeVertexNormals();
  20282. // functions
  20283. function addShape( shape ) {
  20284. const placeholder = [];
  20285. // options
  20286. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20287. const steps = options.steps !== undefined ? options.steps : 1;
  20288. let depth = options.depth !== undefined ? options.depth : 1;
  20289. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20290. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20291. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20292. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20293. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20294. const extrudePath = options.extrudePath;
  20295. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20296. // deprecated options
  20297. if ( options.amount !== undefined ) {
  20298. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  20299. depth = options.amount;
  20300. }
  20301. //
  20302. let extrudePts, extrudeByPath = false;
  20303. let splineTube, binormal, normal, position2;
  20304. if ( extrudePath ) {
  20305. extrudePts = extrudePath.getSpacedPoints( steps );
  20306. extrudeByPath = true;
  20307. bevelEnabled = false; // bevels not supported for path extrusion
  20308. // SETUP TNB variables
  20309. // TODO1 - have a .isClosed in spline?
  20310. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20311. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20312. binormal = new Vector3();
  20313. normal = new Vector3();
  20314. position2 = new Vector3();
  20315. }
  20316. // Safeguards if bevels are not enabled
  20317. if ( ! bevelEnabled ) {
  20318. bevelSegments = 0;
  20319. bevelThickness = 0;
  20320. bevelSize = 0;
  20321. bevelOffset = 0;
  20322. }
  20323. // Variables initialization
  20324. const shapePoints = shape.extractPoints( curveSegments );
  20325. let vertices = shapePoints.shape;
  20326. const holes = shapePoints.holes;
  20327. const reverse = ! ShapeUtils.isClockWise( vertices );
  20328. if ( reverse ) {
  20329. vertices = vertices.reverse();
  20330. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20331. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20332. const ahole = holes[ h ];
  20333. if ( ShapeUtils.isClockWise( ahole ) ) {
  20334. holes[ h ] = ahole.reverse();
  20335. }
  20336. }
  20337. }
  20338. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20339. /* Vertices */
  20340. const contour = vertices; // vertices has all points but contour has only points of circumference
  20341. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20342. const ahole = holes[ h ];
  20343. vertices = vertices.concat( ahole );
  20344. }
  20345. function scalePt2( pt, vec, size ) {
  20346. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20347. return vec.clone().multiplyScalar( size ).add( pt );
  20348. }
  20349. const vlen = vertices.length, flen = faces.length;
  20350. // Find directions for point movement
  20351. function getBevelVec( inPt, inPrev, inNext ) {
  20352. // computes for inPt the corresponding point inPt' on a new contour
  20353. // shifted by 1 unit (length of normalized vector) to the left
  20354. // if we walk along contour clockwise, this new contour is outside the old one
  20355. //
  20356. // inPt' is the intersection of the two lines parallel to the two
  20357. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20358. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20359. // good reading for geometry algorithms (here: line-line intersection)
  20360. // http://geomalgorithms.com/a05-_intersect-1.html
  20361. const v_prev_x = inPt.x - inPrev.x,
  20362. v_prev_y = inPt.y - inPrev.y;
  20363. const v_next_x = inNext.x - inPt.x,
  20364. v_next_y = inNext.y - inPt.y;
  20365. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20366. // check for collinear edges
  20367. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20368. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20369. // not collinear
  20370. // length of vectors for normalizing
  20371. const v_prev_len = Math.sqrt( v_prev_lensq );
  20372. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20373. // shift adjacent points by unit vectors to the left
  20374. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20375. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20376. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20377. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20378. // scaling factor for v_prev to intersection point
  20379. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20380. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20381. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20382. // vector from inPt to intersection point
  20383. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20384. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20385. // Don't normalize!, otherwise sharp corners become ugly
  20386. // but prevent crazy spikes
  20387. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20388. if ( v_trans_lensq <= 2 ) {
  20389. return new Vector2( v_trans_x, v_trans_y );
  20390. } else {
  20391. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20392. }
  20393. } else {
  20394. // handle special case of collinear edges
  20395. let direction_eq = false; // assumes: opposite
  20396. if ( v_prev_x > Number.EPSILON ) {
  20397. if ( v_next_x > Number.EPSILON ) {
  20398. direction_eq = true;
  20399. }
  20400. } else {
  20401. if ( v_prev_x < - Number.EPSILON ) {
  20402. if ( v_next_x < - Number.EPSILON ) {
  20403. direction_eq = true;
  20404. }
  20405. } else {
  20406. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20407. direction_eq = true;
  20408. }
  20409. }
  20410. }
  20411. if ( direction_eq ) {
  20412. // console.log("Warning: lines are a straight sequence");
  20413. v_trans_x = - v_prev_y;
  20414. v_trans_y = v_prev_x;
  20415. shrink_by = Math.sqrt( v_prev_lensq );
  20416. } else {
  20417. // console.log("Warning: lines are a straight spike");
  20418. v_trans_x = v_prev_x;
  20419. v_trans_y = v_prev_y;
  20420. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20421. }
  20422. }
  20423. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20424. }
  20425. const contourMovements = [];
  20426. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20427. if ( j === il ) j = 0;
  20428. if ( k === il ) k = 0;
  20429. // (j)---(i)---(k)
  20430. // console.log('i,j,k', i, j , k)
  20431. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20432. }
  20433. const holesMovements = [];
  20434. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20435. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20436. const ahole = holes[ h ];
  20437. oneHoleMovements = [];
  20438. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20439. if ( j === il ) j = 0;
  20440. if ( k === il ) k = 0;
  20441. // (j)---(i)---(k)
  20442. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20443. }
  20444. holesMovements.push( oneHoleMovements );
  20445. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20446. }
  20447. // Loop bevelSegments, 1 for the front, 1 for the back
  20448. for ( let b = 0; b < bevelSegments; b ++ ) {
  20449. //for ( b = bevelSegments; b > 0; b -- ) {
  20450. const t = b / bevelSegments;
  20451. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20452. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20453. // contract shape
  20454. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20455. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20456. v( vert.x, vert.y, - z );
  20457. }
  20458. // expand holes
  20459. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20460. const ahole = holes[ h ];
  20461. oneHoleMovements = holesMovements[ h ];
  20462. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20463. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20464. v( vert.x, vert.y, - z );
  20465. }
  20466. }
  20467. }
  20468. const bs = bevelSize + bevelOffset;
  20469. // Back facing vertices
  20470. for ( let i = 0; i < vlen; i ++ ) {
  20471. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20472. if ( ! extrudeByPath ) {
  20473. v( vert.x, vert.y, 0 );
  20474. } else {
  20475. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20476. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20477. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20478. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20479. v( position2.x, position2.y, position2.z );
  20480. }
  20481. }
  20482. // Add stepped vertices...
  20483. // Including front facing vertices
  20484. for ( let s = 1; s <= steps; s ++ ) {
  20485. for ( let i = 0; i < vlen; i ++ ) {
  20486. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20487. if ( ! extrudeByPath ) {
  20488. v( vert.x, vert.y, depth / steps * s );
  20489. } else {
  20490. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20491. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20492. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20493. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20494. v( position2.x, position2.y, position2.z );
  20495. }
  20496. }
  20497. }
  20498. // Add bevel segments planes
  20499. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20500. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  20501. const t = b / bevelSegments;
  20502. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20503. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20504. // contract shape
  20505. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20506. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20507. v( vert.x, vert.y, depth + z );
  20508. }
  20509. // expand holes
  20510. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20511. const ahole = holes[ h ];
  20512. oneHoleMovements = holesMovements[ h ];
  20513. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20514. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20515. if ( ! extrudeByPath ) {
  20516. v( vert.x, vert.y, depth + z );
  20517. } else {
  20518. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20519. }
  20520. }
  20521. }
  20522. }
  20523. /* Faces */
  20524. // Top and bottom faces
  20525. buildLidFaces();
  20526. // Sides faces
  20527. buildSideFaces();
  20528. ///// Internal functions
  20529. function buildLidFaces() {
  20530. const start = verticesArray.length / 3;
  20531. if ( bevelEnabled ) {
  20532. let layer = 0; // steps + 1
  20533. let offset = vlen * layer;
  20534. // Bottom faces
  20535. for ( let i = 0; i < flen; i ++ ) {
  20536. const face = faces[ i ];
  20537. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20538. }
  20539. layer = steps + bevelSegments * 2;
  20540. offset = vlen * layer;
  20541. // Top faces
  20542. for ( let i = 0; i < flen; i ++ ) {
  20543. const face = faces[ i ];
  20544. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20545. }
  20546. } else {
  20547. // Bottom faces
  20548. for ( let i = 0; i < flen; i ++ ) {
  20549. const face = faces[ i ];
  20550. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20551. }
  20552. // Top faces
  20553. for ( let i = 0; i < flen; i ++ ) {
  20554. const face = faces[ i ];
  20555. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20556. }
  20557. }
  20558. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  20559. }
  20560. // Create faces for the z-sides of the shape
  20561. function buildSideFaces() {
  20562. const start = verticesArray.length / 3;
  20563. let layeroffset = 0;
  20564. sidewalls( contour, layeroffset );
  20565. layeroffset += contour.length;
  20566. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20567. const ahole = holes[ h ];
  20568. sidewalls( ahole, layeroffset );
  20569. //, true
  20570. layeroffset += ahole.length;
  20571. }
  20572. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  20573. }
  20574. function sidewalls( contour, layeroffset ) {
  20575. let i = contour.length;
  20576. while ( -- i >= 0 ) {
  20577. const j = i;
  20578. let k = i - 1;
  20579. if ( k < 0 ) k = contour.length - 1;
  20580. //console.log('b', i,j, i-1, k,vertices.length);
  20581. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  20582. const slen1 = vlen * s;
  20583. const slen2 = vlen * ( s + 1 );
  20584. const a = layeroffset + j + slen1,
  20585. b = layeroffset + k + slen1,
  20586. c = layeroffset + k + slen2,
  20587. d = layeroffset + j + slen2;
  20588. f4( a, b, c, d );
  20589. }
  20590. }
  20591. }
  20592. function v( x, y, z ) {
  20593. placeholder.push( x );
  20594. placeholder.push( y );
  20595. placeholder.push( z );
  20596. }
  20597. function f3( a, b, c ) {
  20598. addVertex( a );
  20599. addVertex( b );
  20600. addVertex( c );
  20601. const nextIndex = verticesArray.length / 3;
  20602. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20603. addUV( uvs[ 0 ] );
  20604. addUV( uvs[ 1 ] );
  20605. addUV( uvs[ 2 ] );
  20606. }
  20607. function f4( a, b, c, d ) {
  20608. addVertex( a );
  20609. addVertex( b );
  20610. addVertex( d );
  20611. addVertex( b );
  20612. addVertex( c );
  20613. addVertex( d );
  20614. const nextIndex = verticesArray.length / 3;
  20615. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20616. addUV( uvs[ 0 ] );
  20617. addUV( uvs[ 1 ] );
  20618. addUV( uvs[ 3 ] );
  20619. addUV( uvs[ 1 ] );
  20620. addUV( uvs[ 2 ] );
  20621. addUV( uvs[ 3 ] );
  20622. }
  20623. function addVertex( index ) {
  20624. verticesArray.push( placeholder[ index * 3 + 0 ] );
  20625. verticesArray.push( placeholder[ index * 3 + 1 ] );
  20626. verticesArray.push( placeholder[ index * 3 + 2 ] );
  20627. }
  20628. function addUV( vector2 ) {
  20629. uvArray.push( vector2.x );
  20630. uvArray.push( vector2.y );
  20631. }
  20632. }
  20633. }
  20634. toJSON() {
  20635. const data = super.toJSON();
  20636. const shapes = this.parameters.shapes;
  20637. const options = this.parameters.options;
  20638. return toJSON$1( shapes, options, data );
  20639. }
  20640. static fromJSON( data, shapes ) {
  20641. const geometryShapes = [];
  20642. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20643. const shape = shapes[ data.shapes[ j ] ];
  20644. geometryShapes.push( shape );
  20645. }
  20646. const extrudePath = data.options.extrudePath;
  20647. if ( extrudePath !== undefined ) {
  20648. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20649. }
  20650. return new ExtrudeGeometry( geometryShapes, data.options );
  20651. }
  20652. }
  20653. const WorldUVGenerator = {
  20654. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20655. const a_x = vertices[ indexA * 3 ];
  20656. const a_y = vertices[ indexA * 3 + 1 ];
  20657. const b_x = vertices[ indexB * 3 ];
  20658. const b_y = vertices[ indexB * 3 + 1 ];
  20659. const c_x = vertices[ indexC * 3 ];
  20660. const c_y = vertices[ indexC * 3 + 1 ];
  20661. return [
  20662. new Vector2( a_x, a_y ),
  20663. new Vector2( b_x, b_y ),
  20664. new Vector2( c_x, c_y )
  20665. ];
  20666. },
  20667. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20668. const a_x = vertices[ indexA * 3 ];
  20669. const a_y = vertices[ indexA * 3 + 1 ];
  20670. const a_z = vertices[ indexA * 3 + 2 ];
  20671. const b_x = vertices[ indexB * 3 ];
  20672. const b_y = vertices[ indexB * 3 + 1 ];
  20673. const b_z = vertices[ indexB * 3 + 2 ];
  20674. const c_x = vertices[ indexC * 3 ];
  20675. const c_y = vertices[ indexC * 3 + 1 ];
  20676. const c_z = vertices[ indexC * 3 + 2 ];
  20677. const d_x = vertices[ indexD * 3 ];
  20678. const d_y = vertices[ indexD * 3 + 1 ];
  20679. const d_z = vertices[ indexD * 3 + 2 ];
  20680. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  20681. return [
  20682. new Vector2( a_x, 1 - a_z ),
  20683. new Vector2( b_x, 1 - b_z ),
  20684. new Vector2( c_x, 1 - c_z ),
  20685. new Vector2( d_x, 1 - d_z )
  20686. ];
  20687. } else {
  20688. return [
  20689. new Vector2( a_y, 1 - a_z ),
  20690. new Vector2( b_y, 1 - b_z ),
  20691. new Vector2( c_y, 1 - c_z ),
  20692. new Vector2( d_y, 1 - d_z )
  20693. ];
  20694. }
  20695. }
  20696. };
  20697. function toJSON$1( shapes, options, data ) {
  20698. data.shapes = [];
  20699. if ( Array.isArray( shapes ) ) {
  20700. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20701. const shape = shapes[ i ];
  20702. data.shapes.push( shape.uuid );
  20703. }
  20704. } else {
  20705. data.shapes.push( shapes.uuid );
  20706. }
  20707. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  20708. return data;
  20709. }
  20710. class IcosahedronGeometry extends PolyhedronGeometry {
  20711. constructor( radius = 1, detail = 0 ) {
  20712. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20713. const vertices = [
  20714. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20715. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20716. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20717. ];
  20718. const indices = [
  20719. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20720. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20721. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20722. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20723. ];
  20724. super( vertices, indices, radius, detail );
  20725. this.type = 'IcosahedronGeometry';
  20726. this.parameters = {
  20727. radius: radius,
  20728. detail: detail
  20729. };
  20730. }
  20731. static fromJSON( data ) {
  20732. return new IcosahedronGeometry( data.radius, data.detail );
  20733. }
  20734. }
  20735. class LatheGeometry extends BufferGeometry {
  20736. 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 ) {
  20737. super();
  20738. this.type = 'LatheGeometry';
  20739. this.parameters = {
  20740. points: points,
  20741. segments: segments,
  20742. phiStart: phiStart,
  20743. phiLength: phiLength
  20744. };
  20745. segments = Math.floor( segments );
  20746. // clamp phiLength so it's in range of [ 0, 2PI ]
  20747. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20748. // buffers
  20749. const indices = [];
  20750. const vertices = [];
  20751. const uvs = [];
  20752. const initNormals = [];
  20753. const normals = [];
  20754. // helper variables
  20755. const inverseSegments = 1.0 / segments;
  20756. const vertex = new Vector3();
  20757. const uv = new Vector2();
  20758. const normal = new Vector3();
  20759. const curNormal = new Vector3();
  20760. const prevNormal = new Vector3();
  20761. let dx = 0;
  20762. let dy = 0;
  20763. // pre-compute normals for initial "meridian"
  20764. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20765. switch ( j ) {
  20766. case 0: // special handling for 1st vertex on path
  20767. dx = points[ j + 1 ].x - points[ j ].x;
  20768. dy = points[ j + 1 ].y - points[ j ].y;
  20769. normal.x = dy * 1.0;
  20770. normal.y = - dx;
  20771. normal.z = dy * 0.0;
  20772. prevNormal.copy( normal );
  20773. normal.normalize();
  20774. initNormals.push( normal.x, normal.y, normal.z );
  20775. break;
  20776. case ( points.length - 1 ): // special handling for last Vertex on path
  20777. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20778. break;
  20779. default: // default handling for all vertices in between
  20780. dx = points[ j + 1 ].x - points[ j ].x;
  20781. dy = points[ j + 1 ].y - points[ j ].y;
  20782. normal.x = dy * 1.0;
  20783. normal.y = - dx;
  20784. normal.z = dy * 0.0;
  20785. curNormal.copy( normal );
  20786. normal.x += prevNormal.x;
  20787. normal.y += prevNormal.y;
  20788. normal.z += prevNormal.z;
  20789. normal.normalize();
  20790. initNormals.push( normal.x, normal.y, normal.z );
  20791. prevNormal.copy( curNormal );
  20792. }
  20793. }
  20794. // generate vertices, uvs and normals
  20795. for ( let i = 0; i <= segments; i ++ ) {
  20796. const phi = phiStart + i * inverseSegments * phiLength;
  20797. const sin = Math.sin( phi );
  20798. const cos = Math.cos( phi );
  20799. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20800. // vertex
  20801. vertex.x = points[ j ].x * sin;
  20802. vertex.y = points[ j ].y;
  20803. vertex.z = points[ j ].x * cos;
  20804. vertices.push( vertex.x, vertex.y, vertex.z );
  20805. // uv
  20806. uv.x = i / segments;
  20807. uv.y = j / ( points.length - 1 );
  20808. uvs.push( uv.x, uv.y );
  20809. // normal
  20810. const x = initNormals[ 3 * j + 0 ] * sin;
  20811. const y = initNormals[ 3 * j + 1 ];
  20812. const z = initNormals[ 3 * j + 0 ] * cos;
  20813. normals.push( x, y, z );
  20814. }
  20815. }
  20816. // indices
  20817. for ( let i = 0; i < segments; i ++ ) {
  20818. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20819. const base = j + i * points.length;
  20820. const a = base;
  20821. const b = base + points.length;
  20822. const c = base + points.length + 1;
  20823. const d = base + 1;
  20824. // faces
  20825. indices.push( a, b, d );
  20826. indices.push( c, d, b );
  20827. }
  20828. }
  20829. // build geometry
  20830. this.setIndex( indices );
  20831. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20832. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20833. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20834. }
  20835. static fromJSON( data ) {
  20836. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20837. }
  20838. }
  20839. class OctahedronGeometry extends PolyhedronGeometry {
  20840. constructor( radius = 1, detail = 0 ) {
  20841. const vertices = [
  20842. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  20843. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20844. ];
  20845. const indices = [
  20846. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20847. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20848. 1, 3, 4, 1, 4, 2
  20849. ];
  20850. super( vertices, indices, radius, detail );
  20851. this.type = 'OctahedronGeometry';
  20852. this.parameters = {
  20853. radius: radius,
  20854. detail: detail
  20855. };
  20856. }
  20857. static fromJSON( data ) {
  20858. return new OctahedronGeometry( data.radius, data.detail );
  20859. }
  20860. }
  20861. class RingGeometry extends BufferGeometry {
  20862. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20863. super();
  20864. this.type = 'RingGeometry';
  20865. this.parameters = {
  20866. innerRadius: innerRadius,
  20867. outerRadius: outerRadius,
  20868. thetaSegments: thetaSegments,
  20869. phiSegments: phiSegments,
  20870. thetaStart: thetaStart,
  20871. thetaLength: thetaLength
  20872. };
  20873. thetaSegments = Math.max( 3, thetaSegments );
  20874. phiSegments = Math.max( 1, phiSegments );
  20875. // buffers
  20876. const indices = [];
  20877. const vertices = [];
  20878. const normals = [];
  20879. const uvs = [];
  20880. // some helper variables
  20881. let radius = innerRadius;
  20882. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20883. const vertex = new Vector3();
  20884. const uv = new Vector2();
  20885. // generate vertices, normals and uvs
  20886. for ( let j = 0; j <= phiSegments; j ++ ) {
  20887. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20888. // values are generate from the inside of the ring to the outside
  20889. const segment = thetaStart + i / thetaSegments * thetaLength;
  20890. // vertex
  20891. vertex.x = radius * Math.cos( segment );
  20892. vertex.y = radius * Math.sin( segment );
  20893. vertices.push( vertex.x, vertex.y, vertex.z );
  20894. // normal
  20895. normals.push( 0, 0, 1 );
  20896. // uv
  20897. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20898. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20899. uvs.push( uv.x, uv.y );
  20900. }
  20901. // increase the radius for next row of vertices
  20902. radius += radiusStep;
  20903. }
  20904. // indices
  20905. for ( let j = 0; j < phiSegments; j ++ ) {
  20906. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20907. for ( let i = 0; i < thetaSegments; i ++ ) {
  20908. const segment = i + thetaSegmentLevel;
  20909. const a = segment;
  20910. const b = segment + thetaSegments + 1;
  20911. const c = segment + thetaSegments + 2;
  20912. const d = segment + 1;
  20913. // faces
  20914. indices.push( a, b, d );
  20915. indices.push( b, c, d );
  20916. }
  20917. }
  20918. // build geometry
  20919. this.setIndex( indices );
  20920. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20921. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20922. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20923. }
  20924. static fromJSON( data ) {
  20925. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20926. }
  20927. }
  20928. class ShapeGeometry extends BufferGeometry {
  20929. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  20930. super();
  20931. this.type = 'ShapeGeometry';
  20932. this.parameters = {
  20933. shapes: shapes,
  20934. curveSegments: curveSegments
  20935. };
  20936. // buffers
  20937. const indices = [];
  20938. const vertices = [];
  20939. const normals = [];
  20940. const uvs = [];
  20941. // helper variables
  20942. let groupStart = 0;
  20943. let groupCount = 0;
  20944. // allow single and array values for "shapes" parameter
  20945. if ( Array.isArray( shapes ) === false ) {
  20946. addShape( shapes );
  20947. } else {
  20948. for ( let i = 0; i < shapes.length; i ++ ) {
  20949. addShape( shapes[ i ] );
  20950. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20951. groupStart += groupCount;
  20952. groupCount = 0;
  20953. }
  20954. }
  20955. // build geometry
  20956. this.setIndex( indices );
  20957. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20958. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20959. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20960. // helper functions
  20961. function addShape( shape ) {
  20962. const indexOffset = vertices.length / 3;
  20963. const points = shape.extractPoints( curveSegments );
  20964. let shapeVertices = points.shape;
  20965. const shapeHoles = points.holes;
  20966. // check direction of vertices
  20967. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20968. shapeVertices = shapeVertices.reverse();
  20969. }
  20970. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20971. const shapeHole = shapeHoles[ i ];
  20972. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20973. shapeHoles[ i ] = shapeHole.reverse();
  20974. }
  20975. }
  20976. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20977. // join vertices of inner and outer paths to a single array
  20978. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20979. const shapeHole = shapeHoles[ i ];
  20980. shapeVertices = shapeVertices.concat( shapeHole );
  20981. }
  20982. // vertices, normals, uvs
  20983. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20984. const vertex = shapeVertices[ i ];
  20985. vertices.push( vertex.x, vertex.y, 0 );
  20986. normals.push( 0, 0, 1 );
  20987. uvs.push( vertex.x, vertex.y ); // world uvs
  20988. }
  20989. // incides
  20990. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20991. const face = faces[ i ];
  20992. const a = face[ 0 ] + indexOffset;
  20993. const b = face[ 1 ] + indexOffset;
  20994. const c = face[ 2 ] + indexOffset;
  20995. indices.push( a, b, c );
  20996. groupCount += 3;
  20997. }
  20998. }
  20999. }
  21000. toJSON() {
  21001. const data = super.toJSON();
  21002. const shapes = this.parameters.shapes;
  21003. return toJSON( shapes, data );
  21004. }
  21005. static fromJSON( data, shapes ) {
  21006. const geometryShapes = [];
  21007. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21008. const shape = shapes[ data.shapes[ j ] ];
  21009. geometryShapes.push( shape );
  21010. }
  21011. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21012. }
  21013. }
  21014. function toJSON( shapes, data ) {
  21015. data.shapes = [];
  21016. if ( Array.isArray( shapes ) ) {
  21017. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21018. const shape = shapes[ i ];
  21019. data.shapes.push( shape.uuid );
  21020. }
  21021. } else {
  21022. data.shapes.push( shapes.uuid );
  21023. }
  21024. return data;
  21025. }
  21026. class SphereGeometry extends BufferGeometry {
  21027. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21028. super();
  21029. this.type = 'SphereGeometry';
  21030. this.parameters = {
  21031. radius: radius,
  21032. widthSegments: widthSegments,
  21033. heightSegments: heightSegments,
  21034. phiStart: phiStart,
  21035. phiLength: phiLength,
  21036. thetaStart: thetaStart,
  21037. thetaLength: thetaLength
  21038. };
  21039. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21040. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21041. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21042. let index = 0;
  21043. const grid = [];
  21044. const vertex = new Vector3();
  21045. const normal = new Vector3();
  21046. // buffers
  21047. const indices = [];
  21048. const vertices = [];
  21049. const normals = [];
  21050. const uvs = [];
  21051. // generate vertices, normals and uvs
  21052. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21053. const verticesRow = [];
  21054. const v = iy / heightSegments;
  21055. // special case for the poles
  21056. let uOffset = 0;
  21057. if ( iy == 0 && thetaStart == 0 ) {
  21058. uOffset = 0.5 / widthSegments;
  21059. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21060. uOffset = - 0.5 / widthSegments;
  21061. }
  21062. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21063. const u = ix / widthSegments;
  21064. // vertex
  21065. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21066. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21067. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21068. vertices.push( vertex.x, vertex.y, vertex.z );
  21069. // normal
  21070. normal.copy( vertex ).normalize();
  21071. normals.push( normal.x, normal.y, normal.z );
  21072. // uv
  21073. uvs.push( u + uOffset, 1 - v );
  21074. verticesRow.push( index ++ );
  21075. }
  21076. grid.push( verticesRow );
  21077. }
  21078. // indices
  21079. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21080. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21081. const a = grid[ iy ][ ix + 1 ];
  21082. const b = grid[ iy ][ ix ];
  21083. const c = grid[ iy + 1 ][ ix ];
  21084. const d = grid[ iy + 1 ][ ix + 1 ];
  21085. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21086. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21087. }
  21088. }
  21089. // build geometry
  21090. this.setIndex( indices );
  21091. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21092. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21093. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21094. }
  21095. static fromJSON( data ) {
  21096. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21097. }
  21098. }
  21099. class TetrahedronGeometry extends PolyhedronGeometry {
  21100. constructor( radius = 1, detail = 0 ) {
  21101. const vertices = [
  21102. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21103. ];
  21104. const indices = [
  21105. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21106. ];
  21107. super( vertices, indices, radius, detail );
  21108. this.type = 'TetrahedronGeometry';
  21109. this.parameters = {
  21110. radius: radius,
  21111. detail: detail
  21112. };
  21113. }
  21114. static fromJSON( data ) {
  21115. return new TetrahedronGeometry( data.radius, data.detail );
  21116. }
  21117. }
  21118. class TorusGeometry extends BufferGeometry {
  21119. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21120. super();
  21121. this.type = 'TorusGeometry';
  21122. this.parameters = {
  21123. radius: radius,
  21124. tube: tube,
  21125. radialSegments: radialSegments,
  21126. tubularSegments: tubularSegments,
  21127. arc: arc
  21128. };
  21129. radialSegments = Math.floor( radialSegments );
  21130. tubularSegments = Math.floor( tubularSegments );
  21131. // buffers
  21132. const indices = [];
  21133. const vertices = [];
  21134. const normals = [];
  21135. const uvs = [];
  21136. // helper variables
  21137. const center = new Vector3();
  21138. const vertex = new Vector3();
  21139. const normal = new Vector3();
  21140. // generate vertices, normals and uvs
  21141. for ( let j = 0; j <= radialSegments; j ++ ) {
  21142. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21143. const u = i / tubularSegments * arc;
  21144. const v = j / radialSegments * Math.PI * 2;
  21145. // vertex
  21146. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21147. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21148. vertex.z = tube * Math.sin( v );
  21149. vertices.push( vertex.x, vertex.y, vertex.z );
  21150. // normal
  21151. center.x = radius * Math.cos( u );
  21152. center.y = radius * Math.sin( u );
  21153. normal.subVectors( vertex, center ).normalize();
  21154. normals.push( normal.x, normal.y, normal.z );
  21155. // uv
  21156. uvs.push( i / tubularSegments );
  21157. uvs.push( j / radialSegments );
  21158. }
  21159. }
  21160. // generate indices
  21161. for ( let j = 1; j <= radialSegments; j ++ ) {
  21162. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21163. // indices
  21164. const a = ( tubularSegments + 1 ) * j + i - 1;
  21165. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21166. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21167. const d = ( tubularSegments + 1 ) * j + i;
  21168. // faces
  21169. indices.push( a, b, d );
  21170. indices.push( b, c, d );
  21171. }
  21172. }
  21173. // build geometry
  21174. this.setIndex( indices );
  21175. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21176. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21177. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21178. }
  21179. static fromJSON( data ) {
  21180. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21181. }
  21182. }
  21183. class TorusKnotGeometry extends BufferGeometry {
  21184. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21185. super();
  21186. this.type = 'TorusKnotGeometry';
  21187. this.parameters = {
  21188. radius: radius,
  21189. tube: tube,
  21190. tubularSegments: tubularSegments,
  21191. radialSegments: radialSegments,
  21192. p: p,
  21193. q: q
  21194. };
  21195. tubularSegments = Math.floor( tubularSegments );
  21196. radialSegments = Math.floor( radialSegments );
  21197. // buffers
  21198. const indices = [];
  21199. const vertices = [];
  21200. const normals = [];
  21201. const uvs = [];
  21202. // helper variables
  21203. const vertex = new Vector3();
  21204. const normal = new Vector3();
  21205. const P1 = new Vector3();
  21206. const P2 = new Vector3();
  21207. const B = new Vector3();
  21208. const T = new Vector3();
  21209. const N = new Vector3();
  21210. // generate vertices, normals and uvs
  21211. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21212. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  21213. const u = i / tubularSegments * p * Math.PI * 2;
  21214. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21215. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21216. calculatePositionOnCurve( u, p, q, radius, P1 );
  21217. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21218. // calculate orthonormal basis
  21219. T.subVectors( P2, P1 );
  21220. N.addVectors( P2, P1 );
  21221. B.crossVectors( T, N );
  21222. N.crossVectors( B, T );
  21223. // normalize B, N. T can be ignored, we don't use it
  21224. B.normalize();
  21225. N.normalize();
  21226. for ( let j = 0; j <= radialSegments; ++ j ) {
  21227. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21228. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21229. const v = j / radialSegments * Math.PI * 2;
  21230. const cx = - tube * Math.cos( v );
  21231. const cy = tube * Math.sin( v );
  21232. // now calculate the final vertex position.
  21233. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  21234. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21235. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21236. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21237. vertices.push( vertex.x, vertex.y, vertex.z );
  21238. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21239. normal.subVectors( vertex, P1 ).normalize();
  21240. normals.push( normal.x, normal.y, normal.z );
  21241. // uv
  21242. uvs.push( i / tubularSegments );
  21243. uvs.push( j / radialSegments );
  21244. }
  21245. }
  21246. // generate indices
  21247. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21248. for ( let i = 1; i <= radialSegments; i ++ ) {
  21249. // indices
  21250. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21251. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21252. const c = ( radialSegments + 1 ) * j + i;
  21253. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21254. // faces
  21255. indices.push( a, b, d );
  21256. indices.push( b, c, d );
  21257. }
  21258. }
  21259. // build geometry
  21260. this.setIndex( indices );
  21261. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21262. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21263. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21264. // this function calculates the current position on the torus curve
  21265. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21266. const cu = Math.cos( u );
  21267. const su = Math.sin( u );
  21268. const quOverP = q / p * u;
  21269. const cs = Math.cos( quOverP );
  21270. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21271. position.y = radius * ( 2 + cs ) * su * 0.5;
  21272. position.z = radius * Math.sin( quOverP ) * 0.5;
  21273. }
  21274. }
  21275. static fromJSON( data ) {
  21276. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21277. }
  21278. }
  21279. class TubeGeometry extends BufferGeometry {
  21280. 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 ) {
  21281. super();
  21282. this.type = 'TubeGeometry';
  21283. this.parameters = {
  21284. path: path,
  21285. tubularSegments: tubularSegments,
  21286. radius: radius,
  21287. radialSegments: radialSegments,
  21288. closed: closed
  21289. };
  21290. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21291. // expose internals
  21292. this.tangents = frames.tangents;
  21293. this.normals = frames.normals;
  21294. this.binormals = frames.binormals;
  21295. // helper variables
  21296. const vertex = new Vector3();
  21297. const normal = new Vector3();
  21298. const uv = new Vector2();
  21299. let P = new Vector3();
  21300. // buffer
  21301. const vertices = [];
  21302. const normals = [];
  21303. const uvs = [];
  21304. const indices = [];
  21305. // create buffer data
  21306. generateBufferData();
  21307. // build geometry
  21308. this.setIndex( indices );
  21309. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21310. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21311. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21312. // functions
  21313. function generateBufferData() {
  21314. for ( let i = 0; i < tubularSegments; i ++ ) {
  21315. generateSegment( i );
  21316. }
  21317. // if the geometry is not closed, generate the last row of vertices and normals
  21318. // at the regular position on the given path
  21319. //
  21320. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21321. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21322. // uvs are generated in a separate function.
  21323. // this makes it easy compute correct values for closed geometries
  21324. generateUVs();
  21325. // finally create faces
  21326. generateIndices();
  21327. }
  21328. function generateSegment( i ) {
  21329. // we use getPointAt to sample evenly distributed points from the given path
  21330. P = path.getPointAt( i / tubularSegments, P );
  21331. // retrieve corresponding normal and binormal
  21332. const N = frames.normals[ i ];
  21333. const B = frames.binormals[ i ];
  21334. // generate normals and vertices for the current segment
  21335. for ( let j = 0; j <= radialSegments; j ++ ) {
  21336. const v = j / radialSegments * Math.PI * 2;
  21337. const sin = Math.sin( v );
  21338. const cos = - Math.cos( v );
  21339. // normal
  21340. normal.x = ( cos * N.x + sin * B.x );
  21341. normal.y = ( cos * N.y + sin * B.y );
  21342. normal.z = ( cos * N.z + sin * B.z );
  21343. normal.normalize();
  21344. normals.push( normal.x, normal.y, normal.z );
  21345. // vertex
  21346. vertex.x = P.x + radius * normal.x;
  21347. vertex.y = P.y + radius * normal.y;
  21348. vertex.z = P.z + radius * normal.z;
  21349. vertices.push( vertex.x, vertex.y, vertex.z );
  21350. }
  21351. }
  21352. function generateIndices() {
  21353. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21354. for ( let i = 1; i <= radialSegments; i ++ ) {
  21355. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21356. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21357. const c = ( radialSegments + 1 ) * j + i;
  21358. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21359. // faces
  21360. indices.push( a, b, d );
  21361. indices.push( b, c, d );
  21362. }
  21363. }
  21364. }
  21365. function generateUVs() {
  21366. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21367. for ( let j = 0; j <= radialSegments; j ++ ) {
  21368. uv.x = i / tubularSegments;
  21369. uv.y = j / radialSegments;
  21370. uvs.push( uv.x, uv.y );
  21371. }
  21372. }
  21373. }
  21374. }
  21375. toJSON() {
  21376. const data = super.toJSON();
  21377. data.path = this.parameters.path.toJSON();
  21378. return data;
  21379. }
  21380. static fromJSON( data ) {
  21381. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21382. // User defined curves or instances of CurvePath will not be deserialized.
  21383. return new TubeGeometry(
  21384. new Curves[ data.path.type ]().fromJSON( data.path ),
  21385. data.tubularSegments,
  21386. data.radius,
  21387. data.radialSegments,
  21388. data.closed
  21389. );
  21390. }
  21391. }
  21392. class WireframeGeometry extends BufferGeometry {
  21393. constructor( geometry = null ) {
  21394. super();
  21395. this.type = 'WireframeGeometry';
  21396. this.parameters = {
  21397. geometry: geometry
  21398. };
  21399. if ( geometry !== null ) {
  21400. // buffer
  21401. const vertices = [];
  21402. const edges = new Set();
  21403. // helper variables
  21404. const start = new Vector3();
  21405. const end = new Vector3();
  21406. if ( geometry.index !== null ) {
  21407. // indexed BufferGeometry
  21408. const position = geometry.attributes.position;
  21409. const indices = geometry.index;
  21410. let groups = geometry.groups;
  21411. if ( groups.length === 0 ) {
  21412. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  21413. }
  21414. // create a data structure that contains all eges without duplicates
  21415. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21416. const group = groups[ o ];
  21417. const groupStart = group.start;
  21418. const groupCount = group.count;
  21419. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21420. for ( let j = 0; j < 3; j ++ ) {
  21421. const index1 = indices.getX( i + j );
  21422. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21423. start.fromBufferAttribute( position, index1 );
  21424. end.fromBufferAttribute( position, index2 );
  21425. if ( isUniqueEdge( start, end, edges ) === true ) {
  21426. vertices.push( start.x, start.y, start.z );
  21427. vertices.push( end.x, end.y, end.z );
  21428. }
  21429. }
  21430. }
  21431. }
  21432. } else {
  21433. // non-indexed BufferGeometry
  21434. const position = geometry.attributes.position;
  21435. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21436. for ( let j = 0; j < 3; j ++ ) {
  21437. // three edges per triangle, an edge is represented as (index1, index2)
  21438. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21439. const index1 = 3 * i + j;
  21440. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21441. start.fromBufferAttribute( position, index1 );
  21442. end.fromBufferAttribute( position, index2 );
  21443. if ( isUniqueEdge( start, end, edges ) === true ) {
  21444. vertices.push( start.x, start.y, start.z );
  21445. vertices.push( end.x, end.y, end.z );
  21446. }
  21447. }
  21448. }
  21449. }
  21450. // build geometry
  21451. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21452. }
  21453. }
  21454. }
  21455. function isUniqueEdge( start, end, edges ) {
  21456. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21457. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21458. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21459. return false;
  21460. } else {
  21461. edges.add( hash1, hash2 );
  21462. return true;
  21463. }
  21464. }
  21465. var Geometries = /*#__PURE__*/Object.freeze({
  21466. __proto__: null,
  21467. BoxGeometry: BoxGeometry,
  21468. BoxBufferGeometry: BoxGeometry,
  21469. CircleGeometry: CircleGeometry,
  21470. CircleBufferGeometry: CircleGeometry,
  21471. ConeGeometry: ConeGeometry,
  21472. ConeBufferGeometry: ConeGeometry,
  21473. CylinderGeometry: CylinderGeometry,
  21474. CylinderBufferGeometry: CylinderGeometry,
  21475. DodecahedronGeometry: DodecahedronGeometry,
  21476. DodecahedronBufferGeometry: DodecahedronGeometry,
  21477. EdgesGeometry: EdgesGeometry,
  21478. ExtrudeGeometry: ExtrudeGeometry,
  21479. ExtrudeBufferGeometry: ExtrudeGeometry,
  21480. IcosahedronGeometry: IcosahedronGeometry,
  21481. IcosahedronBufferGeometry: IcosahedronGeometry,
  21482. LatheGeometry: LatheGeometry,
  21483. LatheBufferGeometry: LatheGeometry,
  21484. OctahedronGeometry: OctahedronGeometry,
  21485. OctahedronBufferGeometry: OctahedronGeometry,
  21486. PlaneGeometry: PlaneGeometry,
  21487. PlaneBufferGeometry: PlaneGeometry,
  21488. PolyhedronGeometry: PolyhedronGeometry,
  21489. PolyhedronBufferGeometry: PolyhedronGeometry,
  21490. RingGeometry: RingGeometry,
  21491. RingBufferGeometry: RingGeometry,
  21492. ShapeGeometry: ShapeGeometry,
  21493. ShapeBufferGeometry: ShapeGeometry,
  21494. SphereGeometry: SphereGeometry,
  21495. SphereBufferGeometry: SphereGeometry,
  21496. TetrahedronGeometry: TetrahedronGeometry,
  21497. TetrahedronBufferGeometry: TetrahedronGeometry,
  21498. TorusGeometry: TorusGeometry,
  21499. TorusBufferGeometry: TorusGeometry,
  21500. TorusKnotGeometry: TorusKnotGeometry,
  21501. TorusKnotBufferGeometry: TorusKnotGeometry,
  21502. TubeGeometry: TubeGeometry,
  21503. TubeBufferGeometry: TubeGeometry,
  21504. WireframeGeometry: WireframeGeometry
  21505. });
  21506. /**
  21507. * parameters = {
  21508. * color: <THREE.Color>
  21509. * }
  21510. */
  21511. class ShadowMaterial extends Material {
  21512. constructor( parameters ) {
  21513. super();
  21514. this.type = 'ShadowMaterial';
  21515. this.color = new Color( 0x000000 );
  21516. this.transparent = true;
  21517. this.setValues( parameters );
  21518. }
  21519. copy( source ) {
  21520. super.copy( source );
  21521. this.color.copy( source.color );
  21522. return this;
  21523. }
  21524. }
  21525. ShadowMaterial.prototype.isShadowMaterial = true;
  21526. /**
  21527. * parameters = {
  21528. * color: <hex>,
  21529. * roughness: <float>,
  21530. * metalness: <float>,
  21531. * opacity: <float>,
  21532. *
  21533. * map: new THREE.Texture( <Image> ),
  21534. *
  21535. * lightMap: new THREE.Texture( <Image> ),
  21536. * lightMapIntensity: <float>
  21537. *
  21538. * aoMap: new THREE.Texture( <Image> ),
  21539. * aoMapIntensity: <float>
  21540. *
  21541. * emissive: <hex>,
  21542. * emissiveIntensity: <float>
  21543. * emissiveMap: new THREE.Texture( <Image> ),
  21544. *
  21545. * bumpMap: new THREE.Texture( <Image> ),
  21546. * bumpScale: <float>,
  21547. *
  21548. * normalMap: new THREE.Texture( <Image> ),
  21549. * normalMapType: THREE.TangentSpaceNormalMap,
  21550. * normalScale: <Vector2>,
  21551. *
  21552. * displacementMap: new THREE.Texture( <Image> ),
  21553. * displacementScale: <float>,
  21554. * displacementBias: <float>,
  21555. *
  21556. * roughnessMap: new THREE.Texture( <Image> ),
  21557. *
  21558. * metalnessMap: new THREE.Texture( <Image> ),
  21559. *
  21560. * alphaMap: new THREE.Texture( <Image> ),
  21561. *
  21562. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21563. * envMapIntensity: <float>
  21564. *
  21565. * refractionRatio: <float>,
  21566. *
  21567. * wireframe: <boolean>,
  21568. * wireframeLinewidth: <float>,
  21569. *
  21570. * flatShading: <bool>
  21571. * }
  21572. */
  21573. class MeshStandardMaterial extends Material {
  21574. constructor( parameters ) {
  21575. super();
  21576. this.defines = { 'STANDARD': '' };
  21577. this.type = 'MeshStandardMaterial';
  21578. this.color = new Color( 0xffffff ); // diffuse
  21579. this.roughness = 1.0;
  21580. this.metalness = 0.0;
  21581. this.map = null;
  21582. this.lightMap = null;
  21583. this.lightMapIntensity = 1.0;
  21584. this.aoMap = null;
  21585. this.aoMapIntensity = 1.0;
  21586. this.emissive = new Color( 0x000000 );
  21587. this.emissiveIntensity = 1.0;
  21588. this.emissiveMap = null;
  21589. this.bumpMap = null;
  21590. this.bumpScale = 1;
  21591. this.normalMap = null;
  21592. this.normalMapType = TangentSpaceNormalMap;
  21593. this.normalScale = new Vector2( 1, 1 );
  21594. this.displacementMap = null;
  21595. this.displacementScale = 1;
  21596. this.displacementBias = 0;
  21597. this.roughnessMap = null;
  21598. this.metalnessMap = null;
  21599. this.alphaMap = null;
  21600. this.envMap = null;
  21601. this.envMapIntensity = 1.0;
  21602. this.refractionRatio = 0.98;
  21603. this.wireframe = false;
  21604. this.wireframeLinewidth = 1;
  21605. this.wireframeLinecap = 'round';
  21606. this.wireframeLinejoin = 'round';
  21607. this.flatShading = false;
  21608. this.setValues( parameters );
  21609. }
  21610. copy( source ) {
  21611. super.copy( source );
  21612. this.defines = { 'STANDARD': '' };
  21613. this.color.copy( source.color );
  21614. this.roughness = source.roughness;
  21615. this.metalness = source.metalness;
  21616. this.map = source.map;
  21617. this.lightMap = source.lightMap;
  21618. this.lightMapIntensity = source.lightMapIntensity;
  21619. this.aoMap = source.aoMap;
  21620. this.aoMapIntensity = source.aoMapIntensity;
  21621. this.emissive.copy( source.emissive );
  21622. this.emissiveMap = source.emissiveMap;
  21623. this.emissiveIntensity = source.emissiveIntensity;
  21624. this.bumpMap = source.bumpMap;
  21625. this.bumpScale = source.bumpScale;
  21626. this.normalMap = source.normalMap;
  21627. this.normalMapType = source.normalMapType;
  21628. this.normalScale.copy( source.normalScale );
  21629. this.displacementMap = source.displacementMap;
  21630. this.displacementScale = source.displacementScale;
  21631. this.displacementBias = source.displacementBias;
  21632. this.roughnessMap = source.roughnessMap;
  21633. this.metalnessMap = source.metalnessMap;
  21634. this.alphaMap = source.alphaMap;
  21635. this.envMap = source.envMap;
  21636. this.envMapIntensity = source.envMapIntensity;
  21637. this.refractionRatio = source.refractionRatio;
  21638. this.wireframe = source.wireframe;
  21639. this.wireframeLinewidth = source.wireframeLinewidth;
  21640. this.wireframeLinecap = source.wireframeLinecap;
  21641. this.wireframeLinejoin = source.wireframeLinejoin;
  21642. this.flatShading = source.flatShading;
  21643. return this;
  21644. }
  21645. }
  21646. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21647. /**
  21648. * parameters = {
  21649. * clearcoat: <float>,
  21650. * clearcoatMap: new THREE.Texture( <Image> ),
  21651. * clearcoatRoughness: <float>,
  21652. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  21653. * clearcoatNormalScale: <Vector2>,
  21654. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  21655. *
  21656. * ior: <float>,
  21657. * reflectivity: <float>,
  21658. *
  21659. * sheen: <float>,
  21660. * sheenColor: <Color>,
  21661. * sheenColorMap: new THREE.Texture( <Image> ),
  21662. * sheenRoughness: <float>,
  21663. * sheenRoughnessMap: new THREE.Texture( <Image> ),
  21664. *
  21665. * transmission: <float>,
  21666. * transmissionMap: new THREE.Texture( <Image> ),
  21667. *
  21668. * thickness: <float>,
  21669. * thicknessMap: new THREE.Texture( <Image> ),
  21670. * attenuationDistance: <float>,
  21671. * attenuationColor: <Color>,
  21672. *
  21673. * specularIntensity: <float>,
  21674. * specularIntensityMap: new THREE.Texture( <Image> ),
  21675. * specularColor: <Color>,
  21676. * specularColorMap: new THREE.Texture( <Image> )
  21677. * }
  21678. */
  21679. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21680. constructor( parameters ) {
  21681. super();
  21682. this.defines = {
  21683. 'STANDARD': '',
  21684. 'PHYSICAL': ''
  21685. };
  21686. this.type = 'MeshPhysicalMaterial';
  21687. this.clearcoatMap = null;
  21688. this.clearcoatRoughness = 0.0;
  21689. this.clearcoatRoughnessMap = null;
  21690. this.clearcoatNormalScale = new Vector2( 1, 1 );
  21691. this.clearcoatNormalMap = null;
  21692. this.ior = 1.5;
  21693. Object.defineProperty( this, 'reflectivity', {
  21694. get: function () {
  21695. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  21696. },
  21697. set: function ( reflectivity ) {
  21698. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  21699. }
  21700. } );
  21701. this.sheenColor = new Color( 0x000000 );
  21702. this.sheenColorMap = null;
  21703. this.sheenRoughness = 1.0;
  21704. this.sheenRoughnessMap = null;
  21705. this.transmissionMap = null;
  21706. this.thickness = 0;
  21707. this.thicknessMap = null;
  21708. this.attenuationDistance = 0.0;
  21709. this.attenuationColor = new Color( 1, 1, 1 );
  21710. this.specularIntensity = 1.0;
  21711. this.specularIntensityMap = null;
  21712. this.specularColor = new Color( 1, 1, 1 );
  21713. this.specularColorMap = null;
  21714. this._sheen = 0.0;
  21715. this._clearcoat = 0;
  21716. this._transmission = 0;
  21717. this.setValues( parameters );
  21718. }
  21719. get sheen() {
  21720. return this._sheen;
  21721. }
  21722. set sheen( value ) {
  21723. if ( this._sheen > 0 !== value > 0 ) {
  21724. this.version ++;
  21725. }
  21726. this._sheen = value;
  21727. }
  21728. get clearcoat() {
  21729. return this._clearcoat;
  21730. }
  21731. set clearcoat( value ) {
  21732. if ( this._clearcoat > 0 !== value > 0 ) {
  21733. this.version ++;
  21734. }
  21735. this._clearcoat = value;
  21736. }
  21737. get transmission() {
  21738. return this._transmission;
  21739. }
  21740. set transmission( value ) {
  21741. if ( this._transmission > 0 !== value > 0 ) {
  21742. this.version ++;
  21743. }
  21744. this._transmission = value;
  21745. }
  21746. copy( source ) {
  21747. super.copy( source );
  21748. this.defines = {
  21749. 'STANDARD': '',
  21750. 'PHYSICAL': ''
  21751. };
  21752. this.clearcoat = source.clearcoat;
  21753. this.clearcoatMap = source.clearcoatMap;
  21754. this.clearcoatRoughness = source.clearcoatRoughness;
  21755. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21756. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21757. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21758. this.ior = source.ior;
  21759. this.sheen = source.sheen;
  21760. this.sheenColor.copy( source.sheenColor );
  21761. this.sheenColorMap = source.sheenColorMap;
  21762. this.sheenRoughness = source.sheenRoughness;
  21763. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21764. this.transmission = source.transmission;
  21765. this.transmissionMap = source.transmissionMap;
  21766. this.thickness = source.thickness;
  21767. this.thicknessMap = source.thicknessMap;
  21768. this.attenuationDistance = source.attenuationDistance;
  21769. this.attenuationColor.copy( source.attenuationColor );
  21770. this.specularIntensity = source.specularIntensity;
  21771. this.specularIntensityMap = source.specularIntensityMap;
  21772. this.specularColor.copy( source.specularColor );
  21773. this.specularColorMap = source.specularColorMap;
  21774. return this;
  21775. }
  21776. }
  21777. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21778. /**
  21779. * parameters = {
  21780. * color: <hex>,
  21781. * specular: <hex>,
  21782. * shininess: <float>,
  21783. * opacity: <float>,
  21784. *
  21785. * map: new THREE.Texture( <Image> ),
  21786. *
  21787. * lightMap: new THREE.Texture( <Image> ),
  21788. * lightMapIntensity: <float>
  21789. *
  21790. * aoMap: new THREE.Texture( <Image> ),
  21791. * aoMapIntensity: <float>
  21792. *
  21793. * emissive: <hex>,
  21794. * emissiveIntensity: <float>
  21795. * emissiveMap: new THREE.Texture( <Image> ),
  21796. *
  21797. * bumpMap: new THREE.Texture( <Image> ),
  21798. * bumpScale: <float>,
  21799. *
  21800. * normalMap: new THREE.Texture( <Image> ),
  21801. * normalMapType: THREE.TangentSpaceNormalMap,
  21802. * normalScale: <Vector2>,
  21803. *
  21804. * displacementMap: new THREE.Texture( <Image> ),
  21805. * displacementScale: <float>,
  21806. * displacementBias: <float>,
  21807. *
  21808. * specularMap: new THREE.Texture( <Image> ),
  21809. *
  21810. * alphaMap: new THREE.Texture( <Image> ),
  21811. *
  21812. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21813. * combine: THREE.MultiplyOperation,
  21814. * reflectivity: <float>,
  21815. * refractionRatio: <float>,
  21816. *
  21817. * wireframe: <boolean>,
  21818. * wireframeLinewidth: <float>,
  21819. *
  21820. * flatShading: <bool>
  21821. * }
  21822. */
  21823. class MeshPhongMaterial extends Material {
  21824. constructor( parameters ) {
  21825. super();
  21826. this.type = 'MeshPhongMaterial';
  21827. this.color = new Color( 0xffffff ); // diffuse
  21828. this.specular = new Color( 0x111111 );
  21829. this.shininess = 30;
  21830. this.map = null;
  21831. this.lightMap = null;
  21832. this.lightMapIntensity = 1.0;
  21833. this.aoMap = null;
  21834. this.aoMapIntensity = 1.0;
  21835. this.emissive = new Color( 0x000000 );
  21836. this.emissiveIntensity = 1.0;
  21837. this.emissiveMap = null;
  21838. this.bumpMap = null;
  21839. this.bumpScale = 1;
  21840. this.normalMap = null;
  21841. this.normalMapType = TangentSpaceNormalMap;
  21842. this.normalScale = new Vector2( 1, 1 );
  21843. this.displacementMap = null;
  21844. this.displacementScale = 1;
  21845. this.displacementBias = 0;
  21846. this.specularMap = null;
  21847. this.alphaMap = null;
  21848. this.envMap = null;
  21849. this.combine = MultiplyOperation;
  21850. this.reflectivity = 1;
  21851. this.refractionRatio = 0.98;
  21852. this.wireframe = false;
  21853. this.wireframeLinewidth = 1;
  21854. this.wireframeLinecap = 'round';
  21855. this.wireframeLinejoin = 'round';
  21856. this.flatShading = false;
  21857. this.setValues( parameters );
  21858. }
  21859. copy( source ) {
  21860. super.copy( source );
  21861. this.color.copy( source.color );
  21862. this.specular.copy( source.specular );
  21863. this.shininess = source.shininess;
  21864. this.map = source.map;
  21865. this.lightMap = source.lightMap;
  21866. this.lightMapIntensity = source.lightMapIntensity;
  21867. this.aoMap = source.aoMap;
  21868. this.aoMapIntensity = source.aoMapIntensity;
  21869. this.emissive.copy( source.emissive );
  21870. this.emissiveMap = source.emissiveMap;
  21871. this.emissiveIntensity = source.emissiveIntensity;
  21872. this.bumpMap = source.bumpMap;
  21873. this.bumpScale = source.bumpScale;
  21874. this.normalMap = source.normalMap;
  21875. this.normalMapType = source.normalMapType;
  21876. this.normalScale.copy( source.normalScale );
  21877. this.displacementMap = source.displacementMap;
  21878. this.displacementScale = source.displacementScale;
  21879. this.displacementBias = source.displacementBias;
  21880. this.specularMap = source.specularMap;
  21881. this.alphaMap = source.alphaMap;
  21882. this.envMap = source.envMap;
  21883. this.combine = source.combine;
  21884. this.reflectivity = source.reflectivity;
  21885. this.refractionRatio = source.refractionRatio;
  21886. this.wireframe = source.wireframe;
  21887. this.wireframeLinewidth = source.wireframeLinewidth;
  21888. this.wireframeLinecap = source.wireframeLinecap;
  21889. this.wireframeLinejoin = source.wireframeLinejoin;
  21890. this.flatShading = source.flatShading;
  21891. return this;
  21892. }
  21893. }
  21894. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21895. /**
  21896. * parameters = {
  21897. * color: <hex>,
  21898. *
  21899. * map: new THREE.Texture( <Image> ),
  21900. * gradientMap: new THREE.Texture( <Image> ),
  21901. *
  21902. * lightMap: new THREE.Texture( <Image> ),
  21903. * lightMapIntensity: <float>
  21904. *
  21905. * aoMap: new THREE.Texture( <Image> ),
  21906. * aoMapIntensity: <float>
  21907. *
  21908. * emissive: <hex>,
  21909. * emissiveIntensity: <float>
  21910. * emissiveMap: new THREE.Texture( <Image> ),
  21911. *
  21912. * bumpMap: new THREE.Texture( <Image> ),
  21913. * bumpScale: <float>,
  21914. *
  21915. * normalMap: new THREE.Texture( <Image> ),
  21916. * normalMapType: THREE.TangentSpaceNormalMap,
  21917. * normalScale: <Vector2>,
  21918. *
  21919. * displacementMap: new THREE.Texture( <Image> ),
  21920. * displacementScale: <float>,
  21921. * displacementBias: <float>,
  21922. *
  21923. * alphaMap: new THREE.Texture( <Image> ),
  21924. *
  21925. * wireframe: <boolean>,
  21926. * wireframeLinewidth: <float>,
  21927. *
  21928. * }
  21929. */
  21930. class MeshToonMaterial extends Material {
  21931. constructor( parameters ) {
  21932. super();
  21933. this.defines = { 'TOON': '' };
  21934. this.type = 'MeshToonMaterial';
  21935. this.color = new Color( 0xffffff );
  21936. this.map = null;
  21937. this.gradientMap = null;
  21938. this.lightMap = null;
  21939. this.lightMapIntensity = 1.0;
  21940. this.aoMap = null;
  21941. this.aoMapIntensity = 1.0;
  21942. this.emissive = new Color( 0x000000 );
  21943. this.emissiveIntensity = 1.0;
  21944. this.emissiveMap = null;
  21945. this.bumpMap = null;
  21946. this.bumpScale = 1;
  21947. this.normalMap = null;
  21948. this.normalMapType = TangentSpaceNormalMap;
  21949. this.normalScale = new Vector2( 1, 1 );
  21950. this.displacementMap = null;
  21951. this.displacementScale = 1;
  21952. this.displacementBias = 0;
  21953. this.alphaMap = null;
  21954. this.wireframe = false;
  21955. this.wireframeLinewidth = 1;
  21956. this.wireframeLinecap = 'round';
  21957. this.wireframeLinejoin = 'round';
  21958. this.setValues( parameters );
  21959. }
  21960. copy( source ) {
  21961. super.copy( source );
  21962. this.color.copy( source.color );
  21963. this.map = source.map;
  21964. this.gradientMap = source.gradientMap;
  21965. this.lightMap = source.lightMap;
  21966. this.lightMapIntensity = source.lightMapIntensity;
  21967. this.aoMap = source.aoMap;
  21968. this.aoMapIntensity = source.aoMapIntensity;
  21969. this.emissive.copy( source.emissive );
  21970. this.emissiveMap = source.emissiveMap;
  21971. this.emissiveIntensity = source.emissiveIntensity;
  21972. this.bumpMap = source.bumpMap;
  21973. this.bumpScale = source.bumpScale;
  21974. this.normalMap = source.normalMap;
  21975. this.normalMapType = source.normalMapType;
  21976. this.normalScale.copy( source.normalScale );
  21977. this.displacementMap = source.displacementMap;
  21978. this.displacementScale = source.displacementScale;
  21979. this.displacementBias = source.displacementBias;
  21980. this.alphaMap = source.alphaMap;
  21981. this.wireframe = source.wireframe;
  21982. this.wireframeLinewidth = source.wireframeLinewidth;
  21983. this.wireframeLinecap = source.wireframeLinecap;
  21984. this.wireframeLinejoin = source.wireframeLinejoin;
  21985. return this;
  21986. }
  21987. }
  21988. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21989. /**
  21990. * parameters = {
  21991. * opacity: <float>,
  21992. *
  21993. * bumpMap: new THREE.Texture( <Image> ),
  21994. * bumpScale: <float>,
  21995. *
  21996. * normalMap: new THREE.Texture( <Image> ),
  21997. * normalMapType: THREE.TangentSpaceNormalMap,
  21998. * normalScale: <Vector2>,
  21999. *
  22000. * displacementMap: new THREE.Texture( <Image> ),
  22001. * displacementScale: <float>,
  22002. * displacementBias: <float>,
  22003. *
  22004. * wireframe: <boolean>,
  22005. * wireframeLinewidth: <float>
  22006. *
  22007. * flatShading: <bool>
  22008. * }
  22009. */
  22010. class MeshNormalMaterial extends Material {
  22011. constructor( parameters ) {
  22012. super();
  22013. this.type = 'MeshNormalMaterial';
  22014. this.bumpMap = null;
  22015. this.bumpScale = 1;
  22016. this.normalMap = null;
  22017. this.normalMapType = TangentSpaceNormalMap;
  22018. this.normalScale = new Vector2( 1, 1 );
  22019. this.displacementMap = null;
  22020. this.displacementScale = 1;
  22021. this.displacementBias = 0;
  22022. this.wireframe = false;
  22023. this.wireframeLinewidth = 1;
  22024. this.fog = false;
  22025. this.flatShading = false;
  22026. this.setValues( parameters );
  22027. }
  22028. copy( source ) {
  22029. super.copy( source );
  22030. this.bumpMap = source.bumpMap;
  22031. this.bumpScale = source.bumpScale;
  22032. this.normalMap = source.normalMap;
  22033. this.normalMapType = source.normalMapType;
  22034. this.normalScale.copy( source.normalScale );
  22035. this.displacementMap = source.displacementMap;
  22036. this.displacementScale = source.displacementScale;
  22037. this.displacementBias = source.displacementBias;
  22038. this.wireframe = source.wireframe;
  22039. this.wireframeLinewidth = source.wireframeLinewidth;
  22040. this.flatShading = source.flatShading;
  22041. return this;
  22042. }
  22043. }
  22044. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22045. /**
  22046. * parameters = {
  22047. * color: <hex>,
  22048. * opacity: <float>,
  22049. *
  22050. * map: new THREE.Texture( <Image> ),
  22051. *
  22052. * lightMap: new THREE.Texture( <Image> ),
  22053. * lightMapIntensity: <float>
  22054. *
  22055. * aoMap: new THREE.Texture( <Image> ),
  22056. * aoMapIntensity: <float>
  22057. *
  22058. * emissive: <hex>,
  22059. * emissiveIntensity: <float>
  22060. * emissiveMap: new THREE.Texture( <Image> ),
  22061. *
  22062. * specularMap: new THREE.Texture( <Image> ),
  22063. *
  22064. * alphaMap: new THREE.Texture( <Image> ),
  22065. *
  22066. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22067. * combine: THREE.Multiply,
  22068. * reflectivity: <float>,
  22069. * refractionRatio: <float>,
  22070. *
  22071. * wireframe: <boolean>,
  22072. * wireframeLinewidth: <float>,
  22073. *
  22074. * }
  22075. */
  22076. class MeshLambertMaterial extends Material {
  22077. constructor( parameters ) {
  22078. super();
  22079. this.type = 'MeshLambertMaterial';
  22080. this.color = new Color( 0xffffff ); // diffuse
  22081. this.map = null;
  22082. this.lightMap = null;
  22083. this.lightMapIntensity = 1.0;
  22084. this.aoMap = null;
  22085. this.aoMapIntensity = 1.0;
  22086. this.emissive = new Color( 0x000000 );
  22087. this.emissiveIntensity = 1.0;
  22088. this.emissiveMap = null;
  22089. this.specularMap = null;
  22090. this.alphaMap = null;
  22091. this.envMap = null;
  22092. this.combine = MultiplyOperation;
  22093. this.reflectivity = 1;
  22094. this.refractionRatio = 0.98;
  22095. this.wireframe = false;
  22096. this.wireframeLinewidth = 1;
  22097. this.wireframeLinecap = 'round';
  22098. this.wireframeLinejoin = 'round';
  22099. this.setValues( parameters );
  22100. }
  22101. copy( source ) {
  22102. super.copy( source );
  22103. this.color.copy( source.color );
  22104. this.map = source.map;
  22105. this.lightMap = source.lightMap;
  22106. this.lightMapIntensity = source.lightMapIntensity;
  22107. this.aoMap = source.aoMap;
  22108. this.aoMapIntensity = source.aoMapIntensity;
  22109. this.emissive.copy( source.emissive );
  22110. this.emissiveMap = source.emissiveMap;
  22111. this.emissiveIntensity = source.emissiveIntensity;
  22112. this.specularMap = source.specularMap;
  22113. this.alphaMap = source.alphaMap;
  22114. this.envMap = source.envMap;
  22115. this.combine = source.combine;
  22116. this.reflectivity = source.reflectivity;
  22117. this.refractionRatio = source.refractionRatio;
  22118. this.wireframe = source.wireframe;
  22119. this.wireframeLinewidth = source.wireframeLinewidth;
  22120. this.wireframeLinecap = source.wireframeLinecap;
  22121. this.wireframeLinejoin = source.wireframeLinejoin;
  22122. return this;
  22123. }
  22124. }
  22125. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22126. /**
  22127. * parameters = {
  22128. * color: <hex>,
  22129. * opacity: <float>,
  22130. *
  22131. * matcap: new THREE.Texture( <Image> ),
  22132. *
  22133. * map: new THREE.Texture( <Image> ),
  22134. *
  22135. * bumpMap: new THREE.Texture( <Image> ),
  22136. * bumpScale: <float>,
  22137. *
  22138. * normalMap: new THREE.Texture( <Image> ),
  22139. * normalMapType: THREE.TangentSpaceNormalMap,
  22140. * normalScale: <Vector2>,
  22141. *
  22142. * displacementMap: new THREE.Texture( <Image> ),
  22143. * displacementScale: <float>,
  22144. * displacementBias: <float>,
  22145. *
  22146. * alphaMap: new THREE.Texture( <Image> ),
  22147. *
  22148. * flatShading: <bool>
  22149. * }
  22150. */
  22151. class MeshMatcapMaterial extends Material {
  22152. constructor( parameters ) {
  22153. super();
  22154. this.defines = { 'MATCAP': '' };
  22155. this.type = 'MeshMatcapMaterial';
  22156. this.color = new Color( 0xffffff ); // diffuse
  22157. this.matcap = null;
  22158. this.map = null;
  22159. this.bumpMap = null;
  22160. this.bumpScale = 1;
  22161. this.normalMap = null;
  22162. this.normalMapType = TangentSpaceNormalMap;
  22163. this.normalScale = new Vector2( 1, 1 );
  22164. this.displacementMap = null;
  22165. this.displacementScale = 1;
  22166. this.displacementBias = 0;
  22167. this.alphaMap = null;
  22168. this.flatShading = false;
  22169. this.setValues( parameters );
  22170. }
  22171. copy( source ) {
  22172. super.copy( source );
  22173. this.defines = { 'MATCAP': '' };
  22174. this.color.copy( source.color );
  22175. this.matcap = source.matcap;
  22176. this.map = source.map;
  22177. this.bumpMap = source.bumpMap;
  22178. this.bumpScale = source.bumpScale;
  22179. this.normalMap = source.normalMap;
  22180. this.normalMapType = source.normalMapType;
  22181. this.normalScale.copy( source.normalScale );
  22182. this.displacementMap = source.displacementMap;
  22183. this.displacementScale = source.displacementScale;
  22184. this.displacementBias = source.displacementBias;
  22185. this.alphaMap = source.alphaMap;
  22186. this.flatShading = source.flatShading;
  22187. return this;
  22188. }
  22189. }
  22190. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  22191. /**
  22192. * parameters = {
  22193. * color: <hex>,
  22194. * opacity: <float>,
  22195. *
  22196. * linewidth: <float>,
  22197. *
  22198. * scale: <float>,
  22199. * dashSize: <float>,
  22200. * gapSize: <float>
  22201. * }
  22202. */
  22203. class LineDashedMaterial extends LineBasicMaterial {
  22204. constructor( parameters ) {
  22205. super();
  22206. this.type = 'LineDashedMaterial';
  22207. this.scale = 1;
  22208. this.dashSize = 3;
  22209. this.gapSize = 1;
  22210. this.setValues( parameters );
  22211. }
  22212. copy( source ) {
  22213. super.copy( source );
  22214. this.scale = source.scale;
  22215. this.dashSize = source.dashSize;
  22216. this.gapSize = source.gapSize;
  22217. return this;
  22218. }
  22219. }
  22220. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22221. var Materials = /*#__PURE__*/Object.freeze({
  22222. __proto__: null,
  22223. ShadowMaterial: ShadowMaterial,
  22224. SpriteMaterial: SpriteMaterial,
  22225. RawShaderMaterial: RawShaderMaterial,
  22226. ShaderMaterial: ShaderMaterial,
  22227. PointsMaterial: PointsMaterial,
  22228. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22229. MeshStandardMaterial: MeshStandardMaterial,
  22230. MeshPhongMaterial: MeshPhongMaterial,
  22231. MeshToonMaterial: MeshToonMaterial,
  22232. MeshNormalMaterial: MeshNormalMaterial,
  22233. MeshLambertMaterial: MeshLambertMaterial,
  22234. MeshDepthMaterial: MeshDepthMaterial,
  22235. MeshDistanceMaterial: MeshDistanceMaterial,
  22236. MeshBasicMaterial: MeshBasicMaterial,
  22237. MeshMatcapMaterial: MeshMatcapMaterial,
  22238. LineDashedMaterial: LineDashedMaterial,
  22239. LineBasicMaterial: LineBasicMaterial,
  22240. Material: Material
  22241. });
  22242. const AnimationUtils = {
  22243. // same as Array.prototype.slice, but also works on typed arrays
  22244. arraySlice: function ( array, from, to ) {
  22245. if ( AnimationUtils.isTypedArray( array ) ) {
  22246. // in ios9 array.subarray(from, undefined) will return empty array
  22247. // but array.subarray(from) or array.subarray(from, len) is correct
  22248. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22249. }
  22250. return array.slice( from, to );
  22251. },
  22252. // converts an array to a specific type
  22253. convertArray: function ( array, type, forceClone ) {
  22254. if ( ! array || // let 'undefined' and 'null' pass
  22255. ! forceClone && array.constructor === type ) return array;
  22256. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22257. return new type( array ); // create typed array
  22258. }
  22259. return Array.prototype.slice.call( array ); // create Array
  22260. },
  22261. isTypedArray: function ( object ) {
  22262. return ArrayBuffer.isView( object ) &&
  22263. ! ( object instanceof DataView );
  22264. },
  22265. // returns an array by which times and values can be sorted
  22266. getKeyframeOrder: function ( times ) {
  22267. function compareTime( i, j ) {
  22268. return times[ i ] - times[ j ];
  22269. }
  22270. const n = times.length;
  22271. const result = new Array( n );
  22272. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22273. result.sort( compareTime );
  22274. return result;
  22275. },
  22276. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22277. sortedArray: function ( values, stride, order ) {
  22278. const nValues = values.length;
  22279. const result = new values.constructor( nValues );
  22280. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22281. const srcOffset = order[ i ] * stride;
  22282. for ( let j = 0; j !== stride; ++ j ) {
  22283. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22284. }
  22285. }
  22286. return result;
  22287. },
  22288. // function for parsing AOS keyframe formats
  22289. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  22290. let i = 1, key = jsonKeys[ 0 ];
  22291. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22292. key = jsonKeys[ i ++ ];
  22293. }
  22294. if ( key === undefined ) return; // no data
  22295. let value = key[ valuePropertyName ];
  22296. if ( value === undefined ) return; // no data
  22297. if ( Array.isArray( value ) ) {
  22298. do {
  22299. value = key[ valuePropertyName ];
  22300. if ( value !== undefined ) {
  22301. times.push( key.time );
  22302. values.push.apply( values, value ); // push all elements
  22303. }
  22304. key = jsonKeys[ i ++ ];
  22305. } while ( key !== undefined );
  22306. } else if ( value.toArray !== undefined ) {
  22307. // ...assume THREE.Math-ish
  22308. do {
  22309. value = key[ valuePropertyName ];
  22310. if ( value !== undefined ) {
  22311. times.push( key.time );
  22312. value.toArray( values, values.length );
  22313. }
  22314. key = jsonKeys[ i ++ ];
  22315. } while ( key !== undefined );
  22316. } else {
  22317. // otherwise push as-is
  22318. do {
  22319. value = key[ valuePropertyName ];
  22320. if ( value !== undefined ) {
  22321. times.push( key.time );
  22322. values.push( value );
  22323. }
  22324. key = jsonKeys[ i ++ ];
  22325. } while ( key !== undefined );
  22326. }
  22327. },
  22328. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22329. const clip = sourceClip.clone();
  22330. clip.name = name;
  22331. const tracks = [];
  22332. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22333. const track = clip.tracks[ i ];
  22334. const valueSize = track.getValueSize();
  22335. const times = [];
  22336. const values = [];
  22337. for ( let j = 0; j < track.times.length; ++ j ) {
  22338. const frame = track.times[ j ] * fps;
  22339. if ( frame < startFrame || frame >= endFrame ) continue;
  22340. times.push( track.times[ j ] );
  22341. for ( let k = 0; k < valueSize; ++ k ) {
  22342. values.push( track.values[ j * valueSize + k ] );
  22343. }
  22344. }
  22345. if ( times.length === 0 ) continue;
  22346. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  22347. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  22348. tracks.push( track );
  22349. }
  22350. clip.tracks = tracks;
  22351. // find minimum .times value across all tracks in the trimmed clip
  22352. let minStartTime = Infinity;
  22353. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22354. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22355. minStartTime = clip.tracks[ i ].times[ 0 ];
  22356. }
  22357. }
  22358. // shift all tracks such that clip begins at t=0
  22359. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22360. clip.tracks[ i ].shift( - 1 * minStartTime );
  22361. }
  22362. clip.resetDuration();
  22363. return clip;
  22364. },
  22365. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22366. if ( fps <= 0 ) fps = 30;
  22367. const numTracks = referenceClip.tracks.length;
  22368. const referenceTime = referenceFrame / fps;
  22369. // Make each track's values relative to the values at the reference frame
  22370. for ( let i = 0; i < numTracks; ++ i ) {
  22371. const referenceTrack = referenceClip.tracks[ i ];
  22372. const referenceTrackType = referenceTrack.ValueTypeName;
  22373. // Skip this track if it's non-numeric
  22374. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22375. // Find the track in the target clip whose name and type matches the reference track
  22376. const targetTrack = targetClip.tracks.find( function ( track ) {
  22377. return track.name === referenceTrack.name
  22378. && track.ValueTypeName === referenceTrackType;
  22379. } );
  22380. if ( targetTrack === undefined ) continue;
  22381. let referenceOffset = 0;
  22382. const referenceValueSize = referenceTrack.getValueSize();
  22383. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22384. referenceOffset = referenceValueSize / 3;
  22385. }
  22386. let targetOffset = 0;
  22387. const targetValueSize = targetTrack.getValueSize();
  22388. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22389. targetOffset = targetValueSize / 3;
  22390. }
  22391. const lastIndex = referenceTrack.times.length - 1;
  22392. let referenceValue;
  22393. // Find the value to subtract out of the track
  22394. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22395. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22396. const startIndex = referenceOffset;
  22397. const endIndex = referenceValueSize - referenceOffset;
  22398. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22399. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22400. // Reference frame is after the last keyframe, so just use the last keyframe
  22401. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22402. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22403. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  22404. } else {
  22405. // Interpolate to the reference value
  22406. const interpolant = referenceTrack.createInterpolant();
  22407. const startIndex = referenceOffset;
  22408. const endIndex = referenceValueSize - referenceOffset;
  22409. interpolant.evaluate( referenceTime );
  22410. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22411. }
  22412. // Conjugate the quaternion
  22413. if ( referenceTrackType === 'quaternion' ) {
  22414. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22415. referenceQuat.toArray( referenceValue );
  22416. }
  22417. // Subtract the reference value from all of the track values
  22418. const numTimes = targetTrack.times.length;
  22419. for ( let j = 0; j < numTimes; ++ j ) {
  22420. const valueStart = j * targetValueSize + targetOffset;
  22421. if ( referenceTrackType === 'quaternion' ) {
  22422. // Multiply the conjugate for quaternion track types
  22423. Quaternion.multiplyQuaternionsFlat(
  22424. targetTrack.values,
  22425. valueStart,
  22426. referenceValue,
  22427. 0,
  22428. targetTrack.values,
  22429. valueStart
  22430. );
  22431. } else {
  22432. const valueEnd = targetValueSize - targetOffset * 2;
  22433. // Subtract each value for all other numeric track types
  22434. for ( let k = 0; k < valueEnd; ++ k ) {
  22435. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22436. }
  22437. }
  22438. }
  22439. }
  22440. targetClip.blendMode = AdditiveAnimationBlendMode;
  22441. return targetClip;
  22442. }
  22443. };
  22444. /**
  22445. * Abstract base class of interpolants over parametric samples.
  22446. *
  22447. * The parameter domain is one dimensional, typically the time or a path
  22448. * along a curve defined by the data.
  22449. *
  22450. * The sample values can have any dimensionality and derived classes may
  22451. * apply special interpretations to the data.
  22452. *
  22453. * This class provides the interval seek in a Template Method, deferring
  22454. * the actual interpolation to derived classes.
  22455. *
  22456. * Time complexity is O(1) for linear access crossing at most two points
  22457. * and O(log N) for random access, where N is the number of positions.
  22458. *
  22459. * References:
  22460. *
  22461. * http://www.oodesign.com/template-method-pattern.html
  22462. *
  22463. */
  22464. class Interpolant {
  22465. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22466. this.parameterPositions = parameterPositions;
  22467. this._cachedIndex = 0;
  22468. this.resultBuffer = resultBuffer !== undefined ?
  22469. resultBuffer : new sampleValues.constructor( sampleSize );
  22470. this.sampleValues = sampleValues;
  22471. this.valueSize = sampleSize;
  22472. this.settings = null;
  22473. this.DefaultSettings_ = {};
  22474. }
  22475. evaluate( t ) {
  22476. const pp = this.parameterPositions;
  22477. let i1 = this._cachedIndex,
  22478. t1 = pp[ i1 ],
  22479. t0 = pp[ i1 - 1 ];
  22480. validate_interval: {
  22481. seek: {
  22482. let right;
  22483. linear_scan: {
  22484. //- See http://jsperf.com/comparison-to-undefined/3
  22485. //- slower code:
  22486. //-
  22487. //- if ( t >= t1 || t1 === undefined ) {
  22488. forward_scan: if ( ! ( t < t1 ) ) {
  22489. for ( let giveUpAt = i1 + 2; ; ) {
  22490. if ( t1 === undefined ) {
  22491. if ( t < t0 ) break forward_scan;
  22492. // after end
  22493. i1 = pp.length;
  22494. this._cachedIndex = i1;
  22495. return this.afterEnd_( i1 - 1, t, t0 );
  22496. }
  22497. if ( i1 === giveUpAt ) break; // this loop
  22498. t0 = t1;
  22499. t1 = pp[ ++ i1 ];
  22500. if ( t < t1 ) {
  22501. // we have arrived at the sought interval
  22502. break seek;
  22503. }
  22504. }
  22505. // prepare binary search on the right side of the index
  22506. right = pp.length;
  22507. break linear_scan;
  22508. }
  22509. //- slower code:
  22510. //- if ( t < t0 || t0 === undefined ) {
  22511. if ( ! ( t >= t0 ) ) {
  22512. // looping?
  22513. const t1global = pp[ 1 ];
  22514. if ( t < t1global ) {
  22515. i1 = 2; // + 1, using the scan for the details
  22516. t0 = t1global;
  22517. }
  22518. // linear reverse scan
  22519. for ( let giveUpAt = i1 - 2; ; ) {
  22520. if ( t0 === undefined ) {
  22521. // before start
  22522. this._cachedIndex = 0;
  22523. return this.beforeStart_( 0, t, t1 );
  22524. }
  22525. if ( i1 === giveUpAt ) break; // this loop
  22526. t1 = t0;
  22527. t0 = pp[ -- i1 - 1 ];
  22528. if ( t >= t0 ) {
  22529. // we have arrived at the sought interval
  22530. break seek;
  22531. }
  22532. }
  22533. // prepare binary search on the left side of the index
  22534. right = i1;
  22535. i1 = 0;
  22536. break linear_scan;
  22537. }
  22538. // the interval is valid
  22539. break validate_interval;
  22540. } // linear scan
  22541. // binary search
  22542. while ( i1 < right ) {
  22543. const mid = ( i1 + right ) >>> 1;
  22544. if ( t < pp[ mid ] ) {
  22545. right = mid;
  22546. } else {
  22547. i1 = mid + 1;
  22548. }
  22549. }
  22550. t1 = pp[ i1 ];
  22551. t0 = pp[ i1 - 1 ];
  22552. // check boundary cases, again
  22553. if ( t0 === undefined ) {
  22554. this._cachedIndex = 0;
  22555. return this.beforeStart_( 0, t, t1 );
  22556. }
  22557. if ( t1 === undefined ) {
  22558. i1 = pp.length;
  22559. this._cachedIndex = i1;
  22560. return this.afterEnd_( i1 - 1, t0, t );
  22561. }
  22562. } // seek
  22563. this._cachedIndex = i1;
  22564. this.intervalChanged_( i1, t0, t1 );
  22565. } // validate_interval
  22566. return this.interpolate_( i1, t0, t, t1 );
  22567. }
  22568. getSettings_() {
  22569. return this.settings || this.DefaultSettings_;
  22570. }
  22571. copySampleValue_( index ) {
  22572. // copies a sample value to the result buffer
  22573. const result = this.resultBuffer,
  22574. values = this.sampleValues,
  22575. stride = this.valueSize,
  22576. offset = index * stride;
  22577. for ( let i = 0; i !== stride; ++ i ) {
  22578. result[ i ] = values[ offset + i ];
  22579. }
  22580. return result;
  22581. }
  22582. // Template methods for derived classes:
  22583. interpolate_( /* i1, t0, t, t1 */ ) {
  22584. throw new Error( 'call to abstract method' );
  22585. // implementations shall return this.resultBuffer
  22586. }
  22587. intervalChanged_( /* i1, t0, t1 */ ) {
  22588. // empty
  22589. }
  22590. }
  22591. // ALIAS DEFINITIONS
  22592. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22593. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22594. /**
  22595. * Fast and simple cubic spline interpolant.
  22596. *
  22597. * It was derived from a Hermitian construction setting the first derivative
  22598. * at each sample position to the linear slope between neighboring positions
  22599. * over their parameter interval.
  22600. */
  22601. class CubicInterpolant extends Interpolant {
  22602. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22603. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22604. this._weightPrev = - 0;
  22605. this._offsetPrev = - 0;
  22606. this._weightNext = - 0;
  22607. this._offsetNext = - 0;
  22608. this.DefaultSettings_ = {
  22609. endingStart: ZeroCurvatureEnding,
  22610. endingEnd: ZeroCurvatureEnding
  22611. };
  22612. }
  22613. intervalChanged_( i1, t0, t1 ) {
  22614. const pp = this.parameterPositions;
  22615. let iPrev = i1 - 2,
  22616. iNext = i1 + 1,
  22617. tPrev = pp[ iPrev ],
  22618. tNext = pp[ iNext ];
  22619. if ( tPrev === undefined ) {
  22620. switch ( this.getSettings_().endingStart ) {
  22621. case ZeroSlopeEnding:
  22622. // f'(t0) = 0
  22623. iPrev = i1;
  22624. tPrev = 2 * t0 - t1;
  22625. break;
  22626. case WrapAroundEnding:
  22627. // use the other end of the curve
  22628. iPrev = pp.length - 2;
  22629. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22630. break;
  22631. default: // ZeroCurvatureEnding
  22632. // f''(t0) = 0 a.k.a. Natural Spline
  22633. iPrev = i1;
  22634. tPrev = t1;
  22635. }
  22636. }
  22637. if ( tNext === undefined ) {
  22638. switch ( this.getSettings_().endingEnd ) {
  22639. case ZeroSlopeEnding:
  22640. // f'(tN) = 0
  22641. iNext = i1;
  22642. tNext = 2 * t1 - t0;
  22643. break;
  22644. case WrapAroundEnding:
  22645. // use the other end of the curve
  22646. iNext = 1;
  22647. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22648. break;
  22649. default: // ZeroCurvatureEnding
  22650. // f''(tN) = 0, a.k.a. Natural Spline
  22651. iNext = i1 - 1;
  22652. tNext = t0;
  22653. }
  22654. }
  22655. const halfDt = ( t1 - t0 ) * 0.5,
  22656. stride = this.valueSize;
  22657. this._weightPrev = halfDt / ( t0 - tPrev );
  22658. this._weightNext = halfDt / ( tNext - t1 );
  22659. this._offsetPrev = iPrev * stride;
  22660. this._offsetNext = iNext * stride;
  22661. }
  22662. interpolate_( i1, t0, t, t1 ) {
  22663. const result = this.resultBuffer,
  22664. values = this.sampleValues,
  22665. stride = this.valueSize,
  22666. o1 = i1 * stride, o0 = o1 - stride,
  22667. oP = this._offsetPrev, oN = this._offsetNext,
  22668. wP = this._weightPrev, wN = this._weightNext,
  22669. p = ( t - t0 ) / ( t1 - t0 ),
  22670. pp = p * p,
  22671. ppp = pp * p;
  22672. // evaluate polynomials
  22673. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  22674. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  22675. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22676. const sN = wN * ppp - wN * pp;
  22677. // combine data linearly
  22678. for ( let i = 0; i !== stride; ++ i ) {
  22679. result[ i ] =
  22680. sP * values[ oP + i ] +
  22681. s0 * values[ o0 + i ] +
  22682. s1 * values[ o1 + i ] +
  22683. sN * values[ oN + i ];
  22684. }
  22685. return result;
  22686. }
  22687. }
  22688. class LinearInterpolant extends Interpolant {
  22689. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22690. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22691. }
  22692. interpolate_( i1, t0, t, t1 ) {
  22693. const result = this.resultBuffer,
  22694. values = this.sampleValues,
  22695. stride = this.valueSize,
  22696. offset1 = i1 * stride,
  22697. offset0 = offset1 - stride,
  22698. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22699. weight0 = 1 - weight1;
  22700. for ( let i = 0; i !== stride; ++ i ) {
  22701. result[ i ] =
  22702. values[ offset0 + i ] * weight0 +
  22703. values[ offset1 + i ] * weight1;
  22704. }
  22705. return result;
  22706. }
  22707. }
  22708. /**
  22709. *
  22710. * Interpolant that evaluates to the sample value at the position preceeding
  22711. * the parameter.
  22712. */
  22713. class DiscreteInterpolant extends Interpolant {
  22714. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22715. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22716. }
  22717. interpolate_( i1 /*, t0, t, t1 */ ) {
  22718. return this.copySampleValue_( i1 - 1 );
  22719. }
  22720. }
  22721. class KeyframeTrack {
  22722. constructor( name, times, values, interpolation ) {
  22723. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22724. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22725. this.name = name;
  22726. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  22727. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  22728. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22729. }
  22730. // Serialization (in static context, because of constructor invocation
  22731. // and automatic invocation of .toJSON):
  22732. static toJSON( track ) {
  22733. const trackType = track.constructor;
  22734. let json;
  22735. // derived classes can define a static toJSON method
  22736. if ( trackType.toJSON !== this.toJSON ) {
  22737. json = trackType.toJSON( track );
  22738. } else {
  22739. // by default, we assume the data can be serialized as-is
  22740. json = {
  22741. 'name': track.name,
  22742. 'times': AnimationUtils.convertArray( track.times, Array ),
  22743. 'values': AnimationUtils.convertArray( track.values, Array )
  22744. };
  22745. const interpolation = track.getInterpolation();
  22746. if ( interpolation !== track.DefaultInterpolation ) {
  22747. json.interpolation = interpolation;
  22748. }
  22749. }
  22750. json.type = track.ValueTypeName; // mandatory
  22751. return json;
  22752. }
  22753. InterpolantFactoryMethodDiscrete( result ) {
  22754. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22755. }
  22756. InterpolantFactoryMethodLinear( result ) {
  22757. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22758. }
  22759. InterpolantFactoryMethodSmooth( result ) {
  22760. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22761. }
  22762. setInterpolation( interpolation ) {
  22763. let factoryMethod;
  22764. switch ( interpolation ) {
  22765. case InterpolateDiscrete:
  22766. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22767. break;
  22768. case InterpolateLinear:
  22769. factoryMethod = this.InterpolantFactoryMethodLinear;
  22770. break;
  22771. case InterpolateSmooth:
  22772. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22773. break;
  22774. }
  22775. if ( factoryMethod === undefined ) {
  22776. const message = 'unsupported interpolation for ' +
  22777. this.ValueTypeName + ' keyframe track named ' + this.name;
  22778. if ( this.createInterpolant === undefined ) {
  22779. // fall back to default, unless the default itself is messed up
  22780. if ( interpolation !== this.DefaultInterpolation ) {
  22781. this.setInterpolation( this.DefaultInterpolation );
  22782. } else {
  22783. throw new Error( message ); // fatal, in this case
  22784. }
  22785. }
  22786. console.warn( 'THREE.KeyframeTrack:', message );
  22787. return this;
  22788. }
  22789. this.createInterpolant = factoryMethod;
  22790. return this;
  22791. }
  22792. getInterpolation() {
  22793. switch ( this.createInterpolant ) {
  22794. case this.InterpolantFactoryMethodDiscrete:
  22795. return InterpolateDiscrete;
  22796. case this.InterpolantFactoryMethodLinear:
  22797. return InterpolateLinear;
  22798. case this.InterpolantFactoryMethodSmooth:
  22799. return InterpolateSmooth;
  22800. }
  22801. }
  22802. getValueSize() {
  22803. return this.values.length / this.times.length;
  22804. }
  22805. // move all keyframes either forwards or backwards in time
  22806. shift( timeOffset ) {
  22807. if ( timeOffset !== 0.0 ) {
  22808. const times = this.times;
  22809. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22810. times[ i ] += timeOffset;
  22811. }
  22812. }
  22813. return this;
  22814. }
  22815. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22816. scale( timeScale ) {
  22817. if ( timeScale !== 1.0 ) {
  22818. const times = this.times;
  22819. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22820. times[ i ] *= timeScale;
  22821. }
  22822. }
  22823. return this;
  22824. }
  22825. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22826. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22827. trim( startTime, endTime ) {
  22828. const times = this.times,
  22829. nKeys = times.length;
  22830. let from = 0,
  22831. to = nKeys - 1;
  22832. while ( from !== nKeys && times[ from ] < startTime ) {
  22833. ++ from;
  22834. }
  22835. while ( to !== - 1 && times[ to ] > endTime ) {
  22836. -- to;
  22837. }
  22838. ++ to; // inclusive -> exclusive bound
  22839. if ( from !== 0 || to !== nKeys ) {
  22840. // empty tracks are forbidden, so keep at least one keyframe
  22841. if ( from >= to ) {
  22842. to = Math.max( to, 1 );
  22843. from = to - 1;
  22844. }
  22845. const stride = this.getValueSize();
  22846. this.times = AnimationUtils.arraySlice( times, from, to );
  22847. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  22848. }
  22849. return this;
  22850. }
  22851. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22852. validate() {
  22853. let valid = true;
  22854. const valueSize = this.getValueSize();
  22855. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22856. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22857. valid = false;
  22858. }
  22859. const times = this.times,
  22860. values = this.values,
  22861. nKeys = times.length;
  22862. if ( nKeys === 0 ) {
  22863. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22864. valid = false;
  22865. }
  22866. let prevTime = null;
  22867. for ( let i = 0; i !== nKeys; i ++ ) {
  22868. const currTime = times[ i ];
  22869. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22870. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22871. valid = false;
  22872. break;
  22873. }
  22874. if ( prevTime !== null && prevTime > currTime ) {
  22875. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22876. valid = false;
  22877. break;
  22878. }
  22879. prevTime = currTime;
  22880. }
  22881. if ( values !== undefined ) {
  22882. if ( AnimationUtils.isTypedArray( values ) ) {
  22883. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22884. const value = values[ i ];
  22885. if ( isNaN( value ) ) {
  22886. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22887. valid = false;
  22888. break;
  22889. }
  22890. }
  22891. }
  22892. }
  22893. return valid;
  22894. }
  22895. // removes equivalent sequential keys as common in morph target sequences
  22896. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22897. optimize() {
  22898. // times or values may be shared with other tracks, so overwriting is unsafe
  22899. const times = AnimationUtils.arraySlice( this.times ),
  22900. values = AnimationUtils.arraySlice( this.values ),
  22901. stride = this.getValueSize(),
  22902. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22903. lastIndex = times.length - 1;
  22904. let writeIndex = 1;
  22905. for ( let i = 1; i < lastIndex; ++ i ) {
  22906. let keep = false;
  22907. const time = times[ i ];
  22908. const timeNext = times[ i + 1 ];
  22909. // remove adjacent keyframes scheduled at the same time
  22910. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22911. if ( ! smoothInterpolation ) {
  22912. // remove unnecessary keyframes same as their neighbors
  22913. const offset = i * stride,
  22914. offsetP = offset - stride,
  22915. offsetN = offset + stride;
  22916. for ( let j = 0; j !== stride; ++ j ) {
  22917. const value = values[ offset + j ];
  22918. if ( value !== values[ offsetP + j ] ||
  22919. value !== values[ offsetN + j ] ) {
  22920. keep = true;
  22921. break;
  22922. }
  22923. }
  22924. } else {
  22925. keep = true;
  22926. }
  22927. }
  22928. // in-place compaction
  22929. if ( keep ) {
  22930. if ( i !== writeIndex ) {
  22931. times[ writeIndex ] = times[ i ];
  22932. const readOffset = i * stride,
  22933. writeOffset = writeIndex * stride;
  22934. for ( let j = 0; j !== stride; ++ j ) {
  22935. values[ writeOffset + j ] = values[ readOffset + j ];
  22936. }
  22937. }
  22938. ++ writeIndex;
  22939. }
  22940. }
  22941. // flush last keyframe (compaction looks ahead)
  22942. if ( lastIndex > 0 ) {
  22943. times[ writeIndex ] = times[ lastIndex ];
  22944. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22945. values[ writeOffset + j ] = values[ readOffset + j ];
  22946. }
  22947. ++ writeIndex;
  22948. }
  22949. if ( writeIndex !== times.length ) {
  22950. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22951. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22952. } else {
  22953. this.times = times;
  22954. this.values = values;
  22955. }
  22956. return this;
  22957. }
  22958. clone() {
  22959. const times = AnimationUtils.arraySlice( this.times, 0 );
  22960. const values = AnimationUtils.arraySlice( this.values, 0 );
  22961. const TypedKeyframeTrack = this.constructor;
  22962. const track = new TypedKeyframeTrack( this.name, times, values );
  22963. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22964. track.createInterpolant = this.createInterpolant;
  22965. return track;
  22966. }
  22967. }
  22968. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22969. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22970. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22971. /**
  22972. * A Track of Boolean keyframe values.
  22973. */
  22974. class BooleanKeyframeTrack extends KeyframeTrack {}
  22975. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22976. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22977. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22978. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22979. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22980. /**
  22981. * A Track of keyframe values that represent color.
  22982. */
  22983. class ColorKeyframeTrack extends KeyframeTrack {}
  22984. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22985. /**
  22986. * A Track of numeric keyframe values.
  22987. */
  22988. class NumberKeyframeTrack extends KeyframeTrack {}
  22989. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22990. /**
  22991. * Spherical linear unit quaternion interpolant.
  22992. */
  22993. class QuaternionLinearInterpolant extends Interpolant {
  22994. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22995. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22996. }
  22997. interpolate_( i1, t0, t, t1 ) {
  22998. const result = this.resultBuffer,
  22999. values = this.sampleValues,
  23000. stride = this.valueSize,
  23001. alpha = ( t - t0 ) / ( t1 - t0 );
  23002. let offset = i1 * stride;
  23003. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23004. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23005. }
  23006. return result;
  23007. }
  23008. }
  23009. /**
  23010. * A Track of quaternion keyframe values.
  23011. */
  23012. class QuaternionKeyframeTrack extends KeyframeTrack {
  23013. InterpolantFactoryMethodLinear( result ) {
  23014. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23015. }
  23016. }
  23017. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23018. // ValueBufferType is inherited
  23019. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23020. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23021. /**
  23022. * A Track that interpolates Strings
  23023. */
  23024. class StringKeyframeTrack extends KeyframeTrack {}
  23025. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23026. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23027. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23028. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23029. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23030. /**
  23031. * A Track of vectored keyframe values.
  23032. */
  23033. class VectorKeyframeTrack extends KeyframeTrack {}
  23034. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23035. class AnimationClip {
  23036. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23037. this.name = name;
  23038. this.tracks = tracks;
  23039. this.duration = duration;
  23040. this.blendMode = blendMode;
  23041. this.uuid = generateUUID();
  23042. // this means it should figure out its duration by scanning the tracks
  23043. if ( this.duration < 0 ) {
  23044. this.resetDuration();
  23045. }
  23046. }
  23047. static parse( json ) {
  23048. const tracks = [],
  23049. jsonTracks = json.tracks,
  23050. frameTime = 1.0 / ( json.fps || 1.0 );
  23051. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23052. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23053. }
  23054. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23055. clip.uuid = json.uuid;
  23056. return clip;
  23057. }
  23058. static toJSON( clip ) {
  23059. const tracks = [],
  23060. clipTracks = clip.tracks;
  23061. const json = {
  23062. 'name': clip.name,
  23063. 'duration': clip.duration,
  23064. 'tracks': tracks,
  23065. 'uuid': clip.uuid,
  23066. 'blendMode': clip.blendMode
  23067. };
  23068. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23069. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23070. }
  23071. return json;
  23072. }
  23073. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23074. const numMorphTargets = morphTargetSequence.length;
  23075. const tracks = [];
  23076. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23077. let times = [];
  23078. let values = [];
  23079. times.push(
  23080. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23081. i,
  23082. ( i + 1 ) % numMorphTargets );
  23083. values.push( 0, 1, 0 );
  23084. const order = AnimationUtils.getKeyframeOrder( times );
  23085. times = AnimationUtils.sortedArray( times, 1, order );
  23086. values = AnimationUtils.sortedArray( values, 1, order );
  23087. // if there is a key at the first frame, duplicate it as the
  23088. // last frame as well for perfect loop.
  23089. if ( ! noLoop && times[ 0 ] === 0 ) {
  23090. times.push( numMorphTargets );
  23091. values.push( values[ 0 ] );
  23092. }
  23093. tracks.push(
  23094. new NumberKeyframeTrack(
  23095. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23096. times, values
  23097. ).scale( 1.0 / fps ) );
  23098. }
  23099. return new this( name, - 1, tracks );
  23100. }
  23101. static findByName( objectOrClipArray, name ) {
  23102. let clipArray = objectOrClipArray;
  23103. if ( ! Array.isArray( objectOrClipArray ) ) {
  23104. const o = objectOrClipArray;
  23105. clipArray = o.geometry && o.geometry.animations || o.animations;
  23106. }
  23107. for ( let i = 0; i < clipArray.length; i ++ ) {
  23108. if ( clipArray[ i ].name === name ) {
  23109. return clipArray[ i ];
  23110. }
  23111. }
  23112. return null;
  23113. }
  23114. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23115. const animationToMorphTargets = {};
  23116. // tested with https://regex101.com/ on trick sequences
  23117. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23118. const pattern = /^([\w-]*?)([\d]+)$/;
  23119. // sort morph target names into animation groups based
  23120. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23121. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23122. const morphTarget = morphTargets[ i ];
  23123. const parts = morphTarget.name.match( pattern );
  23124. if ( parts && parts.length > 1 ) {
  23125. const name = parts[ 1 ];
  23126. let animationMorphTargets = animationToMorphTargets[ name ];
  23127. if ( ! animationMorphTargets ) {
  23128. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23129. }
  23130. animationMorphTargets.push( morphTarget );
  23131. }
  23132. }
  23133. const clips = [];
  23134. for ( const name in animationToMorphTargets ) {
  23135. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23136. }
  23137. return clips;
  23138. }
  23139. // parse the animation.hierarchy format
  23140. static parseAnimation( animation, bones ) {
  23141. if ( ! animation ) {
  23142. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23143. return null;
  23144. }
  23145. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23146. // only return track if there are actually keys.
  23147. if ( animationKeys.length !== 0 ) {
  23148. const times = [];
  23149. const values = [];
  23150. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  23151. // empty keys are filtered out, so check again
  23152. if ( times.length !== 0 ) {
  23153. destTracks.push( new trackType( trackName, times, values ) );
  23154. }
  23155. }
  23156. };
  23157. const tracks = [];
  23158. const clipName = animation.name || 'default';
  23159. const fps = animation.fps || 30;
  23160. const blendMode = animation.blendMode;
  23161. // automatic length determination in AnimationClip.
  23162. let duration = animation.length || - 1;
  23163. const hierarchyTracks = animation.hierarchy || [];
  23164. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23165. const animationKeys = hierarchyTracks[ h ].keys;
  23166. // skip empty tracks
  23167. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23168. // process morph targets
  23169. if ( animationKeys[ 0 ].morphTargets ) {
  23170. // figure out all morph targets used in this track
  23171. const morphTargetNames = {};
  23172. let k;
  23173. for ( k = 0; k < animationKeys.length; k ++ ) {
  23174. if ( animationKeys[ k ].morphTargets ) {
  23175. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23176. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23177. }
  23178. }
  23179. }
  23180. // create a track for each morph target with all zero
  23181. // morphTargetInfluences except for the keys in which
  23182. // the morphTarget is named.
  23183. for ( const morphTargetName in morphTargetNames ) {
  23184. const times = [];
  23185. const values = [];
  23186. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23187. const animationKey = animationKeys[ k ];
  23188. times.push( animationKey.time );
  23189. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23190. }
  23191. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23192. }
  23193. duration = morphTargetNames.length * ( fps || 1.0 );
  23194. } else {
  23195. // ...assume skeletal animation
  23196. const boneName = '.bones[' + bones[ h ].name + ']';
  23197. addNonemptyTrack(
  23198. VectorKeyframeTrack, boneName + '.position',
  23199. animationKeys, 'pos', tracks );
  23200. addNonemptyTrack(
  23201. QuaternionKeyframeTrack, boneName + '.quaternion',
  23202. animationKeys, 'rot', tracks );
  23203. addNonemptyTrack(
  23204. VectorKeyframeTrack, boneName + '.scale',
  23205. animationKeys, 'scl', tracks );
  23206. }
  23207. }
  23208. if ( tracks.length === 0 ) {
  23209. return null;
  23210. }
  23211. const clip = new this( clipName, duration, tracks, blendMode );
  23212. return clip;
  23213. }
  23214. resetDuration() {
  23215. const tracks = this.tracks;
  23216. let duration = 0;
  23217. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23218. const track = this.tracks[ i ];
  23219. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23220. }
  23221. this.duration = duration;
  23222. return this;
  23223. }
  23224. trim() {
  23225. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23226. this.tracks[ i ].trim( 0, this.duration );
  23227. }
  23228. return this;
  23229. }
  23230. validate() {
  23231. let valid = true;
  23232. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23233. valid = valid && this.tracks[ i ].validate();
  23234. }
  23235. return valid;
  23236. }
  23237. optimize() {
  23238. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23239. this.tracks[ i ].optimize();
  23240. }
  23241. return this;
  23242. }
  23243. clone() {
  23244. const tracks = [];
  23245. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23246. tracks.push( this.tracks[ i ].clone() );
  23247. }
  23248. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23249. }
  23250. toJSON() {
  23251. return this.constructor.toJSON( this );
  23252. }
  23253. }
  23254. function getTrackTypeForValueTypeName( typeName ) {
  23255. switch ( typeName.toLowerCase() ) {
  23256. case 'scalar':
  23257. case 'double':
  23258. case 'float':
  23259. case 'number':
  23260. case 'integer':
  23261. return NumberKeyframeTrack;
  23262. case 'vector':
  23263. case 'vector2':
  23264. case 'vector3':
  23265. case 'vector4':
  23266. return VectorKeyframeTrack;
  23267. case 'color':
  23268. return ColorKeyframeTrack;
  23269. case 'quaternion':
  23270. return QuaternionKeyframeTrack;
  23271. case 'bool':
  23272. case 'boolean':
  23273. return BooleanKeyframeTrack;
  23274. case 'string':
  23275. return StringKeyframeTrack;
  23276. }
  23277. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23278. }
  23279. function parseKeyframeTrack( json ) {
  23280. if ( json.type === undefined ) {
  23281. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23282. }
  23283. const trackType = getTrackTypeForValueTypeName( json.type );
  23284. if ( json.times === undefined ) {
  23285. const times = [], values = [];
  23286. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23287. json.times = times;
  23288. json.values = values;
  23289. }
  23290. // derived classes can define a static parse method
  23291. if ( trackType.parse !== undefined ) {
  23292. return trackType.parse( json );
  23293. } else {
  23294. // by default, we assume a constructor compatible with the base
  23295. return new trackType( json.name, json.times, json.values, json.interpolation );
  23296. }
  23297. }
  23298. const Cache = {
  23299. enabled: false,
  23300. files: {},
  23301. add: function ( key, file ) {
  23302. if ( this.enabled === false ) return;
  23303. // console.log( 'THREE.Cache', 'Adding key:', key );
  23304. this.files[ key ] = file;
  23305. },
  23306. get: function ( key ) {
  23307. if ( this.enabled === false ) return;
  23308. // console.log( 'THREE.Cache', 'Checking key:', key );
  23309. return this.files[ key ];
  23310. },
  23311. remove: function ( key ) {
  23312. delete this.files[ key ];
  23313. },
  23314. clear: function () {
  23315. this.files = {};
  23316. }
  23317. };
  23318. class LoadingManager {
  23319. constructor( onLoad, onProgress, onError ) {
  23320. const scope = this;
  23321. let isLoading = false;
  23322. let itemsLoaded = 0;
  23323. let itemsTotal = 0;
  23324. let urlModifier = undefined;
  23325. const handlers = [];
  23326. // Refer to #5689 for the reason why we don't set .onStart
  23327. // in the constructor
  23328. this.onStart = undefined;
  23329. this.onLoad = onLoad;
  23330. this.onProgress = onProgress;
  23331. this.onError = onError;
  23332. this.itemStart = function ( url ) {
  23333. itemsTotal ++;
  23334. if ( isLoading === false ) {
  23335. if ( scope.onStart !== undefined ) {
  23336. scope.onStart( url, itemsLoaded, itemsTotal );
  23337. }
  23338. }
  23339. isLoading = true;
  23340. };
  23341. this.itemEnd = function ( url ) {
  23342. itemsLoaded ++;
  23343. if ( scope.onProgress !== undefined ) {
  23344. scope.onProgress( url, itemsLoaded, itemsTotal );
  23345. }
  23346. if ( itemsLoaded === itemsTotal ) {
  23347. isLoading = false;
  23348. if ( scope.onLoad !== undefined ) {
  23349. scope.onLoad();
  23350. }
  23351. }
  23352. };
  23353. this.itemError = function ( url ) {
  23354. if ( scope.onError !== undefined ) {
  23355. scope.onError( url );
  23356. }
  23357. };
  23358. this.resolveURL = function ( url ) {
  23359. if ( urlModifier ) {
  23360. return urlModifier( url );
  23361. }
  23362. return url;
  23363. };
  23364. this.setURLModifier = function ( transform ) {
  23365. urlModifier = transform;
  23366. return this;
  23367. };
  23368. this.addHandler = function ( regex, loader ) {
  23369. handlers.push( regex, loader );
  23370. return this;
  23371. };
  23372. this.removeHandler = function ( regex ) {
  23373. const index = handlers.indexOf( regex );
  23374. if ( index !== - 1 ) {
  23375. handlers.splice( index, 2 );
  23376. }
  23377. return this;
  23378. };
  23379. this.getHandler = function ( file ) {
  23380. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23381. const regex = handlers[ i ];
  23382. const loader = handlers[ i + 1 ];
  23383. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23384. if ( regex.test( file ) ) {
  23385. return loader;
  23386. }
  23387. }
  23388. return null;
  23389. };
  23390. }
  23391. }
  23392. const DefaultLoadingManager = new LoadingManager();
  23393. class Loader {
  23394. constructor( manager ) {
  23395. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23396. this.crossOrigin = 'anonymous';
  23397. this.withCredentials = false;
  23398. this.path = '';
  23399. this.resourcePath = '';
  23400. this.requestHeader = {};
  23401. }
  23402. load( /* url, onLoad, onProgress, onError */ ) {}
  23403. loadAsync( url, onProgress ) {
  23404. const scope = this;
  23405. return new Promise( function ( resolve, reject ) {
  23406. scope.load( url, resolve, onProgress, reject );
  23407. } );
  23408. }
  23409. parse( /* data */ ) {}
  23410. setCrossOrigin( crossOrigin ) {
  23411. this.crossOrigin = crossOrigin;
  23412. return this;
  23413. }
  23414. setWithCredentials( value ) {
  23415. this.withCredentials = value;
  23416. return this;
  23417. }
  23418. setPath( path ) {
  23419. this.path = path;
  23420. return this;
  23421. }
  23422. setResourcePath( resourcePath ) {
  23423. this.resourcePath = resourcePath;
  23424. return this;
  23425. }
  23426. setRequestHeader( requestHeader ) {
  23427. this.requestHeader = requestHeader;
  23428. return this;
  23429. }
  23430. }
  23431. const loading = {};
  23432. class FileLoader extends Loader {
  23433. constructor( manager ) {
  23434. super( manager );
  23435. }
  23436. load( url, onLoad, onProgress, onError ) {
  23437. if ( url === undefined ) url = '';
  23438. if ( this.path !== undefined ) url = this.path + url;
  23439. url = this.manager.resolveURL( url );
  23440. const cached = Cache.get( url );
  23441. if ( cached !== undefined ) {
  23442. this.manager.itemStart( url );
  23443. setTimeout( () => {
  23444. if ( onLoad ) onLoad( cached );
  23445. this.manager.itemEnd( url );
  23446. }, 0 );
  23447. return cached;
  23448. }
  23449. // Check if request is duplicate
  23450. if ( loading[ url ] !== undefined ) {
  23451. loading[ url ].push( {
  23452. onLoad: onLoad,
  23453. onProgress: onProgress,
  23454. onError: onError
  23455. } );
  23456. return;
  23457. }
  23458. // Initialise array for duplicate requests
  23459. loading[ url ] = [];
  23460. loading[ url ].push( {
  23461. onLoad: onLoad,
  23462. onProgress: onProgress,
  23463. onError: onError,
  23464. } );
  23465. // create request
  23466. const req = new Request( url, {
  23467. headers: new Headers( this.requestHeader ),
  23468. credentials: this.withCredentials ? 'include' : 'same-origin',
  23469. // An abort controller could be added within a future PR
  23470. } );
  23471. // record states ( avoid data race )
  23472. const mimeType = this.mimeType;
  23473. const responseType = this.responseType;
  23474. // start the fetch
  23475. fetch( req )
  23476. .then( response => {
  23477. if ( response.status === 200 || response.status === 0 ) {
  23478. // Some browsers return HTTP Status 0 when using non-http protocol
  23479. // e.g. 'file://' or 'data://'. Handle as success.
  23480. if ( response.status === 0 ) {
  23481. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23482. }
  23483. if ( typeof ReadableStream === 'undefined' || response.body.getReader === undefined ) {
  23484. return response;
  23485. }
  23486. const callbacks = loading[ url ];
  23487. const reader = response.body.getReader();
  23488. const contentLength = response.headers.get( 'Content-Length' );
  23489. const total = contentLength ? parseInt( contentLength ) : 0;
  23490. const lengthComputable = total !== 0;
  23491. let loaded = 0;
  23492. // periodically read data into the new stream tracking while download progress
  23493. const stream = new ReadableStream( {
  23494. start( controller ) {
  23495. readData();
  23496. function readData() {
  23497. reader.read().then( ( { done, value } ) => {
  23498. if ( done ) {
  23499. controller.close();
  23500. } else {
  23501. loaded += value.byteLength;
  23502. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23503. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23504. const callback = callbacks[ i ];
  23505. if ( callback.onProgress ) callback.onProgress( event );
  23506. }
  23507. controller.enqueue( value );
  23508. readData();
  23509. }
  23510. } );
  23511. }
  23512. }
  23513. } );
  23514. return new Response( stream );
  23515. } else {
  23516. throw Error( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}` );
  23517. }
  23518. } )
  23519. .then( response => {
  23520. switch ( responseType ) {
  23521. case 'arraybuffer':
  23522. return response.arrayBuffer();
  23523. case 'blob':
  23524. return response.blob();
  23525. case 'document':
  23526. return response.text()
  23527. .then( text => {
  23528. const parser = new DOMParser();
  23529. return parser.parseFromString( text, mimeType );
  23530. } );
  23531. case 'json':
  23532. return response.json();
  23533. default:
  23534. if ( mimeType === undefined ) {
  23535. return response.text();
  23536. } else {
  23537. // sniff encoding
  23538. const re = /charset="?([^;"\s]*)"?/i;
  23539. const exec = re.exec( mimeType );
  23540. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23541. const decoder = new TextDecoder( label );
  23542. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23543. }
  23544. }
  23545. } )
  23546. .then( data => {
  23547. // Add to cache only on HTTP success, so that we do not cache
  23548. // error response bodies as proper responses to requests.
  23549. Cache.add( url, data );
  23550. const callbacks = loading[ url ];
  23551. delete loading[ url ];
  23552. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23553. const callback = callbacks[ i ];
  23554. if ( callback.onLoad ) callback.onLoad( data );
  23555. }
  23556. } )
  23557. .catch( err => {
  23558. // Abort errors and other errors are handled the same
  23559. const callbacks = loading[ url ];
  23560. if ( callbacks === undefined ) {
  23561. // When onLoad was called and url was deleted in `loading`
  23562. this.manager.itemError( url );
  23563. throw err;
  23564. }
  23565. delete loading[ url ];
  23566. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23567. const callback = callbacks[ i ];
  23568. if ( callback.onError ) callback.onError( err );
  23569. }
  23570. this.manager.itemError( url );
  23571. } )
  23572. .finally( () => {
  23573. this.manager.itemEnd( url );
  23574. } );
  23575. this.manager.itemStart( url );
  23576. }
  23577. setResponseType( value ) {
  23578. this.responseType = value;
  23579. return this;
  23580. }
  23581. setMimeType( value ) {
  23582. this.mimeType = value;
  23583. return this;
  23584. }
  23585. }
  23586. class AnimationLoader extends Loader {
  23587. constructor( manager ) {
  23588. super( manager );
  23589. }
  23590. load( url, onLoad, onProgress, onError ) {
  23591. const scope = this;
  23592. const loader = new FileLoader( this.manager );
  23593. loader.setPath( this.path );
  23594. loader.setRequestHeader( this.requestHeader );
  23595. loader.setWithCredentials( this.withCredentials );
  23596. loader.load( url, function ( text ) {
  23597. try {
  23598. onLoad( scope.parse( JSON.parse( text ) ) );
  23599. } catch ( e ) {
  23600. if ( onError ) {
  23601. onError( e );
  23602. } else {
  23603. console.error( e );
  23604. }
  23605. scope.manager.itemError( url );
  23606. }
  23607. }, onProgress, onError );
  23608. }
  23609. parse( json ) {
  23610. const animations = [];
  23611. for ( let i = 0; i < json.length; i ++ ) {
  23612. const clip = AnimationClip.parse( json[ i ] );
  23613. animations.push( clip );
  23614. }
  23615. return animations;
  23616. }
  23617. }
  23618. /**
  23619. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23620. *
  23621. * Sub classes have to implement the parse() method which will be used in load().
  23622. */
  23623. class CompressedTextureLoader extends Loader {
  23624. constructor( manager ) {
  23625. super( manager );
  23626. }
  23627. load( url, onLoad, onProgress, onError ) {
  23628. const scope = this;
  23629. const images = [];
  23630. const texture = new CompressedTexture();
  23631. const loader = new FileLoader( this.manager );
  23632. loader.setPath( this.path );
  23633. loader.setResponseType( 'arraybuffer' );
  23634. loader.setRequestHeader( this.requestHeader );
  23635. loader.setWithCredentials( scope.withCredentials );
  23636. let loaded = 0;
  23637. function loadTexture( i ) {
  23638. loader.load( url[ i ], function ( buffer ) {
  23639. const texDatas = scope.parse( buffer, true );
  23640. images[ i ] = {
  23641. width: texDatas.width,
  23642. height: texDatas.height,
  23643. format: texDatas.format,
  23644. mipmaps: texDatas.mipmaps
  23645. };
  23646. loaded += 1;
  23647. if ( loaded === 6 ) {
  23648. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23649. texture.image = images;
  23650. texture.format = texDatas.format;
  23651. texture.needsUpdate = true;
  23652. if ( onLoad ) onLoad( texture );
  23653. }
  23654. }, onProgress, onError );
  23655. }
  23656. if ( Array.isArray( url ) ) {
  23657. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23658. loadTexture( i );
  23659. }
  23660. } else {
  23661. // compressed cubemap texture stored in a single DDS file
  23662. loader.load( url, function ( buffer ) {
  23663. const texDatas = scope.parse( buffer, true );
  23664. if ( texDatas.isCubemap ) {
  23665. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23666. for ( let f = 0; f < faces; f ++ ) {
  23667. images[ f ] = { mipmaps: [] };
  23668. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23669. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23670. images[ f ].format = texDatas.format;
  23671. images[ f ].width = texDatas.width;
  23672. images[ f ].height = texDatas.height;
  23673. }
  23674. }
  23675. texture.image = images;
  23676. } else {
  23677. texture.image.width = texDatas.width;
  23678. texture.image.height = texDatas.height;
  23679. texture.mipmaps = texDatas.mipmaps;
  23680. }
  23681. if ( texDatas.mipmapCount === 1 ) {
  23682. texture.minFilter = LinearFilter;
  23683. }
  23684. texture.format = texDatas.format;
  23685. texture.needsUpdate = true;
  23686. if ( onLoad ) onLoad( texture );
  23687. }, onProgress, onError );
  23688. }
  23689. return texture;
  23690. }
  23691. }
  23692. class ImageLoader extends Loader {
  23693. constructor( manager ) {
  23694. super( manager );
  23695. }
  23696. load( url, onLoad, onProgress, onError ) {
  23697. if ( this.path !== undefined ) url = this.path + url;
  23698. url = this.manager.resolveURL( url );
  23699. const scope = this;
  23700. const cached = Cache.get( url );
  23701. if ( cached !== undefined ) {
  23702. scope.manager.itemStart( url );
  23703. setTimeout( function () {
  23704. if ( onLoad ) onLoad( cached );
  23705. scope.manager.itemEnd( url );
  23706. }, 0 );
  23707. return cached;
  23708. }
  23709. const image = createElementNS( 'img' );
  23710. function onImageLoad() {
  23711. removeEventListeners();
  23712. Cache.add( url, this );
  23713. if ( onLoad ) onLoad( this );
  23714. scope.manager.itemEnd( url );
  23715. }
  23716. function onImageError( event ) {
  23717. removeEventListeners();
  23718. if ( onError ) onError( event );
  23719. scope.manager.itemError( url );
  23720. scope.manager.itemEnd( url );
  23721. }
  23722. function removeEventListeners() {
  23723. image.removeEventListener( 'load', onImageLoad, false );
  23724. image.removeEventListener( 'error', onImageError, false );
  23725. }
  23726. image.addEventListener( 'load', onImageLoad, false );
  23727. image.addEventListener( 'error', onImageError, false );
  23728. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23729. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23730. }
  23731. scope.manager.itemStart( url );
  23732. image.src = url;
  23733. return image;
  23734. }
  23735. }
  23736. class CubeTextureLoader extends Loader {
  23737. constructor( manager ) {
  23738. super( manager );
  23739. }
  23740. load( urls, onLoad, onProgress, onError ) {
  23741. const texture = new CubeTexture();
  23742. const loader = new ImageLoader( this.manager );
  23743. loader.setCrossOrigin( this.crossOrigin );
  23744. loader.setPath( this.path );
  23745. let loaded = 0;
  23746. function loadTexture( i ) {
  23747. loader.load( urls[ i ], function ( image ) {
  23748. texture.images[ i ] = image;
  23749. loaded ++;
  23750. if ( loaded === 6 ) {
  23751. texture.needsUpdate = true;
  23752. if ( onLoad ) onLoad( texture );
  23753. }
  23754. }, undefined, onError );
  23755. }
  23756. for ( let i = 0; i < urls.length; ++ i ) {
  23757. loadTexture( i );
  23758. }
  23759. return texture;
  23760. }
  23761. }
  23762. /**
  23763. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23764. *
  23765. * Sub classes have to implement the parse() method which will be used in load().
  23766. */
  23767. class DataTextureLoader extends Loader {
  23768. constructor( manager ) {
  23769. super( manager );
  23770. }
  23771. load( url, onLoad, onProgress, onError ) {
  23772. const scope = this;
  23773. const texture = new DataTexture();
  23774. const loader = new FileLoader( this.manager );
  23775. loader.setResponseType( 'arraybuffer' );
  23776. loader.setRequestHeader( this.requestHeader );
  23777. loader.setPath( this.path );
  23778. loader.setWithCredentials( scope.withCredentials );
  23779. loader.load( url, function ( buffer ) {
  23780. const texData = scope.parse( buffer );
  23781. if ( ! texData ) return;
  23782. if ( texData.image !== undefined ) {
  23783. texture.image = texData.image;
  23784. } else if ( texData.data !== undefined ) {
  23785. texture.image.width = texData.width;
  23786. texture.image.height = texData.height;
  23787. texture.image.data = texData.data;
  23788. }
  23789. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23790. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23791. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23792. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23793. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23794. if ( texData.encoding !== undefined ) {
  23795. texture.encoding = texData.encoding;
  23796. }
  23797. if ( texData.flipY !== undefined ) {
  23798. texture.flipY = texData.flipY;
  23799. }
  23800. if ( texData.format !== undefined ) {
  23801. texture.format = texData.format;
  23802. }
  23803. if ( texData.type !== undefined ) {
  23804. texture.type = texData.type;
  23805. }
  23806. if ( texData.mipmaps !== undefined ) {
  23807. texture.mipmaps = texData.mipmaps;
  23808. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23809. }
  23810. if ( texData.mipmapCount === 1 ) {
  23811. texture.minFilter = LinearFilter;
  23812. }
  23813. if ( texData.generateMipmaps !== undefined ) {
  23814. texture.generateMipmaps = texData.generateMipmaps;
  23815. }
  23816. texture.needsUpdate = true;
  23817. if ( onLoad ) onLoad( texture, texData );
  23818. }, onProgress, onError );
  23819. return texture;
  23820. }
  23821. }
  23822. class TextureLoader extends Loader {
  23823. constructor( manager ) {
  23824. super( manager );
  23825. }
  23826. load( url, onLoad, onProgress, onError ) {
  23827. const texture = new Texture();
  23828. const loader = new ImageLoader( this.manager );
  23829. loader.setCrossOrigin( this.crossOrigin );
  23830. loader.setPath( this.path );
  23831. loader.load( url, function ( image ) {
  23832. texture.image = image;
  23833. texture.needsUpdate = true;
  23834. if ( onLoad !== undefined ) {
  23835. onLoad( texture );
  23836. }
  23837. }, onProgress, onError );
  23838. return texture;
  23839. }
  23840. }
  23841. class Light extends Object3D {
  23842. constructor( color, intensity = 1 ) {
  23843. super();
  23844. this.type = 'Light';
  23845. this.color = new Color( color );
  23846. this.intensity = intensity;
  23847. }
  23848. dispose() {
  23849. // Empty here in base class; some subclasses override.
  23850. }
  23851. copy( source ) {
  23852. super.copy( source );
  23853. this.color.copy( source.color );
  23854. this.intensity = source.intensity;
  23855. return this;
  23856. }
  23857. toJSON( meta ) {
  23858. const data = super.toJSON( meta );
  23859. data.object.color = this.color.getHex();
  23860. data.object.intensity = this.intensity;
  23861. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23862. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23863. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23864. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23865. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23866. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23867. return data;
  23868. }
  23869. }
  23870. Light.prototype.isLight = true;
  23871. class HemisphereLight extends Light {
  23872. constructor( skyColor, groundColor, intensity ) {
  23873. super( skyColor, intensity );
  23874. this.type = 'HemisphereLight';
  23875. this.position.copy( Object3D.DefaultUp );
  23876. this.updateMatrix();
  23877. this.groundColor = new Color( groundColor );
  23878. }
  23879. copy( source ) {
  23880. Light.prototype.copy.call( this, source );
  23881. this.groundColor.copy( source.groundColor );
  23882. return this;
  23883. }
  23884. }
  23885. HemisphereLight.prototype.isHemisphereLight = true;
  23886. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23887. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23888. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23889. class LightShadow {
  23890. constructor( camera ) {
  23891. this.camera = camera;
  23892. this.bias = 0;
  23893. this.normalBias = 0;
  23894. this.radius = 1;
  23895. this.blurSamples = 8;
  23896. this.mapSize = new Vector2( 512, 512 );
  23897. this.map = null;
  23898. this.mapPass = null;
  23899. this.matrix = new Matrix4();
  23900. this.autoUpdate = true;
  23901. this.needsUpdate = false;
  23902. this._frustum = new Frustum();
  23903. this._frameExtents = new Vector2( 1, 1 );
  23904. this._viewportCount = 1;
  23905. this._viewports = [
  23906. new Vector4( 0, 0, 1, 1 )
  23907. ];
  23908. }
  23909. getViewportCount() {
  23910. return this._viewportCount;
  23911. }
  23912. getFrustum() {
  23913. return this._frustum;
  23914. }
  23915. updateMatrices( light ) {
  23916. const shadowCamera = this.camera;
  23917. const shadowMatrix = this.matrix;
  23918. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23919. shadowCamera.position.copy( _lightPositionWorld$1 );
  23920. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23921. shadowCamera.lookAt( _lookTarget$1 );
  23922. shadowCamera.updateMatrixWorld();
  23923. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23924. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23925. shadowMatrix.set(
  23926. 0.5, 0.0, 0.0, 0.5,
  23927. 0.0, 0.5, 0.0, 0.5,
  23928. 0.0, 0.0, 0.5, 0.5,
  23929. 0.0, 0.0, 0.0, 1.0
  23930. );
  23931. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23932. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23933. }
  23934. getViewport( viewportIndex ) {
  23935. return this._viewports[ viewportIndex ];
  23936. }
  23937. getFrameExtents() {
  23938. return this._frameExtents;
  23939. }
  23940. dispose() {
  23941. if ( this.map ) {
  23942. this.map.dispose();
  23943. }
  23944. if ( this.mapPass ) {
  23945. this.mapPass.dispose();
  23946. }
  23947. }
  23948. copy( source ) {
  23949. this.camera = source.camera.clone();
  23950. this.bias = source.bias;
  23951. this.radius = source.radius;
  23952. this.mapSize.copy( source.mapSize );
  23953. return this;
  23954. }
  23955. clone() {
  23956. return new this.constructor().copy( this );
  23957. }
  23958. toJSON() {
  23959. const object = {};
  23960. if ( this.bias !== 0 ) object.bias = this.bias;
  23961. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23962. if ( this.radius !== 1 ) object.radius = this.radius;
  23963. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23964. object.camera = this.camera.toJSON( false ).object;
  23965. delete object.camera.matrix;
  23966. return object;
  23967. }
  23968. }
  23969. class SpotLightShadow extends LightShadow {
  23970. constructor() {
  23971. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23972. this.focus = 1;
  23973. }
  23974. updateMatrices( light ) {
  23975. const camera = this.camera;
  23976. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23977. const aspect = this.mapSize.width / this.mapSize.height;
  23978. const far = light.distance || camera.far;
  23979. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23980. camera.fov = fov;
  23981. camera.aspect = aspect;
  23982. camera.far = far;
  23983. camera.updateProjectionMatrix();
  23984. }
  23985. super.updateMatrices( light );
  23986. }
  23987. copy( source ) {
  23988. super.copy( source );
  23989. this.focus = source.focus;
  23990. return this;
  23991. }
  23992. }
  23993. SpotLightShadow.prototype.isSpotLightShadow = true;
  23994. class SpotLight extends Light {
  23995. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  23996. super( color, intensity );
  23997. this.type = 'SpotLight';
  23998. this.position.copy( Object3D.DefaultUp );
  23999. this.updateMatrix();
  24000. this.target = new Object3D();
  24001. this.distance = distance;
  24002. this.angle = angle;
  24003. this.penumbra = penumbra;
  24004. this.decay = decay; // for physically correct lights, should be 2.
  24005. this.shadow = new SpotLightShadow();
  24006. }
  24007. get power() {
  24008. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24009. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24010. return this.intensity * Math.PI;
  24011. }
  24012. set power( power ) {
  24013. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24014. this.intensity = power / Math.PI;
  24015. }
  24016. dispose() {
  24017. this.shadow.dispose();
  24018. }
  24019. copy( source ) {
  24020. super.copy( source );
  24021. this.distance = source.distance;
  24022. this.angle = source.angle;
  24023. this.penumbra = source.penumbra;
  24024. this.decay = source.decay;
  24025. this.target = source.target.clone();
  24026. this.shadow = source.shadow.clone();
  24027. return this;
  24028. }
  24029. }
  24030. SpotLight.prototype.isSpotLight = true;
  24031. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24032. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24033. const _lookTarget = /*@__PURE__*/ new Vector3();
  24034. class PointLightShadow extends LightShadow {
  24035. constructor() {
  24036. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24037. this._frameExtents = new Vector2( 4, 2 );
  24038. this._viewportCount = 6;
  24039. this._viewports = [
  24040. // These viewports map a cube-map onto a 2D texture with the
  24041. // following orientation:
  24042. //
  24043. // xzXZ
  24044. // y Y
  24045. //
  24046. // X - Positive x direction
  24047. // x - Negative x direction
  24048. // Y - Positive y direction
  24049. // y - Negative y direction
  24050. // Z - Positive z direction
  24051. // z - Negative z direction
  24052. // positive X
  24053. new Vector4( 2, 1, 1, 1 ),
  24054. // negative X
  24055. new Vector4( 0, 1, 1, 1 ),
  24056. // positive Z
  24057. new Vector4( 3, 1, 1, 1 ),
  24058. // negative Z
  24059. new Vector4( 1, 1, 1, 1 ),
  24060. // positive Y
  24061. new Vector4( 3, 0, 1, 1 ),
  24062. // negative Y
  24063. new Vector4( 1, 0, 1, 1 )
  24064. ];
  24065. this._cubeDirections = [
  24066. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24067. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24068. ];
  24069. this._cubeUps = [
  24070. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24071. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24072. ];
  24073. }
  24074. updateMatrices( light, viewportIndex = 0 ) {
  24075. const camera = this.camera;
  24076. const shadowMatrix = this.matrix;
  24077. const far = light.distance || camera.far;
  24078. if ( far !== camera.far ) {
  24079. camera.far = far;
  24080. camera.updateProjectionMatrix();
  24081. }
  24082. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24083. camera.position.copy( _lightPositionWorld );
  24084. _lookTarget.copy( camera.position );
  24085. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24086. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24087. camera.lookAt( _lookTarget );
  24088. camera.updateMatrixWorld();
  24089. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24090. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24091. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24092. }
  24093. }
  24094. PointLightShadow.prototype.isPointLightShadow = true;
  24095. class PointLight extends Light {
  24096. constructor( color, intensity, distance = 0, decay = 1 ) {
  24097. super( color, intensity );
  24098. this.type = 'PointLight';
  24099. this.distance = distance;
  24100. this.decay = decay; // for physically correct lights, should be 2.
  24101. this.shadow = new PointLightShadow();
  24102. }
  24103. get power() {
  24104. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24105. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24106. return this.intensity * 4 * Math.PI;
  24107. }
  24108. set power( power ) {
  24109. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24110. this.intensity = power / ( 4 * Math.PI );
  24111. }
  24112. dispose() {
  24113. this.shadow.dispose();
  24114. }
  24115. copy( source ) {
  24116. super.copy( source );
  24117. this.distance = source.distance;
  24118. this.decay = source.decay;
  24119. this.shadow = source.shadow.clone();
  24120. return this;
  24121. }
  24122. }
  24123. PointLight.prototype.isPointLight = true;
  24124. class DirectionalLightShadow extends LightShadow {
  24125. constructor() {
  24126. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24127. }
  24128. }
  24129. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  24130. class DirectionalLight extends Light {
  24131. constructor( color, intensity ) {
  24132. super( color, intensity );
  24133. this.type = 'DirectionalLight';
  24134. this.position.copy( Object3D.DefaultUp );
  24135. this.updateMatrix();
  24136. this.target = new Object3D();
  24137. this.shadow = new DirectionalLightShadow();
  24138. }
  24139. dispose() {
  24140. this.shadow.dispose();
  24141. }
  24142. copy( source ) {
  24143. super.copy( source );
  24144. this.target = source.target.clone();
  24145. this.shadow = source.shadow.clone();
  24146. return this;
  24147. }
  24148. }
  24149. DirectionalLight.prototype.isDirectionalLight = true;
  24150. class AmbientLight extends Light {
  24151. constructor( color, intensity ) {
  24152. super( color, intensity );
  24153. this.type = 'AmbientLight';
  24154. }
  24155. }
  24156. AmbientLight.prototype.isAmbientLight = true;
  24157. class RectAreaLight extends Light {
  24158. constructor( color, intensity, width = 10, height = 10 ) {
  24159. super( color, intensity );
  24160. this.type = 'RectAreaLight';
  24161. this.width = width;
  24162. this.height = height;
  24163. }
  24164. get power() {
  24165. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24166. return this.intensity * this.width * this.height * Math.PI;
  24167. }
  24168. set power( power ) {
  24169. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24170. this.intensity = power / ( this.width * this.height * Math.PI );
  24171. }
  24172. copy( source ) {
  24173. super.copy( source );
  24174. this.width = source.width;
  24175. this.height = source.height;
  24176. return this;
  24177. }
  24178. toJSON( meta ) {
  24179. const data = super.toJSON( meta );
  24180. data.object.width = this.width;
  24181. data.object.height = this.height;
  24182. return data;
  24183. }
  24184. }
  24185. RectAreaLight.prototype.isRectAreaLight = true;
  24186. /**
  24187. * Primary reference:
  24188. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24189. *
  24190. * Secondary reference:
  24191. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24192. */
  24193. // 3-band SH defined by 9 coefficients
  24194. class SphericalHarmonics3 {
  24195. constructor() {
  24196. this.coefficients = [];
  24197. for ( let i = 0; i < 9; i ++ ) {
  24198. this.coefficients.push( new Vector3() );
  24199. }
  24200. }
  24201. set( coefficients ) {
  24202. for ( let i = 0; i < 9; i ++ ) {
  24203. this.coefficients[ i ].copy( coefficients[ i ] );
  24204. }
  24205. return this;
  24206. }
  24207. zero() {
  24208. for ( let i = 0; i < 9; i ++ ) {
  24209. this.coefficients[ i ].set( 0, 0, 0 );
  24210. }
  24211. return this;
  24212. }
  24213. // get the radiance in the direction of the normal
  24214. // target is a Vector3
  24215. getAt( normal, target ) {
  24216. // normal is assumed to be unit length
  24217. const x = normal.x, y = normal.y, z = normal.z;
  24218. const coeff = this.coefficients;
  24219. // band 0
  24220. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24221. // band 1
  24222. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24223. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24224. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24225. // band 2
  24226. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24227. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24228. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24229. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24230. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24231. return target;
  24232. }
  24233. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24234. // target is a Vector3
  24235. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24236. getIrradianceAt( normal, target ) {
  24237. // normal is assumed to be unit length
  24238. const x = normal.x, y = normal.y, z = normal.z;
  24239. const coeff = this.coefficients;
  24240. // band 0
  24241. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24242. // band 1
  24243. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24244. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24245. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24246. // band 2
  24247. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24248. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24249. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24250. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24251. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24252. return target;
  24253. }
  24254. add( sh ) {
  24255. for ( let i = 0; i < 9; i ++ ) {
  24256. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24257. }
  24258. return this;
  24259. }
  24260. addScaledSH( sh, s ) {
  24261. for ( let i = 0; i < 9; i ++ ) {
  24262. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24263. }
  24264. return this;
  24265. }
  24266. scale( s ) {
  24267. for ( let i = 0; i < 9; i ++ ) {
  24268. this.coefficients[ i ].multiplyScalar( s );
  24269. }
  24270. return this;
  24271. }
  24272. lerp( sh, alpha ) {
  24273. for ( let i = 0; i < 9; i ++ ) {
  24274. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24275. }
  24276. return this;
  24277. }
  24278. equals( sh ) {
  24279. for ( let i = 0; i < 9; i ++ ) {
  24280. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24281. return false;
  24282. }
  24283. }
  24284. return true;
  24285. }
  24286. copy( sh ) {
  24287. return this.set( sh.coefficients );
  24288. }
  24289. clone() {
  24290. return new this.constructor().copy( this );
  24291. }
  24292. fromArray( array, offset = 0 ) {
  24293. const coefficients = this.coefficients;
  24294. for ( let i = 0; i < 9; i ++ ) {
  24295. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24296. }
  24297. return this;
  24298. }
  24299. toArray( array = [], offset = 0 ) {
  24300. const coefficients = this.coefficients;
  24301. for ( let i = 0; i < 9; i ++ ) {
  24302. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24303. }
  24304. return array;
  24305. }
  24306. // evaluate the basis functions
  24307. // shBasis is an Array[ 9 ]
  24308. static getBasisAt( normal, shBasis ) {
  24309. // normal is assumed to be unit length
  24310. const x = normal.x, y = normal.y, z = normal.z;
  24311. // band 0
  24312. shBasis[ 0 ] = 0.282095;
  24313. // band 1
  24314. shBasis[ 1 ] = 0.488603 * y;
  24315. shBasis[ 2 ] = 0.488603 * z;
  24316. shBasis[ 3 ] = 0.488603 * x;
  24317. // band 2
  24318. shBasis[ 4 ] = 1.092548 * x * y;
  24319. shBasis[ 5 ] = 1.092548 * y * z;
  24320. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24321. shBasis[ 7 ] = 1.092548 * x * z;
  24322. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24323. }
  24324. }
  24325. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  24326. class LightProbe extends Light {
  24327. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24328. super( undefined, intensity );
  24329. this.sh = sh;
  24330. }
  24331. copy( source ) {
  24332. super.copy( source );
  24333. this.sh.copy( source.sh );
  24334. return this;
  24335. }
  24336. fromJSON( json ) {
  24337. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24338. this.sh.fromArray( json.sh );
  24339. return this;
  24340. }
  24341. toJSON( meta ) {
  24342. const data = super.toJSON( meta );
  24343. data.object.sh = this.sh.toArray();
  24344. return data;
  24345. }
  24346. }
  24347. LightProbe.prototype.isLightProbe = true;
  24348. class MaterialLoader extends Loader {
  24349. constructor( manager ) {
  24350. super( manager );
  24351. this.textures = {};
  24352. }
  24353. load( url, onLoad, onProgress, onError ) {
  24354. const scope = this;
  24355. const loader = new FileLoader( scope.manager );
  24356. loader.setPath( scope.path );
  24357. loader.setRequestHeader( scope.requestHeader );
  24358. loader.setWithCredentials( scope.withCredentials );
  24359. loader.load( url, function ( text ) {
  24360. try {
  24361. onLoad( scope.parse( JSON.parse( text ) ) );
  24362. } catch ( e ) {
  24363. if ( onError ) {
  24364. onError( e );
  24365. } else {
  24366. console.error( e );
  24367. }
  24368. scope.manager.itemError( url );
  24369. }
  24370. }, onProgress, onError );
  24371. }
  24372. parse( json ) {
  24373. const textures = this.textures;
  24374. function getTexture( name ) {
  24375. if ( textures[ name ] === undefined ) {
  24376. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24377. }
  24378. return textures[ name ];
  24379. }
  24380. const material = new Materials[ json.type ]();
  24381. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24382. if ( json.name !== undefined ) material.name = json.name;
  24383. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24384. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24385. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24386. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24387. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24388. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24389. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24390. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24391. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24392. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24393. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24394. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24395. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24396. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24397. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24398. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24399. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24400. if ( json.fog !== undefined ) material.fog = json.fog;
  24401. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24402. if ( json.blending !== undefined ) material.blending = json.blending;
  24403. if ( json.combine !== undefined ) material.combine = json.combine;
  24404. if ( json.side !== undefined ) material.side = json.side;
  24405. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24406. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24407. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24408. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24409. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24410. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24411. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24412. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24413. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24414. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24415. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24416. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24417. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24418. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24419. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24420. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24421. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24422. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24423. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24424. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24425. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24426. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24427. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24428. if ( json.scale !== undefined ) material.scale = json.scale;
  24429. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24430. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24431. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24432. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24433. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24434. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24435. if ( json.visible !== undefined ) material.visible = json.visible;
  24436. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24437. if ( json.userData !== undefined ) material.userData = json.userData;
  24438. if ( json.vertexColors !== undefined ) {
  24439. if ( typeof json.vertexColors === 'number' ) {
  24440. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24441. } else {
  24442. material.vertexColors = json.vertexColors;
  24443. }
  24444. }
  24445. // Shader Material
  24446. if ( json.uniforms !== undefined ) {
  24447. for ( const name in json.uniforms ) {
  24448. const uniform = json.uniforms[ name ];
  24449. material.uniforms[ name ] = {};
  24450. switch ( uniform.type ) {
  24451. case 't':
  24452. material.uniforms[ name ].value = getTexture( uniform.value );
  24453. break;
  24454. case 'c':
  24455. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24456. break;
  24457. case 'v2':
  24458. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24459. break;
  24460. case 'v3':
  24461. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24462. break;
  24463. case 'v4':
  24464. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24465. break;
  24466. case 'm3':
  24467. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24468. break;
  24469. case 'm4':
  24470. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24471. break;
  24472. default:
  24473. material.uniforms[ name ].value = uniform.value;
  24474. }
  24475. }
  24476. }
  24477. if ( json.defines !== undefined ) material.defines = json.defines;
  24478. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24479. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24480. if ( json.extensions !== undefined ) {
  24481. for ( const key in json.extensions ) {
  24482. material.extensions[ key ] = json.extensions[ key ];
  24483. }
  24484. }
  24485. // Deprecated
  24486. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24487. // for PointsMaterial
  24488. if ( json.size !== undefined ) material.size = json.size;
  24489. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24490. // maps
  24491. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24492. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24493. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24494. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24495. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24496. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24497. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24498. if ( json.normalScale !== undefined ) {
  24499. let normalScale = json.normalScale;
  24500. if ( Array.isArray( normalScale ) === false ) {
  24501. // Blender exporter used to export a scalar. See #7459
  24502. normalScale = [ normalScale, normalScale ];
  24503. }
  24504. material.normalScale = new Vector2().fromArray( normalScale );
  24505. }
  24506. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24507. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24508. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24509. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24510. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24511. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24512. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24513. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24514. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24515. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24516. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24517. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24518. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24519. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24520. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24521. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24522. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24523. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24524. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24525. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24526. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24527. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24528. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24529. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24530. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24531. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24532. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24533. return material;
  24534. }
  24535. setTextures( value ) {
  24536. this.textures = value;
  24537. return this;
  24538. }
  24539. }
  24540. class LoaderUtils {
  24541. static decodeText( array ) {
  24542. if ( typeof TextDecoder !== 'undefined' ) {
  24543. return new TextDecoder().decode( array );
  24544. }
  24545. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24546. // throws a "maximum call stack size exceeded" error for large arrays.
  24547. let s = '';
  24548. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24549. // Implicitly assumes little-endian.
  24550. s += String.fromCharCode( array[ i ] );
  24551. }
  24552. try {
  24553. // merges multi-byte utf-8 characters.
  24554. return decodeURIComponent( escape( s ) );
  24555. } catch ( e ) { // see #16358
  24556. return s;
  24557. }
  24558. }
  24559. static extractUrlBase( url ) {
  24560. const index = url.lastIndexOf( '/' );
  24561. if ( index === - 1 ) return './';
  24562. return url.substr( 0, index + 1 );
  24563. }
  24564. static resolveURL( url, path ) {
  24565. // Invalid URL
  24566. if ( typeof url !== 'string' || url === '' ) return '';
  24567. // Host Relative URL
  24568. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24569. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24570. }
  24571. // Absolute URL http://,https://,//
  24572. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24573. // Data URI
  24574. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24575. // Blob URL
  24576. if ( /^blob:.*$/i.test( url ) ) return url;
  24577. // Relative URL
  24578. return path + url;
  24579. }
  24580. }
  24581. class InstancedBufferGeometry extends BufferGeometry {
  24582. constructor() {
  24583. super();
  24584. this.type = 'InstancedBufferGeometry';
  24585. this.instanceCount = Infinity;
  24586. }
  24587. copy( source ) {
  24588. super.copy( source );
  24589. this.instanceCount = source.instanceCount;
  24590. return this;
  24591. }
  24592. clone() {
  24593. return new this.constructor().copy( this );
  24594. }
  24595. toJSON() {
  24596. const data = super.toJSON( this );
  24597. data.instanceCount = this.instanceCount;
  24598. data.isInstancedBufferGeometry = true;
  24599. return data;
  24600. }
  24601. }
  24602. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24603. class BufferGeometryLoader extends Loader {
  24604. constructor( manager ) {
  24605. super( manager );
  24606. }
  24607. load( url, onLoad, onProgress, onError ) {
  24608. const scope = this;
  24609. const loader = new FileLoader( scope.manager );
  24610. loader.setPath( scope.path );
  24611. loader.setRequestHeader( scope.requestHeader );
  24612. loader.setWithCredentials( scope.withCredentials );
  24613. loader.load( url, function ( text ) {
  24614. try {
  24615. onLoad( scope.parse( JSON.parse( text ) ) );
  24616. } catch ( e ) {
  24617. if ( onError ) {
  24618. onError( e );
  24619. } else {
  24620. console.error( e );
  24621. }
  24622. scope.manager.itemError( url );
  24623. }
  24624. }, onProgress, onError );
  24625. }
  24626. parse( json ) {
  24627. const interleavedBufferMap = {};
  24628. const arrayBufferMap = {};
  24629. function getInterleavedBuffer( json, uuid ) {
  24630. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24631. const interleavedBuffers = json.interleavedBuffers;
  24632. const interleavedBuffer = interleavedBuffers[ uuid ];
  24633. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24634. const array = getTypedArray( interleavedBuffer.type, buffer );
  24635. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24636. ib.uuid = interleavedBuffer.uuid;
  24637. interleavedBufferMap[ uuid ] = ib;
  24638. return ib;
  24639. }
  24640. function getArrayBuffer( json, uuid ) {
  24641. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24642. const arrayBuffers = json.arrayBuffers;
  24643. const arrayBuffer = arrayBuffers[ uuid ];
  24644. const ab = new Uint32Array( arrayBuffer ).buffer;
  24645. arrayBufferMap[ uuid ] = ab;
  24646. return ab;
  24647. }
  24648. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24649. const index = json.data.index;
  24650. if ( index !== undefined ) {
  24651. const typedArray = getTypedArray( index.type, index.array );
  24652. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24653. }
  24654. const attributes = json.data.attributes;
  24655. for ( const key in attributes ) {
  24656. const attribute = attributes[ key ];
  24657. let bufferAttribute;
  24658. if ( attribute.isInterleavedBufferAttribute ) {
  24659. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24660. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24661. } else {
  24662. const typedArray = getTypedArray( attribute.type, attribute.array );
  24663. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24664. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24665. }
  24666. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24667. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24668. if ( attribute.updateRange !== undefined ) {
  24669. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24670. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24671. }
  24672. geometry.setAttribute( key, bufferAttribute );
  24673. }
  24674. const morphAttributes = json.data.morphAttributes;
  24675. if ( morphAttributes ) {
  24676. for ( const key in morphAttributes ) {
  24677. const attributeArray = morphAttributes[ key ];
  24678. const array = [];
  24679. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24680. const attribute = attributeArray[ i ];
  24681. let bufferAttribute;
  24682. if ( attribute.isInterleavedBufferAttribute ) {
  24683. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24684. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24685. } else {
  24686. const typedArray = getTypedArray( attribute.type, attribute.array );
  24687. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24688. }
  24689. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24690. array.push( bufferAttribute );
  24691. }
  24692. geometry.morphAttributes[ key ] = array;
  24693. }
  24694. }
  24695. const morphTargetsRelative = json.data.morphTargetsRelative;
  24696. if ( morphTargetsRelative ) {
  24697. geometry.morphTargetsRelative = true;
  24698. }
  24699. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24700. if ( groups !== undefined ) {
  24701. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24702. const group = groups[ i ];
  24703. geometry.addGroup( group.start, group.count, group.materialIndex );
  24704. }
  24705. }
  24706. const boundingSphere = json.data.boundingSphere;
  24707. if ( boundingSphere !== undefined ) {
  24708. const center = new Vector3();
  24709. if ( boundingSphere.center !== undefined ) {
  24710. center.fromArray( boundingSphere.center );
  24711. }
  24712. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24713. }
  24714. if ( json.name ) geometry.name = json.name;
  24715. if ( json.userData ) geometry.userData = json.userData;
  24716. return geometry;
  24717. }
  24718. }
  24719. class ObjectLoader extends Loader {
  24720. constructor( manager ) {
  24721. super( manager );
  24722. }
  24723. load( url, onLoad, onProgress, onError ) {
  24724. const scope = this;
  24725. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24726. this.resourcePath = this.resourcePath || path;
  24727. const loader = new FileLoader( this.manager );
  24728. loader.setPath( this.path );
  24729. loader.setRequestHeader( this.requestHeader );
  24730. loader.setWithCredentials( this.withCredentials );
  24731. loader.load( url, function ( text ) {
  24732. let json = null;
  24733. try {
  24734. json = JSON.parse( text );
  24735. } catch ( error ) {
  24736. if ( onError !== undefined ) onError( error );
  24737. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24738. return;
  24739. }
  24740. const metadata = json.metadata;
  24741. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24742. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24743. return;
  24744. }
  24745. scope.parse( json, onLoad );
  24746. }, onProgress, onError );
  24747. }
  24748. async loadAsync( url, onProgress ) {
  24749. const scope = this;
  24750. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24751. this.resourcePath = this.resourcePath || path;
  24752. const loader = new FileLoader( this.manager );
  24753. loader.setPath( this.path );
  24754. loader.setRequestHeader( this.requestHeader );
  24755. loader.setWithCredentials( this.withCredentials );
  24756. const text = await loader.loadAsync( url, onProgress );
  24757. const json = JSON.parse( text );
  24758. const metadata = json.metadata;
  24759. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24760. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24761. }
  24762. return await scope.parseAsync( json );
  24763. }
  24764. parse( json, onLoad ) {
  24765. const animations = this.parseAnimations( json.animations );
  24766. const shapes = this.parseShapes( json.shapes );
  24767. const geometries = this.parseGeometries( json.geometries, shapes );
  24768. const images = this.parseImages( json.images, function () {
  24769. if ( onLoad !== undefined ) onLoad( object );
  24770. } );
  24771. const textures = this.parseTextures( json.textures, images );
  24772. const materials = this.parseMaterials( json.materials, textures );
  24773. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24774. const skeletons = this.parseSkeletons( json.skeletons, object );
  24775. this.bindSkeletons( object, skeletons );
  24776. //
  24777. if ( onLoad !== undefined ) {
  24778. let hasImages = false;
  24779. for ( const uuid in images ) {
  24780. if ( images[ uuid ] instanceof HTMLImageElement ) {
  24781. hasImages = true;
  24782. break;
  24783. }
  24784. }
  24785. if ( hasImages === false ) onLoad( object );
  24786. }
  24787. return object;
  24788. }
  24789. async parseAsync( json ) {
  24790. const animations = this.parseAnimations( json.animations );
  24791. const shapes = this.parseShapes( json.shapes );
  24792. const geometries = this.parseGeometries( json.geometries, shapes );
  24793. const images = await this.parseImagesAsync( json.images );
  24794. const textures = this.parseTextures( json.textures, images );
  24795. const materials = this.parseMaterials( json.materials, textures );
  24796. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24797. const skeletons = this.parseSkeletons( json.skeletons, object );
  24798. this.bindSkeletons( object, skeletons );
  24799. return object;
  24800. }
  24801. parseShapes( json ) {
  24802. const shapes = {};
  24803. if ( json !== undefined ) {
  24804. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24805. const shape = new Shape().fromJSON( json[ i ] );
  24806. shapes[ shape.uuid ] = shape;
  24807. }
  24808. }
  24809. return shapes;
  24810. }
  24811. parseSkeletons( json, object ) {
  24812. const skeletons = {};
  24813. const bones = {};
  24814. // generate bone lookup table
  24815. object.traverse( function ( child ) {
  24816. if ( child.isBone ) bones[ child.uuid ] = child;
  24817. } );
  24818. // create skeletons
  24819. if ( json !== undefined ) {
  24820. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24821. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24822. skeletons[ skeleton.uuid ] = skeleton;
  24823. }
  24824. }
  24825. return skeletons;
  24826. }
  24827. parseGeometries( json, shapes ) {
  24828. const geometries = {};
  24829. if ( json !== undefined ) {
  24830. const bufferGeometryLoader = new BufferGeometryLoader();
  24831. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24832. let geometry;
  24833. const data = json[ i ];
  24834. switch ( data.type ) {
  24835. case 'BufferGeometry':
  24836. case 'InstancedBufferGeometry':
  24837. geometry = bufferGeometryLoader.parse( data );
  24838. break;
  24839. case 'Geometry':
  24840. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  24841. break;
  24842. default:
  24843. if ( data.type in Geometries ) {
  24844. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24845. } else {
  24846. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24847. }
  24848. }
  24849. geometry.uuid = data.uuid;
  24850. if ( data.name !== undefined ) geometry.name = data.name;
  24851. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24852. geometries[ data.uuid ] = geometry;
  24853. }
  24854. }
  24855. return geometries;
  24856. }
  24857. parseMaterials( json, textures ) {
  24858. const cache = {}; // MultiMaterial
  24859. const materials = {};
  24860. if ( json !== undefined ) {
  24861. const loader = new MaterialLoader();
  24862. loader.setTextures( textures );
  24863. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24864. const data = json[ i ];
  24865. if ( data.type === 'MultiMaterial' ) {
  24866. // Deprecated
  24867. const array = [];
  24868. for ( let j = 0; j < data.materials.length; j ++ ) {
  24869. const material = data.materials[ j ];
  24870. if ( cache[ material.uuid ] === undefined ) {
  24871. cache[ material.uuid ] = loader.parse( material );
  24872. }
  24873. array.push( cache[ material.uuid ] );
  24874. }
  24875. materials[ data.uuid ] = array;
  24876. } else {
  24877. if ( cache[ data.uuid ] === undefined ) {
  24878. cache[ data.uuid ] = loader.parse( data );
  24879. }
  24880. materials[ data.uuid ] = cache[ data.uuid ];
  24881. }
  24882. }
  24883. }
  24884. return materials;
  24885. }
  24886. parseAnimations( json ) {
  24887. const animations = {};
  24888. if ( json !== undefined ) {
  24889. for ( let i = 0; i < json.length; i ++ ) {
  24890. const data = json[ i ];
  24891. const clip = AnimationClip.parse( data );
  24892. animations[ clip.uuid ] = clip;
  24893. }
  24894. }
  24895. return animations;
  24896. }
  24897. parseImages( json, onLoad ) {
  24898. const scope = this;
  24899. const images = {};
  24900. let loader;
  24901. function loadImage( url ) {
  24902. scope.manager.itemStart( url );
  24903. return loader.load( url, function () {
  24904. scope.manager.itemEnd( url );
  24905. }, undefined, function () {
  24906. scope.manager.itemError( url );
  24907. scope.manager.itemEnd( url );
  24908. } );
  24909. }
  24910. function deserializeImage( image ) {
  24911. if ( typeof image === 'string' ) {
  24912. const url = image;
  24913. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24914. return loadImage( path );
  24915. } else {
  24916. if ( image.data ) {
  24917. return {
  24918. data: getTypedArray( image.type, image.data ),
  24919. width: image.width,
  24920. height: image.height
  24921. };
  24922. } else {
  24923. return null;
  24924. }
  24925. }
  24926. }
  24927. if ( json !== undefined && json.length > 0 ) {
  24928. const manager = new LoadingManager( onLoad );
  24929. loader = new ImageLoader( manager );
  24930. loader.setCrossOrigin( this.crossOrigin );
  24931. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24932. const image = json[ i ];
  24933. const url = image.url;
  24934. if ( Array.isArray( url ) ) {
  24935. // load array of images e.g CubeTexture
  24936. images[ image.uuid ] = [];
  24937. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24938. const currentUrl = url[ j ];
  24939. const deserializedImage = deserializeImage( currentUrl );
  24940. if ( deserializedImage !== null ) {
  24941. if ( deserializedImage instanceof HTMLImageElement ) {
  24942. images[ image.uuid ].push( deserializedImage );
  24943. } else {
  24944. // special case: handle array of data textures for cube textures
  24945. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24946. }
  24947. }
  24948. }
  24949. } else {
  24950. // load single image
  24951. const deserializedImage = deserializeImage( image.url );
  24952. if ( deserializedImage !== null ) {
  24953. images[ image.uuid ] = deserializedImage;
  24954. }
  24955. }
  24956. }
  24957. }
  24958. return images;
  24959. }
  24960. async parseImagesAsync( json ) {
  24961. const scope = this;
  24962. const images = {};
  24963. let loader;
  24964. async function deserializeImage( image ) {
  24965. if ( typeof image === 'string' ) {
  24966. const url = image;
  24967. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24968. return await loader.loadAsync( path );
  24969. } else {
  24970. if ( image.data ) {
  24971. return {
  24972. data: getTypedArray( image.type, image.data ),
  24973. width: image.width,
  24974. height: image.height
  24975. };
  24976. } else {
  24977. return null;
  24978. }
  24979. }
  24980. }
  24981. if ( json !== undefined && json.length > 0 ) {
  24982. loader = new ImageLoader( this.manager );
  24983. loader.setCrossOrigin( this.crossOrigin );
  24984. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24985. const image = json[ i ];
  24986. const url = image.url;
  24987. if ( Array.isArray( url ) ) {
  24988. // load array of images e.g CubeTexture
  24989. images[ image.uuid ] = [];
  24990. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24991. const currentUrl = url[ j ];
  24992. const deserializedImage = await deserializeImage( currentUrl );
  24993. if ( deserializedImage !== null ) {
  24994. if ( deserializedImage instanceof HTMLImageElement ) {
  24995. images[ image.uuid ].push( deserializedImage );
  24996. } else {
  24997. // special case: handle array of data textures for cube textures
  24998. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24999. }
  25000. }
  25001. }
  25002. } else {
  25003. // load single image
  25004. const deserializedImage = await deserializeImage( image.url );
  25005. if ( deserializedImage !== null ) {
  25006. images[ image.uuid ] = deserializedImage;
  25007. }
  25008. }
  25009. }
  25010. }
  25011. return images;
  25012. }
  25013. parseTextures( json, images ) {
  25014. function parseConstant( value, type ) {
  25015. if ( typeof value === 'number' ) return value;
  25016. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25017. return type[ value ];
  25018. }
  25019. const textures = {};
  25020. if ( json !== undefined ) {
  25021. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25022. const data = json[ i ];
  25023. if ( data.image === undefined ) {
  25024. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25025. }
  25026. if ( images[ data.image ] === undefined ) {
  25027. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25028. }
  25029. let texture;
  25030. const image = images[ data.image ];
  25031. if ( Array.isArray( image ) ) {
  25032. texture = new CubeTexture( image );
  25033. if ( image.length === 6 ) texture.needsUpdate = true;
  25034. } else {
  25035. if ( image && image.data ) {
  25036. texture = new DataTexture( image.data, image.width, image.height );
  25037. } else {
  25038. texture = new Texture( image );
  25039. }
  25040. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25041. }
  25042. texture.uuid = data.uuid;
  25043. if ( data.name !== undefined ) texture.name = data.name;
  25044. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25045. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25046. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25047. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25048. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25049. if ( data.wrap !== undefined ) {
  25050. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25051. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25052. }
  25053. if ( data.format !== undefined ) texture.format = data.format;
  25054. if ( data.type !== undefined ) texture.type = data.type;
  25055. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25056. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25057. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25058. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25059. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25060. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25061. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25062. if ( data.userData !== undefined ) texture.userData = data.userData;
  25063. textures[ data.uuid ] = texture;
  25064. }
  25065. }
  25066. return textures;
  25067. }
  25068. parseObject( data, geometries, materials, textures, animations ) {
  25069. let object;
  25070. function getGeometry( name ) {
  25071. if ( geometries[ name ] === undefined ) {
  25072. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25073. }
  25074. return geometries[ name ];
  25075. }
  25076. function getMaterial( name ) {
  25077. if ( name === undefined ) return undefined;
  25078. if ( Array.isArray( name ) ) {
  25079. const array = [];
  25080. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25081. const uuid = name[ i ];
  25082. if ( materials[ uuid ] === undefined ) {
  25083. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25084. }
  25085. array.push( materials[ uuid ] );
  25086. }
  25087. return array;
  25088. }
  25089. if ( materials[ name ] === undefined ) {
  25090. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25091. }
  25092. return materials[ name ];
  25093. }
  25094. function getTexture( uuid ) {
  25095. if ( textures[ uuid ] === undefined ) {
  25096. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25097. }
  25098. return textures[ uuid ];
  25099. }
  25100. let geometry, material;
  25101. switch ( data.type ) {
  25102. case 'Scene':
  25103. object = new Scene();
  25104. if ( data.background !== undefined ) {
  25105. if ( Number.isInteger( data.background ) ) {
  25106. object.background = new Color( data.background );
  25107. } else {
  25108. object.background = getTexture( data.background );
  25109. }
  25110. }
  25111. if ( data.environment !== undefined ) {
  25112. object.environment = getTexture( data.environment );
  25113. }
  25114. if ( data.fog !== undefined ) {
  25115. if ( data.fog.type === 'Fog' ) {
  25116. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25117. } else if ( data.fog.type === 'FogExp2' ) {
  25118. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25119. }
  25120. }
  25121. break;
  25122. case 'PerspectiveCamera':
  25123. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25124. if ( data.focus !== undefined ) object.focus = data.focus;
  25125. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25126. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25127. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25128. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25129. break;
  25130. case 'OrthographicCamera':
  25131. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25132. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25133. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25134. break;
  25135. case 'AmbientLight':
  25136. object = new AmbientLight( data.color, data.intensity );
  25137. break;
  25138. case 'DirectionalLight':
  25139. object = new DirectionalLight( data.color, data.intensity );
  25140. break;
  25141. case 'PointLight':
  25142. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25143. break;
  25144. case 'RectAreaLight':
  25145. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25146. break;
  25147. case 'SpotLight':
  25148. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25149. break;
  25150. case 'HemisphereLight':
  25151. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25152. break;
  25153. case 'LightProbe':
  25154. object = new LightProbe().fromJSON( data );
  25155. break;
  25156. case 'SkinnedMesh':
  25157. geometry = getGeometry( data.geometry );
  25158. material = getMaterial( data.material );
  25159. object = new SkinnedMesh( geometry, material );
  25160. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25161. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25162. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25163. break;
  25164. case 'Mesh':
  25165. geometry = getGeometry( data.geometry );
  25166. material = getMaterial( data.material );
  25167. object = new Mesh( geometry, material );
  25168. break;
  25169. case 'InstancedMesh':
  25170. geometry = getGeometry( data.geometry );
  25171. material = getMaterial( data.material );
  25172. const count = data.count;
  25173. const instanceMatrix = data.instanceMatrix;
  25174. const instanceColor = data.instanceColor;
  25175. object = new InstancedMesh( geometry, material, count );
  25176. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25177. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25178. break;
  25179. case 'LOD':
  25180. object = new LOD();
  25181. break;
  25182. case 'Line':
  25183. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25184. break;
  25185. case 'LineLoop':
  25186. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25187. break;
  25188. case 'LineSegments':
  25189. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25190. break;
  25191. case 'PointCloud':
  25192. case 'Points':
  25193. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25194. break;
  25195. case 'Sprite':
  25196. object = new Sprite( getMaterial( data.material ) );
  25197. break;
  25198. case 'Group':
  25199. object = new Group();
  25200. break;
  25201. case 'Bone':
  25202. object = new Bone();
  25203. break;
  25204. default:
  25205. object = new Object3D();
  25206. }
  25207. object.uuid = data.uuid;
  25208. if ( data.name !== undefined ) object.name = data.name;
  25209. if ( data.matrix !== undefined ) {
  25210. object.matrix.fromArray( data.matrix );
  25211. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25212. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25213. } else {
  25214. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25215. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25216. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25217. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25218. }
  25219. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25220. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25221. if ( data.shadow ) {
  25222. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25223. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25224. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25225. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25226. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25227. }
  25228. if ( data.visible !== undefined ) object.visible = data.visible;
  25229. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25230. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25231. if ( data.userData !== undefined ) object.userData = data.userData;
  25232. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25233. if ( data.children !== undefined ) {
  25234. const children = data.children;
  25235. for ( let i = 0; i < children.length; i ++ ) {
  25236. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25237. }
  25238. }
  25239. if ( data.animations !== undefined ) {
  25240. const objectAnimations = data.animations;
  25241. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25242. const uuid = objectAnimations[ i ];
  25243. object.animations.push( animations[ uuid ] );
  25244. }
  25245. }
  25246. if ( data.type === 'LOD' ) {
  25247. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25248. const levels = data.levels;
  25249. for ( let l = 0; l < levels.length; l ++ ) {
  25250. const level = levels[ l ];
  25251. const child = object.getObjectByProperty( 'uuid', level.object );
  25252. if ( child !== undefined ) {
  25253. object.addLevel( child, level.distance );
  25254. }
  25255. }
  25256. }
  25257. return object;
  25258. }
  25259. bindSkeletons( object, skeletons ) {
  25260. if ( Object.keys( skeletons ).length === 0 ) return;
  25261. object.traverse( function ( child ) {
  25262. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25263. const skeleton = skeletons[ child.skeleton ];
  25264. if ( skeleton === undefined ) {
  25265. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25266. } else {
  25267. child.bind( skeleton, child.bindMatrix );
  25268. }
  25269. }
  25270. } );
  25271. }
  25272. /* DEPRECATED */
  25273. setTexturePath( value ) {
  25274. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  25275. return this.setResourcePath( value );
  25276. }
  25277. }
  25278. const TEXTURE_MAPPING = {
  25279. UVMapping: UVMapping,
  25280. CubeReflectionMapping: CubeReflectionMapping,
  25281. CubeRefractionMapping: CubeRefractionMapping,
  25282. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25283. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25284. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25285. CubeUVRefractionMapping: CubeUVRefractionMapping
  25286. };
  25287. const TEXTURE_WRAPPING = {
  25288. RepeatWrapping: RepeatWrapping,
  25289. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25290. MirroredRepeatWrapping: MirroredRepeatWrapping
  25291. };
  25292. const TEXTURE_FILTER = {
  25293. NearestFilter: NearestFilter,
  25294. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25295. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25296. LinearFilter: LinearFilter,
  25297. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25298. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25299. };
  25300. class ImageBitmapLoader extends Loader {
  25301. constructor( manager ) {
  25302. super( manager );
  25303. if ( typeof createImageBitmap === 'undefined' ) {
  25304. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25305. }
  25306. if ( typeof fetch === 'undefined' ) {
  25307. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25308. }
  25309. this.options = { premultiplyAlpha: 'none' };
  25310. }
  25311. setOptions( options ) {
  25312. this.options = options;
  25313. return this;
  25314. }
  25315. load( url, onLoad, onProgress, onError ) {
  25316. if ( url === undefined ) url = '';
  25317. if ( this.path !== undefined ) url = this.path + url;
  25318. url = this.manager.resolveURL( url );
  25319. const scope = this;
  25320. const cached = Cache.get( url );
  25321. if ( cached !== undefined ) {
  25322. scope.manager.itemStart( url );
  25323. setTimeout( function () {
  25324. if ( onLoad ) onLoad( cached );
  25325. scope.manager.itemEnd( url );
  25326. }, 0 );
  25327. return cached;
  25328. }
  25329. const fetchOptions = {};
  25330. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25331. fetchOptions.headers = this.requestHeader;
  25332. fetch( url, fetchOptions ).then( function ( res ) {
  25333. return res.blob();
  25334. } ).then( function ( blob ) {
  25335. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25336. } ).then( function ( imageBitmap ) {
  25337. Cache.add( url, imageBitmap );
  25338. if ( onLoad ) onLoad( imageBitmap );
  25339. scope.manager.itemEnd( url );
  25340. } ).catch( function ( e ) {
  25341. if ( onError ) onError( e );
  25342. scope.manager.itemError( url );
  25343. scope.manager.itemEnd( url );
  25344. } );
  25345. scope.manager.itemStart( url );
  25346. }
  25347. }
  25348. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  25349. let _context;
  25350. const AudioContext = {
  25351. getContext: function () {
  25352. if ( _context === undefined ) {
  25353. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25354. }
  25355. return _context;
  25356. },
  25357. setContext: function ( value ) {
  25358. _context = value;
  25359. }
  25360. };
  25361. class AudioLoader extends Loader {
  25362. constructor( manager ) {
  25363. super( manager );
  25364. }
  25365. load( url, onLoad, onProgress, onError ) {
  25366. const scope = this;
  25367. const loader = new FileLoader( this.manager );
  25368. loader.setResponseType( 'arraybuffer' );
  25369. loader.setPath( this.path );
  25370. loader.setRequestHeader( this.requestHeader );
  25371. loader.setWithCredentials( this.withCredentials );
  25372. loader.load( url, function ( buffer ) {
  25373. try {
  25374. // Create a copy of the buffer. The `decodeAudioData` method
  25375. // detaches the buffer when complete, preventing reuse.
  25376. const bufferCopy = buffer.slice( 0 );
  25377. const context = AudioContext.getContext();
  25378. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25379. onLoad( audioBuffer );
  25380. } );
  25381. } catch ( e ) {
  25382. if ( onError ) {
  25383. onError( e );
  25384. } else {
  25385. console.error( e );
  25386. }
  25387. scope.manager.itemError( url );
  25388. }
  25389. }, onProgress, onError );
  25390. }
  25391. }
  25392. class HemisphereLightProbe extends LightProbe {
  25393. constructor( skyColor, groundColor, intensity = 1 ) {
  25394. super( undefined, intensity );
  25395. const color1 = new Color().set( skyColor );
  25396. const color2 = new Color().set( groundColor );
  25397. const sky = new Vector3( color1.r, color1.g, color1.b );
  25398. const ground = new Vector3( color2.r, color2.g, color2.b );
  25399. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25400. const c0 = Math.sqrt( Math.PI );
  25401. const c1 = c0 * Math.sqrt( 0.75 );
  25402. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25403. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25404. }
  25405. }
  25406. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  25407. class AmbientLightProbe extends LightProbe {
  25408. constructor( color, intensity = 1 ) {
  25409. super( undefined, intensity );
  25410. const color1 = new Color().set( color );
  25411. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25412. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25413. }
  25414. }
  25415. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  25416. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25417. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25418. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25419. class StereoCamera {
  25420. constructor() {
  25421. this.type = 'StereoCamera';
  25422. this.aspect = 1;
  25423. this.eyeSep = 0.064;
  25424. this.cameraL = new PerspectiveCamera();
  25425. this.cameraL.layers.enable( 1 );
  25426. this.cameraL.matrixAutoUpdate = false;
  25427. this.cameraR = new PerspectiveCamera();
  25428. this.cameraR.layers.enable( 2 );
  25429. this.cameraR.matrixAutoUpdate = false;
  25430. this._cache = {
  25431. focus: null,
  25432. fov: null,
  25433. aspect: null,
  25434. near: null,
  25435. far: null,
  25436. zoom: null,
  25437. eyeSep: null
  25438. };
  25439. }
  25440. update( camera ) {
  25441. const cache = this._cache;
  25442. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25443. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25444. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25445. if ( needsUpdate ) {
  25446. cache.focus = camera.focus;
  25447. cache.fov = camera.fov;
  25448. cache.aspect = camera.aspect * this.aspect;
  25449. cache.near = camera.near;
  25450. cache.far = camera.far;
  25451. cache.zoom = camera.zoom;
  25452. cache.eyeSep = this.eyeSep;
  25453. // Off-axis stereoscopic effect based on
  25454. // http://paulbourke.net/stereographics/stereorender/
  25455. _projectionMatrix.copy( camera.projectionMatrix );
  25456. const eyeSepHalf = cache.eyeSep / 2;
  25457. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25458. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25459. let xmin, xmax;
  25460. // translate xOffset
  25461. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25462. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25463. // for left eye
  25464. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25465. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25466. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25467. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25468. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25469. // for right eye
  25470. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25471. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25472. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25473. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25474. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25475. }
  25476. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25477. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25478. }
  25479. }
  25480. class Clock {
  25481. constructor( autoStart = true ) {
  25482. this.autoStart = autoStart;
  25483. this.startTime = 0;
  25484. this.oldTime = 0;
  25485. this.elapsedTime = 0;
  25486. this.running = false;
  25487. }
  25488. start() {
  25489. this.startTime = now();
  25490. this.oldTime = this.startTime;
  25491. this.elapsedTime = 0;
  25492. this.running = true;
  25493. }
  25494. stop() {
  25495. this.getElapsedTime();
  25496. this.running = false;
  25497. this.autoStart = false;
  25498. }
  25499. getElapsedTime() {
  25500. this.getDelta();
  25501. return this.elapsedTime;
  25502. }
  25503. getDelta() {
  25504. let diff = 0;
  25505. if ( this.autoStart && ! this.running ) {
  25506. this.start();
  25507. return 0;
  25508. }
  25509. if ( this.running ) {
  25510. const newTime = now();
  25511. diff = ( newTime - this.oldTime ) / 1000;
  25512. this.oldTime = newTime;
  25513. this.elapsedTime += diff;
  25514. }
  25515. return diff;
  25516. }
  25517. }
  25518. function now() {
  25519. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25520. }
  25521. const _position$1 = /*@__PURE__*/ new Vector3();
  25522. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25523. const _scale$1 = /*@__PURE__*/ new Vector3();
  25524. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25525. class AudioListener extends Object3D {
  25526. constructor() {
  25527. super();
  25528. this.type = 'AudioListener';
  25529. this.context = AudioContext.getContext();
  25530. this.gain = this.context.createGain();
  25531. this.gain.connect( this.context.destination );
  25532. this.filter = null;
  25533. this.timeDelta = 0;
  25534. // private
  25535. this._clock = new Clock();
  25536. }
  25537. getInput() {
  25538. return this.gain;
  25539. }
  25540. removeFilter() {
  25541. if ( this.filter !== null ) {
  25542. this.gain.disconnect( this.filter );
  25543. this.filter.disconnect( this.context.destination );
  25544. this.gain.connect( this.context.destination );
  25545. this.filter = null;
  25546. }
  25547. return this;
  25548. }
  25549. getFilter() {
  25550. return this.filter;
  25551. }
  25552. setFilter( value ) {
  25553. if ( this.filter !== null ) {
  25554. this.gain.disconnect( this.filter );
  25555. this.filter.disconnect( this.context.destination );
  25556. } else {
  25557. this.gain.disconnect( this.context.destination );
  25558. }
  25559. this.filter = value;
  25560. this.gain.connect( this.filter );
  25561. this.filter.connect( this.context.destination );
  25562. return this;
  25563. }
  25564. getMasterVolume() {
  25565. return this.gain.gain.value;
  25566. }
  25567. setMasterVolume( value ) {
  25568. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25569. return this;
  25570. }
  25571. updateMatrixWorld( force ) {
  25572. super.updateMatrixWorld( force );
  25573. const listener = this.context.listener;
  25574. const up = this.up;
  25575. this.timeDelta = this._clock.getDelta();
  25576. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25577. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25578. if ( listener.positionX ) {
  25579. // code path for Chrome (see #14393)
  25580. const endTime = this.context.currentTime + this.timeDelta;
  25581. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25582. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25583. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25584. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25585. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25586. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25587. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25588. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25589. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25590. } else {
  25591. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25592. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25593. }
  25594. }
  25595. }
  25596. class Audio extends Object3D {
  25597. constructor( listener ) {
  25598. super();
  25599. this.type = 'Audio';
  25600. this.listener = listener;
  25601. this.context = listener.context;
  25602. this.gain = this.context.createGain();
  25603. this.gain.connect( listener.getInput() );
  25604. this.autoplay = false;
  25605. this.buffer = null;
  25606. this.detune = 0;
  25607. this.loop = false;
  25608. this.loopStart = 0;
  25609. this.loopEnd = 0;
  25610. this.offset = 0;
  25611. this.duration = undefined;
  25612. this.playbackRate = 1;
  25613. this.isPlaying = false;
  25614. this.hasPlaybackControl = true;
  25615. this.source = null;
  25616. this.sourceType = 'empty';
  25617. this._startedAt = 0;
  25618. this._progress = 0;
  25619. this._connected = false;
  25620. this.filters = [];
  25621. }
  25622. getOutput() {
  25623. return this.gain;
  25624. }
  25625. setNodeSource( audioNode ) {
  25626. this.hasPlaybackControl = false;
  25627. this.sourceType = 'audioNode';
  25628. this.source = audioNode;
  25629. this.connect();
  25630. return this;
  25631. }
  25632. setMediaElementSource( mediaElement ) {
  25633. this.hasPlaybackControl = false;
  25634. this.sourceType = 'mediaNode';
  25635. this.source = this.context.createMediaElementSource( mediaElement );
  25636. this.connect();
  25637. return this;
  25638. }
  25639. setMediaStreamSource( mediaStream ) {
  25640. this.hasPlaybackControl = false;
  25641. this.sourceType = 'mediaStreamNode';
  25642. this.source = this.context.createMediaStreamSource( mediaStream );
  25643. this.connect();
  25644. return this;
  25645. }
  25646. setBuffer( audioBuffer ) {
  25647. this.buffer = audioBuffer;
  25648. this.sourceType = 'buffer';
  25649. if ( this.autoplay ) this.play();
  25650. return this;
  25651. }
  25652. play( delay = 0 ) {
  25653. if ( this.isPlaying === true ) {
  25654. console.warn( 'THREE.Audio: Audio is already playing.' );
  25655. return;
  25656. }
  25657. if ( this.hasPlaybackControl === false ) {
  25658. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25659. return;
  25660. }
  25661. this._startedAt = this.context.currentTime + delay;
  25662. const source = this.context.createBufferSource();
  25663. source.buffer = this.buffer;
  25664. source.loop = this.loop;
  25665. source.loopStart = this.loopStart;
  25666. source.loopEnd = this.loopEnd;
  25667. source.onended = this.onEnded.bind( this );
  25668. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25669. this.isPlaying = true;
  25670. this.source = source;
  25671. this.setDetune( this.detune );
  25672. this.setPlaybackRate( this.playbackRate );
  25673. return this.connect();
  25674. }
  25675. pause() {
  25676. if ( this.hasPlaybackControl === false ) {
  25677. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25678. return;
  25679. }
  25680. if ( this.isPlaying === true ) {
  25681. // update current progress
  25682. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25683. if ( this.loop === true ) {
  25684. // ensure _progress does not exceed duration with looped audios
  25685. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25686. }
  25687. this.source.stop();
  25688. this.source.onended = null;
  25689. this.isPlaying = false;
  25690. }
  25691. return this;
  25692. }
  25693. stop() {
  25694. if ( this.hasPlaybackControl === false ) {
  25695. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25696. return;
  25697. }
  25698. this._progress = 0;
  25699. this.source.stop();
  25700. this.source.onended = null;
  25701. this.isPlaying = false;
  25702. return this;
  25703. }
  25704. connect() {
  25705. if ( this.filters.length > 0 ) {
  25706. this.source.connect( this.filters[ 0 ] );
  25707. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25708. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25709. }
  25710. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25711. } else {
  25712. this.source.connect( this.getOutput() );
  25713. }
  25714. this._connected = true;
  25715. return this;
  25716. }
  25717. disconnect() {
  25718. if ( this.filters.length > 0 ) {
  25719. this.source.disconnect( this.filters[ 0 ] );
  25720. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25721. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25722. }
  25723. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25724. } else {
  25725. this.source.disconnect( this.getOutput() );
  25726. }
  25727. this._connected = false;
  25728. return this;
  25729. }
  25730. getFilters() {
  25731. return this.filters;
  25732. }
  25733. setFilters( value ) {
  25734. if ( ! value ) value = [];
  25735. if ( this._connected === true ) {
  25736. this.disconnect();
  25737. this.filters = value.slice();
  25738. this.connect();
  25739. } else {
  25740. this.filters = value.slice();
  25741. }
  25742. return this;
  25743. }
  25744. setDetune( value ) {
  25745. this.detune = value;
  25746. if ( this.source.detune === undefined ) return; // only set detune when available
  25747. if ( this.isPlaying === true ) {
  25748. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25749. }
  25750. return this;
  25751. }
  25752. getDetune() {
  25753. return this.detune;
  25754. }
  25755. getFilter() {
  25756. return this.getFilters()[ 0 ];
  25757. }
  25758. setFilter( filter ) {
  25759. return this.setFilters( filter ? [ filter ] : [] );
  25760. }
  25761. setPlaybackRate( value ) {
  25762. if ( this.hasPlaybackControl === false ) {
  25763. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25764. return;
  25765. }
  25766. this.playbackRate = value;
  25767. if ( this.isPlaying === true ) {
  25768. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25769. }
  25770. return this;
  25771. }
  25772. getPlaybackRate() {
  25773. return this.playbackRate;
  25774. }
  25775. onEnded() {
  25776. this.isPlaying = false;
  25777. }
  25778. getLoop() {
  25779. if ( this.hasPlaybackControl === false ) {
  25780. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25781. return false;
  25782. }
  25783. return this.loop;
  25784. }
  25785. setLoop( value ) {
  25786. if ( this.hasPlaybackControl === false ) {
  25787. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25788. return;
  25789. }
  25790. this.loop = value;
  25791. if ( this.isPlaying === true ) {
  25792. this.source.loop = this.loop;
  25793. }
  25794. return this;
  25795. }
  25796. setLoopStart( value ) {
  25797. this.loopStart = value;
  25798. return this;
  25799. }
  25800. setLoopEnd( value ) {
  25801. this.loopEnd = value;
  25802. return this;
  25803. }
  25804. getVolume() {
  25805. return this.gain.gain.value;
  25806. }
  25807. setVolume( value ) {
  25808. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25809. return this;
  25810. }
  25811. }
  25812. const _position = /*@__PURE__*/ new Vector3();
  25813. const _quaternion = /*@__PURE__*/ new Quaternion();
  25814. const _scale = /*@__PURE__*/ new Vector3();
  25815. const _orientation = /*@__PURE__*/ new Vector3();
  25816. class PositionalAudio extends Audio {
  25817. constructor( listener ) {
  25818. super( listener );
  25819. this.panner = this.context.createPanner();
  25820. this.panner.panningModel = 'HRTF';
  25821. this.panner.connect( this.gain );
  25822. }
  25823. getOutput() {
  25824. return this.panner;
  25825. }
  25826. getRefDistance() {
  25827. return this.panner.refDistance;
  25828. }
  25829. setRefDistance( value ) {
  25830. this.panner.refDistance = value;
  25831. return this;
  25832. }
  25833. getRolloffFactor() {
  25834. return this.panner.rolloffFactor;
  25835. }
  25836. setRolloffFactor( value ) {
  25837. this.panner.rolloffFactor = value;
  25838. return this;
  25839. }
  25840. getDistanceModel() {
  25841. return this.panner.distanceModel;
  25842. }
  25843. setDistanceModel( value ) {
  25844. this.panner.distanceModel = value;
  25845. return this;
  25846. }
  25847. getMaxDistance() {
  25848. return this.panner.maxDistance;
  25849. }
  25850. setMaxDistance( value ) {
  25851. this.panner.maxDistance = value;
  25852. return this;
  25853. }
  25854. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25855. this.panner.coneInnerAngle = coneInnerAngle;
  25856. this.panner.coneOuterAngle = coneOuterAngle;
  25857. this.panner.coneOuterGain = coneOuterGain;
  25858. return this;
  25859. }
  25860. updateMatrixWorld( force ) {
  25861. super.updateMatrixWorld( force );
  25862. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25863. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25864. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25865. const panner = this.panner;
  25866. if ( panner.positionX ) {
  25867. // code path for Chrome and Firefox (see #14393)
  25868. const endTime = this.context.currentTime + this.listener.timeDelta;
  25869. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25870. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25871. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25872. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25873. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25874. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25875. } else {
  25876. panner.setPosition( _position.x, _position.y, _position.z );
  25877. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25878. }
  25879. }
  25880. }
  25881. class AudioAnalyser {
  25882. constructor( audio, fftSize = 2048 ) {
  25883. this.analyser = audio.context.createAnalyser();
  25884. this.analyser.fftSize = fftSize;
  25885. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25886. audio.getOutput().connect( this.analyser );
  25887. }
  25888. getFrequencyData() {
  25889. this.analyser.getByteFrequencyData( this.data );
  25890. return this.data;
  25891. }
  25892. getAverageFrequency() {
  25893. let value = 0;
  25894. const data = this.getFrequencyData();
  25895. for ( let i = 0; i < data.length; i ++ ) {
  25896. value += data[ i ];
  25897. }
  25898. return value / data.length;
  25899. }
  25900. }
  25901. class PropertyMixer {
  25902. constructor( binding, typeName, valueSize ) {
  25903. this.binding = binding;
  25904. this.valueSize = valueSize;
  25905. let mixFunction,
  25906. mixFunctionAdditive,
  25907. setIdentity;
  25908. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25909. //
  25910. // interpolators can use .buffer as their .result
  25911. // the data then goes to 'incoming'
  25912. //
  25913. // 'accu0' and 'accu1' are used frame-interleaved for
  25914. // the cumulative result and are compared to detect
  25915. // changes
  25916. //
  25917. // 'orig' stores the original state of the property
  25918. //
  25919. // 'add' is used for additive cumulative results
  25920. //
  25921. // 'work' is optional and is only present for quaternion types. It is used
  25922. // to store intermediate quaternion multiplication results
  25923. switch ( typeName ) {
  25924. case 'quaternion':
  25925. mixFunction = this._slerp;
  25926. mixFunctionAdditive = this._slerpAdditive;
  25927. setIdentity = this._setAdditiveIdentityQuaternion;
  25928. this.buffer = new Float64Array( valueSize * 6 );
  25929. this._workIndex = 5;
  25930. break;
  25931. case 'string':
  25932. case 'bool':
  25933. mixFunction = this._select;
  25934. // Use the regular mix function and for additive on these types,
  25935. // additive is not relevant for non-numeric types
  25936. mixFunctionAdditive = this._select;
  25937. setIdentity = this._setAdditiveIdentityOther;
  25938. this.buffer = new Array( valueSize * 5 );
  25939. break;
  25940. default:
  25941. mixFunction = this._lerp;
  25942. mixFunctionAdditive = this._lerpAdditive;
  25943. setIdentity = this._setAdditiveIdentityNumeric;
  25944. this.buffer = new Float64Array( valueSize * 5 );
  25945. }
  25946. this._mixBufferRegion = mixFunction;
  25947. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25948. this._setIdentity = setIdentity;
  25949. this._origIndex = 3;
  25950. this._addIndex = 4;
  25951. this.cumulativeWeight = 0;
  25952. this.cumulativeWeightAdditive = 0;
  25953. this.useCount = 0;
  25954. this.referenceCount = 0;
  25955. }
  25956. // accumulate data in the 'incoming' region into 'accu<i>'
  25957. accumulate( accuIndex, weight ) {
  25958. // note: happily accumulating nothing when weight = 0, the caller knows
  25959. // the weight and shouldn't have made the call in the first place
  25960. const buffer = this.buffer,
  25961. stride = this.valueSize,
  25962. offset = accuIndex * stride + stride;
  25963. let currentWeight = this.cumulativeWeight;
  25964. if ( currentWeight === 0 ) {
  25965. // accuN := incoming * weight
  25966. for ( let i = 0; i !== stride; ++ i ) {
  25967. buffer[ offset + i ] = buffer[ i ];
  25968. }
  25969. currentWeight = weight;
  25970. } else {
  25971. // accuN := accuN + incoming * weight
  25972. currentWeight += weight;
  25973. const mix = weight / currentWeight;
  25974. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25975. }
  25976. this.cumulativeWeight = currentWeight;
  25977. }
  25978. // accumulate data in the 'incoming' region into 'add'
  25979. accumulateAdditive( weight ) {
  25980. const buffer = this.buffer,
  25981. stride = this.valueSize,
  25982. offset = stride * this._addIndex;
  25983. if ( this.cumulativeWeightAdditive === 0 ) {
  25984. // add = identity
  25985. this._setIdentity();
  25986. }
  25987. // add := add + incoming * weight
  25988. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25989. this.cumulativeWeightAdditive += weight;
  25990. }
  25991. // apply the state of 'accu<i>' to the binding when accus differ
  25992. apply( accuIndex ) {
  25993. const stride = this.valueSize,
  25994. buffer = this.buffer,
  25995. offset = accuIndex * stride + stride,
  25996. weight = this.cumulativeWeight,
  25997. weightAdditive = this.cumulativeWeightAdditive,
  25998. binding = this.binding;
  25999. this.cumulativeWeight = 0;
  26000. this.cumulativeWeightAdditive = 0;
  26001. if ( weight < 1 ) {
  26002. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26003. const originalValueOffset = stride * this._origIndex;
  26004. this._mixBufferRegion(
  26005. buffer, offset, originalValueOffset, 1 - weight, stride );
  26006. }
  26007. if ( weightAdditive > 0 ) {
  26008. // accuN := accuN + additive accuN
  26009. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26010. }
  26011. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26012. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26013. // value has changed -> update scene graph
  26014. binding.setValue( buffer, offset );
  26015. break;
  26016. }
  26017. }
  26018. }
  26019. // remember the state of the bound property and copy it to both accus
  26020. saveOriginalState() {
  26021. const binding = this.binding;
  26022. const buffer = this.buffer,
  26023. stride = this.valueSize,
  26024. originalValueOffset = stride * this._origIndex;
  26025. binding.getValue( buffer, originalValueOffset );
  26026. // accu[0..1] := orig -- initially detect changes against the original
  26027. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26028. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26029. }
  26030. // Add to identity for additive
  26031. this._setIdentity();
  26032. this.cumulativeWeight = 0;
  26033. this.cumulativeWeightAdditive = 0;
  26034. }
  26035. // apply the state previously taken via 'saveOriginalState' to the binding
  26036. restoreOriginalState() {
  26037. const originalValueOffset = this.valueSize * 3;
  26038. this.binding.setValue( this.buffer, originalValueOffset );
  26039. }
  26040. _setAdditiveIdentityNumeric() {
  26041. const startIndex = this._addIndex * this.valueSize;
  26042. const endIndex = startIndex + this.valueSize;
  26043. for ( let i = startIndex; i < endIndex; i ++ ) {
  26044. this.buffer[ i ] = 0;
  26045. }
  26046. }
  26047. _setAdditiveIdentityQuaternion() {
  26048. this._setAdditiveIdentityNumeric();
  26049. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26050. }
  26051. _setAdditiveIdentityOther() {
  26052. const startIndex = this._origIndex * this.valueSize;
  26053. const targetIndex = this._addIndex * this.valueSize;
  26054. for ( let i = 0; i < this.valueSize; i ++ ) {
  26055. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26056. }
  26057. }
  26058. // mix functions
  26059. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26060. if ( t >= 0.5 ) {
  26061. for ( let i = 0; i !== stride; ++ i ) {
  26062. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26063. }
  26064. }
  26065. }
  26066. _slerp( buffer, dstOffset, srcOffset, t ) {
  26067. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26068. }
  26069. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26070. const workOffset = this._workIndex * stride;
  26071. // Store result in intermediate buffer offset
  26072. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26073. // Slerp to the intermediate result
  26074. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26075. }
  26076. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26077. const s = 1 - t;
  26078. for ( let i = 0; i !== stride; ++ i ) {
  26079. const j = dstOffset + i;
  26080. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26081. }
  26082. }
  26083. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26084. for ( let i = 0; i !== stride; ++ i ) {
  26085. const j = dstOffset + i;
  26086. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26087. }
  26088. }
  26089. }
  26090. // Characters [].:/ are reserved for track binding syntax.
  26091. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26092. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26093. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26094. // only latin characters, and the unicode \p{L} is not yet supported. So
  26095. // instead, we exclude reserved characters and match everything else.
  26096. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26097. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26098. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26099. // be matched to parse the rest of the track name.
  26100. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26101. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26102. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26103. // Object on target node, and accessor. May not contain reserved
  26104. // characters. Accessor may contain any character except closing bracket.
  26105. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26106. // Property and accessor. May not contain reserved characters. Accessor may
  26107. // contain any non-bracket characters.
  26108. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26109. const _trackRe = new RegExp( ''
  26110. + '^'
  26111. + _directoryRe
  26112. + _nodeRe
  26113. + _objectRe
  26114. + _propertyRe
  26115. + '$'
  26116. );
  26117. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26118. class Composite {
  26119. constructor( targetGroup, path, optionalParsedPath ) {
  26120. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26121. this._targetGroup = targetGroup;
  26122. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26123. }
  26124. getValue( array, offset ) {
  26125. this.bind(); // bind all binding
  26126. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26127. binding = this._bindings[ firstValidIndex ];
  26128. // and only call .getValue on the first
  26129. if ( binding !== undefined ) binding.getValue( array, offset );
  26130. }
  26131. setValue( array, offset ) {
  26132. const bindings = this._bindings;
  26133. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26134. bindings[ i ].setValue( array, offset );
  26135. }
  26136. }
  26137. bind() {
  26138. const bindings = this._bindings;
  26139. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26140. bindings[ i ].bind();
  26141. }
  26142. }
  26143. unbind() {
  26144. const bindings = this._bindings;
  26145. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26146. bindings[ i ].unbind();
  26147. }
  26148. }
  26149. }
  26150. // Note: This class uses a State pattern on a per-method basis:
  26151. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26152. // prototype version of these methods with one that represents
  26153. // the bound state. When the property is not found, the methods
  26154. // become no-ops.
  26155. class PropertyBinding {
  26156. constructor( rootNode, path, parsedPath ) {
  26157. this.path = path;
  26158. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26159. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26160. this.rootNode = rootNode;
  26161. // initial state of these methods that calls 'bind'
  26162. this.getValue = this._getValue_unbound;
  26163. this.setValue = this._setValue_unbound;
  26164. }
  26165. static create( root, path, parsedPath ) {
  26166. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26167. return new PropertyBinding( root, path, parsedPath );
  26168. } else {
  26169. return new PropertyBinding.Composite( root, path, parsedPath );
  26170. }
  26171. }
  26172. /**
  26173. * Replaces spaces with underscores and removes unsupported characters from
  26174. * node names, to ensure compatibility with parseTrackName().
  26175. *
  26176. * @param {string} name Node name to be sanitized.
  26177. * @return {string}
  26178. */
  26179. static sanitizeNodeName( name ) {
  26180. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26181. }
  26182. static parseTrackName( trackName ) {
  26183. const matches = _trackRe.exec( trackName );
  26184. if ( ! matches ) {
  26185. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26186. }
  26187. const results = {
  26188. // directoryName: matches[ 1 ], // (tschw) currently unused
  26189. nodeName: matches[ 2 ],
  26190. objectName: matches[ 3 ],
  26191. objectIndex: matches[ 4 ],
  26192. propertyName: matches[ 5 ], // required
  26193. propertyIndex: matches[ 6 ]
  26194. };
  26195. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26196. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26197. const objectName = results.nodeName.substring( lastDot + 1 );
  26198. // Object names must be checked against an allowlist. Otherwise, there
  26199. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26200. // 'bar' could be the objectName, or part of a nodeName (which can
  26201. // include '.' characters).
  26202. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26203. results.nodeName = results.nodeName.substring( 0, lastDot );
  26204. results.objectName = objectName;
  26205. }
  26206. }
  26207. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26208. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26209. }
  26210. return results;
  26211. }
  26212. static findNode( root, nodeName ) {
  26213. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26214. return root;
  26215. }
  26216. // search into skeleton bones.
  26217. if ( root.skeleton ) {
  26218. const bone = root.skeleton.getBoneByName( nodeName );
  26219. if ( bone !== undefined ) {
  26220. return bone;
  26221. }
  26222. }
  26223. // search into node subtree.
  26224. if ( root.children ) {
  26225. const searchNodeSubtree = function ( children ) {
  26226. for ( let i = 0; i < children.length; i ++ ) {
  26227. const childNode = children[ i ];
  26228. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26229. return childNode;
  26230. }
  26231. const result = searchNodeSubtree( childNode.children );
  26232. if ( result ) return result;
  26233. }
  26234. return null;
  26235. };
  26236. const subTreeNode = searchNodeSubtree( root.children );
  26237. if ( subTreeNode ) {
  26238. return subTreeNode;
  26239. }
  26240. }
  26241. return null;
  26242. }
  26243. // these are used to "bind" a nonexistent property
  26244. _getValue_unavailable() {}
  26245. _setValue_unavailable() {}
  26246. // Getters
  26247. _getValue_direct( buffer, offset ) {
  26248. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26249. }
  26250. _getValue_array( buffer, offset ) {
  26251. const source = this.resolvedProperty;
  26252. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26253. buffer[ offset ++ ] = source[ i ];
  26254. }
  26255. }
  26256. _getValue_arrayElement( buffer, offset ) {
  26257. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26258. }
  26259. _getValue_toArray( buffer, offset ) {
  26260. this.resolvedProperty.toArray( buffer, offset );
  26261. }
  26262. // Direct
  26263. _setValue_direct( buffer, offset ) {
  26264. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26265. }
  26266. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26267. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26268. this.targetObject.needsUpdate = true;
  26269. }
  26270. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26271. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26272. this.targetObject.matrixWorldNeedsUpdate = true;
  26273. }
  26274. // EntireArray
  26275. _setValue_array( buffer, offset ) {
  26276. const dest = this.resolvedProperty;
  26277. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26278. dest[ i ] = buffer[ offset ++ ];
  26279. }
  26280. }
  26281. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26282. const dest = this.resolvedProperty;
  26283. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26284. dest[ i ] = buffer[ offset ++ ];
  26285. }
  26286. this.targetObject.needsUpdate = true;
  26287. }
  26288. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26289. const dest = this.resolvedProperty;
  26290. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26291. dest[ i ] = buffer[ offset ++ ];
  26292. }
  26293. this.targetObject.matrixWorldNeedsUpdate = true;
  26294. }
  26295. // ArrayElement
  26296. _setValue_arrayElement( buffer, offset ) {
  26297. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26298. }
  26299. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26300. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26301. this.targetObject.needsUpdate = true;
  26302. }
  26303. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26304. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26305. this.targetObject.matrixWorldNeedsUpdate = true;
  26306. }
  26307. // HasToFromArray
  26308. _setValue_fromArray( buffer, offset ) {
  26309. this.resolvedProperty.fromArray( buffer, offset );
  26310. }
  26311. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26312. this.resolvedProperty.fromArray( buffer, offset );
  26313. this.targetObject.needsUpdate = true;
  26314. }
  26315. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26316. this.resolvedProperty.fromArray( buffer, offset );
  26317. this.targetObject.matrixWorldNeedsUpdate = true;
  26318. }
  26319. _getValue_unbound( targetArray, offset ) {
  26320. this.bind();
  26321. this.getValue( targetArray, offset );
  26322. }
  26323. _setValue_unbound( sourceArray, offset ) {
  26324. this.bind();
  26325. this.setValue( sourceArray, offset );
  26326. }
  26327. // create getter / setter pair for a property in the scene graph
  26328. bind() {
  26329. let targetObject = this.node;
  26330. const parsedPath = this.parsedPath;
  26331. const objectName = parsedPath.objectName;
  26332. const propertyName = parsedPath.propertyName;
  26333. let propertyIndex = parsedPath.propertyIndex;
  26334. if ( ! targetObject ) {
  26335. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26336. this.node = targetObject;
  26337. }
  26338. // set fail state so we can just 'return' on error
  26339. this.getValue = this._getValue_unavailable;
  26340. this.setValue = this._setValue_unavailable;
  26341. // ensure there is a value node
  26342. if ( ! targetObject ) {
  26343. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26344. return;
  26345. }
  26346. if ( objectName ) {
  26347. let objectIndex = parsedPath.objectIndex;
  26348. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26349. switch ( objectName ) {
  26350. case 'materials':
  26351. if ( ! targetObject.material ) {
  26352. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26353. return;
  26354. }
  26355. if ( ! targetObject.material.materials ) {
  26356. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26357. return;
  26358. }
  26359. targetObject = targetObject.material.materials;
  26360. break;
  26361. case 'bones':
  26362. if ( ! targetObject.skeleton ) {
  26363. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26364. return;
  26365. }
  26366. // potential future optimization: skip this if propertyIndex is already an integer
  26367. // and convert the integer string to a true integer.
  26368. targetObject = targetObject.skeleton.bones;
  26369. // support resolving morphTarget names into indices.
  26370. for ( let i = 0; i < targetObject.length; i ++ ) {
  26371. if ( targetObject[ i ].name === objectIndex ) {
  26372. objectIndex = i;
  26373. break;
  26374. }
  26375. }
  26376. break;
  26377. default:
  26378. if ( targetObject[ objectName ] === undefined ) {
  26379. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26380. return;
  26381. }
  26382. targetObject = targetObject[ objectName ];
  26383. }
  26384. if ( objectIndex !== undefined ) {
  26385. if ( targetObject[ objectIndex ] === undefined ) {
  26386. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26387. return;
  26388. }
  26389. targetObject = targetObject[ objectIndex ];
  26390. }
  26391. }
  26392. // resolve property
  26393. const nodeProperty = targetObject[ propertyName ];
  26394. if ( nodeProperty === undefined ) {
  26395. const nodeName = parsedPath.nodeName;
  26396. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26397. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26398. return;
  26399. }
  26400. // determine versioning scheme
  26401. let versioning = this.Versioning.None;
  26402. this.targetObject = targetObject;
  26403. if ( targetObject.needsUpdate !== undefined ) { // material
  26404. versioning = this.Versioning.NeedsUpdate;
  26405. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26406. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26407. }
  26408. // determine how the property gets bound
  26409. let bindingType = this.BindingType.Direct;
  26410. if ( propertyIndex !== undefined ) {
  26411. // access a sub element of the property array (only primitives are supported right now)
  26412. if ( propertyName === 'morphTargetInfluences' ) {
  26413. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26414. // support resolving morphTarget names into indices.
  26415. if ( ! targetObject.geometry ) {
  26416. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26417. return;
  26418. }
  26419. if ( targetObject.geometry.isBufferGeometry ) {
  26420. if ( ! targetObject.geometry.morphAttributes ) {
  26421. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26422. return;
  26423. }
  26424. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26425. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26426. }
  26427. } else {
  26428. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  26429. return;
  26430. }
  26431. }
  26432. bindingType = this.BindingType.ArrayElement;
  26433. this.resolvedProperty = nodeProperty;
  26434. this.propertyIndex = propertyIndex;
  26435. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26436. // must use copy for Object3D.Euler/Quaternion
  26437. bindingType = this.BindingType.HasFromToArray;
  26438. this.resolvedProperty = nodeProperty;
  26439. } else if ( Array.isArray( nodeProperty ) ) {
  26440. bindingType = this.BindingType.EntireArray;
  26441. this.resolvedProperty = nodeProperty;
  26442. } else {
  26443. this.propertyName = propertyName;
  26444. }
  26445. // select getter / setter
  26446. this.getValue = this.GetterByBindingType[ bindingType ];
  26447. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26448. }
  26449. unbind() {
  26450. this.node = null;
  26451. // back to the prototype version of getValue / setValue
  26452. // note: avoiding to mutate the shape of 'this' via 'delete'
  26453. this.getValue = this._getValue_unbound;
  26454. this.setValue = this._setValue_unbound;
  26455. }
  26456. }
  26457. PropertyBinding.Composite = Composite;
  26458. PropertyBinding.prototype.BindingType = {
  26459. Direct: 0,
  26460. EntireArray: 1,
  26461. ArrayElement: 2,
  26462. HasFromToArray: 3
  26463. };
  26464. PropertyBinding.prototype.Versioning = {
  26465. None: 0,
  26466. NeedsUpdate: 1,
  26467. MatrixWorldNeedsUpdate: 2
  26468. };
  26469. PropertyBinding.prototype.GetterByBindingType = [
  26470. PropertyBinding.prototype._getValue_direct,
  26471. PropertyBinding.prototype._getValue_array,
  26472. PropertyBinding.prototype._getValue_arrayElement,
  26473. PropertyBinding.prototype._getValue_toArray,
  26474. ];
  26475. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26476. [
  26477. // Direct
  26478. PropertyBinding.prototype._setValue_direct,
  26479. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26480. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26481. ], [
  26482. // EntireArray
  26483. PropertyBinding.prototype._setValue_array,
  26484. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26485. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26486. ], [
  26487. // ArrayElement
  26488. PropertyBinding.prototype._setValue_arrayElement,
  26489. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26490. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26491. ], [
  26492. // HasToFromArray
  26493. PropertyBinding.prototype._setValue_fromArray,
  26494. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26495. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26496. ]
  26497. ];
  26498. /**
  26499. *
  26500. * A group of objects that receives a shared animation state.
  26501. *
  26502. * Usage:
  26503. *
  26504. * - Add objects you would otherwise pass as 'root' to the
  26505. * constructor or the .clipAction method of AnimationMixer.
  26506. *
  26507. * - Instead pass this object as 'root'.
  26508. *
  26509. * - You can also add and remove objects later when the mixer
  26510. * is running.
  26511. *
  26512. * Note:
  26513. *
  26514. * Objects of this class appear as one object to the mixer,
  26515. * so cache control of the individual objects must be done
  26516. * on the group.
  26517. *
  26518. * Limitation:
  26519. *
  26520. * - The animated properties must be compatible among the
  26521. * all objects in the group.
  26522. *
  26523. * - A single property can either be controlled through a
  26524. * target group or directly, but not both.
  26525. */
  26526. class AnimationObjectGroup {
  26527. constructor() {
  26528. this.uuid = generateUUID();
  26529. // cached objects followed by the active ones
  26530. this._objects = Array.prototype.slice.call( arguments );
  26531. this.nCachedObjects_ = 0; // threshold
  26532. // note: read by PropertyBinding.Composite
  26533. const indices = {};
  26534. this._indicesByUUID = indices; // for bookkeeping
  26535. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26536. indices[ arguments[ i ].uuid ] = i;
  26537. }
  26538. this._paths = []; // inside: string
  26539. this._parsedPaths = []; // inside: { we don't care, here }
  26540. this._bindings = []; // inside: Array< PropertyBinding >
  26541. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26542. const scope = this;
  26543. this.stats = {
  26544. objects: {
  26545. get total() {
  26546. return scope._objects.length;
  26547. },
  26548. get inUse() {
  26549. return this.total - scope.nCachedObjects_;
  26550. }
  26551. },
  26552. get bindingsPerObject() {
  26553. return scope._bindings.length;
  26554. }
  26555. };
  26556. }
  26557. add() {
  26558. const objects = this._objects,
  26559. indicesByUUID = this._indicesByUUID,
  26560. paths = this._paths,
  26561. parsedPaths = this._parsedPaths,
  26562. bindings = this._bindings,
  26563. nBindings = bindings.length;
  26564. let knownObject = undefined,
  26565. nObjects = objects.length,
  26566. nCachedObjects = this.nCachedObjects_;
  26567. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26568. const object = arguments[ i ],
  26569. uuid = object.uuid;
  26570. let index = indicesByUUID[ uuid ];
  26571. if ( index === undefined ) {
  26572. // unknown object -> add it to the ACTIVE region
  26573. index = nObjects ++;
  26574. indicesByUUID[ uuid ] = index;
  26575. objects.push( object );
  26576. // accounting is done, now do the same for all bindings
  26577. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26578. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26579. }
  26580. } else if ( index < nCachedObjects ) {
  26581. knownObject = objects[ index ];
  26582. // move existing object to the ACTIVE region
  26583. const firstActiveIndex = -- nCachedObjects,
  26584. lastCachedObject = objects[ firstActiveIndex ];
  26585. indicesByUUID[ lastCachedObject.uuid ] = index;
  26586. objects[ index ] = lastCachedObject;
  26587. indicesByUUID[ uuid ] = firstActiveIndex;
  26588. objects[ firstActiveIndex ] = object;
  26589. // accounting is done, now do the same for all bindings
  26590. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26591. const bindingsForPath = bindings[ j ],
  26592. lastCached = bindingsForPath[ firstActiveIndex ];
  26593. let binding = bindingsForPath[ index ];
  26594. bindingsForPath[ index ] = lastCached;
  26595. if ( binding === undefined ) {
  26596. // since we do not bother to create new bindings
  26597. // for objects that are cached, the binding may
  26598. // or may not exist
  26599. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26600. }
  26601. bindingsForPath[ firstActiveIndex ] = binding;
  26602. }
  26603. } else if ( objects[ index ] !== knownObject ) {
  26604. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26605. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26606. } // else the object is already where we want it to be
  26607. } // for arguments
  26608. this.nCachedObjects_ = nCachedObjects;
  26609. }
  26610. remove() {
  26611. const objects = this._objects,
  26612. indicesByUUID = this._indicesByUUID,
  26613. bindings = this._bindings,
  26614. nBindings = bindings.length;
  26615. let nCachedObjects = this.nCachedObjects_;
  26616. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26617. const object = arguments[ i ],
  26618. uuid = object.uuid,
  26619. index = indicesByUUID[ uuid ];
  26620. if ( index !== undefined && index >= nCachedObjects ) {
  26621. // move existing object into the CACHED region
  26622. const lastCachedIndex = nCachedObjects ++,
  26623. firstActiveObject = objects[ lastCachedIndex ];
  26624. indicesByUUID[ firstActiveObject.uuid ] = index;
  26625. objects[ index ] = firstActiveObject;
  26626. indicesByUUID[ uuid ] = lastCachedIndex;
  26627. objects[ lastCachedIndex ] = object;
  26628. // accounting is done, now do the same for all bindings
  26629. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26630. const bindingsForPath = bindings[ j ],
  26631. firstActive = bindingsForPath[ lastCachedIndex ],
  26632. binding = bindingsForPath[ index ];
  26633. bindingsForPath[ index ] = firstActive;
  26634. bindingsForPath[ lastCachedIndex ] = binding;
  26635. }
  26636. }
  26637. } // for arguments
  26638. this.nCachedObjects_ = nCachedObjects;
  26639. }
  26640. // remove & forget
  26641. uncache() {
  26642. const objects = this._objects,
  26643. indicesByUUID = this._indicesByUUID,
  26644. bindings = this._bindings,
  26645. nBindings = bindings.length;
  26646. let nCachedObjects = this.nCachedObjects_,
  26647. nObjects = objects.length;
  26648. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26649. const object = arguments[ i ],
  26650. uuid = object.uuid,
  26651. index = indicesByUUID[ uuid ];
  26652. if ( index !== undefined ) {
  26653. delete indicesByUUID[ uuid ];
  26654. if ( index < nCachedObjects ) {
  26655. // object is cached, shrink the CACHED region
  26656. const firstActiveIndex = -- nCachedObjects,
  26657. lastCachedObject = objects[ firstActiveIndex ],
  26658. lastIndex = -- nObjects,
  26659. lastObject = objects[ lastIndex ];
  26660. // last cached object takes this object's place
  26661. indicesByUUID[ lastCachedObject.uuid ] = index;
  26662. objects[ index ] = lastCachedObject;
  26663. // last object goes to the activated slot and pop
  26664. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26665. objects[ firstActiveIndex ] = lastObject;
  26666. objects.pop();
  26667. // accounting is done, now do the same for all bindings
  26668. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26669. const bindingsForPath = bindings[ j ],
  26670. lastCached = bindingsForPath[ firstActiveIndex ],
  26671. last = bindingsForPath[ lastIndex ];
  26672. bindingsForPath[ index ] = lastCached;
  26673. bindingsForPath[ firstActiveIndex ] = last;
  26674. bindingsForPath.pop();
  26675. }
  26676. } else {
  26677. // object is active, just swap with the last and pop
  26678. const lastIndex = -- nObjects,
  26679. lastObject = objects[ lastIndex ];
  26680. if ( lastIndex > 0 ) {
  26681. indicesByUUID[ lastObject.uuid ] = index;
  26682. }
  26683. objects[ index ] = lastObject;
  26684. objects.pop();
  26685. // accounting is done, now do the same for all bindings
  26686. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26687. const bindingsForPath = bindings[ j ];
  26688. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26689. bindingsForPath.pop();
  26690. }
  26691. } // cached or active
  26692. } // if object is known
  26693. } // for arguments
  26694. this.nCachedObjects_ = nCachedObjects;
  26695. }
  26696. // Internal interface used by befriended PropertyBinding.Composite:
  26697. subscribe_( path, parsedPath ) {
  26698. // returns an array of bindings for the given path that is changed
  26699. // according to the contained objects in the group
  26700. const indicesByPath = this._bindingsIndicesByPath;
  26701. let index = indicesByPath[ path ];
  26702. const bindings = this._bindings;
  26703. if ( index !== undefined ) return bindings[ index ];
  26704. const paths = this._paths,
  26705. parsedPaths = this._parsedPaths,
  26706. objects = this._objects,
  26707. nObjects = objects.length,
  26708. nCachedObjects = this.nCachedObjects_,
  26709. bindingsForPath = new Array( nObjects );
  26710. index = bindings.length;
  26711. indicesByPath[ path ] = index;
  26712. paths.push( path );
  26713. parsedPaths.push( parsedPath );
  26714. bindings.push( bindingsForPath );
  26715. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26716. const object = objects[ i ];
  26717. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26718. }
  26719. return bindingsForPath;
  26720. }
  26721. unsubscribe_( path ) {
  26722. // tells the group to forget about a property path and no longer
  26723. // update the array previously obtained with 'subscribe_'
  26724. const indicesByPath = this._bindingsIndicesByPath,
  26725. index = indicesByPath[ path ];
  26726. if ( index !== undefined ) {
  26727. const paths = this._paths,
  26728. parsedPaths = this._parsedPaths,
  26729. bindings = this._bindings,
  26730. lastBindingsIndex = bindings.length - 1,
  26731. lastBindings = bindings[ lastBindingsIndex ],
  26732. lastBindingsPath = path[ lastBindingsIndex ];
  26733. indicesByPath[ lastBindingsPath ] = index;
  26734. bindings[ index ] = lastBindings;
  26735. bindings.pop();
  26736. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26737. parsedPaths.pop();
  26738. paths[ index ] = paths[ lastBindingsIndex ];
  26739. paths.pop();
  26740. }
  26741. }
  26742. }
  26743. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26744. class AnimationAction {
  26745. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26746. this._mixer = mixer;
  26747. this._clip = clip;
  26748. this._localRoot = localRoot;
  26749. this.blendMode = blendMode;
  26750. const tracks = clip.tracks,
  26751. nTracks = tracks.length,
  26752. interpolants = new Array( nTracks );
  26753. const interpolantSettings = {
  26754. endingStart: ZeroCurvatureEnding,
  26755. endingEnd: ZeroCurvatureEnding
  26756. };
  26757. for ( let i = 0; i !== nTracks; ++ i ) {
  26758. const interpolant = tracks[ i ].createInterpolant( null );
  26759. interpolants[ i ] = interpolant;
  26760. interpolant.settings = interpolantSettings;
  26761. }
  26762. this._interpolantSettings = interpolantSettings;
  26763. this._interpolants = interpolants; // bound by the mixer
  26764. // inside: PropertyMixer (managed by the mixer)
  26765. this._propertyBindings = new Array( nTracks );
  26766. this._cacheIndex = null; // for the memory manager
  26767. this._byClipCacheIndex = null; // for the memory manager
  26768. this._timeScaleInterpolant = null;
  26769. this._weightInterpolant = null;
  26770. this.loop = LoopRepeat;
  26771. this._loopCount = - 1;
  26772. // global mixer time when the action is to be started
  26773. // it's set back to 'null' upon start of the action
  26774. this._startTime = null;
  26775. // scaled local time of the action
  26776. // gets clamped or wrapped to 0..clip.duration according to loop
  26777. this.time = 0;
  26778. this.timeScale = 1;
  26779. this._effectiveTimeScale = 1;
  26780. this.weight = 1;
  26781. this._effectiveWeight = 1;
  26782. this.repetitions = Infinity; // no. of repetitions when looping
  26783. this.paused = false; // true -> zero effective time scale
  26784. this.enabled = true; // false -> zero effective weight
  26785. this.clampWhenFinished = false;// keep feeding the last frame?
  26786. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26787. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26788. }
  26789. // State & Scheduling
  26790. play() {
  26791. this._mixer._activateAction( this );
  26792. return this;
  26793. }
  26794. stop() {
  26795. this._mixer._deactivateAction( this );
  26796. return this.reset();
  26797. }
  26798. reset() {
  26799. this.paused = false;
  26800. this.enabled = true;
  26801. this.time = 0; // restart clip
  26802. this._loopCount = - 1;// forget previous loops
  26803. this._startTime = null;// forget scheduling
  26804. return this.stopFading().stopWarping();
  26805. }
  26806. isRunning() {
  26807. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26808. this._startTime === null && this._mixer._isActiveAction( this );
  26809. }
  26810. // return true when play has been called
  26811. isScheduled() {
  26812. return this._mixer._isActiveAction( this );
  26813. }
  26814. startAt( time ) {
  26815. this._startTime = time;
  26816. return this;
  26817. }
  26818. setLoop( mode, repetitions ) {
  26819. this.loop = mode;
  26820. this.repetitions = repetitions;
  26821. return this;
  26822. }
  26823. // Weight
  26824. // set the weight stopping any scheduled fading
  26825. // although .enabled = false yields an effective weight of zero, this
  26826. // method does *not* change .enabled, because it would be confusing
  26827. setEffectiveWeight( weight ) {
  26828. this.weight = weight;
  26829. // note: same logic as when updated at runtime
  26830. this._effectiveWeight = this.enabled ? weight : 0;
  26831. return this.stopFading();
  26832. }
  26833. // return the weight considering fading and .enabled
  26834. getEffectiveWeight() {
  26835. return this._effectiveWeight;
  26836. }
  26837. fadeIn( duration ) {
  26838. return this._scheduleFading( duration, 0, 1 );
  26839. }
  26840. fadeOut( duration ) {
  26841. return this._scheduleFading( duration, 1, 0 );
  26842. }
  26843. crossFadeFrom( fadeOutAction, duration, warp ) {
  26844. fadeOutAction.fadeOut( duration );
  26845. this.fadeIn( duration );
  26846. if ( warp ) {
  26847. const fadeInDuration = this._clip.duration,
  26848. fadeOutDuration = fadeOutAction._clip.duration,
  26849. startEndRatio = fadeOutDuration / fadeInDuration,
  26850. endStartRatio = fadeInDuration / fadeOutDuration;
  26851. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26852. this.warp( endStartRatio, 1.0, duration );
  26853. }
  26854. return this;
  26855. }
  26856. crossFadeTo( fadeInAction, duration, warp ) {
  26857. return fadeInAction.crossFadeFrom( this, duration, warp );
  26858. }
  26859. stopFading() {
  26860. const weightInterpolant = this._weightInterpolant;
  26861. if ( weightInterpolant !== null ) {
  26862. this._weightInterpolant = null;
  26863. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26864. }
  26865. return this;
  26866. }
  26867. // Time Scale Control
  26868. // set the time scale stopping any scheduled warping
  26869. // although .paused = true yields an effective time scale of zero, this
  26870. // method does *not* change .paused, because it would be confusing
  26871. setEffectiveTimeScale( timeScale ) {
  26872. this.timeScale = timeScale;
  26873. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26874. return this.stopWarping();
  26875. }
  26876. // return the time scale considering warping and .paused
  26877. getEffectiveTimeScale() {
  26878. return this._effectiveTimeScale;
  26879. }
  26880. setDuration( duration ) {
  26881. this.timeScale = this._clip.duration / duration;
  26882. return this.stopWarping();
  26883. }
  26884. syncWith( action ) {
  26885. this.time = action.time;
  26886. this.timeScale = action.timeScale;
  26887. return this.stopWarping();
  26888. }
  26889. halt( duration ) {
  26890. return this.warp( this._effectiveTimeScale, 0, duration );
  26891. }
  26892. warp( startTimeScale, endTimeScale, duration ) {
  26893. const mixer = this._mixer,
  26894. now = mixer.time,
  26895. timeScale = this.timeScale;
  26896. let interpolant = this._timeScaleInterpolant;
  26897. if ( interpolant === null ) {
  26898. interpolant = mixer._lendControlInterpolant();
  26899. this._timeScaleInterpolant = interpolant;
  26900. }
  26901. const times = interpolant.parameterPositions,
  26902. values = interpolant.sampleValues;
  26903. times[ 0 ] = now;
  26904. times[ 1 ] = now + duration;
  26905. values[ 0 ] = startTimeScale / timeScale;
  26906. values[ 1 ] = endTimeScale / timeScale;
  26907. return this;
  26908. }
  26909. stopWarping() {
  26910. const timeScaleInterpolant = this._timeScaleInterpolant;
  26911. if ( timeScaleInterpolant !== null ) {
  26912. this._timeScaleInterpolant = null;
  26913. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26914. }
  26915. return this;
  26916. }
  26917. // Object Accessors
  26918. getMixer() {
  26919. return this._mixer;
  26920. }
  26921. getClip() {
  26922. return this._clip;
  26923. }
  26924. getRoot() {
  26925. return this._localRoot || this._mixer._root;
  26926. }
  26927. // Interna
  26928. _update( time, deltaTime, timeDirection, accuIndex ) {
  26929. // called by the mixer
  26930. if ( ! this.enabled ) {
  26931. // call ._updateWeight() to update ._effectiveWeight
  26932. this._updateWeight( time );
  26933. return;
  26934. }
  26935. const startTime = this._startTime;
  26936. if ( startTime !== null ) {
  26937. // check for scheduled start of action
  26938. const timeRunning = ( time - startTime ) * timeDirection;
  26939. if ( timeRunning < 0 || timeDirection === 0 ) {
  26940. return; // yet to come / don't decide when delta = 0
  26941. }
  26942. // start
  26943. this._startTime = null; // unschedule
  26944. deltaTime = timeDirection * timeRunning;
  26945. }
  26946. // apply time scale and advance time
  26947. deltaTime *= this._updateTimeScale( time );
  26948. const clipTime = this._updateTime( deltaTime );
  26949. // note: _updateTime may disable the action resulting in
  26950. // an effective weight of 0
  26951. const weight = this._updateWeight( time );
  26952. if ( weight > 0 ) {
  26953. const interpolants = this._interpolants;
  26954. const propertyMixers = this._propertyBindings;
  26955. switch ( this.blendMode ) {
  26956. case AdditiveAnimationBlendMode:
  26957. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26958. interpolants[ j ].evaluate( clipTime );
  26959. propertyMixers[ j ].accumulateAdditive( weight );
  26960. }
  26961. break;
  26962. case NormalAnimationBlendMode:
  26963. default:
  26964. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26965. interpolants[ j ].evaluate( clipTime );
  26966. propertyMixers[ j ].accumulate( accuIndex, weight );
  26967. }
  26968. }
  26969. }
  26970. }
  26971. _updateWeight( time ) {
  26972. let weight = 0;
  26973. if ( this.enabled ) {
  26974. weight = this.weight;
  26975. const interpolant = this._weightInterpolant;
  26976. if ( interpolant !== null ) {
  26977. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26978. weight *= interpolantValue;
  26979. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26980. this.stopFading();
  26981. if ( interpolantValue === 0 ) {
  26982. // faded out, disable
  26983. this.enabled = false;
  26984. }
  26985. }
  26986. }
  26987. }
  26988. this._effectiveWeight = weight;
  26989. return weight;
  26990. }
  26991. _updateTimeScale( time ) {
  26992. let timeScale = 0;
  26993. if ( ! this.paused ) {
  26994. timeScale = this.timeScale;
  26995. const interpolant = this._timeScaleInterpolant;
  26996. if ( interpolant !== null ) {
  26997. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26998. timeScale *= interpolantValue;
  26999. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27000. this.stopWarping();
  27001. if ( timeScale === 0 ) {
  27002. // motion has halted, pause
  27003. this.paused = true;
  27004. } else {
  27005. // warp done - apply final time scale
  27006. this.timeScale = timeScale;
  27007. }
  27008. }
  27009. }
  27010. }
  27011. this._effectiveTimeScale = timeScale;
  27012. return timeScale;
  27013. }
  27014. _updateTime( deltaTime ) {
  27015. const duration = this._clip.duration;
  27016. const loop = this.loop;
  27017. let time = this.time + deltaTime;
  27018. let loopCount = this._loopCount;
  27019. const pingPong = ( loop === LoopPingPong );
  27020. if ( deltaTime === 0 ) {
  27021. if ( loopCount === - 1 ) return time;
  27022. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27023. }
  27024. if ( loop === LoopOnce ) {
  27025. if ( loopCount === - 1 ) {
  27026. // just started
  27027. this._loopCount = 0;
  27028. this._setEndings( true, true, false );
  27029. }
  27030. handle_stop: {
  27031. if ( time >= duration ) {
  27032. time = duration;
  27033. } else if ( time < 0 ) {
  27034. time = 0;
  27035. } else {
  27036. this.time = time;
  27037. break handle_stop;
  27038. }
  27039. if ( this.clampWhenFinished ) this.paused = true;
  27040. else this.enabled = false;
  27041. this.time = time;
  27042. this._mixer.dispatchEvent( {
  27043. type: 'finished', action: this,
  27044. direction: deltaTime < 0 ? - 1 : 1
  27045. } );
  27046. }
  27047. } else { // repetitive Repeat or PingPong
  27048. if ( loopCount === - 1 ) {
  27049. // just started
  27050. if ( deltaTime >= 0 ) {
  27051. loopCount = 0;
  27052. this._setEndings( true, this.repetitions === 0, pingPong );
  27053. } else {
  27054. // when looping in reverse direction, the initial
  27055. // transition through zero counts as a repetition,
  27056. // so leave loopCount at -1
  27057. this._setEndings( this.repetitions === 0, true, pingPong );
  27058. }
  27059. }
  27060. if ( time >= duration || time < 0 ) {
  27061. // wrap around
  27062. const loopDelta = Math.floor( time / duration ); // signed
  27063. time -= duration * loopDelta;
  27064. loopCount += Math.abs( loopDelta );
  27065. const pending = this.repetitions - loopCount;
  27066. if ( pending <= 0 ) {
  27067. // have to stop (switch state, clamp time, fire event)
  27068. if ( this.clampWhenFinished ) this.paused = true;
  27069. else this.enabled = false;
  27070. time = deltaTime > 0 ? duration : 0;
  27071. this.time = time;
  27072. this._mixer.dispatchEvent( {
  27073. type: 'finished', action: this,
  27074. direction: deltaTime > 0 ? 1 : - 1
  27075. } );
  27076. } else {
  27077. // keep running
  27078. if ( pending === 1 ) {
  27079. // entering the last round
  27080. const atStart = deltaTime < 0;
  27081. this._setEndings( atStart, ! atStart, pingPong );
  27082. } else {
  27083. this._setEndings( false, false, pingPong );
  27084. }
  27085. this._loopCount = loopCount;
  27086. this.time = time;
  27087. this._mixer.dispatchEvent( {
  27088. type: 'loop', action: this, loopDelta: loopDelta
  27089. } );
  27090. }
  27091. } else {
  27092. this.time = time;
  27093. }
  27094. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27095. // invert time for the "pong round"
  27096. return duration - time;
  27097. }
  27098. }
  27099. return time;
  27100. }
  27101. _setEndings( atStart, atEnd, pingPong ) {
  27102. const settings = this._interpolantSettings;
  27103. if ( pingPong ) {
  27104. settings.endingStart = ZeroSlopeEnding;
  27105. settings.endingEnd = ZeroSlopeEnding;
  27106. } else {
  27107. // assuming for LoopOnce atStart == atEnd == true
  27108. if ( atStart ) {
  27109. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27110. } else {
  27111. settings.endingStart = WrapAroundEnding;
  27112. }
  27113. if ( atEnd ) {
  27114. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27115. } else {
  27116. settings.endingEnd = WrapAroundEnding;
  27117. }
  27118. }
  27119. }
  27120. _scheduleFading( duration, weightNow, weightThen ) {
  27121. const mixer = this._mixer, now = mixer.time;
  27122. let interpolant = this._weightInterpolant;
  27123. if ( interpolant === null ) {
  27124. interpolant = mixer._lendControlInterpolant();
  27125. this._weightInterpolant = interpolant;
  27126. }
  27127. const times = interpolant.parameterPositions,
  27128. values = interpolant.sampleValues;
  27129. times[ 0 ] = now;
  27130. values[ 0 ] = weightNow;
  27131. times[ 1 ] = now + duration;
  27132. values[ 1 ] = weightThen;
  27133. return this;
  27134. }
  27135. }
  27136. class AnimationMixer extends EventDispatcher {
  27137. constructor( root ) {
  27138. super();
  27139. this._root = root;
  27140. this._initMemoryManager();
  27141. this._accuIndex = 0;
  27142. this.time = 0;
  27143. this.timeScale = 1.0;
  27144. }
  27145. _bindAction( action, prototypeAction ) {
  27146. const root = action._localRoot || this._root,
  27147. tracks = action._clip.tracks,
  27148. nTracks = tracks.length,
  27149. bindings = action._propertyBindings,
  27150. interpolants = action._interpolants,
  27151. rootUuid = root.uuid,
  27152. bindingsByRoot = this._bindingsByRootAndName;
  27153. let bindingsByName = bindingsByRoot[ rootUuid ];
  27154. if ( bindingsByName === undefined ) {
  27155. bindingsByName = {};
  27156. bindingsByRoot[ rootUuid ] = bindingsByName;
  27157. }
  27158. for ( let i = 0; i !== nTracks; ++ i ) {
  27159. const track = tracks[ i ],
  27160. trackName = track.name;
  27161. let binding = bindingsByName[ trackName ];
  27162. if ( binding !== undefined ) {
  27163. ++ binding.referenceCount;
  27164. bindings[ i ] = binding;
  27165. } else {
  27166. binding = bindings[ i ];
  27167. if ( binding !== undefined ) {
  27168. // existing binding, make sure the cache knows
  27169. if ( binding._cacheIndex === null ) {
  27170. ++ binding.referenceCount;
  27171. this._addInactiveBinding( binding, rootUuid, trackName );
  27172. }
  27173. continue;
  27174. }
  27175. const path = prototypeAction && prototypeAction.
  27176. _propertyBindings[ i ].binding.parsedPath;
  27177. binding = new PropertyMixer(
  27178. PropertyBinding.create( root, trackName, path ),
  27179. track.ValueTypeName, track.getValueSize() );
  27180. ++ binding.referenceCount;
  27181. this._addInactiveBinding( binding, rootUuid, trackName );
  27182. bindings[ i ] = binding;
  27183. }
  27184. interpolants[ i ].resultBuffer = binding.buffer;
  27185. }
  27186. }
  27187. _activateAction( action ) {
  27188. if ( ! this._isActiveAction( action ) ) {
  27189. if ( action._cacheIndex === null ) {
  27190. // this action has been forgotten by the cache, but the user
  27191. // appears to be still using it -> rebind
  27192. const rootUuid = ( action._localRoot || this._root ).uuid,
  27193. clipUuid = action._clip.uuid,
  27194. actionsForClip = this._actionsByClip[ clipUuid ];
  27195. this._bindAction( action,
  27196. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27197. this._addInactiveAction( action, clipUuid, rootUuid );
  27198. }
  27199. const bindings = action._propertyBindings;
  27200. // increment reference counts / sort out state
  27201. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27202. const binding = bindings[ i ];
  27203. if ( binding.useCount ++ === 0 ) {
  27204. this._lendBinding( binding );
  27205. binding.saveOriginalState();
  27206. }
  27207. }
  27208. this._lendAction( action );
  27209. }
  27210. }
  27211. _deactivateAction( action ) {
  27212. if ( this._isActiveAction( action ) ) {
  27213. const bindings = action._propertyBindings;
  27214. // decrement reference counts / sort out state
  27215. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27216. const binding = bindings[ i ];
  27217. if ( -- binding.useCount === 0 ) {
  27218. binding.restoreOriginalState();
  27219. this._takeBackBinding( binding );
  27220. }
  27221. }
  27222. this._takeBackAction( action );
  27223. }
  27224. }
  27225. // Memory manager
  27226. _initMemoryManager() {
  27227. this._actions = []; // 'nActiveActions' followed by inactive ones
  27228. this._nActiveActions = 0;
  27229. this._actionsByClip = {};
  27230. // inside:
  27231. // {
  27232. // knownActions: Array< AnimationAction > - used as prototypes
  27233. // actionByRoot: AnimationAction - lookup
  27234. // }
  27235. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27236. this._nActiveBindings = 0;
  27237. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27238. this._controlInterpolants = []; // same game as above
  27239. this._nActiveControlInterpolants = 0;
  27240. const scope = this;
  27241. this.stats = {
  27242. actions: {
  27243. get total() {
  27244. return scope._actions.length;
  27245. },
  27246. get inUse() {
  27247. return scope._nActiveActions;
  27248. }
  27249. },
  27250. bindings: {
  27251. get total() {
  27252. return scope._bindings.length;
  27253. },
  27254. get inUse() {
  27255. return scope._nActiveBindings;
  27256. }
  27257. },
  27258. controlInterpolants: {
  27259. get total() {
  27260. return scope._controlInterpolants.length;
  27261. },
  27262. get inUse() {
  27263. return scope._nActiveControlInterpolants;
  27264. }
  27265. }
  27266. };
  27267. }
  27268. // Memory management for AnimationAction objects
  27269. _isActiveAction( action ) {
  27270. const index = action._cacheIndex;
  27271. return index !== null && index < this._nActiveActions;
  27272. }
  27273. _addInactiveAction( action, clipUuid, rootUuid ) {
  27274. const actions = this._actions,
  27275. actionsByClip = this._actionsByClip;
  27276. let actionsForClip = actionsByClip[ clipUuid ];
  27277. if ( actionsForClip === undefined ) {
  27278. actionsForClip = {
  27279. knownActions: [ action ],
  27280. actionByRoot: {}
  27281. };
  27282. action._byClipCacheIndex = 0;
  27283. actionsByClip[ clipUuid ] = actionsForClip;
  27284. } else {
  27285. const knownActions = actionsForClip.knownActions;
  27286. action._byClipCacheIndex = knownActions.length;
  27287. knownActions.push( action );
  27288. }
  27289. action._cacheIndex = actions.length;
  27290. actions.push( action );
  27291. actionsForClip.actionByRoot[ rootUuid ] = action;
  27292. }
  27293. _removeInactiveAction( action ) {
  27294. const actions = this._actions,
  27295. lastInactiveAction = actions[ actions.length - 1 ],
  27296. cacheIndex = action._cacheIndex;
  27297. lastInactiveAction._cacheIndex = cacheIndex;
  27298. actions[ cacheIndex ] = lastInactiveAction;
  27299. actions.pop();
  27300. action._cacheIndex = null;
  27301. const clipUuid = action._clip.uuid,
  27302. actionsByClip = this._actionsByClip,
  27303. actionsForClip = actionsByClip[ clipUuid ],
  27304. knownActionsForClip = actionsForClip.knownActions,
  27305. lastKnownAction =
  27306. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27307. byClipCacheIndex = action._byClipCacheIndex;
  27308. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27309. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27310. knownActionsForClip.pop();
  27311. action._byClipCacheIndex = null;
  27312. const actionByRoot = actionsForClip.actionByRoot,
  27313. rootUuid = ( action._localRoot || this._root ).uuid;
  27314. delete actionByRoot[ rootUuid ];
  27315. if ( knownActionsForClip.length === 0 ) {
  27316. delete actionsByClip[ clipUuid ];
  27317. }
  27318. this._removeInactiveBindingsForAction( action );
  27319. }
  27320. _removeInactiveBindingsForAction( action ) {
  27321. const bindings = action._propertyBindings;
  27322. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27323. const binding = bindings[ i ];
  27324. if ( -- binding.referenceCount === 0 ) {
  27325. this._removeInactiveBinding( binding );
  27326. }
  27327. }
  27328. }
  27329. _lendAction( action ) {
  27330. // [ active actions | inactive actions ]
  27331. // [ active actions >| inactive actions ]
  27332. // s a
  27333. // <-swap->
  27334. // a s
  27335. const actions = this._actions,
  27336. prevIndex = action._cacheIndex,
  27337. lastActiveIndex = this._nActiveActions ++,
  27338. firstInactiveAction = actions[ lastActiveIndex ];
  27339. action._cacheIndex = lastActiveIndex;
  27340. actions[ lastActiveIndex ] = action;
  27341. firstInactiveAction._cacheIndex = prevIndex;
  27342. actions[ prevIndex ] = firstInactiveAction;
  27343. }
  27344. _takeBackAction( action ) {
  27345. // [ active actions | inactive actions ]
  27346. // [ active actions |< inactive actions ]
  27347. // a s
  27348. // <-swap->
  27349. // s a
  27350. const actions = this._actions,
  27351. prevIndex = action._cacheIndex,
  27352. firstInactiveIndex = -- this._nActiveActions,
  27353. lastActiveAction = actions[ firstInactiveIndex ];
  27354. action._cacheIndex = firstInactiveIndex;
  27355. actions[ firstInactiveIndex ] = action;
  27356. lastActiveAction._cacheIndex = prevIndex;
  27357. actions[ prevIndex ] = lastActiveAction;
  27358. }
  27359. // Memory management for PropertyMixer objects
  27360. _addInactiveBinding( binding, rootUuid, trackName ) {
  27361. const bindingsByRoot = this._bindingsByRootAndName,
  27362. bindings = this._bindings;
  27363. let bindingByName = bindingsByRoot[ rootUuid ];
  27364. if ( bindingByName === undefined ) {
  27365. bindingByName = {};
  27366. bindingsByRoot[ rootUuid ] = bindingByName;
  27367. }
  27368. bindingByName[ trackName ] = binding;
  27369. binding._cacheIndex = bindings.length;
  27370. bindings.push( binding );
  27371. }
  27372. _removeInactiveBinding( binding ) {
  27373. const bindings = this._bindings,
  27374. propBinding = binding.binding,
  27375. rootUuid = propBinding.rootNode.uuid,
  27376. trackName = propBinding.path,
  27377. bindingsByRoot = this._bindingsByRootAndName,
  27378. bindingByName = bindingsByRoot[ rootUuid ],
  27379. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27380. cacheIndex = binding._cacheIndex;
  27381. lastInactiveBinding._cacheIndex = cacheIndex;
  27382. bindings[ cacheIndex ] = lastInactiveBinding;
  27383. bindings.pop();
  27384. delete bindingByName[ trackName ];
  27385. if ( Object.keys( bindingByName ).length === 0 ) {
  27386. delete bindingsByRoot[ rootUuid ];
  27387. }
  27388. }
  27389. _lendBinding( binding ) {
  27390. const bindings = this._bindings,
  27391. prevIndex = binding._cacheIndex,
  27392. lastActiveIndex = this._nActiveBindings ++,
  27393. firstInactiveBinding = bindings[ lastActiveIndex ];
  27394. binding._cacheIndex = lastActiveIndex;
  27395. bindings[ lastActiveIndex ] = binding;
  27396. firstInactiveBinding._cacheIndex = prevIndex;
  27397. bindings[ prevIndex ] = firstInactiveBinding;
  27398. }
  27399. _takeBackBinding( binding ) {
  27400. const bindings = this._bindings,
  27401. prevIndex = binding._cacheIndex,
  27402. firstInactiveIndex = -- this._nActiveBindings,
  27403. lastActiveBinding = bindings[ firstInactiveIndex ];
  27404. binding._cacheIndex = firstInactiveIndex;
  27405. bindings[ firstInactiveIndex ] = binding;
  27406. lastActiveBinding._cacheIndex = prevIndex;
  27407. bindings[ prevIndex ] = lastActiveBinding;
  27408. }
  27409. // Memory management of Interpolants for weight and time scale
  27410. _lendControlInterpolant() {
  27411. const interpolants = this._controlInterpolants,
  27412. lastActiveIndex = this._nActiveControlInterpolants ++;
  27413. let interpolant = interpolants[ lastActiveIndex ];
  27414. if ( interpolant === undefined ) {
  27415. interpolant = new LinearInterpolant(
  27416. new Float32Array( 2 ), new Float32Array( 2 ),
  27417. 1, this._controlInterpolantsResultBuffer );
  27418. interpolant.__cacheIndex = lastActiveIndex;
  27419. interpolants[ lastActiveIndex ] = interpolant;
  27420. }
  27421. return interpolant;
  27422. }
  27423. _takeBackControlInterpolant( interpolant ) {
  27424. const interpolants = this._controlInterpolants,
  27425. prevIndex = interpolant.__cacheIndex,
  27426. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27427. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27428. interpolant.__cacheIndex = firstInactiveIndex;
  27429. interpolants[ firstInactiveIndex ] = interpolant;
  27430. lastActiveInterpolant.__cacheIndex = prevIndex;
  27431. interpolants[ prevIndex ] = lastActiveInterpolant;
  27432. }
  27433. // return an action for a clip optionally using a custom root target
  27434. // object (this method allocates a lot of dynamic memory in case a
  27435. // previously unknown clip/root combination is specified)
  27436. clipAction( clip, optionalRoot, blendMode ) {
  27437. const root = optionalRoot || this._root,
  27438. rootUuid = root.uuid;
  27439. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27440. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27441. const actionsForClip = this._actionsByClip[ clipUuid ];
  27442. let prototypeAction = null;
  27443. if ( blendMode === undefined ) {
  27444. if ( clipObject !== null ) {
  27445. blendMode = clipObject.blendMode;
  27446. } else {
  27447. blendMode = NormalAnimationBlendMode;
  27448. }
  27449. }
  27450. if ( actionsForClip !== undefined ) {
  27451. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27452. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27453. return existingAction;
  27454. }
  27455. // we know the clip, so we don't have to parse all
  27456. // the bindings again but can just copy
  27457. prototypeAction = actionsForClip.knownActions[ 0 ];
  27458. // also, take the clip from the prototype action
  27459. if ( clipObject === null )
  27460. clipObject = prototypeAction._clip;
  27461. }
  27462. // clip must be known when specified via string
  27463. if ( clipObject === null ) return null;
  27464. // allocate all resources required to run it
  27465. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27466. this._bindAction( newAction, prototypeAction );
  27467. // and make the action known to the memory manager
  27468. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27469. return newAction;
  27470. }
  27471. // get an existing action
  27472. existingAction( clip, optionalRoot ) {
  27473. const root = optionalRoot || this._root,
  27474. rootUuid = root.uuid,
  27475. clipObject = typeof clip === 'string' ?
  27476. AnimationClip.findByName( root, clip ) : clip,
  27477. clipUuid = clipObject ? clipObject.uuid : clip,
  27478. actionsForClip = this._actionsByClip[ clipUuid ];
  27479. if ( actionsForClip !== undefined ) {
  27480. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27481. }
  27482. return null;
  27483. }
  27484. // deactivates all previously scheduled actions
  27485. stopAllAction() {
  27486. const actions = this._actions,
  27487. nActions = this._nActiveActions;
  27488. for ( let i = nActions - 1; i >= 0; -- i ) {
  27489. actions[ i ].stop();
  27490. }
  27491. return this;
  27492. }
  27493. // advance the time and update apply the animation
  27494. update( deltaTime ) {
  27495. deltaTime *= this.timeScale;
  27496. const actions = this._actions,
  27497. nActions = this._nActiveActions,
  27498. time = this.time += deltaTime,
  27499. timeDirection = Math.sign( deltaTime ),
  27500. accuIndex = this._accuIndex ^= 1;
  27501. // run active actions
  27502. for ( let i = 0; i !== nActions; ++ i ) {
  27503. const action = actions[ i ];
  27504. action._update( time, deltaTime, timeDirection, accuIndex );
  27505. }
  27506. // update scene graph
  27507. const bindings = this._bindings,
  27508. nBindings = this._nActiveBindings;
  27509. for ( let i = 0; i !== nBindings; ++ i ) {
  27510. bindings[ i ].apply( accuIndex );
  27511. }
  27512. return this;
  27513. }
  27514. // Allows you to seek to a specific time in an animation.
  27515. setTime( timeInSeconds ) {
  27516. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27517. for ( let i = 0; i < this._actions.length; i ++ ) {
  27518. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27519. }
  27520. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27521. }
  27522. // return this mixer's root target object
  27523. getRoot() {
  27524. return this._root;
  27525. }
  27526. // free all resources specific to a particular clip
  27527. uncacheClip( clip ) {
  27528. const actions = this._actions,
  27529. clipUuid = clip.uuid,
  27530. actionsByClip = this._actionsByClip,
  27531. actionsForClip = actionsByClip[ clipUuid ];
  27532. if ( actionsForClip !== undefined ) {
  27533. // note: just calling _removeInactiveAction would mess up the
  27534. // iteration state and also require updating the state we can
  27535. // just throw away
  27536. const actionsToRemove = actionsForClip.knownActions;
  27537. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27538. const action = actionsToRemove[ i ];
  27539. this._deactivateAction( action );
  27540. const cacheIndex = action._cacheIndex,
  27541. lastInactiveAction = actions[ actions.length - 1 ];
  27542. action._cacheIndex = null;
  27543. action._byClipCacheIndex = null;
  27544. lastInactiveAction._cacheIndex = cacheIndex;
  27545. actions[ cacheIndex ] = lastInactiveAction;
  27546. actions.pop();
  27547. this._removeInactiveBindingsForAction( action );
  27548. }
  27549. delete actionsByClip[ clipUuid ];
  27550. }
  27551. }
  27552. // free all resources specific to a particular root target object
  27553. uncacheRoot( root ) {
  27554. const rootUuid = root.uuid,
  27555. actionsByClip = this._actionsByClip;
  27556. for ( const clipUuid in actionsByClip ) {
  27557. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27558. action = actionByRoot[ rootUuid ];
  27559. if ( action !== undefined ) {
  27560. this._deactivateAction( action );
  27561. this._removeInactiveAction( action );
  27562. }
  27563. }
  27564. const bindingsByRoot = this._bindingsByRootAndName,
  27565. bindingByName = bindingsByRoot[ rootUuid ];
  27566. if ( bindingByName !== undefined ) {
  27567. for ( const trackName in bindingByName ) {
  27568. const binding = bindingByName[ trackName ];
  27569. binding.restoreOriginalState();
  27570. this._removeInactiveBinding( binding );
  27571. }
  27572. }
  27573. }
  27574. // remove a targeted clip from the cache
  27575. uncacheAction( clip, optionalRoot ) {
  27576. const action = this.existingAction( clip, optionalRoot );
  27577. if ( action !== null ) {
  27578. this._deactivateAction( action );
  27579. this._removeInactiveAction( action );
  27580. }
  27581. }
  27582. }
  27583. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  27584. class Uniform {
  27585. constructor( value ) {
  27586. if ( typeof value === 'string' ) {
  27587. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27588. value = arguments[ 1 ];
  27589. }
  27590. this.value = value;
  27591. }
  27592. clone() {
  27593. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27594. }
  27595. }
  27596. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27597. constructor( array, stride, meshPerAttribute = 1 ) {
  27598. super( array, stride );
  27599. this.meshPerAttribute = meshPerAttribute;
  27600. }
  27601. copy( source ) {
  27602. super.copy( source );
  27603. this.meshPerAttribute = source.meshPerAttribute;
  27604. return this;
  27605. }
  27606. clone( data ) {
  27607. const ib = super.clone( data );
  27608. ib.meshPerAttribute = this.meshPerAttribute;
  27609. return ib;
  27610. }
  27611. toJSON( data ) {
  27612. const json = super.toJSON( data );
  27613. json.isInstancedInterleavedBuffer = true;
  27614. json.meshPerAttribute = this.meshPerAttribute;
  27615. return json;
  27616. }
  27617. }
  27618. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27619. class GLBufferAttribute {
  27620. constructor( buffer, type, itemSize, elementSize, count ) {
  27621. this.buffer = buffer;
  27622. this.type = type;
  27623. this.itemSize = itemSize;
  27624. this.elementSize = elementSize;
  27625. this.count = count;
  27626. this.version = 0;
  27627. }
  27628. set needsUpdate( value ) {
  27629. if ( value === true ) this.version ++;
  27630. }
  27631. setBuffer( buffer ) {
  27632. this.buffer = buffer;
  27633. return this;
  27634. }
  27635. setType( type, elementSize ) {
  27636. this.type = type;
  27637. this.elementSize = elementSize;
  27638. return this;
  27639. }
  27640. setItemSize( itemSize ) {
  27641. this.itemSize = itemSize;
  27642. return this;
  27643. }
  27644. setCount( count ) {
  27645. this.count = count;
  27646. return this;
  27647. }
  27648. }
  27649. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27650. class Raycaster {
  27651. constructor( origin, direction, near = 0, far = Infinity ) {
  27652. this.ray = new Ray( origin, direction );
  27653. // direction is assumed to be normalized (for accurate distance calculations)
  27654. this.near = near;
  27655. this.far = far;
  27656. this.camera = null;
  27657. this.layers = new Layers();
  27658. this.params = {
  27659. Mesh: {},
  27660. Line: { threshold: 1 },
  27661. LOD: {},
  27662. Points: { threshold: 1 },
  27663. Sprite: {}
  27664. };
  27665. }
  27666. set( origin, direction ) {
  27667. // direction is assumed to be normalized (for accurate distance calculations)
  27668. this.ray.set( origin, direction );
  27669. }
  27670. setFromCamera( coords, camera ) {
  27671. if ( camera && camera.isPerspectiveCamera ) {
  27672. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27673. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27674. this.camera = camera;
  27675. } else if ( camera && camera.isOrthographicCamera ) {
  27676. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27677. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27678. this.camera = camera;
  27679. } else {
  27680. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27681. }
  27682. }
  27683. intersectObject( object, recursive = true, intersects = [] ) {
  27684. intersectObject( object, this, intersects, recursive );
  27685. intersects.sort( ascSort );
  27686. return intersects;
  27687. }
  27688. intersectObjects( objects, recursive = true, intersects = [] ) {
  27689. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27690. intersectObject( objects[ i ], this, intersects, recursive );
  27691. }
  27692. intersects.sort( ascSort );
  27693. return intersects;
  27694. }
  27695. }
  27696. function ascSort( a, b ) {
  27697. return a.distance - b.distance;
  27698. }
  27699. function intersectObject( object, raycaster, intersects, recursive ) {
  27700. if ( object.layers.test( raycaster.layers ) ) {
  27701. object.raycast( raycaster, intersects );
  27702. }
  27703. if ( recursive === true ) {
  27704. const children = object.children;
  27705. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27706. intersectObject( children[ i ], raycaster, intersects, true );
  27707. }
  27708. }
  27709. }
  27710. /**
  27711. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27712. *
  27713. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27714. * The azimuthal angle (theta) is measured from the positive z-axis.
  27715. */
  27716. class Spherical {
  27717. constructor( radius = 1, phi = 0, theta = 0 ) {
  27718. this.radius = radius;
  27719. this.phi = phi; // polar angle
  27720. this.theta = theta; // azimuthal angle
  27721. return this;
  27722. }
  27723. set( radius, phi, theta ) {
  27724. this.radius = radius;
  27725. this.phi = phi;
  27726. this.theta = theta;
  27727. return this;
  27728. }
  27729. copy( other ) {
  27730. this.radius = other.radius;
  27731. this.phi = other.phi;
  27732. this.theta = other.theta;
  27733. return this;
  27734. }
  27735. // restrict phi to be betwee EPS and PI-EPS
  27736. makeSafe() {
  27737. const EPS = 0.000001;
  27738. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27739. return this;
  27740. }
  27741. setFromVector3( v ) {
  27742. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27743. }
  27744. setFromCartesianCoords( x, y, z ) {
  27745. this.radius = Math.sqrt( x * x + y * y + z * z );
  27746. if ( this.radius === 0 ) {
  27747. this.theta = 0;
  27748. this.phi = 0;
  27749. } else {
  27750. this.theta = Math.atan2( x, z );
  27751. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27752. }
  27753. return this;
  27754. }
  27755. clone() {
  27756. return new this.constructor().copy( this );
  27757. }
  27758. }
  27759. /**
  27760. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27761. */
  27762. class Cylindrical {
  27763. constructor( radius = 1, theta = 0, y = 0 ) {
  27764. this.radius = radius; // distance from the origin to a point in the x-z plane
  27765. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27766. this.y = y; // height above the x-z plane
  27767. return this;
  27768. }
  27769. set( radius, theta, y ) {
  27770. this.radius = radius;
  27771. this.theta = theta;
  27772. this.y = y;
  27773. return this;
  27774. }
  27775. copy( other ) {
  27776. this.radius = other.radius;
  27777. this.theta = other.theta;
  27778. this.y = other.y;
  27779. return this;
  27780. }
  27781. setFromVector3( v ) {
  27782. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27783. }
  27784. setFromCartesianCoords( x, y, z ) {
  27785. this.radius = Math.sqrt( x * x + z * z );
  27786. this.theta = Math.atan2( x, z );
  27787. this.y = y;
  27788. return this;
  27789. }
  27790. clone() {
  27791. return new this.constructor().copy( this );
  27792. }
  27793. }
  27794. const _vector$4 = /*@__PURE__*/ new Vector2();
  27795. class Box2 {
  27796. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  27797. this.min = min;
  27798. this.max = max;
  27799. }
  27800. set( min, max ) {
  27801. this.min.copy( min );
  27802. this.max.copy( max );
  27803. return this;
  27804. }
  27805. setFromPoints( points ) {
  27806. this.makeEmpty();
  27807. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27808. this.expandByPoint( points[ i ] );
  27809. }
  27810. return this;
  27811. }
  27812. setFromCenterAndSize( center, size ) {
  27813. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  27814. this.min.copy( center ).sub( halfSize );
  27815. this.max.copy( center ).add( halfSize );
  27816. return this;
  27817. }
  27818. clone() {
  27819. return new this.constructor().copy( this );
  27820. }
  27821. copy( box ) {
  27822. this.min.copy( box.min );
  27823. this.max.copy( box.max );
  27824. return this;
  27825. }
  27826. makeEmpty() {
  27827. this.min.x = this.min.y = + Infinity;
  27828. this.max.x = this.max.y = - Infinity;
  27829. return this;
  27830. }
  27831. isEmpty() {
  27832. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27833. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27834. }
  27835. getCenter( target ) {
  27836. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27837. }
  27838. getSize( target ) {
  27839. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27840. }
  27841. expandByPoint( point ) {
  27842. this.min.min( point );
  27843. this.max.max( point );
  27844. return this;
  27845. }
  27846. expandByVector( vector ) {
  27847. this.min.sub( vector );
  27848. this.max.add( vector );
  27849. return this;
  27850. }
  27851. expandByScalar( scalar ) {
  27852. this.min.addScalar( - scalar );
  27853. this.max.addScalar( scalar );
  27854. return this;
  27855. }
  27856. containsPoint( point ) {
  27857. return point.x < this.min.x || point.x > this.max.x ||
  27858. point.y < this.min.y || point.y > this.max.y ? false : true;
  27859. }
  27860. containsBox( box ) {
  27861. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27862. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27863. }
  27864. getParameter( point, target ) {
  27865. // This can potentially have a divide by zero if the box
  27866. // has a size dimension of 0.
  27867. return target.set(
  27868. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27869. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27870. );
  27871. }
  27872. intersectsBox( box ) {
  27873. // using 4 splitting planes to rule out intersections
  27874. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27875. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27876. }
  27877. clampPoint( point, target ) {
  27878. return target.copy( point ).clamp( this.min, this.max );
  27879. }
  27880. distanceToPoint( point ) {
  27881. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  27882. return clampedPoint.sub( point ).length();
  27883. }
  27884. intersect( box ) {
  27885. this.min.max( box.min );
  27886. this.max.min( box.max );
  27887. return this;
  27888. }
  27889. union( box ) {
  27890. this.min.min( box.min );
  27891. this.max.max( box.max );
  27892. return this;
  27893. }
  27894. translate( offset ) {
  27895. this.min.add( offset );
  27896. this.max.add( offset );
  27897. return this;
  27898. }
  27899. equals( box ) {
  27900. return box.min.equals( this.min ) && box.max.equals( this.max );
  27901. }
  27902. }
  27903. Box2.prototype.isBox2 = true;
  27904. const _startP = /*@__PURE__*/ new Vector3();
  27905. const _startEnd = /*@__PURE__*/ new Vector3();
  27906. class Line3 {
  27907. constructor( start = new Vector3(), end = new Vector3() ) {
  27908. this.start = start;
  27909. this.end = end;
  27910. }
  27911. set( start, end ) {
  27912. this.start.copy( start );
  27913. this.end.copy( end );
  27914. return this;
  27915. }
  27916. copy( line ) {
  27917. this.start.copy( line.start );
  27918. this.end.copy( line.end );
  27919. return this;
  27920. }
  27921. getCenter( target ) {
  27922. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27923. }
  27924. delta( target ) {
  27925. return target.subVectors( this.end, this.start );
  27926. }
  27927. distanceSq() {
  27928. return this.start.distanceToSquared( this.end );
  27929. }
  27930. distance() {
  27931. return this.start.distanceTo( this.end );
  27932. }
  27933. at( t, target ) {
  27934. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27935. }
  27936. closestPointToPointParameter( point, clampToLine ) {
  27937. _startP.subVectors( point, this.start );
  27938. _startEnd.subVectors( this.end, this.start );
  27939. const startEnd2 = _startEnd.dot( _startEnd );
  27940. const startEnd_startP = _startEnd.dot( _startP );
  27941. let t = startEnd_startP / startEnd2;
  27942. if ( clampToLine ) {
  27943. t = clamp( t, 0, 1 );
  27944. }
  27945. return t;
  27946. }
  27947. closestPointToPoint( point, clampToLine, target ) {
  27948. const t = this.closestPointToPointParameter( point, clampToLine );
  27949. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27950. }
  27951. applyMatrix4( matrix ) {
  27952. this.start.applyMatrix4( matrix );
  27953. this.end.applyMatrix4( matrix );
  27954. return this;
  27955. }
  27956. equals( line ) {
  27957. return line.start.equals( this.start ) && line.end.equals( this.end );
  27958. }
  27959. clone() {
  27960. return new this.constructor().copy( this );
  27961. }
  27962. }
  27963. const _vector$3 = /*@__PURE__*/ new Vector3();
  27964. class SpotLightHelper extends Object3D {
  27965. constructor( light, color ) {
  27966. super();
  27967. this.light = light;
  27968. this.light.updateMatrixWorld();
  27969. this.matrix = light.matrixWorld;
  27970. this.matrixAutoUpdate = false;
  27971. this.color = color;
  27972. const geometry = new BufferGeometry();
  27973. const positions = [
  27974. 0, 0, 0, 0, 0, 1,
  27975. 0, 0, 0, 1, 0, 1,
  27976. 0, 0, 0, - 1, 0, 1,
  27977. 0, 0, 0, 0, 1, 1,
  27978. 0, 0, 0, 0, - 1, 1
  27979. ];
  27980. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27981. const p1 = ( i / l ) * Math.PI * 2;
  27982. const p2 = ( j / l ) * Math.PI * 2;
  27983. positions.push(
  27984. Math.cos( p1 ), Math.sin( p1 ), 1,
  27985. Math.cos( p2 ), Math.sin( p2 ), 1
  27986. );
  27987. }
  27988. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27989. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27990. this.cone = new LineSegments( geometry, material );
  27991. this.add( this.cone );
  27992. this.update();
  27993. }
  27994. dispose() {
  27995. this.cone.geometry.dispose();
  27996. this.cone.material.dispose();
  27997. }
  27998. update() {
  27999. this.light.updateMatrixWorld();
  28000. const coneLength = this.light.distance ? this.light.distance : 1000;
  28001. const coneWidth = coneLength * Math.tan( this.light.angle );
  28002. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28003. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28004. this.cone.lookAt( _vector$3 );
  28005. if ( this.color !== undefined ) {
  28006. this.cone.material.color.set( this.color );
  28007. } else {
  28008. this.cone.material.color.copy( this.light.color );
  28009. }
  28010. }
  28011. }
  28012. const _vector$2 = /*@__PURE__*/ new Vector3();
  28013. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28014. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28015. class SkeletonHelper extends LineSegments {
  28016. constructor( object ) {
  28017. const bones = getBoneList( object );
  28018. const geometry = new BufferGeometry();
  28019. const vertices = [];
  28020. const colors = [];
  28021. const color1 = new Color( 0, 0, 1 );
  28022. const color2 = new Color( 0, 1, 0 );
  28023. for ( let i = 0; i < bones.length; i ++ ) {
  28024. const bone = bones[ i ];
  28025. if ( bone.parent && bone.parent.isBone ) {
  28026. vertices.push( 0, 0, 0 );
  28027. vertices.push( 0, 0, 0 );
  28028. colors.push( color1.r, color1.g, color1.b );
  28029. colors.push( color2.r, color2.g, color2.b );
  28030. }
  28031. }
  28032. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28033. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28034. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28035. super( geometry, material );
  28036. this.type = 'SkeletonHelper';
  28037. this.isSkeletonHelper = true;
  28038. this.root = object;
  28039. this.bones = bones;
  28040. this.matrix = object.matrixWorld;
  28041. this.matrixAutoUpdate = false;
  28042. }
  28043. updateMatrixWorld( force ) {
  28044. const bones = this.bones;
  28045. const geometry = this.geometry;
  28046. const position = geometry.getAttribute( 'position' );
  28047. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28048. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28049. const bone = bones[ i ];
  28050. if ( bone.parent && bone.parent.isBone ) {
  28051. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28052. _vector$2.setFromMatrixPosition( _boneMatrix );
  28053. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28054. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28055. _vector$2.setFromMatrixPosition( _boneMatrix );
  28056. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28057. j += 2;
  28058. }
  28059. }
  28060. geometry.getAttribute( 'position' ).needsUpdate = true;
  28061. super.updateMatrixWorld( force );
  28062. }
  28063. }
  28064. function getBoneList( object ) {
  28065. const boneList = [];
  28066. if ( object && object.isBone ) {
  28067. boneList.push( object );
  28068. }
  28069. for ( let i = 0; i < object.children.length; i ++ ) {
  28070. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28071. }
  28072. return boneList;
  28073. }
  28074. class PointLightHelper extends Mesh {
  28075. constructor( light, sphereSize, color ) {
  28076. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28077. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28078. super( geometry, material );
  28079. this.light = light;
  28080. this.light.updateMatrixWorld();
  28081. this.color = color;
  28082. this.type = 'PointLightHelper';
  28083. this.matrix = this.light.matrixWorld;
  28084. this.matrixAutoUpdate = false;
  28085. this.update();
  28086. /*
  28087. // TODO: delete this comment?
  28088. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28089. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28090. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28091. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28092. const d = light.distance;
  28093. if ( d === 0.0 ) {
  28094. this.lightDistance.visible = false;
  28095. } else {
  28096. this.lightDistance.scale.set( d, d, d );
  28097. }
  28098. this.add( this.lightDistance );
  28099. */
  28100. }
  28101. dispose() {
  28102. this.geometry.dispose();
  28103. this.material.dispose();
  28104. }
  28105. update() {
  28106. if ( this.color !== undefined ) {
  28107. this.material.color.set( this.color );
  28108. } else {
  28109. this.material.color.copy( this.light.color );
  28110. }
  28111. /*
  28112. const d = this.light.distance;
  28113. if ( d === 0.0 ) {
  28114. this.lightDistance.visible = false;
  28115. } else {
  28116. this.lightDistance.visible = true;
  28117. this.lightDistance.scale.set( d, d, d );
  28118. }
  28119. */
  28120. }
  28121. }
  28122. const _vector$1 = /*@__PURE__*/ new Vector3();
  28123. const _color1 = /*@__PURE__*/ new Color();
  28124. const _color2 = /*@__PURE__*/ new Color();
  28125. class HemisphereLightHelper extends Object3D {
  28126. constructor( light, size, color ) {
  28127. super();
  28128. this.light = light;
  28129. this.light.updateMatrixWorld();
  28130. this.matrix = light.matrixWorld;
  28131. this.matrixAutoUpdate = false;
  28132. this.color = color;
  28133. const geometry = new OctahedronGeometry( size );
  28134. geometry.rotateY( Math.PI * 0.5 );
  28135. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28136. if ( this.color === undefined ) this.material.vertexColors = true;
  28137. const position = geometry.getAttribute( 'position' );
  28138. const colors = new Float32Array( position.count * 3 );
  28139. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28140. this.add( new Mesh( geometry, this.material ) );
  28141. this.update();
  28142. }
  28143. dispose() {
  28144. this.children[ 0 ].geometry.dispose();
  28145. this.children[ 0 ].material.dispose();
  28146. }
  28147. update() {
  28148. const mesh = this.children[ 0 ];
  28149. if ( this.color !== undefined ) {
  28150. this.material.color.set( this.color );
  28151. } else {
  28152. const colors = mesh.geometry.getAttribute( 'color' );
  28153. _color1.copy( this.light.color );
  28154. _color2.copy( this.light.groundColor );
  28155. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28156. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28157. colors.setXYZ( i, color.r, color.g, color.b );
  28158. }
  28159. colors.needsUpdate = true;
  28160. }
  28161. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28162. }
  28163. }
  28164. class GridHelper extends LineSegments {
  28165. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28166. color1 = new Color( color1 );
  28167. color2 = new Color( color2 );
  28168. const center = divisions / 2;
  28169. const step = size / divisions;
  28170. const halfSize = size / 2;
  28171. const vertices = [], colors = [];
  28172. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28173. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28174. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28175. const color = i === center ? color1 : color2;
  28176. color.toArray( colors, j ); j += 3;
  28177. color.toArray( colors, j ); j += 3;
  28178. color.toArray( colors, j ); j += 3;
  28179. color.toArray( colors, j ); j += 3;
  28180. }
  28181. const geometry = new BufferGeometry();
  28182. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28183. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28184. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28185. super( geometry, material );
  28186. this.type = 'GridHelper';
  28187. }
  28188. }
  28189. class PolarGridHelper extends LineSegments {
  28190. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28191. color1 = new Color( color1 );
  28192. color2 = new Color( color2 );
  28193. const vertices = [];
  28194. const colors = [];
  28195. // create the radials
  28196. for ( let i = 0; i <= radials; i ++ ) {
  28197. const v = ( i / radials ) * ( Math.PI * 2 );
  28198. const x = Math.sin( v ) * radius;
  28199. const z = Math.cos( v ) * radius;
  28200. vertices.push( 0, 0, 0 );
  28201. vertices.push( x, 0, z );
  28202. const color = ( i & 1 ) ? color1 : color2;
  28203. colors.push( color.r, color.g, color.b );
  28204. colors.push( color.r, color.g, color.b );
  28205. }
  28206. // create the circles
  28207. for ( let i = 0; i <= circles; i ++ ) {
  28208. const color = ( i & 1 ) ? color1 : color2;
  28209. const r = radius - ( radius / circles * i );
  28210. for ( let j = 0; j < divisions; j ++ ) {
  28211. // first vertex
  28212. let v = ( j / divisions ) * ( Math.PI * 2 );
  28213. let x = Math.sin( v ) * r;
  28214. let z = Math.cos( v ) * r;
  28215. vertices.push( x, 0, z );
  28216. colors.push( color.r, color.g, color.b );
  28217. // second vertex
  28218. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28219. x = Math.sin( v ) * r;
  28220. z = Math.cos( v ) * r;
  28221. vertices.push( x, 0, z );
  28222. colors.push( color.r, color.g, color.b );
  28223. }
  28224. }
  28225. const geometry = new BufferGeometry();
  28226. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28227. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28228. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28229. super( geometry, material );
  28230. this.type = 'PolarGridHelper';
  28231. }
  28232. }
  28233. const _v1 = /*@__PURE__*/ new Vector3();
  28234. const _v2 = /*@__PURE__*/ new Vector3();
  28235. const _v3 = /*@__PURE__*/ new Vector3();
  28236. class DirectionalLightHelper extends Object3D {
  28237. constructor( light, size, color ) {
  28238. super();
  28239. this.light = light;
  28240. this.light.updateMatrixWorld();
  28241. this.matrix = light.matrixWorld;
  28242. this.matrixAutoUpdate = false;
  28243. this.color = color;
  28244. if ( size === undefined ) size = 1;
  28245. let geometry = new BufferGeometry();
  28246. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28247. - size, size, 0,
  28248. size, size, 0,
  28249. size, - size, 0,
  28250. - size, - size, 0,
  28251. - size, size, 0
  28252. ], 3 ) );
  28253. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28254. this.lightPlane = new Line( geometry, material );
  28255. this.add( this.lightPlane );
  28256. geometry = new BufferGeometry();
  28257. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28258. this.targetLine = new Line( geometry, material );
  28259. this.add( this.targetLine );
  28260. this.update();
  28261. }
  28262. dispose() {
  28263. this.lightPlane.geometry.dispose();
  28264. this.lightPlane.material.dispose();
  28265. this.targetLine.geometry.dispose();
  28266. this.targetLine.material.dispose();
  28267. }
  28268. update() {
  28269. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28270. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28271. _v3.subVectors( _v2, _v1 );
  28272. this.lightPlane.lookAt( _v2 );
  28273. if ( this.color !== undefined ) {
  28274. this.lightPlane.material.color.set( this.color );
  28275. this.targetLine.material.color.set( this.color );
  28276. } else {
  28277. this.lightPlane.material.color.copy( this.light.color );
  28278. this.targetLine.material.color.copy( this.light.color );
  28279. }
  28280. this.targetLine.lookAt( _v2 );
  28281. this.targetLine.scale.z = _v3.length();
  28282. }
  28283. }
  28284. const _vector = /*@__PURE__*/ new Vector3();
  28285. const _camera = /*@__PURE__*/ new Camera();
  28286. /**
  28287. * - shows frustum, line of sight and up of the camera
  28288. * - suitable for fast updates
  28289. * - based on frustum visualization in lightgl.js shadowmap example
  28290. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28291. */
  28292. class CameraHelper extends LineSegments {
  28293. constructor( camera ) {
  28294. const geometry = new BufferGeometry();
  28295. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28296. const vertices = [];
  28297. const colors = [];
  28298. const pointMap = {};
  28299. // colors
  28300. const colorFrustum = new Color( 0xffaa00 );
  28301. const colorCone = new Color( 0xff0000 );
  28302. const colorUp = new Color( 0x00aaff );
  28303. const colorTarget = new Color( 0xffffff );
  28304. const colorCross = new Color( 0x333333 );
  28305. // near
  28306. addLine( 'n1', 'n2', colorFrustum );
  28307. addLine( 'n2', 'n4', colorFrustum );
  28308. addLine( 'n4', 'n3', colorFrustum );
  28309. addLine( 'n3', 'n1', colorFrustum );
  28310. // far
  28311. addLine( 'f1', 'f2', colorFrustum );
  28312. addLine( 'f2', 'f4', colorFrustum );
  28313. addLine( 'f4', 'f3', colorFrustum );
  28314. addLine( 'f3', 'f1', colorFrustum );
  28315. // sides
  28316. addLine( 'n1', 'f1', colorFrustum );
  28317. addLine( 'n2', 'f2', colorFrustum );
  28318. addLine( 'n3', 'f3', colorFrustum );
  28319. addLine( 'n4', 'f4', colorFrustum );
  28320. // cone
  28321. addLine( 'p', 'n1', colorCone );
  28322. addLine( 'p', 'n2', colorCone );
  28323. addLine( 'p', 'n3', colorCone );
  28324. addLine( 'p', 'n4', colorCone );
  28325. // up
  28326. addLine( 'u1', 'u2', colorUp );
  28327. addLine( 'u2', 'u3', colorUp );
  28328. addLine( 'u3', 'u1', colorUp );
  28329. // target
  28330. addLine( 'c', 't', colorTarget );
  28331. addLine( 'p', 'c', colorCross );
  28332. // cross
  28333. addLine( 'cn1', 'cn2', colorCross );
  28334. addLine( 'cn3', 'cn4', colorCross );
  28335. addLine( 'cf1', 'cf2', colorCross );
  28336. addLine( 'cf3', 'cf4', colorCross );
  28337. function addLine( a, b, color ) {
  28338. addPoint( a, color );
  28339. addPoint( b, color );
  28340. }
  28341. function addPoint( id, color ) {
  28342. vertices.push( 0, 0, 0 );
  28343. colors.push( color.r, color.g, color.b );
  28344. if ( pointMap[ id ] === undefined ) {
  28345. pointMap[ id ] = [];
  28346. }
  28347. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28348. }
  28349. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28350. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28351. super( geometry, material );
  28352. this.type = 'CameraHelper';
  28353. this.camera = camera;
  28354. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28355. this.matrix = camera.matrixWorld;
  28356. this.matrixAutoUpdate = false;
  28357. this.pointMap = pointMap;
  28358. this.update();
  28359. }
  28360. update() {
  28361. const geometry = this.geometry;
  28362. const pointMap = this.pointMap;
  28363. const w = 1, h = 1;
  28364. // we need just camera projection matrix inverse
  28365. // world matrix must be identity
  28366. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28367. // center / target
  28368. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28369. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28370. // near
  28371. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28372. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28373. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28374. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28375. // far
  28376. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28377. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28378. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28379. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28380. // up
  28381. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28382. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28383. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28384. // cross
  28385. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28386. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28387. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28388. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28389. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28390. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28391. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28392. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28393. geometry.getAttribute( 'position' ).needsUpdate = true;
  28394. }
  28395. dispose() {
  28396. this.geometry.dispose();
  28397. this.material.dispose();
  28398. }
  28399. }
  28400. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28401. _vector.set( x, y, z ).unproject( camera );
  28402. const points = pointMap[ point ];
  28403. if ( points !== undefined ) {
  28404. const position = geometry.getAttribute( 'position' );
  28405. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28406. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28407. }
  28408. }
  28409. }
  28410. const _box = /*@__PURE__*/ new Box3();
  28411. class BoxHelper extends LineSegments {
  28412. constructor( object, color = 0xffff00 ) {
  28413. 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 ] );
  28414. const positions = new Float32Array( 8 * 3 );
  28415. const geometry = new BufferGeometry();
  28416. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28417. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28418. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28419. this.object = object;
  28420. this.type = 'BoxHelper';
  28421. this.matrixAutoUpdate = false;
  28422. this.update();
  28423. }
  28424. update( object ) {
  28425. if ( object !== undefined ) {
  28426. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28427. }
  28428. if ( this.object !== undefined ) {
  28429. _box.setFromObject( this.object );
  28430. }
  28431. if ( _box.isEmpty() ) return;
  28432. const min = _box.min;
  28433. const max = _box.max;
  28434. /*
  28435. 5____4
  28436. 1/___0/|
  28437. | 6__|_7
  28438. 2/___3/
  28439. 0: max.x, max.y, max.z
  28440. 1: min.x, max.y, max.z
  28441. 2: min.x, min.y, max.z
  28442. 3: max.x, min.y, max.z
  28443. 4: max.x, max.y, min.z
  28444. 5: min.x, max.y, min.z
  28445. 6: min.x, min.y, min.z
  28446. 7: max.x, min.y, min.z
  28447. */
  28448. const position = this.geometry.attributes.position;
  28449. const array = position.array;
  28450. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28451. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28452. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28453. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28454. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28455. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28456. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28457. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28458. position.needsUpdate = true;
  28459. this.geometry.computeBoundingSphere();
  28460. }
  28461. setFromObject( object ) {
  28462. this.object = object;
  28463. this.update();
  28464. return this;
  28465. }
  28466. copy( source ) {
  28467. LineSegments.prototype.copy.call( this, source );
  28468. this.object = source.object;
  28469. return this;
  28470. }
  28471. }
  28472. class Box3Helper extends LineSegments {
  28473. constructor( box, color = 0xffff00 ) {
  28474. 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 ] );
  28475. 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 ];
  28476. const geometry = new BufferGeometry();
  28477. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28478. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28479. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28480. this.box = box;
  28481. this.type = 'Box3Helper';
  28482. this.geometry.computeBoundingSphere();
  28483. }
  28484. updateMatrixWorld( force ) {
  28485. const box = this.box;
  28486. if ( box.isEmpty() ) return;
  28487. box.getCenter( this.position );
  28488. box.getSize( this.scale );
  28489. this.scale.multiplyScalar( 0.5 );
  28490. super.updateMatrixWorld( force );
  28491. }
  28492. }
  28493. class PlaneHelper extends Line {
  28494. constructor( plane, size = 1, hex = 0xffff00 ) {
  28495. const color = hex;
  28496. 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 ];
  28497. const geometry = new BufferGeometry();
  28498. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28499. geometry.computeBoundingSphere();
  28500. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28501. this.type = 'PlaneHelper';
  28502. this.plane = plane;
  28503. this.size = size;
  28504. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28505. const geometry2 = new BufferGeometry();
  28506. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28507. geometry2.computeBoundingSphere();
  28508. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28509. }
  28510. updateMatrixWorld( force ) {
  28511. let scale = - this.plane.constant;
  28512. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28513. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28514. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28515. this.lookAt( this.plane.normal );
  28516. super.updateMatrixWorld( force );
  28517. }
  28518. }
  28519. const _axis = /*@__PURE__*/ new Vector3();
  28520. let _lineGeometry, _coneGeometry;
  28521. class ArrowHelper extends Object3D {
  28522. // dir is assumed to be normalized
  28523. 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 ) {
  28524. super();
  28525. this.type = 'ArrowHelper';
  28526. if ( _lineGeometry === undefined ) {
  28527. _lineGeometry = new BufferGeometry();
  28528. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28529. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28530. _coneGeometry.translate( 0, - 0.5, 0 );
  28531. }
  28532. this.position.copy( origin );
  28533. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28534. this.line.matrixAutoUpdate = false;
  28535. this.add( this.line );
  28536. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28537. this.cone.matrixAutoUpdate = false;
  28538. this.add( this.cone );
  28539. this.setDirection( dir );
  28540. this.setLength( length, headLength, headWidth );
  28541. }
  28542. setDirection( dir ) {
  28543. // dir is assumed to be normalized
  28544. if ( dir.y > 0.99999 ) {
  28545. this.quaternion.set( 0, 0, 0, 1 );
  28546. } else if ( dir.y < - 0.99999 ) {
  28547. this.quaternion.set( 1, 0, 0, 0 );
  28548. } else {
  28549. _axis.set( dir.z, 0, - dir.x ).normalize();
  28550. const radians = Math.acos( dir.y );
  28551. this.quaternion.setFromAxisAngle( _axis, radians );
  28552. }
  28553. }
  28554. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28555. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28556. this.line.updateMatrix();
  28557. this.cone.scale.set( headWidth, headLength, headWidth );
  28558. this.cone.position.y = length;
  28559. this.cone.updateMatrix();
  28560. }
  28561. setColor( color ) {
  28562. this.line.material.color.set( color );
  28563. this.cone.material.color.set( color );
  28564. }
  28565. copy( source ) {
  28566. super.copy( source, false );
  28567. this.line.copy( source.line );
  28568. this.cone.copy( source.cone );
  28569. return this;
  28570. }
  28571. }
  28572. class AxesHelper extends LineSegments {
  28573. constructor( size = 1 ) {
  28574. const vertices = [
  28575. 0, 0, 0, size, 0, 0,
  28576. 0, 0, 0, 0, size, 0,
  28577. 0, 0, 0, 0, 0, size
  28578. ];
  28579. const colors = [
  28580. 1, 0, 0, 1, 0.6, 0,
  28581. 0, 1, 0, 0.6, 1, 0,
  28582. 0, 0, 1, 0, 0.6, 1
  28583. ];
  28584. const geometry = new BufferGeometry();
  28585. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28586. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28587. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28588. super( geometry, material );
  28589. this.type = 'AxesHelper';
  28590. }
  28591. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28592. const color = new Color();
  28593. const array = this.geometry.attributes.color.array;
  28594. color.set( xAxisColor );
  28595. color.toArray( array, 0 );
  28596. color.toArray( array, 3 );
  28597. color.set( yAxisColor );
  28598. color.toArray( array, 6 );
  28599. color.toArray( array, 9 );
  28600. color.set( zAxisColor );
  28601. color.toArray( array, 12 );
  28602. color.toArray( array, 15 );
  28603. this.geometry.attributes.color.needsUpdate = true;
  28604. return this;
  28605. }
  28606. dispose() {
  28607. this.geometry.dispose();
  28608. this.material.dispose();
  28609. }
  28610. }
  28611. class ShapePath {
  28612. constructor() {
  28613. this.type = 'ShapePath';
  28614. this.color = new Color();
  28615. this.subPaths = [];
  28616. this.currentPath = null;
  28617. }
  28618. moveTo( x, y ) {
  28619. this.currentPath = new Path();
  28620. this.subPaths.push( this.currentPath );
  28621. this.currentPath.moveTo( x, y );
  28622. return this;
  28623. }
  28624. lineTo( x, y ) {
  28625. this.currentPath.lineTo( x, y );
  28626. return this;
  28627. }
  28628. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  28629. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28630. return this;
  28631. }
  28632. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28633. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28634. return this;
  28635. }
  28636. splineThru( pts ) {
  28637. this.currentPath.splineThru( pts );
  28638. return this;
  28639. }
  28640. toShapes( isCCW, noHoles ) {
  28641. function toShapesNoHoles( inSubpaths ) {
  28642. const shapes = [];
  28643. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28644. const tmpPath = inSubpaths[ i ];
  28645. const tmpShape = new Shape();
  28646. tmpShape.curves = tmpPath.curves;
  28647. shapes.push( tmpShape );
  28648. }
  28649. return shapes;
  28650. }
  28651. function isPointInsidePolygon( inPt, inPolygon ) {
  28652. const polyLen = inPolygon.length;
  28653. // inPt on polygon contour => immediate success or
  28654. // toggling of inside/outside at every single! intersection point of an edge
  28655. // with the horizontal line through inPt, left of inPt
  28656. // not counting lowerY endpoints of edges and whole edges on that line
  28657. let inside = false;
  28658. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28659. let edgeLowPt = inPolygon[ p ];
  28660. let edgeHighPt = inPolygon[ q ];
  28661. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28662. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28663. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28664. // not parallel
  28665. if ( edgeDy < 0 ) {
  28666. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28667. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28668. }
  28669. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28670. if ( inPt.y === edgeLowPt.y ) {
  28671. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28672. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28673. } else {
  28674. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28675. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28676. if ( perpEdge < 0 ) continue;
  28677. inside = ! inside; // true intersection left of inPt
  28678. }
  28679. } else {
  28680. // parallel or collinear
  28681. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28682. // edge lies on the same horizontal line as inPt
  28683. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28684. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28685. // continue;
  28686. }
  28687. }
  28688. return inside;
  28689. }
  28690. const isClockWise = ShapeUtils.isClockWise;
  28691. const subPaths = this.subPaths;
  28692. if ( subPaths.length === 0 ) return [];
  28693. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28694. let solid, tmpPath, tmpShape;
  28695. const shapes = [];
  28696. if ( subPaths.length === 1 ) {
  28697. tmpPath = subPaths[ 0 ];
  28698. tmpShape = new Shape();
  28699. tmpShape.curves = tmpPath.curves;
  28700. shapes.push( tmpShape );
  28701. return shapes;
  28702. }
  28703. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28704. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28705. // console.log("Holes first", holesFirst);
  28706. const betterShapeHoles = [];
  28707. const newShapes = [];
  28708. let newShapeHoles = [];
  28709. let mainIdx = 0;
  28710. let tmpPoints;
  28711. newShapes[ mainIdx ] = undefined;
  28712. newShapeHoles[ mainIdx ] = [];
  28713. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  28714. tmpPath = subPaths[ i ];
  28715. tmpPoints = tmpPath.getPoints();
  28716. solid = isClockWise( tmpPoints );
  28717. solid = isCCW ? ! solid : solid;
  28718. if ( solid ) {
  28719. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28720. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28721. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28722. if ( holesFirst ) mainIdx ++;
  28723. newShapeHoles[ mainIdx ] = [];
  28724. //console.log('cw', i);
  28725. } else {
  28726. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28727. //console.log('ccw', i);
  28728. }
  28729. }
  28730. // only Holes? -> probably all Shapes with wrong orientation
  28731. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28732. if ( newShapes.length > 1 ) {
  28733. let ambiguous = false;
  28734. const toChange = [];
  28735. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28736. betterShapeHoles[ sIdx ] = [];
  28737. }
  28738. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28739. const sho = newShapeHoles[ sIdx ];
  28740. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28741. const ho = sho[ hIdx ];
  28742. let hole_unassigned = true;
  28743. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28744. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28745. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  28746. if ( hole_unassigned ) {
  28747. hole_unassigned = false;
  28748. betterShapeHoles[ s2Idx ].push( ho );
  28749. } else {
  28750. ambiguous = true;
  28751. }
  28752. }
  28753. }
  28754. if ( hole_unassigned ) {
  28755. betterShapeHoles[ sIdx ].push( ho );
  28756. }
  28757. }
  28758. }
  28759. // console.log("ambiguous: ", ambiguous);
  28760. if ( toChange.length > 0 ) {
  28761. // console.log("to change: ", toChange);
  28762. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  28763. }
  28764. }
  28765. let tmpHoles;
  28766. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  28767. tmpShape = newShapes[ i ].s;
  28768. shapes.push( tmpShape );
  28769. tmpHoles = newShapeHoles[ i ];
  28770. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28771. tmpShape.holes.push( tmpHoles[ j ].h );
  28772. }
  28773. }
  28774. //console.log("shape", shapes);
  28775. return shapes;
  28776. }
  28777. }
  28778. const _floatView = new Float32Array( 1 );
  28779. const _int32View = new Int32Array( _floatView.buffer );
  28780. class DataUtils {
  28781. // Converts float32 to float16 (stored as uint16 value).
  28782. static toHalfFloat( val ) {
  28783. if ( val > 65504 ) {
  28784. console.warn( 'THREE.DataUtils.toHalfFloat(): value exceeds 65504.' );
  28785. val = 65504; // maximum representable value in float16
  28786. }
  28787. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28788. /* This method is faster than the OpenEXR implementation (very often
  28789. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28790. * by James Tursa?s half-precision code. */
  28791. _floatView[ 0 ] = val;
  28792. const x = _int32View[ 0 ];
  28793. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  28794. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  28795. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  28796. /* If zero, or denormal, or exponent underflows too much for a denormal
  28797. * half, return signed zero. */
  28798. if ( e < 103 ) return bits;
  28799. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28800. if ( e > 142 ) {
  28801. bits |= 0x7c00;
  28802. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28803. * not Inf, so make sure we set one mantissa bit too. */
  28804. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  28805. return bits;
  28806. }
  28807. /* If exponent underflows but not too much, return a denormal */
  28808. if ( e < 113 ) {
  28809. m |= 0x0800;
  28810. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28811. * to 1, which is OK. */
  28812. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  28813. return bits;
  28814. }
  28815. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  28816. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28817. * the exponent, which is OK. */
  28818. bits += m & 1;
  28819. return bits;
  28820. }
  28821. }
  28822. const LineStrip = 0;
  28823. const LinePieces = 1;
  28824. const NoColors = 0;
  28825. const FaceColors = 1;
  28826. const VertexColors = 2;
  28827. function MeshFaceMaterial( materials ) {
  28828. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  28829. return materials;
  28830. }
  28831. function MultiMaterial( materials = [] ) {
  28832. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  28833. materials.isMultiMaterial = true;
  28834. materials.materials = materials;
  28835. materials.clone = function () {
  28836. return materials.slice();
  28837. };
  28838. return materials;
  28839. }
  28840. function PointCloud( geometry, material ) {
  28841. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28842. return new Points( geometry, material );
  28843. }
  28844. function Particle( material ) {
  28845. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28846. return new Sprite( material );
  28847. }
  28848. function ParticleSystem( geometry, material ) {
  28849. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28850. return new Points( geometry, material );
  28851. }
  28852. function PointCloudMaterial( parameters ) {
  28853. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28854. return new PointsMaterial( parameters );
  28855. }
  28856. function ParticleBasicMaterial( parameters ) {
  28857. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28858. return new PointsMaterial( parameters );
  28859. }
  28860. function ParticleSystemMaterial( parameters ) {
  28861. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28862. return new PointsMaterial( parameters );
  28863. }
  28864. function Vertex( x, y, z ) {
  28865. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28866. return new Vector3( x, y, z );
  28867. }
  28868. //
  28869. function DynamicBufferAttribute( array, itemSize ) {
  28870. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  28871. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  28872. }
  28873. function Int8Attribute( array, itemSize ) {
  28874. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28875. return new Int8BufferAttribute( array, itemSize );
  28876. }
  28877. function Uint8Attribute( array, itemSize ) {
  28878. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28879. return new Uint8BufferAttribute( array, itemSize );
  28880. }
  28881. function Uint8ClampedAttribute( array, itemSize ) {
  28882. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28883. return new Uint8ClampedBufferAttribute( array, itemSize );
  28884. }
  28885. function Int16Attribute( array, itemSize ) {
  28886. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28887. return new Int16BufferAttribute( array, itemSize );
  28888. }
  28889. function Uint16Attribute( array, itemSize ) {
  28890. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28891. return new Uint16BufferAttribute( array, itemSize );
  28892. }
  28893. function Int32Attribute( array, itemSize ) {
  28894. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28895. return new Int32BufferAttribute( array, itemSize );
  28896. }
  28897. function Uint32Attribute( array, itemSize ) {
  28898. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28899. return new Uint32BufferAttribute( array, itemSize );
  28900. }
  28901. function Float32Attribute( array, itemSize ) {
  28902. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28903. return new Float32BufferAttribute( array, itemSize );
  28904. }
  28905. function Float64Attribute( array, itemSize ) {
  28906. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  28907. return new Float64BufferAttribute( array, itemSize );
  28908. }
  28909. //
  28910. Curve.create = function ( construct, getPoint ) {
  28911. console.log( 'THREE.Curve.create() has been deprecated' );
  28912. construct.prototype = Object.create( Curve.prototype );
  28913. construct.prototype.constructor = construct;
  28914. construct.prototype.getPoint = getPoint;
  28915. return construct;
  28916. };
  28917. //
  28918. Path.prototype.fromPoints = function ( points ) {
  28919. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28920. return this.setFromPoints( points );
  28921. };
  28922. //
  28923. function AxisHelper( size ) {
  28924. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28925. return new AxesHelper( size );
  28926. }
  28927. function BoundingBoxHelper( object, color ) {
  28928. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28929. return new BoxHelper( object, color );
  28930. }
  28931. function EdgesHelper( object, hex ) {
  28932. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28933. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28934. }
  28935. GridHelper.prototype.setColors = function () {
  28936. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28937. };
  28938. SkeletonHelper.prototype.update = function () {
  28939. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28940. };
  28941. function WireframeHelper( object, hex ) {
  28942. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28943. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28944. }
  28945. //
  28946. Loader.prototype.extractUrlBase = function ( url ) {
  28947. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28948. return LoaderUtils.extractUrlBase( url );
  28949. };
  28950. Loader.Handlers = {
  28951. add: function ( /* regex, loader */ ) {
  28952. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28953. },
  28954. get: function ( /* file */ ) {
  28955. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28956. }
  28957. };
  28958. function XHRLoader( manager ) {
  28959. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28960. return new FileLoader( manager );
  28961. }
  28962. function BinaryTextureLoader( manager ) {
  28963. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28964. return new DataTextureLoader( manager );
  28965. }
  28966. //
  28967. Box2.prototype.center = function ( optionalTarget ) {
  28968. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28969. return this.getCenter( optionalTarget );
  28970. };
  28971. Box2.prototype.empty = function () {
  28972. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28973. return this.isEmpty();
  28974. };
  28975. Box2.prototype.isIntersectionBox = function ( box ) {
  28976. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28977. return this.intersectsBox( box );
  28978. };
  28979. Box2.prototype.size = function ( optionalTarget ) {
  28980. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28981. return this.getSize( optionalTarget );
  28982. };
  28983. //
  28984. Box3.prototype.center = function ( optionalTarget ) {
  28985. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28986. return this.getCenter( optionalTarget );
  28987. };
  28988. Box3.prototype.empty = function () {
  28989. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28990. return this.isEmpty();
  28991. };
  28992. Box3.prototype.isIntersectionBox = function ( box ) {
  28993. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28994. return this.intersectsBox( box );
  28995. };
  28996. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28997. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28998. return this.intersectsSphere( sphere );
  28999. };
  29000. Box3.prototype.size = function ( optionalTarget ) {
  29001. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29002. return this.getSize( optionalTarget );
  29003. };
  29004. //
  29005. Sphere.prototype.empty = function () {
  29006. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  29007. return this.isEmpty();
  29008. };
  29009. //
  29010. Frustum.prototype.setFromMatrix = function ( m ) {
  29011. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  29012. return this.setFromProjectionMatrix( m );
  29013. };
  29014. //
  29015. Line3.prototype.center = function ( optionalTarget ) {
  29016. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29017. return this.getCenter( optionalTarget );
  29018. };
  29019. //
  29020. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  29021. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  29022. return this.toArray( array, offset );
  29023. };
  29024. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  29025. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29026. return vector.applyMatrix3( this );
  29027. };
  29028. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  29029. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  29030. };
  29031. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  29032. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  29033. return attribute.applyMatrix3( this );
  29034. };
  29035. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  29036. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29037. };
  29038. Matrix3.prototype.getInverse = function ( matrix ) {
  29039. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29040. return this.copy( matrix ).invert();
  29041. };
  29042. //
  29043. Matrix4.prototype.extractPosition = function ( m ) {
  29044. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29045. return this.copyPosition( m );
  29046. };
  29047. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  29048. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  29049. return this.toArray( array, offset );
  29050. };
  29051. Matrix4.prototype.getPosition = function () {
  29052. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29053. return new Vector3().setFromMatrixColumn( this, 3 );
  29054. };
  29055. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  29056. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29057. return this.makeRotationFromQuaternion( q );
  29058. };
  29059. Matrix4.prototype.multiplyToArray = function () {
  29060. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  29061. };
  29062. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  29063. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29064. return vector.applyMatrix4( this );
  29065. };
  29066. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  29067. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29068. return vector.applyMatrix4( this );
  29069. };
  29070. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  29071. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  29072. };
  29073. Matrix4.prototype.rotateAxis = function ( v ) {
  29074. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29075. v.transformDirection( this );
  29076. };
  29077. Matrix4.prototype.crossVector = function ( vector ) {
  29078. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29079. return vector.applyMatrix4( this );
  29080. };
  29081. Matrix4.prototype.translate = function () {
  29082. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29083. };
  29084. Matrix4.prototype.rotateX = function () {
  29085. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29086. };
  29087. Matrix4.prototype.rotateY = function () {
  29088. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29089. };
  29090. Matrix4.prototype.rotateZ = function () {
  29091. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29092. };
  29093. Matrix4.prototype.rotateByAxis = function () {
  29094. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29095. };
  29096. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  29097. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  29098. return attribute.applyMatrix4( this );
  29099. };
  29100. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  29101. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29102. };
  29103. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  29104. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29105. return this.makePerspective( left, right, top, bottom, near, far );
  29106. };
  29107. Matrix4.prototype.getInverse = function ( matrix ) {
  29108. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29109. return this.copy( matrix ).invert();
  29110. };
  29111. //
  29112. Plane.prototype.isIntersectionLine = function ( line ) {
  29113. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29114. return this.intersectsLine( line );
  29115. };
  29116. //
  29117. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29118. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29119. return vector.applyQuaternion( this );
  29120. };
  29121. Quaternion.prototype.inverse = function ( ) {
  29122. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  29123. return this.invert();
  29124. };
  29125. //
  29126. Ray.prototype.isIntersectionBox = function ( box ) {
  29127. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29128. return this.intersectsBox( box );
  29129. };
  29130. Ray.prototype.isIntersectionPlane = function ( plane ) {
  29131. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29132. return this.intersectsPlane( plane );
  29133. };
  29134. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  29135. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29136. return this.intersectsSphere( sphere );
  29137. };
  29138. //
  29139. Triangle.prototype.area = function () {
  29140. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  29141. return this.getArea();
  29142. };
  29143. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  29144. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29145. return this.getBarycoord( point, target );
  29146. };
  29147. Triangle.prototype.midpoint = function ( target ) {
  29148. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  29149. return this.getMidpoint( target );
  29150. };
  29151. Triangle.prototypenormal = function ( target ) {
  29152. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29153. return this.getNormal( target );
  29154. };
  29155. Triangle.prototype.plane = function ( target ) {
  29156. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  29157. return this.getPlane( target );
  29158. };
  29159. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  29160. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29161. return Triangle.getBarycoord( point, a, b, c, target );
  29162. };
  29163. Triangle.normal = function ( a, b, c, target ) {
  29164. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29165. return Triangle.getNormal( a, b, c, target );
  29166. };
  29167. //
  29168. Shape.prototype.extractAllPoints = function ( divisions ) {
  29169. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  29170. return this.extractPoints( divisions );
  29171. };
  29172. Shape.prototype.extrude = function ( options ) {
  29173. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29174. return new ExtrudeGeometry( this, options );
  29175. };
  29176. Shape.prototype.makeGeometry = function ( options ) {
  29177. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29178. return new ShapeGeometry( this, options );
  29179. };
  29180. //
  29181. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  29182. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29183. return this.fromBufferAttribute( attribute, index, offset );
  29184. };
  29185. Vector2.prototype.distanceToManhattan = function ( v ) {
  29186. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29187. return this.manhattanDistanceTo( v );
  29188. };
  29189. Vector2.prototype.lengthManhattan = function () {
  29190. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  29191. return this.manhattanLength();
  29192. };
  29193. //
  29194. Vector3.prototype.setEulerFromRotationMatrix = function () {
  29195. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29196. };
  29197. Vector3.prototype.setEulerFromQuaternion = function () {
  29198. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29199. };
  29200. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  29201. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29202. return this.setFromMatrixPosition( m );
  29203. };
  29204. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  29205. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29206. return this.setFromMatrixScale( m );
  29207. };
  29208. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  29209. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29210. return this.setFromMatrixColumn( matrix, index );
  29211. };
  29212. Vector3.prototype.applyProjection = function ( m ) {
  29213. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  29214. return this.applyMatrix4( m );
  29215. };
  29216. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  29217. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29218. return this.fromBufferAttribute( attribute, index, offset );
  29219. };
  29220. Vector3.prototype.distanceToManhattan = function ( v ) {
  29221. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29222. return this.manhattanDistanceTo( v );
  29223. };
  29224. Vector3.prototype.lengthManhattan = function () {
  29225. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  29226. return this.manhattanLength();
  29227. };
  29228. //
  29229. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  29230. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29231. return this.fromBufferAttribute( attribute, index, offset );
  29232. };
  29233. Vector4.prototype.lengthManhattan = function () {
  29234. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  29235. return this.manhattanLength();
  29236. };
  29237. //
  29238. Object3D.prototype.getChildByName = function ( name ) {
  29239. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29240. return this.getObjectByName( name );
  29241. };
  29242. Object3D.prototype.renderDepth = function () {
  29243. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29244. };
  29245. Object3D.prototype.translate = function ( distance, axis ) {
  29246. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29247. return this.translateOnAxis( axis, distance );
  29248. };
  29249. Object3D.prototype.getWorldRotation = function () {
  29250. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  29251. };
  29252. Object3D.prototype.applyMatrix = function ( matrix ) {
  29253. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  29254. return this.applyMatrix4( matrix );
  29255. };
  29256. Object.defineProperties( Object3D.prototype, {
  29257. eulerOrder: {
  29258. get: function () {
  29259. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29260. return this.rotation.order;
  29261. },
  29262. set: function ( value ) {
  29263. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29264. this.rotation.order = value;
  29265. }
  29266. },
  29267. useQuaternion: {
  29268. get: function () {
  29269. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29270. },
  29271. set: function () {
  29272. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29273. }
  29274. }
  29275. } );
  29276. Mesh.prototype.setDrawMode = function () {
  29277. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29278. };
  29279. Object.defineProperties( Mesh.prototype, {
  29280. drawMode: {
  29281. get: function () {
  29282. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  29283. return TrianglesDrawMode;
  29284. },
  29285. set: function () {
  29286. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29287. }
  29288. }
  29289. } );
  29290. SkinnedMesh.prototype.initBones = function () {
  29291. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  29292. };
  29293. //
  29294. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29295. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  29296. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  29297. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29298. this.setFocalLength( focalLength );
  29299. };
  29300. //
  29301. Object.defineProperties( Light.prototype, {
  29302. onlyShadow: {
  29303. set: function () {
  29304. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29305. }
  29306. },
  29307. shadowCameraFov: {
  29308. set: function ( value ) {
  29309. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29310. this.shadow.camera.fov = value;
  29311. }
  29312. },
  29313. shadowCameraLeft: {
  29314. set: function ( value ) {
  29315. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29316. this.shadow.camera.left = value;
  29317. }
  29318. },
  29319. shadowCameraRight: {
  29320. set: function ( value ) {
  29321. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29322. this.shadow.camera.right = value;
  29323. }
  29324. },
  29325. shadowCameraTop: {
  29326. set: function ( value ) {
  29327. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29328. this.shadow.camera.top = value;
  29329. }
  29330. },
  29331. shadowCameraBottom: {
  29332. set: function ( value ) {
  29333. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29334. this.shadow.camera.bottom = value;
  29335. }
  29336. },
  29337. shadowCameraNear: {
  29338. set: function ( value ) {
  29339. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29340. this.shadow.camera.near = value;
  29341. }
  29342. },
  29343. shadowCameraFar: {
  29344. set: function ( value ) {
  29345. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29346. this.shadow.camera.far = value;
  29347. }
  29348. },
  29349. shadowCameraVisible: {
  29350. set: function () {
  29351. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29352. }
  29353. },
  29354. shadowBias: {
  29355. set: function ( value ) {
  29356. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29357. this.shadow.bias = value;
  29358. }
  29359. },
  29360. shadowDarkness: {
  29361. set: function () {
  29362. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29363. }
  29364. },
  29365. shadowMapWidth: {
  29366. set: function ( value ) {
  29367. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29368. this.shadow.mapSize.width = value;
  29369. }
  29370. },
  29371. shadowMapHeight: {
  29372. set: function ( value ) {
  29373. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29374. this.shadow.mapSize.height = value;
  29375. }
  29376. }
  29377. } );
  29378. //
  29379. Object.defineProperties( BufferAttribute.prototype, {
  29380. length: {
  29381. get: function () {
  29382. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29383. return this.array.length;
  29384. }
  29385. },
  29386. dynamic: {
  29387. get: function () {
  29388. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29389. return this.usage === DynamicDrawUsage;
  29390. },
  29391. set: function ( /* value */ ) {
  29392. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29393. this.setUsage( DynamicDrawUsage );
  29394. }
  29395. }
  29396. } );
  29397. BufferAttribute.prototype.setDynamic = function ( value ) {
  29398. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29399. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29400. return this;
  29401. };
  29402. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  29403. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  29404. },
  29405. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  29406. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29407. };
  29408. //
  29409. BufferGeometry.prototype.addIndex = function ( index ) {
  29410. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29411. this.setIndex( index );
  29412. };
  29413. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  29414. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  29415. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  29416. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  29417. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  29418. }
  29419. if ( name === 'index' ) {
  29420. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  29421. this.setIndex( attribute );
  29422. return this;
  29423. }
  29424. return this.setAttribute( name, attribute );
  29425. };
  29426. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  29427. if ( indexOffset !== undefined ) {
  29428. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29429. }
  29430. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29431. this.addGroup( start, count );
  29432. };
  29433. BufferGeometry.prototype.clearDrawCalls = function () {
  29434. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29435. this.clearGroups();
  29436. };
  29437. BufferGeometry.prototype.computeOffsets = function () {
  29438. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29439. };
  29440. BufferGeometry.prototype.removeAttribute = function ( name ) {
  29441. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  29442. return this.deleteAttribute( name );
  29443. };
  29444. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  29445. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29446. return this.applyMatrix4( matrix );
  29447. };
  29448. Object.defineProperties( BufferGeometry.prototype, {
  29449. drawcalls: {
  29450. get: function () {
  29451. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29452. return this.groups;
  29453. }
  29454. },
  29455. offsets: {
  29456. get: function () {
  29457. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29458. return this.groups;
  29459. }
  29460. }
  29461. } );
  29462. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  29463. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29464. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29465. return this;
  29466. };
  29467. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  29468. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29469. };
  29470. //
  29471. ExtrudeGeometry.prototype.getArrays = function () {
  29472. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  29473. };
  29474. ExtrudeGeometry.prototype.addShapeList = function () {
  29475. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  29476. };
  29477. ExtrudeGeometry.prototype.addShape = function () {
  29478. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  29479. };
  29480. //
  29481. Scene.prototype.dispose = function () {
  29482. console.error( 'THREE.Scene: .dispose() has been removed.' );
  29483. };
  29484. //
  29485. Uniform.prototype.onUpdate = function () {
  29486. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29487. return this;
  29488. };
  29489. //
  29490. Object.defineProperties( Material.prototype, {
  29491. wrapAround: {
  29492. get: function () {
  29493. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29494. },
  29495. set: function () {
  29496. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29497. }
  29498. },
  29499. overdraw: {
  29500. get: function () {
  29501. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29502. },
  29503. set: function () {
  29504. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29505. }
  29506. },
  29507. wrapRGB: {
  29508. get: function () {
  29509. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  29510. return new Color();
  29511. }
  29512. },
  29513. shading: {
  29514. get: function () {
  29515. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29516. },
  29517. set: function ( value ) {
  29518. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29519. this.flatShading = ( value === FlatShading );
  29520. }
  29521. },
  29522. stencilMask: {
  29523. get: function () {
  29524. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29525. return this.stencilFuncMask;
  29526. },
  29527. set: function ( value ) {
  29528. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29529. this.stencilFuncMask = value;
  29530. }
  29531. },
  29532. vertexTangents: {
  29533. get: function () {
  29534. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29535. },
  29536. set: function () {
  29537. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29538. }
  29539. },
  29540. } );
  29541. Object.defineProperties( ShaderMaterial.prototype, {
  29542. derivatives: {
  29543. get: function () {
  29544. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29545. return this.extensions.derivatives;
  29546. },
  29547. set: function ( value ) {
  29548. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29549. this.extensions.derivatives = value;
  29550. }
  29551. }
  29552. } );
  29553. //
  29554. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  29555. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  29556. this.setRenderTarget( renderTarget );
  29557. this.clear( color, depth, stencil );
  29558. };
  29559. WebGLRenderer.prototype.animate = function ( callback ) {
  29560. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  29561. this.setAnimationLoop( callback );
  29562. };
  29563. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  29564. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  29565. return this.getRenderTarget();
  29566. };
  29567. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  29568. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  29569. return this.capabilities.getMaxAnisotropy();
  29570. };
  29571. WebGLRenderer.prototype.getPrecision = function () {
  29572. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  29573. return this.capabilities.precision;
  29574. };
  29575. WebGLRenderer.prototype.resetGLState = function () {
  29576. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  29577. return this.state.reset();
  29578. };
  29579. WebGLRenderer.prototype.supportsFloatTextures = function () {
  29580. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29581. return this.extensions.get( 'OES_texture_float' );
  29582. };
  29583. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  29584. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29585. return this.extensions.get( 'OES_texture_half_float' );
  29586. };
  29587. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  29588. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29589. return this.extensions.get( 'OES_standard_derivatives' );
  29590. };
  29591. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  29592. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29593. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29594. };
  29595. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  29596. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29597. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29598. };
  29599. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  29600. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29601. return this.extensions.get( 'EXT_blend_minmax' );
  29602. };
  29603. WebGLRenderer.prototype.supportsVertexTextures = function () {
  29604. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29605. return this.capabilities.vertexTextures;
  29606. };
  29607. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  29608. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29609. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29610. };
  29611. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  29612. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29613. this.setScissorTest( boolean );
  29614. };
  29615. WebGLRenderer.prototype.initMaterial = function () {
  29616. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29617. };
  29618. WebGLRenderer.prototype.addPrePlugin = function () {
  29619. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29620. };
  29621. WebGLRenderer.prototype.addPostPlugin = function () {
  29622. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29623. };
  29624. WebGLRenderer.prototype.updateShadowMap = function () {
  29625. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29626. };
  29627. WebGLRenderer.prototype.setFaceCulling = function () {
  29628. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  29629. };
  29630. WebGLRenderer.prototype.allocTextureUnit = function () {
  29631. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  29632. };
  29633. WebGLRenderer.prototype.setTexture = function () {
  29634. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  29635. };
  29636. WebGLRenderer.prototype.setTexture2D = function () {
  29637. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  29638. };
  29639. WebGLRenderer.prototype.setTextureCube = function () {
  29640. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  29641. };
  29642. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29643. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  29644. return this.getActiveMipmapLevel();
  29645. };
  29646. Object.defineProperties( WebGLRenderer.prototype, {
  29647. shadowMapEnabled: {
  29648. get: function () {
  29649. return this.shadowMap.enabled;
  29650. },
  29651. set: function ( value ) {
  29652. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29653. this.shadowMap.enabled = value;
  29654. }
  29655. },
  29656. shadowMapType: {
  29657. get: function () {
  29658. return this.shadowMap.type;
  29659. },
  29660. set: function ( value ) {
  29661. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29662. this.shadowMap.type = value;
  29663. }
  29664. },
  29665. shadowMapCullFace: {
  29666. get: function () {
  29667. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29668. return undefined;
  29669. },
  29670. set: function ( /* value */ ) {
  29671. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29672. }
  29673. },
  29674. context: {
  29675. get: function () {
  29676. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  29677. return this.getContext();
  29678. }
  29679. },
  29680. vr: {
  29681. get: function () {
  29682. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  29683. return this.xr;
  29684. }
  29685. },
  29686. gammaInput: {
  29687. get: function () {
  29688. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29689. return false;
  29690. },
  29691. set: function () {
  29692. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29693. }
  29694. },
  29695. gammaOutput: {
  29696. get: function () {
  29697. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29698. return false;
  29699. },
  29700. set: function ( value ) {
  29701. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29702. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  29703. }
  29704. },
  29705. toneMappingWhitePoint: {
  29706. get: function () {
  29707. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29708. return 1.0;
  29709. },
  29710. set: function () {
  29711. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29712. }
  29713. },
  29714. gammaFactor: {
  29715. get: function () {
  29716. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  29717. return 2;
  29718. },
  29719. set: function () {
  29720. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  29721. }
  29722. }
  29723. } );
  29724. Object.defineProperties( WebGLShadowMap.prototype, {
  29725. cullFace: {
  29726. get: function () {
  29727. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29728. return undefined;
  29729. },
  29730. set: function ( /* cullFace */ ) {
  29731. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29732. }
  29733. },
  29734. renderReverseSided: {
  29735. get: function () {
  29736. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29737. return undefined;
  29738. },
  29739. set: function () {
  29740. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29741. }
  29742. },
  29743. renderSingleSided: {
  29744. get: function () {
  29745. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29746. return undefined;
  29747. },
  29748. set: function () {
  29749. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29750. }
  29751. }
  29752. } );
  29753. function WebGLRenderTargetCube( width, height, options ) {
  29754. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  29755. return new WebGLCubeRenderTarget( width, options );
  29756. }
  29757. //
  29758. Object.defineProperties( WebGLRenderTarget.prototype, {
  29759. wrapS: {
  29760. get: function () {
  29761. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29762. return this.texture.wrapS;
  29763. },
  29764. set: function ( value ) {
  29765. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29766. this.texture.wrapS = value;
  29767. }
  29768. },
  29769. wrapT: {
  29770. get: function () {
  29771. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29772. return this.texture.wrapT;
  29773. },
  29774. set: function ( value ) {
  29775. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29776. this.texture.wrapT = value;
  29777. }
  29778. },
  29779. magFilter: {
  29780. get: function () {
  29781. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29782. return this.texture.magFilter;
  29783. },
  29784. set: function ( value ) {
  29785. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29786. this.texture.magFilter = value;
  29787. }
  29788. },
  29789. minFilter: {
  29790. get: function () {
  29791. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29792. return this.texture.minFilter;
  29793. },
  29794. set: function ( value ) {
  29795. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29796. this.texture.minFilter = value;
  29797. }
  29798. },
  29799. anisotropy: {
  29800. get: function () {
  29801. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29802. return this.texture.anisotropy;
  29803. },
  29804. set: function ( value ) {
  29805. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29806. this.texture.anisotropy = value;
  29807. }
  29808. },
  29809. offset: {
  29810. get: function () {
  29811. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29812. return this.texture.offset;
  29813. },
  29814. set: function ( value ) {
  29815. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29816. this.texture.offset = value;
  29817. }
  29818. },
  29819. repeat: {
  29820. get: function () {
  29821. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29822. return this.texture.repeat;
  29823. },
  29824. set: function ( value ) {
  29825. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29826. this.texture.repeat = value;
  29827. }
  29828. },
  29829. format: {
  29830. get: function () {
  29831. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29832. return this.texture.format;
  29833. },
  29834. set: function ( value ) {
  29835. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29836. this.texture.format = value;
  29837. }
  29838. },
  29839. type: {
  29840. get: function () {
  29841. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29842. return this.texture.type;
  29843. },
  29844. set: function ( value ) {
  29845. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29846. this.texture.type = value;
  29847. }
  29848. },
  29849. generateMipmaps: {
  29850. get: function () {
  29851. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29852. return this.texture.generateMipmaps;
  29853. },
  29854. set: function ( value ) {
  29855. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29856. this.texture.generateMipmaps = value;
  29857. }
  29858. }
  29859. } );
  29860. //
  29861. Audio.prototype.load = function ( file ) {
  29862. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29863. const scope = this;
  29864. const audioLoader = new AudioLoader();
  29865. audioLoader.load( file, function ( buffer ) {
  29866. scope.setBuffer( buffer );
  29867. } );
  29868. return this;
  29869. };
  29870. AudioAnalyser.prototype.getData = function () {
  29871. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29872. return this.getFrequencyData();
  29873. };
  29874. //
  29875. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29876. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29877. return this.update( renderer, scene );
  29878. };
  29879. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29880. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29881. return this.renderTarget.clear( renderer, color, depth, stencil );
  29882. };
  29883. ImageUtils.crossOrigin = undefined;
  29884. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29885. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29886. const loader = new TextureLoader();
  29887. loader.setCrossOrigin( this.crossOrigin );
  29888. const texture = loader.load( url, onLoad, undefined, onError );
  29889. if ( mapping ) texture.mapping = mapping;
  29890. return texture;
  29891. };
  29892. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29893. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29894. const loader = new CubeTextureLoader();
  29895. loader.setCrossOrigin( this.crossOrigin );
  29896. const texture = loader.load( urls, onLoad, undefined, onError );
  29897. if ( mapping ) texture.mapping = mapping;
  29898. return texture;
  29899. };
  29900. ImageUtils.loadCompressedTexture = function () {
  29901. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29902. };
  29903. ImageUtils.loadCompressedTextureCube = function () {
  29904. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29905. };
  29906. //
  29907. function CanvasRenderer() {
  29908. console.error( 'THREE.CanvasRenderer has been removed' );
  29909. }
  29910. //
  29911. function JSONLoader() {
  29912. console.error( 'THREE.JSONLoader has been removed.' );
  29913. }
  29914. //
  29915. const SceneUtils = {
  29916. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29917. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29918. },
  29919. detach: function ( /* child, parent, scene */ ) {
  29920. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29921. },
  29922. attach: function ( /* child, scene, parent */ ) {
  29923. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29924. }
  29925. };
  29926. //
  29927. function LensFlare() {
  29928. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29929. }
  29930. //
  29931. function ParametricGeometry() {
  29932. console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' );
  29933. return new BufferGeometry();
  29934. }
  29935. function TextGeometry() {
  29936. console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' );
  29937. return new BufferGeometry();
  29938. }
  29939. function FontLoader() {
  29940. console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' );
  29941. }
  29942. function Font() {
  29943. console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' );
  29944. }
  29945. function ImmediateRenderObject() {
  29946. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29947. }
  29948. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29949. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29950. revision: REVISION,
  29951. } } ) );
  29952. }
  29953. if ( typeof window !== 'undefined' ) {
  29954. if ( window.__THREE__ ) {
  29955. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29956. } else {
  29957. window.__THREE__ = REVISION;
  29958. }
  29959. }
  29960. 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, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, 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, RGBFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry as RingBufferGeometry, RingGeometry, 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, 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, _SRGBAFormat, sRGBEncoding };