three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '129dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const FlatShading = 1;
  21. const SmoothShading = 2;
  22. const NoBlending = 0;
  23. const NormalBlending = 1;
  24. const AdditiveBlending = 2;
  25. const SubtractiveBlending = 3;
  26. const MultiplyBlending = 4;
  27. const CustomBlending = 5;
  28. const AddEquation = 100;
  29. const SubtractEquation = 101;
  30. const ReverseSubtractEquation = 102;
  31. const MinEquation = 103;
  32. const MaxEquation = 104;
  33. const ZeroFactor = 200;
  34. const OneFactor = 201;
  35. const SrcColorFactor = 202;
  36. const OneMinusSrcColorFactor = 203;
  37. const SrcAlphaFactor = 204;
  38. const OneMinusSrcAlphaFactor = 205;
  39. const DstAlphaFactor = 206;
  40. const OneMinusDstAlphaFactor = 207;
  41. const DstColorFactor = 208;
  42. const OneMinusDstColorFactor = 209;
  43. const SrcAlphaSaturateFactor = 210;
  44. const NeverDepth = 0;
  45. const AlwaysDepth = 1;
  46. const LessDepth = 2;
  47. const LessEqualDepth = 3;
  48. const EqualDepth = 4;
  49. const GreaterEqualDepth = 5;
  50. const GreaterDepth = 6;
  51. const NotEqualDepth = 7;
  52. const MultiplyOperation = 0;
  53. const MixOperation = 1;
  54. const AddOperation = 2;
  55. const NoToneMapping = 0;
  56. const LinearToneMapping = 1;
  57. const ReinhardToneMapping = 2;
  58. const CineonToneMapping = 3;
  59. const ACESFilmicToneMapping = 4;
  60. const CustomToneMapping = 5;
  61. const UVMapping = 300;
  62. const CubeReflectionMapping = 301;
  63. const CubeRefractionMapping = 302;
  64. const EquirectangularReflectionMapping = 303;
  65. const EquirectangularRefractionMapping = 304;
  66. const CubeUVReflectionMapping = 306;
  67. const CubeUVRefractionMapping = 307;
  68. const RepeatWrapping = 1000;
  69. const ClampToEdgeWrapping = 1001;
  70. const MirroredRepeatWrapping = 1002;
  71. const NearestFilter = 1003;
  72. const NearestMipmapNearestFilter = 1004;
  73. const NearestMipMapNearestFilter = 1004;
  74. const NearestMipmapLinearFilter = 1005;
  75. const NearestMipMapLinearFilter = 1005;
  76. const LinearFilter = 1006;
  77. const LinearMipmapNearestFilter = 1007;
  78. const LinearMipMapNearestFilter = 1007;
  79. const LinearMipmapLinearFilter = 1008;
  80. const LinearMipMapLinearFilter = 1008;
  81. const UnsignedByteType = 1009;
  82. const ByteType = 1010;
  83. const ShortType = 1011;
  84. const UnsignedShortType = 1012;
  85. const IntType = 1013;
  86. const UnsignedIntType = 1014;
  87. const FloatType = 1015;
  88. const HalfFloatType = 1016;
  89. const UnsignedShort4444Type = 1017;
  90. const UnsignedShort5551Type = 1018;
  91. const UnsignedShort565Type = 1019;
  92. const UnsignedInt248Type = 1020;
  93. const AlphaFormat = 1021;
  94. const RGBFormat = 1022;
  95. const RGBAFormat = 1023;
  96. const LuminanceFormat = 1024;
  97. const LuminanceAlphaFormat = 1025;
  98. const RGBEFormat = RGBAFormat;
  99. const DepthFormat = 1026;
  100. const DepthStencilFormat = 1027;
  101. const RedFormat = 1028;
  102. const RedIntegerFormat = 1029;
  103. const RGFormat = 1030;
  104. const RGIntegerFormat = 1031;
  105. const RGBIntegerFormat = 1032;
  106. const RGBAIntegerFormat = 1033;
  107. const RGB_S3TC_DXT1_Format = 33776;
  108. const RGBA_S3TC_DXT1_Format = 33777;
  109. const RGBA_S3TC_DXT3_Format = 33778;
  110. const RGBA_S3TC_DXT5_Format = 33779;
  111. const RGB_PVRTC_4BPPV1_Format = 35840;
  112. const RGB_PVRTC_2BPPV1_Format = 35841;
  113. const RGBA_PVRTC_4BPPV1_Format = 35842;
  114. const RGBA_PVRTC_2BPPV1_Format = 35843;
  115. const RGB_ETC1_Format = 36196;
  116. const RGB_ETC2_Format = 37492;
  117. const RGBA_ETC2_EAC_Format = 37496;
  118. const RGBA_ASTC_4x4_Format = 37808;
  119. const RGBA_ASTC_5x4_Format = 37809;
  120. const RGBA_ASTC_5x5_Format = 37810;
  121. const RGBA_ASTC_6x5_Format = 37811;
  122. const RGBA_ASTC_6x6_Format = 37812;
  123. const RGBA_ASTC_8x5_Format = 37813;
  124. const RGBA_ASTC_8x6_Format = 37814;
  125. const RGBA_ASTC_8x8_Format = 37815;
  126. const RGBA_ASTC_10x5_Format = 37816;
  127. const RGBA_ASTC_10x6_Format = 37817;
  128. const RGBA_ASTC_10x8_Format = 37818;
  129. const RGBA_ASTC_10x10_Format = 37819;
  130. const RGBA_ASTC_12x10_Format = 37820;
  131. const RGBA_ASTC_12x12_Format = 37821;
  132. const RGBA_BPTC_Format = 36492;
  133. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  134. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  135. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  136. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  137. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  138. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  139. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  140. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  141. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  142. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  143. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  144. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  145. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  146. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  147. const LoopOnce = 2200;
  148. const LoopRepeat = 2201;
  149. const LoopPingPong = 2202;
  150. const InterpolateDiscrete = 2300;
  151. const InterpolateLinear = 2301;
  152. const InterpolateSmooth = 2302;
  153. const ZeroCurvatureEnding = 2400;
  154. const ZeroSlopeEnding = 2401;
  155. const WrapAroundEnding = 2402;
  156. const NormalAnimationBlendMode = 2500;
  157. const AdditiveAnimationBlendMode = 2501;
  158. const TrianglesDrawMode = 0;
  159. const TriangleStripDrawMode = 1;
  160. const TriangleFanDrawMode = 2;
  161. const LinearEncoding = 3000;
  162. const sRGBEncoding = 3001;
  163. const GammaEncoding = 3007;
  164. const RGBEEncoding = 3002;
  165. const LogLuvEncoding = 3003;
  166. const RGBM7Encoding = 3004;
  167. const RGBM16Encoding = 3005;
  168. const RGBDEncoding = 3006;
  169. const BasicDepthPacking = 3200;
  170. const RGBADepthPacking = 3201;
  171. const TangentSpaceNormalMap = 0;
  172. const ObjectSpaceNormalMap = 1;
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const StaticDrawUsage = 35044;
  190. const DynamicDrawUsage = 35048;
  191. const StreamDrawUsage = 35040;
  192. const StaticReadUsage = 35045;
  193. const DynamicReadUsage = 35049;
  194. const StreamReadUsage = 35041;
  195. const StaticCopyUsage = 35046;
  196. const DynamicCopyUsage = 35050;
  197. const StreamCopyUsage = 35042;
  198. const GLSL1 = '100';
  199. const GLSL3 = '300 es';
  200. /**
  201. * https://github.com/mrdoob/eventdispatcher.js/
  202. */
  203. class EventDispatcher {
  204. addEventListener( type, listener ) {
  205. if ( this._listeners === undefined ) this._listeners = {};
  206. const listeners = this._listeners;
  207. if ( listeners[ type ] === undefined ) {
  208. listeners[ type ] = [];
  209. }
  210. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  211. listeners[ type ].push( listener );
  212. }
  213. }
  214. hasEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) return false;
  216. const listeners = this._listeners;
  217. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  218. }
  219. removeEventListener( type, listener ) {
  220. if ( this._listeners === undefined ) return;
  221. const listeners = this._listeners;
  222. const listenerArray = listeners[ type ];
  223. if ( listenerArray !== undefined ) {
  224. const index = listenerArray.indexOf( listener );
  225. if ( index !== - 1 ) {
  226. listenerArray.splice( index, 1 );
  227. }
  228. }
  229. }
  230. dispatchEvent( event ) {
  231. if ( this._listeners === undefined ) return;
  232. const listeners = this._listeners;
  233. const listenerArray = listeners[ event.type ];
  234. if ( listenerArray !== undefined ) {
  235. event.target = this;
  236. // Make a copy, in case listeners are removed while iterating.
  237. const array = listenerArray.slice( 0 );
  238. for ( let i = 0, l = array.length; i < l; i ++ ) {
  239. array[ i ].call( this, event );
  240. }
  241. event.target = null;
  242. }
  243. }
  244. }
  245. const _lut = [];
  246. for ( let i = 0; i < 256; i ++ ) {
  247. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  248. }
  249. let _seed = 1234567;
  250. const DEG2RAD = Math.PI / 180;
  251. const RAD2DEG = 180 / Math.PI;
  252. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  253. function generateUUID() {
  254. const d0 = Math.random() * 0xffffffff | 0;
  255. const d1 = Math.random() * 0xffffffff | 0;
  256. const d2 = Math.random() * 0xffffffff | 0;
  257. const d3 = Math.random() * 0xffffffff | 0;
  258. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  259. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  260. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  261. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  262. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  263. return uuid.toUpperCase();
  264. }
  265. function clamp( value, min, max ) {
  266. return Math.max( min, Math.min( max, value ) );
  267. }
  268. // compute euclidian modulo of m % n
  269. // https://en.wikipedia.org/wiki/Modulo_operation
  270. function euclideanModulo( n, m ) {
  271. return ( ( n % m ) + m ) % m;
  272. }
  273. // Linear mapping from range <a1, a2> to range <b1, b2>
  274. function mapLinear( x, a1, a2, b1, b2 ) {
  275. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  276. }
  277. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  278. function inverseLerp( x, y, value ) {
  279. if ( x !== y ) {
  280. return ( value - x ) / ( y - x );
  281. } else {
  282. return 0;
  283. }
  284. }
  285. // https://en.wikipedia.org/wiki/Linear_interpolation
  286. function lerp( x, y, t ) {
  287. return ( 1 - t ) * x + t * y;
  288. }
  289. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  290. function damp( x, y, lambda, dt ) {
  291. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  292. }
  293. // https://www.desmos.com/calculator/vcsjnyz7x4
  294. function pingpong( x, length = 1 ) {
  295. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  296. }
  297. // http://en.wikipedia.org/wiki/Smoothstep
  298. function smoothstep( x, min, max ) {
  299. if ( x <= min ) return 0;
  300. if ( x >= max ) return 1;
  301. x = ( x - min ) / ( max - min );
  302. return x * x * ( 3 - 2 * x );
  303. }
  304. function smootherstep( x, min, max ) {
  305. if ( x <= min ) return 0;
  306. if ( x >= max ) return 1;
  307. x = ( x - min ) / ( max - min );
  308. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  309. }
  310. // Random integer from <low, high> interval
  311. function randInt( low, high ) {
  312. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  313. }
  314. // Random float from <low, high> interval
  315. function randFloat( low, high ) {
  316. return low + Math.random() * ( high - low );
  317. }
  318. // Random float from <-range/2, range/2> interval
  319. function randFloatSpread( range ) {
  320. return range * ( 0.5 - Math.random() );
  321. }
  322. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom( s ) {
  324. if ( s !== undefined ) _seed = s % 2147483647;
  325. // Park-Miller algorithm
  326. _seed = _seed * 16807 % 2147483647;
  327. return ( _seed - 1 ) / 2147483646;
  328. }
  329. function degToRad( degrees ) {
  330. return degrees * DEG2RAD;
  331. }
  332. function radToDeg( radians ) {
  333. return radians * RAD2DEG;
  334. }
  335. function isPowerOfTwo( value ) {
  336. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  337. }
  338. function ceilPowerOfTwo( value ) {
  339. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  340. }
  341. function floorPowerOfTwo( value ) {
  342. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  343. }
  344. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  345. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  346. // rotations are applied to the axes in the order specified by 'order'
  347. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  348. // angles are in radians
  349. const cos = Math.cos;
  350. const sin = Math.sin;
  351. const c2 = cos( b / 2 );
  352. const s2 = sin( b / 2 );
  353. const c13 = cos( ( a + c ) / 2 );
  354. const s13 = sin( ( a + c ) / 2 );
  355. const c1_3 = cos( ( a - c ) / 2 );
  356. const s1_3 = sin( ( a - c ) / 2 );
  357. const c3_1 = cos( ( c - a ) / 2 );
  358. const s3_1 = sin( ( c - a ) / 2 );
  359. switch ( order ) {
  360. case 'XYX':
  361. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  362. break;
  363. case 'YZY':
  364. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  365. break;
  366. case 'ZXZ':
  367. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  368. break;
  369. case 'XZX':
  370. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  371. break;
  372. case 'YXY':
  373. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  374. break;
  375. case 'ZYZ':
  376. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  377. break;
  378. default:
  379. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  380. }
  381. }
  382. var MathUtils = /*#__PURE__*/Object.freeze({
  383. __proto__: null,
  384. DEG2RAD: DEG2RAD,
  385. RAD2DEG: RAD2DEG,
  386. generateUUID: generateUUID,
  387. clamp: clamp,
  388. euclideanModulo: euclideanModulo,
  389. mapLinear: mapLinear,
  390. inverseLerp: inverseLerp,
  391. lerp: lerp,
  392. damp: damp,
  393. pingpong: pingpong,
  394. smoothstep: smoothstep,
  395. smootherstep: smootherstep,
  396. randInt: randInt,
  397. randFloat: randFloat,
  398. randFloatSpread: randFloatSpread,
  399. seededRandom: seededRandom,
  400. degToRad: degToRad,
  401. radToDeg: radToDeg,
  402. isPowerOfTwo: isPowerOfTwo,
  403. ceilPowerOfTwo: ceilPowerOfTwo,
  404. floorPowerOfTwo: floorPowerOfTwo,
  405. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  406. });
  407. class Vector2 {
  408. constructor( x = 0, y = 0 ) {
  409. this.x = x;
  410. this.y = y;
  411. }
  412. get width() {
  413. return this.x;
  414. }
  415. set width( value ) {
  416. this.x = value;
  417. }
  418. get height() {
  419. return this.y;
  420. }
  421. set height( value ) {
  422. this.y = value;
  423. }
  424. set( x, y ) {
  425. this.x = x;
  426. this.y = y;
  427. return this;
  428. }
  429. setScalar( scalar ) {
  430. this.x = scalar;
  431. this.y = scalar;
  432. return this;
  433. }
  434. setX( x ) {
  435. this.x = x;
  436. return this;
  437. }
  438. setY( y ) {
  439. this.y = y;
  440. return this;
  441. }
  442. setComponent( index, value ) {
  443. switch ( index ) {
  444. case 0: this.x = value; break;
  445. case 1: this.y = value; break;
  446. default: throw new Error( 'index is out of range: ' + index );
  447. }
  448. return this;
  449. }
  450. getComponent( index ) {
  451. switch ( index ) {
  452. case 0: return this.x;
  453. case 1: return this.y;
  454. default: throw new Error( 'index is out of range: ' + index );
  455. }
  456. }
  457. clone() {
  458. return new this.constructor( this.x, this.y );
  459. }
  460. copy( v ) {
  461. this.x = v.x;
  462. this.y = v.y;
  463. return this;
  464. }
  465. add( v, w ) {
  466. if ( w !== undefined ) {
  467. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  468. return this.addVectors( v, w );
  469. }
  470. this.x += v.x;
  471. this.y += v.y;
  472. return this;
  473. }
  474. addScalar( s ) {
  475. this.x += s;
  476. this.y += s;
  477. return this;
  478. }
  479. addVectors( a, b ) {
  480. this.x = a.x + b.x;
  481. this.y = a.y + b.y;
  482. return this;
  483. }
  484. addScaledVector( v, s ) {
  485. this.x += v.x * s;
  486. this.y += v.y * s;
  487. return this;
  488. }
  489. sub( v, w ) {
  490. if ( w !== undefined ) {
  491. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  492. return this.subVectors( v, w );
  493. }
  494. this.x -= v.x;
  495. this.y -= v.y;
  496. return this;
  497. }
  498. subScalar( s ) {
  499. this.x -= s;
  500. this.y -= s;
  501. return this;
  502. }
  503. subVectors( a, b ) {
  504. this.x = a.x - b.x;
  505. this.y = a.y - b.y;
  506. return this;
  507. }
  508. multiply( v ) {
  509. this.x *= v.x;
  510. this.y *= v.y;
  511. return this;
  512. }
  513. multiplyScalar( scalar ) {
  514. this.x *= scalar;
  515. this.y *= scalar;
  516. return this;
  517. }
  518. divide( v ) {
  519. this.x /= v.x;
  520. this.y /= v.y;
  521. return this;
  522. }
  523. divideScalar( scalar ) {
  524. return this.multiplyScalar( 1 / scalar );
  525. }
  526. applyMatrix3( m ) {
  527. const x = this.x, y = this.y;
  528. const e = m.elements;
  529. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  530. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  531. return this;
  532. }
  533. min( v ) {
  534. this.x = Math.min( this.x, v.x );
  535. this.y = Math.min( this.y, v.y );
  536. return this;
  537. }
  538. max( v ) {
  539. this.x = Math.max( this.x, v.x );
  540. this.y = Math.max( this.y, v.y );
  541. return this;
  542. }
  543. clamp( min, max ) {
  544. // assumes min < max, componentwise
  545. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  546. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  547. return this;
  548. }
  549. clampScalar( minVal, maxVal ) {
  550. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  551. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  552. return this;
  553. }
  554. clampLength( min, max ) {
  555. const length = this.length();
  556. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  557. }
  558. floor() {
  559. this.x = Math.floor( this.x );
  560. this.y = Math.floor( this.y );
  561. return this;
  562. }
  563. ceil() {
  564. this.x = Math.ceil( this.x );
  565. this.y = Math.ceil( this.y );
  566. return this;
  567. }
  568. round() {
  569. this.x = Math.round( this.x );
  570. this.y = Math.round( this.y );
  571. return this;
  572. }
  573. roundToZero() {
  574. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  575. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  576. return this;
  577. }
  578. negate() {
  579. this.x = - this.x;
  580. this.y = - this.y;
  581. return this;
  582. }
  583. dot( v ) {
  584. return this.x * v.x + this.y * v.y;
  585. }
  586. cross( v ) {
  587. return this.x * v.y - this.y * v.x;
  588. }
  589. lengthSq() {
  590. return this.x * this.x + this.y * this.y;
  591. }
  592. length() {
  593. return Math.sqrt( this.x * this.x + this.y * this.y );
  594. }
  595. manhattanLength() {
  596. return Math.abs( this.x ) + Math.abs( this.y );
  597. }
  598. normalize() {
  599. return this.divideScalar( this.length() || 1 );
  600. }
  601. angle() {
  602. // computes the angle in radians with respect to the positive x-axis
  603. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  604. return angle;
  605. }
  606. distanceTo( v ) {
  607. return Math.sqrt( this.distanceToSquared( v ) );
  608. }
  609. distanceToSquared( v ) {
  610. const dx = this.x - v.x, dy = this.y - v.y;
  611. return dx * dx + dy * dy;
  612. }
  613. manhattanDistanceTo( v ) {
  614. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  615. }
  616. setLength( length ) {
  617. return this.normalize().multiplyScalar( length );
  618. }
  619. lerp( v, alpha ) {
  620. this.x += ( v.x - this.x ) * alpha;
  621. this.y += ( v.y - this.y ) * alpha;
  622. return this;
  623. }
  624. lerpVectors( v1, v2, alpha ) {
  625. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  626. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  627. return this;
  628. }
  629. equals( v ) {
  630. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  631. }
  632. fromArray( array, offset = 0 ) {
  633. this.x = array[ offset ];
  634. this.y = array[ offset + 1 ];
  635. return this;
  636. }
  637. toArray( array = [], offset = 0 ) {
  638. array[ offset ] = this.x;
  639. array[ offset + 1 ] = this.y;
  640. return array;
  641. }
  642. fromBufferAttribute( attribute, index, offset ) {
  643. if ( offset !== undefined ) {
  644. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  645. }
  646. this.x = attribute.getX( index );
  647. this.y = attribute.getY( index );
  648. return this;
  649. }
  650. rotateAround( center, angle ) {
  651. const c = Math.cos( angle ), s = Math.sin( angle );
  652. const x = this.x - center.x;
  653. const y = this.y - center.y;
  654. this.x = x * c - y * s + center.x;
  655. this.y = x * s + y * c + center.y;
  656. return this;
  657. }
  658. random() {
  659. this.x = Math.random();
  660. this.y = Math.random();
  661. return this;
  662. }
  663. }
  664. Vector2.prototype.isVector2 = true;
  665. class Matrix3 {
  666. constructor() {
  667. this.elements = [
  668. 1, 0, 0,
  669. 0, 1, 0,
  670. 0, 0, 1
  671. ];
  672. if ( arguments.length > 0 ) {
  673. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  674. }
  675. }
  676. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  677. const te = this.elements;
  678. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  679. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  680. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  681. return this;
  682. }
  683. identity() {
  684. this.set(
  685. 1, 0, 0,
  686. 0, 1, 0,
  687. 0, 0, 1
  688. );
  689. return this;
  690. }
  691. copy( m ) {
  692. const te = this.elements;
  693. const me = m.elements;
  694. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  695. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  696. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  697. return this;
  698. }
  699. extractBasis( xAxis, yAxis, zAxis ) {
  700. xAxis.setFromMatrix3Column( this, 0 );
  701. yAxis.setFromMatrix3Column( this, 1 );
  702. zAxis.setFromMatrix3Column( this, 2 );
  703. return this;
  704. }
  705. setFromMatrix4( m ) {
  706. const me = m.elements;
  707. this.set(
  708. me[ 0 ], me[ 4 ], me[ 8 ],
  709. me[ 1 ], me[ 5 ], me[ 9 ],
  710. me[ 2 ], me[ 6 ], me[ 10 ]
  711. );
  712. return this;
  713. }
  714. multiply( m ) {
  715. return this.multiplyMatrices( this, m );
  716. }
  717. premultiply( m ) {
  718. return this.multiplyMatrices( m, this );
  719. }
  720. multiplyMatrices( a, b ) {
  721. const ae = a.elements;
  722. const be = b.elements;
  723. const te = this.elements;
  724. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  725. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  726. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  727. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  728. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  729. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  730. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  731. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  732. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  733. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  734. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  735. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  736. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  737. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  738. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  739. return this;
  740. }
  741. multiplyScalar( s ) {
  742. const te = this.elements;
  743. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  744. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  745. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  746. return this;
  747. }
  748. determinant() {
  749. const te = this.elements;
  750. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  751. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  752. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  753. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  754. }
  755. invert() {
  756. const te = this.elements,
  757. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  758. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  759. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  760. t11 = n33 * n22 - n32 * n23,
  761. t12 = n32 * n13 - n33 * n12,
  762. t13 = n23 * n12 - n22 * n13,
  763. det = n11 * t11 + n21 * t12 + n31 * t13;
  764. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  765. const detInv = 1 / det;
  766. te[ 0 ] = t11 * detInv;
  767. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  768. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  769. te[ 3 ] = t12 * detInv;
  770. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  771. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  772. te[ 6 ] = t13 * detInv;
  773. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  774. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  775. return this;
  776. }
  777. transpose() {
  778. let tmp;
  779. const m = this.elements;
  780. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  781. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  782. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  783. return this;
  784. }
  785. getNormalMatrix( matrix4 ) {
  786. return this.setFromMatrix4( matrix4 ).invert().transpose();
  787. }
  788. transposeIntoArray( r ) {
  789. const m = this.elements;
  790. r[ 0 ] = m[ 0 ];
  791. r[ 1 ] = m[ 3 ];
  792. r[ 2 ] = m[ 6 ];
  793. r[ 3 ] = m[ 1 ];
  794. r[ 4 ] = m[ 4 ];
  795. r[ 5 ] = m[ 7 ];
  796. r[ 6 ] = m[ 2 ];
  797. r[ 7 ] = m[ 5 ];
  798. r[ 8 ] = m[ 8 ];
  799. return this;
  800. }
  801. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  802. const c = Math.cos( rotation );
  803. const s = Math.sin( rotation );
  804. this.set(
  805. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  806. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  807. 0, 0, 1
  808. );
  809. return this;
  810. }
  811. scale( sx, sy ) {
  812. const te = this.elements;
  813. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  814. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  815. return this;
  816. }
  817. rotate( theta ) {
  818. const c = Math.cos( theta );
  819. const s = Math.sin( theta );
  820. const te = this.elements;
  821. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  822. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  823. te[ 0 ] = c * a11 + s * a21;
  824. te[ 3 ] = c * a12 + s * a22;
  825. te[ 6 ] = c * a13 + s * a23;
  826. te[ 1 ] = - s * a11 + c * a21;
  827. te[ 4 ] = - s * a12 + c * a22;
  828. te[ 7 ] = - s * a13 + c * a23;
  829. return this;
  830. }
  831. translate( tx, ty ) {
  832. const te = this.elements;
  833. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  834. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  835. return this;
  836. }
  837. equals( matrix ) {
  838. const te = this.elements;
  839. const me = matrix.elements;
  840. for ( let i = 0; i < 9; i ++ ) {
  841. if ( te[ i ] !== me[ i ] ) return false;
  842. }
  843. return true;
  844. }
  845. fromArray( array, offset = 0 ) {
  846. for ( let i = 0; i < 9; i ++ ) {
  847. this.elements[ i ] = array[ i + offset ];
  848. }
  849. return this;
  850. }
  851. toArray( array = [], offset = 0 ) {
  852. const te = this.elements;
  853. array[ offset ] = te[ 0 ];
  854. array[ offset + 1 ] = te[ 1 ];
  855. array[ offset + 2 ] = te[ 2 ];
  856. array[ offset + 3 ] = te[ 3 ];
  857. array[ offset + 4 ] = te[ 4 ];
  858. array[ offset + 5 ] = te[ 5 ];
  859. array[ offset + 6 ] = te[ 6 ];
  860. array[ offset + 7 ] = te[ 7 ];
  861. array[ offset + 8 ] = te[ 8 ];
  862. return array;
  863. }
  864. clone() {
  865. return new this.constructor().fromArray( this.elements );
  866. }
  867. }
  868. Matrix3.prototype.isMatrix3 = true;
  869. let _canvas;
  870. class ImageUtils {
  871. static getDataURL( image ) {
  872. if ( /^data:/i.test( image.src ) ) {
  873. return image.src;
  874. }
  875. if ( typeof HTMLCanvasElement == 'undefined' ) {
  876. return image.src;
  877. }
  878. let canvas;
  879. if ( image instanceof HTMLCanvasElement ) {
  880. canvas = image;
  881. } else {
  882. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  883. _canvas.width = image.width;
  884. _canvas.height = image.height;
  885. const context = _canvas.getContext( '2d' );
  886. if ( image instanceof ImageData ) {
  887. context.putImageData( image, 0, 0 );
  888. } else {
  889. context.drawImage( image, 0, 0, image.width, image.height );
  890. }
  891. canvas = _canvas;
  892. }
  893. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  894. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  895. return canvas.toDataURL( 'image/jpeg', 0.6 );
  896. } else {
  897. return canvas.toDataURL( 'image/png' );
  898. }
  899. }
  900. }
  901. let textureId = 0;
  902. class Texture extends EventDispatcher {
  903. 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 ) {
  904. super();
  905. Object.defineProperty( this, 'id', { value: textureId ++ } );
  906. this.uuid = generateUUID();
  907. this.name = '';
  908. this.image = image;
  909. this.mipmaps = [];
  910. this.mapping = mapping;
  911. this.wrapS = wrapS;
  912. this.wrapT = wrapT;
  913. this.magFilter = magFilter;
  914. this.minFilter = minFilter;
  915. this.anisotropy = anisotropy;
  916. this.format = format;
  917. this.internalFormat = null;
  918. this.type = type;
  919. this.offset = new Vector2( 0, 0 );
  920. this.repeat = new Vector2( 1, 1 );
  921. this.center = new Vector2( 0, 0 );
  922. this.rotation = 0;
  923. this.matrixAutoUpdate = true;
  924. this.matrix = new Matrix3();
  925. this.generateMipmaps = true;
  926. this.premultiplyAlpha = false;
  927. this.flipY = true;
  928. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  929. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  930. //
  931. // Also changing the encoding after already used by a Material will not automatically make the Material
  932. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  933. this.encoding = encoding;
  934. this.version = 0;
  935. this.onUpdate = null;
  936. }
  937. updateMatrix() {
  938. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  939. }
  940. clone() {
  941. return new this.constructor().copy( this );
  942. }
  943. copy( source ) {
  944. this.name = source.name;
  945. this.image = source.image;
  946. this.mipmaps = source.mipmaps.slice( 0 );
  947. this.mapping = source.mapping;
  948. this.wrapS = source.wrapS;
  949. this.wrapT = source.wrapT;
  950. this.magFilter = source.magFilter;
  951. this.minFilter = source.minFilter;
  952. this.anisotropy = source.anisotropy;
  953. this.format = source.format;
  954. this.internalFormat = source.internalFormat;
  955. this.type = source.type;
  956. this.offset.copy( source.offset );
  957. this.repeat.copy( source.repeat );
  958. this.center.copy( source.center );
  959. this.rotation = source.rotation;
  960. this.matrixAutoUpdate = source.matrixAutoUpdate;
  961. this.matrix.copy( source.matrix );
  962. this.generateMipmaps = source.generateMipmaps;
  963. this.premultiplyAlpha = source.premultiplyAlpha;
  964. this.flipY = source.flipY;
  965. this.unpackAlignment = source.unpackAlignment;
  966. this.encoding = source.encoding;
  967. return this;
  968. }
  969. toJSON( meta ) {
  970. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  971. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  972. return meta.textures[ this.uuid ];
  973. }
  974. const output = {
  975. metadata: {
  976. version: 4.5,
  977. type: 'Texture',
  978. generator: 'Texture.toJSON'
  979. },
  980. uuid: this.uuid,
  981. name: this.name,
  982. mapping: this.mapping,
  983. repeat: [ this.repeat.x, this.repeat.y ],
  984. offset: [ this.offset.x, this.offset.y ],
  985. center: [ this.center.x, this.center.y ],
  986. rotation: this.rotation,
  987. wrap: [ this.wrapS, this.wrapT ],
  988. format: this.format,
  989. type: this.type,
  990. encoding: this.encoding,
  991. minFilter: this.minFilter,
  992. magFilter: this.magFilter,
  993. anisotropy: this.anisotropy,
  994. flipY: this.flipY,
  995. premultiplyAlpha: this.premultiplyAlpha,
  996. unpackAlignment: this.unpackAlignment
  997. };
  998. if ( this.image !== undefined ) {
  999. // TODO: Move to THREE.Image
  1000. const image = this.image;
  1001. if ( image.uuid === undefined ) {
  1002. image.uuid = generateUUID(); // UGH
  1003. }
  1004. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1005. let url;
  1006. if ( Array.isArray( image ) ) {
  1007. // process array of images e.g. CubeTexture
  1008. url = [];
  1009. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1010. // check cube texture with data textures
  1011. if ( image[ i ].isDataTexture ) {
  1012. url.push( serializeImage( image[ i ].image ) );
  1013. } else {
  1014. url.push( serializeImage( image[ i ] ) );
  1015. }
  1016. }
  1017. } else {
  1018. // process single image
  1019. url = serializeImage( image );
  1020. }
  1021. meta.images[ image.uuid ] = {
  1022. uuid: image.uuid,
  1023. url: url
  1024. };
  1025. }
  1026. output.image = image.uuid;
  1027. }
  1028. if ( ! isRootObject ) {
  1029. meta.textures[ this.uuid ] = output;
  1030. }
  1031. return output;
  1032. }
  1033. dispose() {
  1034. this.dispatchEvent( { type: 'dispose' } );
  1035. }
  1036. transformUv( uv ) {
  1037. if ( this.mapping !== UVMapping ) return uv;
  1038. uv.applyMatrix3( this.matrix );
  1039. if ( uv.x < 0 || uv.x > 1 ) {
  1040. switch ( this.wrapS ) {
  1041. case RepeatWrapping:
  1042. uv.x = uv.x - Math.floor( uv.x );
  1043. break;
  1044. case ClampToEdgeWrapping:
  1045. uv.x = uv.x < 0 ? 0 : 1;
  1046. break;
  1047. case MirroredRepeatWrapping:
  1048. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1049. uv.x = Math.ceil( uv.x ) - uv.x;
  1050. } else {
  1051. uv.x = uv.x - Math.floor( uv.x );
  1052. }
  1053. break;
  1054. }
  1055. }
  1056. if ( uv.y < 0 || uv.y > 1 ) {
  1057. switch ( this.wrapT ) {
  1058. case RepeatWrapping:
  1059. uv.y = uv.y - Math.floor( uv.y );
  1060. break;
  1061. case ClampToEdgeWrapping:
  1062. uv.y = uv.y < 0 ? 0 : 1;
  1063. break;
  1064. case MirroredRepeatWrapping:
  1065. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1066. uv.y = Math.ceil( uv.y ) - uv.y;
  1067. } else {
  1068. uv.y = uv.y - Math.floor( uv.y );
  1069. }
  1070. break;
  1071. }
  1072. }
  1073. if ( this.flipY ) {
  1074. uv.y = 1 - uv.y;
  1075. }
  1076. return uv;
  1077. }
  1078. set needsUpdate( value ) {
  1079. if ( value === true ) this.version ++;
  1080. }
  1081. }
  1082. Texture.DEFAULT_IMAGE = undefined;
  1083. Texture.DEFAULT_MAPPING = UVMapping;
  1084. Texture.prototype.isTexture = true;
  1085. function serializeImage( image ) {
  1086. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1087. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1088. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1089. // default images
  1090. return ImageUtils.getDataURL( image );
  1091. } else {
  1092. if ( image.data ) {
  1093. // images of DataTexture
  1094. return {
  1095. data: Array.prototype.slice.call( image.data ),
  1096. width: image.width,
  1097. height: image.height,
  1098. type: image.data.constructor.name
  1099. };
  1100. } else {
  1101. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1102. return {};
  1103. }
  1104. }
  1105. }
  1106. class Vector4 {
  1107. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1108. this.x = x;
  1109. this.y = y;
  1110. this.z = z;
  1111. this.w = w;
  1112. }
  1113. get width() {
  1114. return this.z;
  1115. }
  1116. set width( value ) {
  1117. this.z = value;
  1118. }
  1119. get height() {
  1120. return this.w;
  1121. }
  1122. set height( value ) {
  1123. this.w = value;
  1124. }
  1125. set( x, y, z, w ) {
  1126. this.x = x;
  1127. this.y = y;
  1128. this.z = z;
  1129. this.w = w;
  1130. return this;
  1131. }
  1132. setScalar( scalar ) {
  1133. this.x = scalar;
  1134. this.y = scalar;
  1135. this.z = scalar;
  1136. this.w = scalar;
  1137. return this;
  1138. }
  1139. setX( x ) {
  1140. this.x = x;
  1141. return this;
  1142. }
  1143. setY( y ) {
  1144. this.y = y;
  1145. return this;
  1146. }
  1147. setZ( z ) {
  1148. this.z = z;
  1149. return this;
  1150. }
  1151. setW( w ) {
  1152. this.w = w;
  1153. return this;
  1154. }
  1155. setComponent( index, value ) {
  1156. switch ( index ) {
  1157. case 0: this.x = value; break;
  1158. case 1: this.y = value; break;
  1159. case 2: this.z = value; break;
  1160. case 3: this.w = value; break;
  1161. default: throw new Error( 'index is out of range: ' + index );
  1162. }
  1163. return this;
  1164. }
  1165. getComponent( index ) {
  1166. switch ( index ) {
  1167. case 0: return this.x;
  1168. case 1: return this.y;
  1169. case 2: return this.z;
  1170. case 3: return this.w;
  1171. default: throw new Error( 'index is out of range: ' + index );
  1172. }
  1173. }
  1174. clone() {
  1175. return new this.constructor( this.x, this.y, this.z, this.w );
  1176. }
  1177. copy( v ) {
  1178. this.x = v.x;
  1179. this.y = v.y;
  1180. this.z = v.z;
  1181. this.w = ( v.w !== undefined ) ? v.w : 1;
  1182. return this;
  1183. }
  1184. add( v, w ) {
  1185. if ( w !== undefined ) {
  1186. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1187. return this.addVectors( v, w );
  1188. }
  1189. this.x += v.x;
  1190. this.y += v.y;
  1191. this.z += v.z;
  1192. this.w += v.w;
  1193. return this;
  1194. }
  1195. addScalar( s ) {
  1196. this.x += s;
  1197. this.y += s;
  1198. this.z += s;
  1199. this.w += s;
  1200. return this;
  1201. }
  1202. addVectors( a, b ) {
  1203. this.x = a.x + b.x;
  1204. this.y = a.y + b.y;
  1205. this.z = a.z + b.z;
  1206. this.w = a.w + b.w;
  1207. return this;
  1208. }
  1209. addScaledVector( v, s ) {
  1210. this.x += v.x * s;
  1211. this.y += v.y * s;
  1212. this.z += v.z * s;
  1213. this.w += v.w * s;
  1214. return this;
  1215. }
  1216. sub( v, w ) {
  1217. if ( w !== undefined ) {
  1218. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1219. return this.subVectors( v, w );
  1220. }
  1221. this.x -= v.x;
  1222. this.y -= v.y;
  1223. this.z -= v.z;
  1224. this.w -= v.w;
  1225. return this;
  1226. }
  1227. subScalar( s ) {
  1228. this.x -= s;
  1229. this.y -= s;
  1230. this.z -= s;
  1231. this.w -= s;
  1232. return this;
  1233. }
  1234. subVectors( a, b ) {
  1235. this.x = a.x - b.x;
  1236. this.y = a.y - b.y;
  1237. this.z = a.z - b.z;
  1238. this.w = a.w - b.w;
  1239. return this;
  1240. }
  1241. multiply( v ) {
  1242. this.x *= v.x;
  1243. this.y *= v.y;
  1244. this.z *= v.z;
  1245. this.w *= v.w;
  1246. return this;
  1247. }
  1248. multiplyScalar( scalar ) {
  1249. this.x *= scalar;
  1250. this.y *= scalar;
  1251. this.z *= scalar;
  1252. this.w *= scalar;
  1253. return this;
  1254. }
  1255. applyMatrix4( m ) {
  1256. const x = this.x, y = this.y, z = this.z, w = this.w;
  1257. const e = m.elements;
  1258. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1259. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1260. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1261. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1262. return this;
  1263. }
  1264. divideScalar( scalar ) {
  1265. return this.multiplyScalar( 1 / scalar );
  1266. }
  1267. setAxisAngleFromQuaternion( q ) {
  1268. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1269. // q is assumed to be normalized
  1270. this.w = 2 * Math.acos( q.w );
  1271. const s = Math.sqrt( 1 - q.w * q.w );
  1272. if ( s < 0.0001 ) {
  1273. this.x = 1;
  1274. this.y = 0;
  1275. this.z = 0;
  1276. } else {
  1277. this.x = q.x / s;
  1278. this.y = q.y / s;
  1279. this.z = q.z / s;
  1280. }
  1281. return this;
  1282. }
  1283. setAxisAngleFromRotationMatrix( m ) {
  1284. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1285. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1286. let angle, x, y, z; // variables for result
  1287. const epsilon = 0.01, // margin to allow for rounding errors
  1288. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1289. te = m.elements,
  1290. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1291. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1292. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1293. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1294. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1295. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1296. // singularity found
  1297. // first check for identity matrix which must have +1 for all terms
  1298. // in leading diagonal and zero in other terms
  1299. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1300. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1301. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1302. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1303. // this singularity is identity matrix so angle = 0
  1304. this.set( 1, 0, 0, 0 );
  1305. return this; // zero angle, arbitrary axis
  1306. }
  1307. // otherwise this singularity is angle = 180
  1308. angle = Math.PI;
  1309. const xx = ( m11 + 1 ) / 2;
  1310. const yy = ( m22 + 1 ) / 2;
  1311. const zz = ( m33 + 1 ) / 2;
  1312. const xy = ( m12 + m21 ) / 4;
  1313. const xz = ( m13 + m31 ) / 4;
  1314. const yz = ( m23 + m32 ) / 4;
  1315. if ( ( xx > yy ) && ( xx > zz ) ) {
  1316. // m11 is the largest diagonal term
  1317. if ( xx < epsilon ) {
  1318. x = 0;
  1319. y = 0.707106781;
  1320. z = 0.707106781;
  1321. } else {
  1322. x = Math.sqrt( xx );
  1323. y = xy / x;
  1324. z = xz / x;
  1325. }
  1326. } else if ( yy > zz ) {
  1327. // m22 is the largest diagonal term
  1328. if ( yy < epsilon ) {
  1329. x = 0.707106781;
  1330. y = 0;
  1331. z = 0.707106781;
  1332. } else {
  1333. y = Math.sqrt( yy );
  1334. x = xy / y;
  1335. z = yz / y;
  1336. }
  1337. } else {
  1338. // m33 is the largest diagonal term so base result on this
  1339. if ( zz < epsilon ) {
  1340. x = 0.707106781;
  1341. y = 0.707106781;
  1342. z = 0;
  1343. } else {
  1344. z = Math.sqrt( zz );
  1345. x = xz / z;
  1346. y = yz / z;
  1347. }
  1348. }
  1349. this.set( x, y, z, angle );
  1350. return this; // return 180 deg rotation
  1351. }
  1352. // as we have reached here there are no singularities so we can handle normally
  1353. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1354. ( m13 - m31 ) * ( m13 - m31 ) +
  1355. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1356. if ( Math.abs( s ) < 0.001 ) s = 1;
  1357. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1358. // caught by singularity test above, but I've left it in just in case
  1359. this.x = ( m32 - m23 ) / s;
  1360. this.y = ( m13 - m31 ) / s;
  1361. this.z = ( m21 - m12 ) / s;
  1362. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1363. return this;
  1364. }
  1365. min( v ) {
  1366. this.x = Math.min( this.x, v.x );
  1367. this.y = Math.min( this.y, v.y );
  1368. this.z = Math.min( this.z, v.z );
  1369. this.w = Math.min( this.w, v.w );
  1370. return this;
  1371. }
  1372. max( v ) {
  1373. this.x = Math.max( this.x, v.x );
  1374. this.y = Math.max( this.y, v.y );
  1375. this.z = Math.max( this.z, v.z );
  1376. this.w = Math.max( this.w, v.w );
  1377. return this;
  1378. }
  1379. clamp( min, max ) {
  1380. // assumes min < max, componentwise
  1381. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1382. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1383. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1384. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1385. return this;
  1386. }
  1387. clampScalar( minVal, maxVal ) {
  1388. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1389. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1390. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1391. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1392. return this;
  1393. }
  1394. clampLength( min, max ) {
  1395. const length = this.length();
  1396. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1397. }
  1398. floor() {
  1399. this.x = Math.floor( this.x );
  1400. this.y = Math.floor( this.y );
  1401. this.z = Math.floor( this.z );
  1402. this.w = Math.floor( this.w );
  1403. return this;
  1404. }
  1405. ceil() {
  1406. this.x = Math.ceil( this.x );
  1407. this.y = Math.ceil( this.y );
  1408. this.z = Math.ceil( this.z );
  1409. this.w = Math.ceil( this.w );
  1410. return this;
  1411. }
  1412. round() {
  1413. this.x = Math.round( this.x );
  1414. this.y = Math.round( this.y );
  1415. this.z = Math.round( this.z );
  1416. this.w = Math.round( this.w );
  1417. return this;
  1418. }
  1419. roundToZero() {
  1420. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1421. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1422. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1423. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1424. return this;
  1425. }
  1426. negate() {
  1427. this.x = - this.x;
  1428. this.y = - this.y;
  1429. this.z = - this.z;
  1430. this.w = - this.w;
  1431. return this;
  1432. }
  1433. dot( v ) {
  1434. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1435. }
  1436. lengthSq() {
  1437. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1438. }
  1439. length() {
  1440. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1441. }
  1442. manhattanLength() {
  1443. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1444. }
  1445. normalize() {
  1446. return this.divideScalar( this.length() || 1 );
  1447. }
  1448. setLength( length ) {
  1449. return this.normalize().multiplyScalar( length );
  1450. }
  1451. lerp( v, alpha ) {
  1452. this.x += ( v.x - this.x ) * alpha;
  1453. this.y += ( v.y - this.y ) * alpha;
  1454. this.z += ( v.z - this.z ) * alpha;
  1455. this.w += ( v.w - this.w ) * alpha;
  1456. return this;
  1457. }
  1458. lerpVectors( v1, v2, alpha ) {
  1459. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1460. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1461. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1462. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1463. return this;
  1464. }
  1465. equals( v ) {
  1466. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1467. }
  1468. fromArray( array, offset = 0 ) {
  1469. this.x = array[ offset ];
  1470. this.y = array[ offset + 1 ];
  1471. this.z = array[ offset + 2 ];
  1472. this.w = array[ offset + 3 ];
  1473. return this;
  1474. }
  1475. toArray( array = [], offset = 0 ) {
  1476. array[ offset ] = this.x;
  1477. array[ offset + 1 ] = this.y;
  1478. array[ offset + 2 ] = this.z;
  1479. array[ offset + 3 ] = this.w;
  1480. return array;
  1481. }
  1482. fromBufferAttribute( attribute, index, offset ) {
  1483. if ( offset !== undefined ) {
  1484. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1485. }
  1486. this.x = attribute.getX( index );
  1487. this.y = attribute.getY( index );
  1488. this.z = attribute.getZ( index );
  1489. this.w = attribute.getW( index );
  1490. return this;
  1491. }
  1492. random() {
  1493. this.x = Math.random();
  1494. this.y = Math.random();
  1495. this.z = Math.random();
  1496. this.w = Math.random();
  1497. return this;
  1498. }
  1499. }
  1500. Vector4.prototype.isVector4 = true;
  1501. /*
  1502. In options, we can specify:
  1503. * Texture parameters for an auto-generated target texture
  1504. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1505. */
  1506. class WebGLRenderTarget extends EventDispatcher {
  1507. constructor( width, height, options ) {
  1508. super();
  1509. this.width = width;
  1510. this.height = height;
  1511. this.depth = 1;
  1512. this.scissor = new Vector4( 0, 0, width, height );
  1513. this.scissorTest = false;
  1514. this.viewport = new Vector4( 0, 0, width, height );
  1515. options = options || {};
  1516. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1517. this.texture.image = {};
  1518. this.texture.image.width = width;
  1519. this.texture.image.height = height;
  1520. this.texture.image.depth = 1;
  1521. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1522. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1523. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1524. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1525. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1526. }
  1527. setTexture( texture ) {
  1528. texture.image = {
  1529. width: this.width,
  1530. height: this.height,
  1531. depth: this.depth
  1532. };
  1533. this.texture = texture;
  1534. }
  1535. setSize( width, height, depth = 1 ) {
  1536. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1537. this.width = width;
  1538. this.height = height;
  1539. this.depth = depth;
  1540. this.texture.image.width = width;
  1541. this.texture.image.height = height;
  1542. this.texture.image.depth = depth;
  1543. this.dispose();
  1544. }
  1545. this.viewport.set( 0, 0, width, height );
  1546. this.scissor.set( 0, 0, width, height );
  1547. }
  1548. clone() {
  1549. return new this.constructor().copy( this );
  1550. }
  1551. copy( source ) {
  1552. this.width = source.width;
  1553. this.height = source.height;
  1554. this.depth = source.depth;
  1555. this.viewport.copy( source.viewport );
  1556. this.texture = source.texture.clone();
  1557. this.texture.image = { ...this.texture.image }; // See #20328.
  1558. this.depthBuffer = source.depthBuffer;
  1559. this.stencilBuffer = source.stencilBuffer;
  1560. this.depthTexture = source.depthTexture;
  1561. return this;
  1562. }
  1563. dispose() {
  1564. this.dispatchEvent( { type: 'dispose' } );
  1565. }
  1566. }
  1567. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1568. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1569. constructor( width, height, count ) {
  1570. super( width, height );
  1571. const texture = this.texture;
  1572. this.texture = [];
  1573. for ( let i = 0; i < count; i ++ ) {
  1574. this.texture[ i ] = texture.clone();
  1575. }
  1576. }
  1577. setSize( width, height, depth = 1 ) {
  1578. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1579. this.width = width;
  1580. this.height = height;
  1581. this.depth = depth;
  1582. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1583. this.texture[ i ].image.width = width;
  1584. this.texture[ i ].image.height = height;
  1585. this.texture[ i ].image.depth = depth;
  1586. }
  1587. this.dispose();
  1588. }
  1589. this.viewport.set( 0, 0, width, height );
  1590. this.scissor.set( 0, 0, width, height );
  1591. return this;
  1592. }
  1593. copy( source ) {
  1594. this.dispose();
  1595. this.width = source.width;
  1596. this.height = source.height;
  1597. this.depth = source.depth;
  1598. this.viewport.set( 0, 0, this.width, this.height );
  1599. this.scissor.set( 0, 0, this.width, this.height );
  1600. this.depthBuffer = source.depthBuffer;
  1601. this.stencilBuffer = source.stencilBuffer;
  1602. this.depthTexture = source.depthTexture;
  1603. this.texture.length = 0;
  1604. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1605. this.texture[ i ] = source.texture[ i ].clone();
  1606. }
  1607. return this;
  1608. }
  1609. }
  1610. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1611. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1612. constructor( width, height, options ) {
  1613. super( width, height, options );
  1614. this.samples = 4;
  1615. }
  1616. copy( source ) {
  1617. super.copy.call( this, source );
  1618. this.samples = source.samples;
  1619. return this;
  1620. }
  1621. }
  1622. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1623. class Quaternion {
  1624. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1625. this._x = x;
  1626. this._y = y;
  1627. this._z = z;
  1628. this._w = w;
  1629. }
  1630. static slerp( qa, qb, qm, t ) {
  1631. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  1632. return qm.slerpQuaternions( qa, qb, t );
  1633. }
  1634. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1635. // fuzz-free, array-based Quaternion SLERP operation
  1636. let x0 = src0[ srcOffset0 + 0 ],
  1637. y0 = src0[ srcOffset0 + 1 ],
  1638. z0 = src0[ srcOffset0 + 2 ],
  1639. w0 = src0[ srcOffset0 + 3 ];
  1640. const x1 = src1[ srcOffset1 + 0 ],
  1641. y1 = src1[ srcOffset1 + 1 ],
  1642. z1 = src1[ srcOffset1 + 2 ],
  1643. w1 = src1[ srcOffset1 + 3 ];
  1644. if ( t === 0 ) {
  1645. dst[ dstOffset + 0 ] = x0;
  1646. dst[ dstOffset + 1 ] = y0;
  1647. dst[ dstOffset + 2 ] = z0;
  1648. dst[ dstOffset + 3 ] = w0;
  1649. return;
  1650. }
  1651. if ( t === 1 ) {
  1652. dst[ dstOffset + 0 ] = x1;
  1653. dst[ dstOffset + 1 ] = y1;
  1654. dst[ dstOffset + 2 ] = z1;
  1655. dst[ dstOffset + 3 ] = w1;
  1656. return;
  1657. }
  1658. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1659. let s = 1 - t;
  1660. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1661. dir = ( cos >= 0 ? 1 : - 1 ),
  1662. sqrSin = 1 - cos * cos;
  1663. // Skip the Slerp for tiny steps to avoid numeric problems:
  1664. if ( sqrSin > Number.EPSILON ) {
  1665. const sin = Math.sqrt( sqrSin ),
  1666. len = Math.atan2( sin, cos * dir );
  1667. s = Math.sin( s * len ) / sin;
  1668. t = Math.sin( t * len ) / sin;
  1669. }
  1670. const tDir = t * dir;
  1671. x0 = x0 * s + x1 * tDir;
  1672. y0 = y0 * s + y1 * tDir;
  1673. z0 = z0 * s + z1 * tDir;
  1674. w0 = w0 * s + w1 * tDir;
  1675. // Normalize in case we just did a lerp:
  1676. if ( s === 1 - t ) {
  1677. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1678. x0 *= f;
  1679. y0 *= f;
  1680. z0 *= f;
  1681. w0 *= f;
  1682. }
  1683. }
  1684. dst[ dstOffset ] = x0;
  1685. dst[ dstOffset + 1 ] = y0;
  1686. dst[ dstOffset + 2 ] = z0;
  1687. dst[ dstOffset + 3 ] = w0;
  1688. }
  1689. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1690. const x0 = src0[ srcOffset0 ];
  1691. const y0 = src0[ srcOffset0 + 1 ];
  1692. const z0 = src0[ srcOffset0 + 2 ];
  1693. const w0 = src0[ srcOffset0 + 3 ];
  1694. const x1 = src1[ srcOffset1 ];
  1695. const y1 = src1[ srcOffset1 + 1 ];
  1696. const z1 = src1[ srcOffset1 + 2 ];
  1697. const w1 = src1[ srcOffset1 + 3 ];
  1698. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1699. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1700. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1701. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1702. return dst;
  1703. }
  1704. get x() {
  1705. return this._x;
  1706. }
  1707. set x( value ) {
  1708. this._x = value;
  1709. this._onChangeCallback();
  1710. }
  1711. get y() {
  1712. return this._y;
  1713. }
  1714. set y( value ) {
  1715. this._y = value;
  1716. this._onChangeCallback();
  1717. }
  1718. get z() {
  1719. return this._z;
  1720. }
  1721. set z( value ) {
  1722. this._z = value;
  1723. this._onChangeCallback();
  1724. }
  1725. get w() {
  1726. return this._w;
  1727. }
  1728. set w( value ) {
  1729. this._w = value;
  1730. this._onChangeCallback();
  1731. }
  1732. set( x, y, z, w ) {
  1733. this._x = x;
  1734. this._y = y;
  1735. this._z = z;
  1736. this._w = w;
  1737. this._onChangeCallback();
  1738. return this;
  1739. }
  1740. clone() {
  1741. return new this.constructor( this._x, this._y, this._z, this._w );
  1742. }
  1743. copy( quaternion ) {
  1744. this._x = quaternion.x;
  1745. this._y = quaternion.y;
  1746. this._z = quaternion.z;
  1747. this._w = quaternion.w;
  1748. this._onChangeCallback();
  1749. return this;
  1750. }
  1751. setFromEuler( euler, update ) {
  1752. if ( ! ( euler && euler.isEuler ) ) {
  1753. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1754. }
  1755. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1756. // http://www.mathworks.com/matlabcentral/fileexchange/
  1757. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1758. // content/SpinCalc.m
  1759. const cos = Math.cos;
  1760. const sin = Math.sin;
  1761. const c1 = cos( x / 2 );
  1762. const c2 = cos( y / 2 );
  1763. const c3 = cos( z / 2 );
  1764. const s1 = sin( x / 2 );
  1765. const s2 = sin( y / 2 );
  1766. const s3 = sin( z / 2 );
  1767. switch ( order ) {
  1768. case 'XYZ':
  1769. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1770. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1771. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1772. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1773. break;
  1774. case 'YXZ':
  1775. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1776. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1777. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1778. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1779. break;
  1780. case 'ZXY':
  1781. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1782. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1783. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1784. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1785. break;
  1786. case 'ZYX':
  1787. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1788. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1789. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1790. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1791. break;
  1792. case 'YZX':
  1793. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1794. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1795. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1796. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1797. break;
  1798. case 'XZY':
  1799. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1800. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1801. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1802. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1803. break;
  1804. default:
  1805. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1806. }
  1807. if ( update !== false ) this._onChangeCallback();
  1808. return this;
  1809. }
  1810. setFromAxisAngle( axis, angle ) {
  1811. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1812. // assumes axis is normalized
  1813. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1814. this._x = axis.x * s;
  1815. this._y = axis.y * s;
  1816. this._z = axis.z * s;
  1817. this._w = Math.cos( halfAngle );
  1818. this._onChangeCallback();
  1819. return this;
  1820. }
  1821. setFromRotationMatrix( m ) {
  1822. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1823. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1824. const te = m.elements,
  1825. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1826. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1827. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1828. trace = m11 + m22 + m33;
  1829. if ( trace > 0 ) {
  1830. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1831. this._w = 0.25 / s;
  1832. this._x = ( m32 - m23 ) * s;
  1833. this._y = ( m13 - m31 ) * s;
  1834. this._z = ( m21 - m12 ) * s;
  1835. } else if ( m11 > m22 && m11 > m33 ) {
  1836. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1837. this._w = ( m32 - m23 ) / s;
  1838. this._x = 0.25 * s;
  1839. this._y = ( m12 + m21 ) / s;
  1840. this._z = ( m13 + m31 ) / s;
  1841. } else if ( m22 > m33 ) {
  1842. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1843. this._w = ( m13 - m31 ) / s;
  1844. this._x = ( m12 + m21 ) / s;
  1845. this._y = 0.25 * s;
  1846. this._z = ( m23 + m32 ) / s;
  1847. } else {
  1848. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1849. this._w = ( m21 - m12 ) / s;
  1850. this._x = ( m13 + m31 ) / s;
  1851. this._y = ( m23 + m32 ) / s;
  1852. this._z = 0.25 * s;
  1853. }
  1854. this._onChangeCallback();
  1855. return this;
  1856. }
  1857. setFromUnitVectors( vFrom, vTo ) {
  1858. // assumes direction vectors vFrom and vTo are normalized
  1859. let r = vFrom.dot( vTo ) + 1;
  1860. if ( r < Number.EPSILON ) {
  1861. // vFrom and vTo point in opposite directions
  1862. r = 0;
  1863. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1864. this._x = - vFrom.y;
  1865. this._y = vFrom.x;
  1866. this._z = 0;
  1867. this._w = r;
  1868. } else {
  1869. this._x = 0;
  1870. this._y = - vFrom.z;
  1871. this._z = vFrom.y;
  1872. this._w = r;
  1873. }
  1874. } else {
  1875. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1876. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1877. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1878. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1879. this._w = r;
  1880. }
  1881. return this.normalize();
  1882. }
  1883. angleTo( q ) {
  1884. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1885. }
  1886. rotateTowards( q, step ) {
  1887. const angle = this.angleTo( q );
  1888. if ( angle === 0 ) return this;
  1889. const t = Math.min( 1, step / angle );
  1890. this.slerp( q, t );
  1891. return this;
  1892. }
  1893. identity() {
  1894. return this.set( 0, 0, 0, 1 );
  1895. }
  1896. invert() {
  1897. // quaternion is assumed to have unit length
  1898. return this.conjugate();
  1899. }
  1900. conjugate() {
  1901. this._x *= - 1;
  1902. this._y *= - 1;
  1903. this._z *= - 1;
  1904. this._onChangeCallback();
  1905. return this;
  1906. }
  1907. dot( v ) {
  1908. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1909. }
  1910. lengthSq() {
  1911. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1912. }
  1913. length() {
  1914. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1915. }
  1916. normalize() {
  1917. let l = this.length();
  1918. if ( l === 0 ) {
  1919. this._x = 0;
  1920. this._y = 0;
  1921. this._z = 0;
  1922. this._w = 1;
  1923. } else {
  1924. l = 1 / l;
  1925. this._x = this._x * l;
  1926. this._y = this._y * l;
  1927. this._z = this._z * l;
  1928. this._w = this._w * l;
  1929. }
  1930. this._onChangeCallback();
  1931. return this;
  1932. }
  1933. multiply( q, p ) {
  1934. if ( p !== undefined ) {
  1935. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1936. return this.multiplyQuaternions( q, p );
  1937. }
  1938. return this.multiplyQuaternions( this, q );
  1939. }
  1940. premultiply( q ) {
  1941. return this.multiplyQuaternions( q, this );
  1942. }
  1943. multiplyQuaternions( a, b ) {
  1944. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1945. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1946. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1947. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1948. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1949. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1950. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1951. this._onChangeCallback();
  1952. return this;
  1953. }
  1954. slerp( qb, t ) {
  1955. if ( t === 0 ) return this;
  1956. if ( t === 1 ) return this.copy( qb );
  1957. const x = this._x, y = this._y, z = this._z, w = this._w;
  1958. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1959. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1960. if ( cosHalfTheta < 0 ) {
  1961. this._w = - qb._w;
  1962. this._x = - qb._x;
  1963. this._y = - qb._y;
  1964. this._z = - qb._z;
  1965. cosHalfTheta = - cosHalfTheta;
  1966. } else {
  1967. this.copy( qb );
  1968. }
  1969. if ( cosHalfTheta >= 1.0 ) {
  1970. this._w = w;
  1971. this._x = x;
  1972. this._y = y;
  1973. this._z = z;
  1974. return this;
  1975. }
  1976. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1977. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1978. const s = 1 - t;
  1979. this._w = s * w + t * this._w;
  1980. this._x = s * x + t * this._x;
  1981. this._y = s * y + t * this._y;
  1982. this._z = s * z + t * this._z;
  1983. this.normalize();
  1984. this._onChangeCallback();
  1985. return this;
  1986. }
  1987. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1988. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1989. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1990. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1991. this._w = ( w * ratioA + this._w * ratioB );
  1992. this._x = ( x * ratioA + this._x * ratioB );
  1993. this._y = ( y * ratioA + this._y * ratioB );
  1994. this._z = ( z * ratioA + this._z * ratioB );
  1995. this._onChangeCallback();
  1996. return this;
  1997. }
  1998. slerpQuaternions( qa, qb, t ) {
  1999. this.copy( qa ).slerp( qb, t );
  2000. }
  2001. equals( quaternion ) {
  2002. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2003. }
  2004. fromArray( array, offset = 0 ) {
  2005. this._x = array[ offset ];
  2006. this._y = array[ offset + 1 ];
  2007. this._z = array[ offset + 2 ];
  2008. this._w = array[ offset + 3 ];
  2009. this._onChangeCallback();
  2010. return this;
  2011. }
  2012. toArray( array = [], offset = 0 ) {
  2013. array[ offset ] = this._x;
  2014. array[ offset + 1 ] = this._y;
  2015. array[ offset + 2 ] = this._z;
  2016. array[ offset + 3 ] = this._w;
  2017. return array;
  2018. }
  2019. fromBufferAttribute( attribute, index ) {
  2020. this._x = attribute.getX( index );
  2021. this._y = attribute.getY( index );
  2022. this._z = attribute.getZ( index );
  2023. this._w = attribute.getW( index );
  2024. return this;
  2025. }
  2026. _onChange( callback ) {
  2027. this._onChangeCallback = callback;
  2028. return this;
  2029. }
  2030. _onChangeCallback() {}
  2031. }
  2032. Quaternion.prototype.isQuaternion = true;
  2033. class Vector3 {
  2034. constructor( x = 0, y = 0, z = 0 ) {
  2035. this.x = x;
  2036. this.y = y;
  2037. this.z = z;
  2038. }
  2039. set( x, y, z ) {
  2040. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2041. this.x = x;
  2042. this.y = y;
  2043. this.z = z;
  2044. return this;
  2045. }
  2046. setScalar( scalar ) {
  2047. this.x = scalar;
  2048. this.y = scalar;
  2049. this.z = scalar;
  2050. return this;
  2051. }
  2052. setX( x ) {
  2053. this.x = x;
  2054. return this;
  2055. }
  2056. setY( y ) {
  2057. this.y = y;
  2058. return this;
  2059. }
  2060. setZ( z ) {
  2061. this.z = z;
  2062. return this;
  2063. }
  2064. setComponent( index, value ) {
  2065. switch ( index ) {
  2066. case 0: this.x = value; break;
  2067. case 1: this.y = value; break;
  2068. case 2: this.z = value; break;
  2069. default: throw new Error( 'index is out of range: ' + index );
  2070. }
  2071. return this;
  2072. }
  2073. getComponent( index ) {
  2074. switch ( index ) {
  2075. case 0: return this.x;
  2076. case 1: return this.y;
  2077. case 2: return this.z;
  2078. default: throw new Error( 'index is out of range: ' + index );
  2079. }
  2080. }
  2081. clone() {
  2082. return new this.constructor( this.x, this.y, this.z );
  2083. }
  2084. copy( v ) {
  2085. this.x = v.x;
  2086. this.y = v.y;
  2087. this.z = v.z;
  2088. return this;
  2089. }
  2090. add( v, w ) {
  2091. if ( w !== undefined ) {
  2092. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2093. return this.addVectors( v, w );
  2094. }
  2095. this.x += v.x;
  2096. this.y += v.y;
  2097. this.z += v.z;
  2098. return this;
  2099. }
  2100. addScalar( s ) {
  2101. this.x += s;
  2102. this.y += s;
  2103. this.z += s;
  2104. return this;
  2105. }
  2106. addVectors( a, b ) {
  2107. this.x = a.x + b.x;
  2108. this.y = a.y + b.y;
  2109. this.z = a.z + b.z;
  2110. return this;
  2111. }
  2112. addScaledVector( v, s ) {
  2113. this.x += v.x * s;
  2114. this.y += v.y * s;
  2115. this.z += v.z * s;
  2116. return this;
  2117. }
  2118. sub( v, w ) {
  2119. if ( w !== undefined ) {
  2120. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2121. return this.subVectors( v, w );
  2122. }
  2123. this.x -= v.x;
  2124. this.y -= v.y;
  2125. this.z -= v.z;
  2126. return this;
  2127. }
  2128. subScalar( s ) {
  2129. this.x -= s;
  2130. this.y -= s;
  2131. this.z -= s;
  2132. return this;
  2133. }
  2134. subVectors( a, b ) {
  2135. this.x = a.x - b.x;
  2136. this.y = a.y - b.y;
  2137. this.z = a.z - b.z;
  2138. return this;
  2139. }
  2140. multiply( v, w ) {
  2141. if ( w !== undefined ) {
  2142. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2143. return this.multiplyVectors( v, w );
  2144. }
  2145. this.x *= v.x;
  2146. this.y *= v.y;
  2147. this.z *= v.z;
  2148. return this;
  2149. }
  2150. multiplyScalar( scalar ) {
  2151. this.x *= scalar;
  2152. this.y *= scalar;
  2153. this.z *= scalar;
  2154. return this;
  2155. }
  2156. multiplyVectors( a, b ) {
  2157. this.x = a.x * b.x;
  2158. this.y = a.y * b.y;
  2159. this.z = a.z * b.z;
  2160. return this;
  2161. }
  2162. applyEuler( euler ) {
  2163. if ( ! ( euler && euler.isEuler ) ) {
  2164. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2165. }
  2166. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2167. }
  2168. applyAxisAngle( axis, angle ) {
  2169. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2170. }
  2171. applyMatrix3( m ) {
  2172. const x = this.x, y = this.y, z = this.z;
  2173. const e = m.elements;
  2174. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2175. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2176. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2177. return this;
  2178. }
  2179. applyNormalMatrix( m ) {
  2180. return this.applyMatrix3( m ).normalize();
  2181. }
  2182. applyMatrix4( m ) {
  2183. const x = this.x, y = this.y, z = this.z;
  2184. const e = m.elements;
  2185. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2186. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2187. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2188. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2189. return this;
  2190. }
  2191. applyQuaternion( q ) {
  2192. const x = this.x, y = this.y, z = this.z;
  2193. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2194. // calculate quat * vector
  2195. const ix = qw * x + qy * z - qz * y;
  2196. const iy = qw * y + qz * x - qx * z;
  2197. const iz = qw * z + qx * y - qy * x;
  2198. const iw = - qx * x - qy * y - qz * z;
  2199. // calculate result * inverse quat
  2200. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2201. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2202. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2203. return this;
  2204. }
  2205. project( camera ) {
  2206. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2207. }
  2208. unproject( camera ) {
  2209. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2210. }
  2211. transformDirection( m ) {
  2212. // input: THREE.Matrix4 affine matrix
  2213. // vector interpreted as a direction
  2214. const x = this.x, y = this.y, z = this.z;
  2215. const e = m.elements;
  2216. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2217. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2218. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2219. return this.normalize();
  2220. }
  2221. divide( v ) {
  2222. this.x /= v.x;
  2223. this.y /= v.y;
  2224. this.z /= v.z;
  2225. return this;
  2226. }
  2227. divideScalar( scalar ) {
  2228. return this.multiplyScalar( 1 / scalar );
  2229. }
  2230. min( v ) {
  2231. this.x = Math.min( this.x, v.x );
  2232. this.y = Math.min( this.y, v.y );
  2233. this.z = Math.min( this.z, v.z );
  2234. return this;
  2235. }
  2236. max( v ) {
  2237. this.x = Math.max( this.x, v.x );
  2238. this.y = Math.max( this.y, v.y );
  2239. this.z = Math.max( this.z, v.z );
  2240. return this;
  2241. }
  2242. clamp( min, max ) {
  2243. // assumes min < max, componentwise
  2244. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2245. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2246. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2247. return this;
  2248. }
  2249. clampScalar( minVal, maxVal ) {
  2250. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2251. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2252. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2253. return this;
  2254. }
  2255. clampLength( min, max ) {
  2256. const length = this.length();
  2257. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2258. }
  2259. floor() {
  2260. this.x = Math.floor( this.x );
  2261. this.y = Math.floor( this.y );
  2262. this.z = Math.floor( this.z );
  2263. return this;
  2264. }
  2265. ceil() {
  2266. this.x = Math.ceil( this.x );
  2267. this.y = Math.ceil( this.y );
  2268. this.z = Math.ceil( this.z );
  2269. return this;
  2270. }
  2271. round() {
  2272. this.x = Math.round( this.x );
  2273. this.y = Math.round( this.y );
  2274. this.z = Math.round( this.z );
  2275. return this;
  2276. }
  2277. roundToZero() {
  2278. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2279. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2280. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2281. return this;
  2282. }
  2283. negate() {
  2284. this.x = - this.x;
  2285. this.y = - this.y;
  2286. this.z = - this.z;
  2287. return this;
  2288. }
  2289. dot( v ) {
  2290. return this.x * v.x + this.y * v.y + this.z * v.z;
  2291. }
  2292. // TODO lengthSquared?
  2293. lengthSq() {
  2294. return this.x * this.x + this.y * this.y + this.z * this.z;
  2295. }
  2296. length() {
  2297. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2298. }
  2299. manhattanLength() {
  2300. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2301. }
  2302. normalize() {
  2303. return this.divideScalar( this.length() || 1 );
  2304. }
  2305. setLength( length ) {
  2306. return this.normalize().multiplyScalar( length );
  2307. }
  2308. lerp( v, alpha ) {
  2309. this.x += ( v.x - this.x ) * alpha;
  2310. this.y += ( v.y - this.y ) * alpha;
  2311. this.z += ( v.z - this.z ) * alpha;
  2312. return this;
  2313. }
  2314. lerpVectors( v1, v2, alpha ) {
  2315. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2316. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2317. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2318. return this;
  2319. }
  2320. cross( v, w ) {
  2321. if ( w !== undefined ) {
  2322. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2323. return this.crossVectors( v, w );
  2324. }
  2325. return this.crossVectors( this, v );
  2326. }
  2327. crossVectors( a, b ) {
  2328. const ax = a.x, ay = a.y, az = a.z;
  2329. const bx = b.x, by = b.y, bz = b.z;
  2330. this.x = ay * bz - az * by;
  2331. this.y = az * bx - ax * bz;
  2332. this.z = ax * by - ay * bx;
  2333. return this;
  2334. }
  2335. projectOnVector( v ) {
  2336. const denominator = v.lengthSq();
  2337. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2338. const scalar = v.dot( this ) / denominator;
  2339. return this.copy( v ).multiplyScalar( scalar );
  2340. }
  2341. projectOnPlane( planeNormal ) {
  2342. _vector$c.copy( this ).projectOnVector( planeNormal );
  2343. return this.sub( _vector$c );
  2344. }
  2345. reflect( normal ) {
  2346. // reflect incident vector off plane orthogonal to normal
  2347. // normal is assumed to have unit length
  2348. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2349. }
  2350. angleTo( v ) {
  2351. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2352. if ( denominator === 0 ) return Math.PI / 2;
  2353. const theta = this.dot( v ) / denominator;
  2354. // clamp, to handle numerical problems
  2355. return Math.acos( clamp( theta, - 1, 1 ) );
  2356. }
  2357. distanceTo( v ) {
  2358. return Math.sqrt( this.distanceToSquared( v ) );
  2359. }
  2360. distanceToSquared( v ) {
  2361. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2362. return dx * dx + dy * dy + dz * dz;
  2363. }
  2364. manhattanDistanceTo( v ) {
  2365. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2366. }
  2367. setFromSpherical( s ) {
  2368. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2369. }
  2370. setFromSphericalCoords( radius, phi, theta ) {
  2371. const sinPhiRadius = Math.sin( phi ) * radius;
  2372. this.x = sinPhiRadius * Math.sin( theta );
  2373. this.y = Math.cos( phi ) * radius;
  2374. this.z = sinPhiRadius * Math.cos( theta );
  2375. return this;
  2376. }
  2377. setFromCylindrical( c ) {
  2378. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2379. }
  2380. setFromCylindricalCoords( radius, theta, y ) {
  2381. this.x = radius * Math.sin( theta );
  2382. this.y = y;
  2383. this.z = radius * Math.cos( theta );
  2384. return this;
  2385. }
  2386. setFromMatrixPosition( m ) {
  2387. const e = m.elements;
  2388. this.x = e[ 12 ];
  2389. this.y = e[ 13 ];
  2390. this.z = e[ 14 ];
  2391. return this;
  2392. }
  2393. setFromMatrixScale( m ) {
  2394. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2395. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2396. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2397. this.x = sx;
  2398. this.y = sy;
  2399. this.z = sz;
  2400. return this;
  2401. }
  2402. setFromMatrixColumn( m, index ) {
  2403. return this.fromArray( m.elements, index * 4 );
  2404. }
  2405. setFromMatrix3Column( m, index ) {
  2406. return this.fromArray( m.elements, index * 3 );
  2407. }
  2408. equals( v ) {
  2409. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2410. }
  2411. fromArray( array, offset = 0 ) {
  2412. this.x = array[ offset ];
  2413. this.y = array[ offset + 1 ];
  2414. this.z = array[ offset + 2 ];
  2415. return this;
  2416. }
  2417. toArray( array = [], offset = 0 ) {
  2418. array[ offset ] = this.x;
  2419. array[ offset + 1 ] = this.y;
  2420. array[ offset + 2 ] = this.z;
  2421. return array;
  2422. }
  2423. fromBufferAttribute( attribute, index, offset ) {
  2424. if ( offset !== undefined ) {
  2425. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2426. }
  2427. this.x = attribute.getX( index );
  2428. this.y = attribute.getY( index );
  2429. this.z = attribute.getZ( index );
  2430. return this;
  2431. }
  2432. random() {
  2433. this.x = Math.random();
  2434. this.y = Math.random();
  2435. this.z = Math.random();
  2436. return this;
  2437. }
  2438. }
  2439. Vector3.prototype.isVector3 = true;
  2440. const _vector$c = /*@__PURE__*/ new Vector3();
  2441. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2442. class Box3 {
  2443. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2444. this.min = min;
  2445. this.max = max;
  2446. }
  2447. set( min, max ) {
  2448. this.min.copy( min );
  2449. this.max.copy( max );
  2450. return this;
  2451. }
  2452. setFromArray( array ) {
  2453. let minX = + Infinity;
  2454. let minY = + Infinity;
  2455. let minZ = + Infinity;
  2456. let maxX = - Infinity;
  2457. let maxY = - Infinity;
  2458. let maxZ = - Infinity;
  2459. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2460. const x = array[ i ];
  2461. const y = array[ i + 1 ];
  2462. const z = array[ i + 2 ];
  2463. if ( x < minX ) minX = x;
  2464. if ( y < minY ) minY = y;
  2465. if ( z < minZ ) minZ = z;
  2466. if ( x > maxX ) maxX = x;
  2467. if ( y > maxY ) maxY = y;
  2468. if ( z > maxZ ) maxZ = z;
  2469. }
  2470. this.min.set( minX, minY, minZ );
  2471. this.max.set( maxX, maxY, maxZ );
  2472. return this;
  2473. }
  2474. setFromBufferAttribute( attribute ) {
  2475. let minX = + Infinity;
  2476. let minY = + Infinity;
  2477. let minZ = + Infinity;
  2478. let maxX = - Infinity;
  2479. let maxY = - Infinity;
  2480. let maxZ = - Infinity;
  2481. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2482. const x = attribute.getX( i );
  2483. const y = attribute.getY( i );
  2484. const z = attribute.getZ( i );
  2485. if ( x < minX ) minX = x;
  2486. if ( y < minY ) minY = y;
  2487. if ( z < minZ ) minZ = z;
  2488. if ( x > maxX ) maxX = x;
  2489. if ( y > maxY ) maxY = y;
  2490. if ( z > maxZ ) maxZ = z;
  2491. }
  2492. this.min.set( minX, minY, minZ );
  2493. this.max.set( maxX, maxY, maxZ );
  2494. return this;
  2495. }
  2496. setFromPoints( points ) {
  2497. this.makeEmpty();
  2498. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2499. this.expandByPoint( points[ i ] );
  2500. }
  2501. return this;
  2502. }
  2503. setFromCenterAndSize( center, size ) {
  2504. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2505. this.min.copy( center ).sub( halfSize );
  2506. this.max.copy( center ).add( halfSize );
  2507. return this;
  2508. }
  2509. setFromObject( object ) {
  2510. this.makeEmpty();
  2511. return this.expandByObject( object );
  2512. }
  2513. clone() {
  2514. return new this.constructor().copy( this );
  2515. }
  2516. copy( box ) {
  2517. this.min.copy( box.min );
  2518. this.max.copy( box.max );
  2519. return this;
  2520. }
  2521. makeEmpty() {
  2522. this.min.x = this.min.y = this.min.z = + Infinity;
  2523. this.max.x = this.max.y = this.max.z = - Infinity;
  2524. return this;
  2525. }
  2526. isEmpty() {
  2527. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2528. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2529. }
  2530. getCenter( target ) {
  2531. if ( target === undefined ) {
  2532. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  2533. target = new Vector3();
  2534. }
  2535. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2536. }
  2537. getSize( target ) {
  2538. if ( target === undefined ) {
  2539. console.warn( 'THREE.Box3: .getSize() target is now required' );
  2540. target = new Vector3();
  2541. }
  2542. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2543. }
  2544. expandByPoint( point ) {
  2545. this.min.min( point );
  2546. this.max.max( point );
  2547. return this;
  2548. }
  2549. expandByVector( vector ) {
  2550. this.min.sub( vector );
  2551. this.max.add( vector );
  2552. return this;
  2553. }
  2554. expandByScalar( scalar ) {
  2555. this.min.addScalar( - scalar );
  2556. this.max.addScalar( scalar );
  2557. return this;
  2558. }
  2559. expandByObject( object ) {
  2560. // Computes the world-axis-aligned bounding box of an object (including its children),
  2561. // accounting for both the object's, and children's, world transforms
  2562. object.updateWorldMatrix( false, false );
  2563. const geometry = object.geometry;
  2564. if ( geometry !== undefined ) {
  2565. if ( geometry.boundingBox === null ) {
  2566. geometry.computeBoundingBox();
  2567. }
  2568. _box$3.copy( geometry.boundingBox );
  2569. _box$3.applyMatrix4( object.matrixWorld );
  2570. this.union( _box$3 );
  2571. }
  2572. const children = object.children;
  2573. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2574. this.expandByObject( children[ i ] );
  2575. }
  2576. return this;
  2577. }
  2578. containsPoint( point ) {
  2579. return point.x < this.min.x || point.x > this.max.x ||
  2580. point.y < this.min.y || point.y > this.max.y ||
  2581. point.z < this.min.z || point.z > this.max.z ? false : true;
  2582. }
  2583. containsBox( box ) {
  2584. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2585. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2586. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2587. }
  2588. getParameter( point, target ) {
  2589. // This can potentially have a divide by zero if the box
  2590. // has a size dimension of 0.
  2591. if ( target === undefined ) {
  2592. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  2593. target = new Vector3();
  2594. }
  2595. return target.set(
  2596. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2597. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2598. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2599. );
  2600. }
  2601. intersectsBox( box ) {
  2602. // using 6 splitting planes to rule out intersections.
  2603. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2604. box.max.y < this.min.y || box.min.y > this.max.y ||
  2605. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2606. }
  2607. intersectsSphere( sphere ) {
  2608. // Find the point on the AABB closest to the sphere center.
  2609. this.clampPoint( sphere.center, _vector$b );
  2610. // If that point is inside the sphere, the AABB and sphere intersect.
  2611. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2612. }
  2613. intersectsPlane( plane ) {
  2614. // We compute the minimum and maximum dot product values. If those values
  2615. // are on the same side (back or front) of the plane, then there is no intersection.
  2616. let min, max;
  2617. if ( plane.normal.x > 0 ) {
  2618. min = plane.normal.x * this.min.x;
  2619. max = plane.normal.x * this.max.x;
  2620. } else {
  2621. min = plane.normal.x * this.max.x;
  2622. max = plane.normal.x * this.min.x;
  2623. }
  2624. if ( plane.normal.y > 0 ) {
  2625. min += plane.normal.y * this.min.y;
  2626. max += plane.normal.y * this.max.y;
  2627. } else {
  2628. min += plane.normal.y * this.max.y;
  2629. max += plane.normal.y * this.min.y;
  2630. }
  2631. if ( plane.normal.z > 0 ) {
  2632. min += plane.normal.z * this.min.z;
  2633. max += plane.normal.z * this.max.z;
  2634. } else {
  2635. min += plane.normal.z * this.max.z;
  2636. max += plane.normal.z * this.min.z;
  2637. }
  2638. return ( min <= - plane.constant && max >= - plane.constant );
  2639. }
  2640. intersectsTriangle( triangle ) {
  2641. if ( this.isEmpty() ) {
  2642. return false;
  2643. }
  2644. // compute box center and extents
  2645. this.getCenter( _center );
  2646. _extents.subVectors( this.max, _center );
  2647. // translate triangle to aabb origin
  2648. _v0$2.subVectors( triangle.a, _center );
  2649. _v1$7.subVectors( triangle.b, _center );
  2650. _v2$3.subVectors( triangle.c, _center );
  2651. // compute edge vectors for triangle
  2652. _f0.subVectors( _v1$7, _v0$2 );
  2653. _f1.subVectors( _v2$3, _v1$7 );
  2654. _f2.subVectors( _v0$2, _v2$3 );
  2655. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2656. // 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
  2657. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2658. let axes = [
  2659. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2660. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2661. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2662. ];
  2663. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2664. return false;
  2665. }
  2666. // test 3 face normals from the aabb
  2667. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2668. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2669. return false;
  2670. }
  2671. // finally testing the face normal of the triangle
  2672. // use already existing triangle edge vectors here
  2673. _triangleNormal.crossVectors( _f0, _f1 );
  2674. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2675. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  2676. }
  2677. clampPoint( point, target ) {
  2678. if ( target === undefined ) {
  2679. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  2680. target = new Vector3();
  2681. }
  2682. return target.copy( point ).clamp( this.min, this.max );
  2683. }
  2684. distanceToPoint( point ) {
  2685. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  2686. return clampedPoint.sub( point ).length();
  2687. }
  2688. getBoundingSphere( target ) {
  2689. if ( target === undefined ) {
  2690. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  2691. //target = new Sphere(); // removed to avoid cyclic dependency
  2692. }
  2693. this.getCenter( target.center );
  2694. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2695. return target;
  2696. }
  2697. intersect( box ) {
  2698. this.min.max( box.min );
  2699. this.max.min( box.max );
  2700. // 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.
  2701. if ( this.isEmpty() ) this.makeEmpty();
  2702. return this;
  2703. }
  2704. union( box ) {
  2705. this.min.min( box.min );
  2706. this.max.max( box.max );
  2707. return this;
  2708. }
  2709. applyMatrix4( matrix ) {
  2710. // transform of empty box is an empty box.
  2711. if ( this.isEmpty() ) return this;
  2712. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2713. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2714. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2715. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2716. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2717. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2718. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2719. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2720. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2721. this.setFromPoints( _points );
  2722. return this;
  2723. }
  2724. translate( offset ) {
  2725. this.min.add( offset );
  2726. this.max.add( offset );
  2727. return this;
  2728. }
  2729. equals( box ) {
  2730. return box.min.equals( this.min ) && box.max.equals( this.max );
  2731. }
  2732. }
  2733. Box3.prototype.isBox3 = true;
  2734. const _points = [
  2735. /*@__PURE__*/ new Vector3(),
  2736. /*@__PURE__*/ new Vector3(),
  2737. /*@__PURE__*/ new Vector3(),
  2738. /*@__PURE__*/ new Vector3(),
  2739. /*@__PURE__*/ new Vector3(),
  2740. /*@__PURE__*/ new Vector3(),
  2741. /*@__PURE__*/ new Vector3(),
  2742. /*@__PURE__*/ new Vector3()
  2743. ];
  2744. const _vector$b = /*@__PURE__*/ new Vector3();
  2745. const _box$3 = /*@__PURE__*/ new Box3();
  2746. // triangle centered vertices
  2747. const _v0$2 = /*@__PURE__*/ new Vector3();
  2748. const _v1$7 = /*@__PURE__*/ new Vector3();
  2749. const _v2$3 = /*@__PURE__*/ new Vector3();
  2750. // triangle edge vectors
  2751. const _f0 = /*@__PURE__*/ new Vector3();
  2752. const _f1 = /*@__PURE__*/ new Vector3();
  2753. const _f2 = /*@__PURE__*/ new Vector3();
  2754. const _center = /*@__PURE__*/ new Vector3();
  2755. const _extents = /*@__PURE__*/ new Vector3();
  2756. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2757. const _testAxis = /*@__PURE__*/ new Vector3();
  2758. function satForAxes( axes, v0, v1, v2, extents ) {
  2759. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2760. _testAxis.fromArray( axes, i );
  2761. // project the aabb onto the seperating axis
  2762. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2763. // project all 3 vertices of the triangle onto the seperating axis
  2764. const p0 = v0.dot( _testAxis );
  2765. const p1 = v1.dot( _testAxis );
  2766. const p2 = v2.dot( _testAxis );
  2767. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2768. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2769. // points of the projected triangle are outside the projected half-length of the aabb
  2770. // the axis is seperating and we can exit
  2771. return false;
  2772. }
  2773. }
  2774. return true;
  2775. }
  2776. const _box$2 = /*@__PURE__*/ new Box3();
  2777. const _v1$6 = /*@__PURE__*/ new Vector3();
  2778. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  2779. const _toPoint = /*@__PURE__*/ new Vector3();
  2780. class Sphere {
  2781. constructor( center = new Vector3(), radius = - 1 ) {
  2782. this.center = center;
  2783. this.radius = radius;
  2784. }
  2785. set( center, radius ) {
  2786. this.center.copy( center );
  2787. this.radius = radius;
  2788. return this;
  2789. }
  2790. setFromPoints( points, optionalCenter ) {
  2791. const center = this.center;
  2792. if ( optionalCenter !== undefined ) {
  2793. center.copy( optionalCenter );
  2794. } else {
  2795. _box$2.setFromPoints( points ).getCenter( center );
  2796. }
  2797. let maxRadiusSq = 0;
  2798. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2799. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2800. }
  2801. this.radius = Math.sqrt( maxRadiusSq );
  2802. return this;
  2803. }
  2804. copy( sphere ) {
  2805. this.center.copy( sphere.center );
  2806. this.radius = sphere.radius;
  2807. return this;
  2808. }
  2809. isEmpty() {
  2810. return ( this.radius < 0 );
  2811. }
  2812. makeEmpty() {
  2813. this.center.set( 0, 0, 0 );
  2814. this.radius = - 1;
  2815. return this;
  2816. }
  2817. containsPoint( point ) {
  2818. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2819. }
  2820. distanceToPoint( point ) {
  2821. return ( point.distanceTo( this.center ) - this.radius );
  2822. }
  2823. intersectsSphere( sphere ) {
  2824. const radiusSum = this.radius + sphere.radius;
  2825. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2826. }
  2827. intersectsBox( box ) {
  2828. return box.intersectsSphere( this );
  2829. }
  2830. intersectsPlane( plane ) {
  2831. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2832. }
  2833. clampPoint( point, target ) {
  2834. const deltaLengthSq = this.center.distanceToSquared( point );
  2835. if ( target === undefined ) {
  2836. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  2837. target = new Vector3();
  2838. }
  2839. target.copy( point );
  2840. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2841. target.sub( this.center ).normalize();
  2842. target.multiplyScalar( this.radius ).add( this.center );
  2843. }
  2844. return target;
  2845. }
  2846. getBoundingBox( target ) {
  2847. if ( target === undefined ) {
  2848. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  2849. target = new Box3();
  2850. }
  2851. if ( this.isEmpty() ) {
  2852. // Empty sphere produces empty bounding box
  2853. target.makeEmpty();
  2854. return target;
  2855. }
  2856. target.set( this.center, this.center );
  2857. target.expandByScalar( this.radius );
  2858. return target;
  2859. }
  2860. applyMatrix4( matrix ) {
  2861. this.center.applyMatrix4( matrix );
  2862. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2863. return this;
  2864. }
  2865. translate( offset ) {
  2866. this.center.add( offset );
  2867. return this;
  2868. }
  2869. expandByPoint( point ) {
  2870. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2871. _toPoint.subVectors( point, this.center );
  2872. const lengthSq = _toPoint.lengthSq();
  2873. if ( lengthSq > ( this.radius * this.radius ) ) {
  2874. const length = Math.sqrt( lengthSq );
  2875. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  2876. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2877. // and the other half to position. This gives a tighter enclosure, instead of if
  2878. // the whole missing distance were just added to radius.
  2879. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  2880. this.radius += missingRadiusHalf;
  2881. }
  2882. return this;
  2883. }
  2884. union( sphere ) {
  2885. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2886. // To enclose another sphere into this sphere, we only need to enclose two points:
  2887. // 1) Enclose the farthest point on the other sphere into this sphere.
  2888. // 2) Enclose the opposite point of the farthest point into this sphere.
  2889. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  2890. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  2891. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  2892. return this;
  2893. }
  2894. equals( sphere ) {
  2895. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2896. }
  2897. clone() {
  2898. return new this.constructor().copy( this );
  2899. }
  2900. }
  2901. const _vector$a = /*@__PURE__*/ new Vector3();
  2902. const _segCenter = /*@__PURE__*/ new Vector3();
  2903. const _segDir = /*@__PURE__*/ new Vector3();
  2904. const _diff = /*@__PURE__*/ new Vector3();
  2905. const _edge1 = /*@__PURE__*/ new Vector3();
  2906. const _edge2 = /*@__PURE__*/ new Vector3();
  2907. const _normal$1 = /*@__PURE__*/ new Vector3();
  2908. class Ray {
  2909. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  2910. this.origin = origin;
  2911. this.direction = direction;
  2912. }
  2913. set( origin, direction ) {
  2914. this.origin.copy( origin );
  2915. this.direction.copy( direction );
  2916. return this;
  2917. }
  2918. copy( ray ) {
  2919. this.origin.copy( ray.origin );
  2920. this.direction.copy( ray.direction );
  2921. return this;
  2922. }
  2923. at( t, target ) {
  2924. if ( target === undefined ) {
  2925. console.warn( 'THREE.Ray: .at() target is now required' );
  2926. target = new Vector3();
  2927. }
  2928. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2929. }
  2930. lookAt( v ) {
  2931. this.direction.copy( v ).sub( this.origin ).normalize();
  2932. return this;
  2933. }
  2934. recast( t ) {
  2935. this.origin.copy( this.at( t, _vector$a ) );
  2936. return this;
  2937. }
  2938. closestPointToPoint( point, target ) {
  2939. if ( target === undefined ) {
  2940. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  2941. target = new Vector3();
  2942. }
  2943. target.subVectors( point, this.origin );
  2944. const directionDistance = target.dot( this.direction );
  2945. if ( directionDistance < 0 ) {
  2946. return target.copy( this.origin );
  2947. }
  2948. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2949. }
  2950. distanceToPoint( point ) {
  2951. return Math.sqrt( this.distanceSqToPoint( point ) );
  2952. }
  2953. distanceSqToPoint( point ) {
  2954. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  2955. // point behind the ray
  2956. if ( directionDistance < 0 ) {
  2957. return this.origin.distanceToSquared( point );
  2958. }
  2959. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2960. return _vector$a.distanceToSquared( point );
  2961. }
  2962. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  2963. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2964. // It returns the min distance between the ray and the segment
  2965. // defined by v0 and v1
  2966. // It can also set two optional targets :
  2967. // - The closest point on the ray
  2968. // - The closest point on the segment
  2969. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  2970. _segDir.copy( v1 ).sub( v0 ).normalize();
  2971. _diff.copy( this.origin ).sub( _segCenter );
  2972. const segExtent = v0.distanceTo( v1 ) * 0.5;
  2973. const a01 = - this.direction.dot( _segDir );
  2974. const b0 = _diff.dot( this.direction );
  2975. const b1 = - _diff.dot( _segDir );
  2976. const c = _diff.lengthSq();
  2977. const det = Math.abs( 1 - a01 * a01 );
  2978. let s0, s1, sqrDist, extDet;
  2979. if ( det > 0 ) {
  2980. // The ray and segment are not parallel.
  2981. s0 = a01 * b1 - b0;
  2982. s1 = a01 * b0 - b1;
  2983. extDet = segExtent * det;
  2984. if ( s0 >= 0 ) {
  2985. if ( s1 >= - extDet ) {
  2986. if ( s1 <= extDet ) {
  2987. // region 0
  2988. // Minimum at interior points of ray and segment.
  2989. const invDet = 1 / det;
  2990. s0 *= invDet;
  2991. s1 *= invDet;
  2992. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  2993. } else {
  2994. // region 1
  2995. s1 = segExtent;
  2996. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2997. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2998. }
  2999. } else {
  3000. // region 5
  3001. s1 = - segExtent;
  3002. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3003. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3004. }
  3005. } else {
  3006. if ( s1 <= - extDet ) {
  3007. // region 4
  3008. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3009. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3010. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3011. } else if ( s1 <= extDet ) {
  3012. // region 3
  3013. s0 = 0;
  3014. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3015. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3016. } else {
  3017. // region 2
  3018. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3019. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3020. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3021. }
  3022. }
  3023. } else {
  3024. // Ray and segment are parallel.
  3025. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3026. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3027. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3028. }
  3029. if ( optionalPointOnRay ) {
  3030. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3031. }
  3032. if ( optionalPointOnSegment ) {
  3033. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3034. }
  3035. return sqrDist;
  3036. }
  3037. intersectSphere( sphere, target ) {
  3038. _vector$a.subVectors( sphere.center, this.origin );
  3039. const tca = _vector$a.dot( this.direction );
  3040. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3041. const radius2 = sphere.radius * sphere.radius;
  3042. if ( d2 > radius2 ) return null;
  3043. const thc = Math.sqrt( radius2 - d2 );
  3044. // t0 = first intersect point - entrance on front of sphere
  3045. const t0 = tca - thc;
  3046. // t1 = second intersect point - exit point on back of sphere
  3047. const t1 = tca + thc;
  3048. // test to see if both t0 and t1 are behind the ray - if so, return null
  3049. if ( t0 < 0 && t1 < 0 ) return null;
  3050. // test to see if t0 is behind the ray:
  3051. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3052. // in order to always return an intersect point that is in front of the ray.
  3053. if ( t0 < 0 ) return this.at( t1, target );
  3054. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3055. return this.at( t0, target );
  3056. }
  3057. intersectsSphere( sphere ) {
  3058. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3059. }
  3060. distanceToPlane( plane ) {
  3061. const denominator = plane.normal.dot( this.direction );
  3062. if ( denominator === 0 ) {
  3063. // line is coplanar, return origin
  3064. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3065. return 0;
  3066. }
  3067. // Null is preferable to undefined since undefined means.... it is undefined
  3068. return null;
  3069. }
  3070. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3071. // Return if the ray never intersects the plane
  3072. return t >= 0 ? t : null;
  3073. }
  3074. intersectPlane( plane, target ) {
  3075. const t = this.distanceToPlane( plane );
  3076. if ( t === null ) {
  3077. return null;
  3078. }
  3079. return this.at( t, target );
  3080. }
  3081. intersectsPlane( plane ) {
  3082. // check if the ray lies on the plane first
  3083. const distToPoint = plane.distanceToPoint( this.origin );
  3084. if ( distToPoint === 0 ) {
  3085. return true;
  3086. }
  3087. const denominator = plane.normal.dot( this.direction );
  3088. if ( denominator * distToPoint < 0 ) {
  3089. return true;
  3090. }
  3091. // ray origin is behind the plane (and is pointing behind it)
  3092. return false;
  3093. }
  3094. intersectBox( box, target ) {
  3095. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3096. const invdirx = 1 / this.direction.x,
  3097. invdiry = 1 / this.direction.y,
  3098. invdirz = 1 / this.direction.z;
  3099. const origin = this.origin;
  3100. if ( invdirx >= 0 ) {
  3101. tmin = ( box.min.x - origin.x ) * invdirx;
  3102. tmax = ( box.max.x - origin.x ) * invdirx;
  3103. } else {
  3104. tmin = ( box.max.x - origin.x ) * invdirx;
  3105. tmax = ( box.min.x - origin.x ) * invdirx;
  3106. }
  3107. if ( invdiry >= 0 ) {
  3108. tymin = ( box.min.y - origin.y ) * invdiry;
  3109. tymax = ( box.max.y - origin.y ) * invdiry;
  3110. } else {
  3111. tymin = ( box.max.y - origin.y ) * invdiry;
  3112. tymax = ( box.min.y - origin.y ) * invdiry;
  3113. }
  3114. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3115. // These lines also handle the case where tmin or tmax is NaN
  3116. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3117. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3118. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3119. if ( invdirz >= 0 ) {
  3120. tzmin = ( box.min.z - origin.z ) * invdirz;
  3121. tzmax = ( box.max.z - origin.z ) * invdirz;
  3122. } else {
  3123. tzmin = ( box.max.z - origin.z ) * invdirz;
  3124. tzmax = ( box.min.z - origin.z ) * invdirz;
  3125. }
  3126. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3127. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3128. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3129. //return point closest to the ray (positive side)
  3130. if ( tmax < 0 ) return null;
  3131. return this.at( tmin >= 0 ? tmin : tmax, target );
  3132. }
  3133. intersectsBox( box ) {
  3134. return this.intersectBox( box, _vector$a ) !== null;
  3135. }
  3136. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3137. // Compute the offset origin, edges, and normal.
  3138. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3139. _edge1.subVectors( b, a );
  3140. _edge2.subVectors( c, a );
  3141. _normal$1.crossVectors( _edge1, _edge2 );
  3142. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3143. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3144. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3145. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3146. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3147. let DdN = this.direction.dot( _normal$1 );
  3148. let sign;
  3149. if ( DdN > 0 ) {
  3150. if ( backfaceCulling ) return null;
  3151. sign = 1;
  3152. } else if ( DdN < 0 ) {
  3153. sign = - 1;
  3154. DdN = - DdN;
  3155. } else {
  3156. return null;
  3157. }
  3158. _diff.subVectors( this.origin, a );
  3159. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3160. // b1 < 0, no intersection
  3161. if ( DdQxE2 < 0 ) {
  3162. return null;
  3163. }
  3164. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3165. // b2 < 0, no intersection
  3166. if ( DdE1xQ < 0 ) {
  3167. return null;
  3168. }
  3169. // b1+b2 > 1, no intersection
  3170. if ( DdQxE2 + DdE1xQ > DdN ) {
  3171. return null;
  3172. }
  3173. // Line intersects triangle, check if ray does.
  3174. const QdN = - sign * _diff.dot( _normal$1 );
  3175. // t < 0, no intersection
  3176. if ( QdN < 0 ) {
  3177. return null;
  3178. }
  3179. // Ray intersects triangle.
  3180. return this.at( QdN / DdN, target );
  3181. }
  3182. applyMatrix4( matrix4 ) {
  3183. this.origin.applyMatrix4( matrix4 );
  3184. this.direction.transformDirection( matrix4 );
  3185. return this;
  3186. }
  3187. equals( ray ) {
  3188. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3189. }
  3190. clone() {
  3191. return new this.constructor().copy( this );
  3192. }
  3193. }
  3194. class Matrix4 {
  3195. constructor() {
  3196. this.elements = [
  3197. 1, 0, 0, 0,
  3198. 0, 1, 0, 0,
  3199. 0, 0, 1, 0,
  3200. 0, 0, 0, 1
  3201. ];
  3202. if ( arguments.length > 0 ) {
  3203. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3204. }
  3205. }
  3206. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3207. const te = this.elements;
  3208. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3209. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3210. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3211. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3212. return this;
  3213. }
  3214. identity() {
  3215. this.set(
  3216. 1, 0, 0, 0,
  3217. 0, 1, 0, 0,
  3218. 0, 0, 1, 0,
  3219. 0, 0, 0, 1
  3220. );
  3221. return this;
  3222. }
  3223. clone() {
  3224. return new Matrix4().fromArray( this.elements );
  3225. }
  3226. copy( m ) {
  3227. const te = this.elements;
  3228. const me = m.elements;
  3229. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3230. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3231. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3232. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3233. return this;
  3234. }
  3235. copyPosition( m ) {
  3236. const te = this.elements, me = m.elements;
  3237. te[ 12 ] = me[ 12 ];
  3238. te[ 13 ] = me[ 13 ];
  3239. te[ 14 ] = me[ 14 ];
  3240. return this;
  3241. }
  3242. setFromMatrix3( m ) {
  3243. const me = m.elements;
  3244. this.set(
  3245. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3246. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3247. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3248. 0, 0, 0, 1
  3249. );
  3250. return this;
  3251. }
  3252. extractBasis( xAxis, yAxis, zAxis ) {
  3253. xAxis.setFromMatrixColumn( this, 0 );
  3254. yAxis.setFromMatrixColumn( this, 1 );
  3255. zAxis.setFromMatrixColumn( this, 2 );
  3256. return this;
  3257. }
  3258. makeBasis( xAxis, yAxis, zAxis ) {
  3259. this.set(
  3260. xAxis.x, yAxis.x, zAxis.x, 0,
  3261. xAxis.y, yAxis.y, zAxis.y, 0,
  3262. xAxis.z, yAxis.z, zAxis.z, 0,
  3263. 0, 0, 0, 1
  3264. );
  3265. return this;
  3266. }
  3267. extractRotation( m ) {
  3268. // this method does not support reflection matrices
  3269. const te = this.elements;
  3270. const me = m.elements;
  3271. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3272. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3273. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3274. te[ 0 ] = me[ 0 ] * scaleX;
  3275. te[ 1 ] = me[ 1 ] * scaleX;
  3276. te[ 2 ] = me[ 2 ] * scaleX;
  3277. te[ 3 ] = 0;
  3278. te[ 4 ] = me[ 4 ] * scaleY;
  3279. te[ 5 ] = me[ 5 ] * scaleY;
  3280. te[ 6 ] = me[ 6 ] * scaleY;
  3281. te[ 7 ] = 0;
  3282. te[ 8 ] = me[ 8 ] * scaleZ;
  3283. te[ 9 ] = me[ 9 ] * scaleZ;
  3284. te[ 10 ] = me[ 10 ] * scaleZ;
  3285. te[ 11 ] = 0;
  3286. te[ 12 ] = 0;
  3287. te[ 13 ] = 0;
  3288. te[ 14 ] = 0;
  3289. te[ 15 ] = 1;
  3290. return this;
  3291. }
  3292. makeRotationFromEuler( euler ) {
  3293. if ( ! ( euler && euler.isEuler ) ) {
  3294. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3295. }
  3296. const te = this.elements;
  3297. const x = euler.x, y = euler.y, z = euler.z;
  3298. const a = Math.cos( x ), b = Math.sin( x );
  3299. const c = Math.cos( y ), d = Math.sin( y );
  3300. const e = Math.cos( z ), f = Math.sin( z );
  3301. if ( euler.order === 'XYZ' ) {
  3302. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3303. te[ 0 ] = c * e;
  3304. te[ 4 ] = - c * f;
  3305. te[ 8 ] = d;
  3306. te[ 1 ] = af + be * d;
  3307. te[ 5 ] = ae - bf * d;
  3308. te[ 9 ] = - b * c;
  3309. te[ 2 ] = bf - ae * d;
  3310. te[ 6 ] = be + af * d;
  3311. te[ 10 ] = a * c;
  3312. } else if ( euler.order === 'YXZ' ) {
  3313. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3314. te[ 0 ] = ce + df * b;
  3315. te[ 4 ] = de * b - cf;
  3316. te[ 8 ] = a * d;
  3317. te[ 1 ] = a * f;
  3318. te[ 5 ] = a * e;
  3319. te[ 9 ] = - b;
  3320. te[ 2 ] = cf * b - de;
  3321. te[ 6 ] = df + ce * b;
  3322. te[ 10 ] = a * c;
  3323. } else if ( euler.order === 'ZXY' ) {
  3324. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3325. te[ 0 ] = ce - df * b;
  3326. te[ 4 ] = - a * f;
  3327. te[ 8 ] = de + cf * b;
  3328. te[ 1 ] = cf + de * b;
  3329. te[ 5 ] = a * e;
  3330. te[ 9 ] = df - ce * b;
  3331. te[ 2 ] = - a * d;
  3332. te[ 6 ] = b;
  3333. te[ 10 ] = a * c;
  3334. } else if ( euler.order === 'ZYX' ) {
  3335. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3336. te[ 0 ] = c * e;
  3337. te[ 4 ] = be * d - af;
  3338. te[ 8 ] = ae * d + bf;
  3339. te[ 1 ] = c * f;
  3340. te[ 5 ] = bf * d + ae;
  3341. te[ 9 ] = af * d - be;
  3342. te[ 2 ] = - d;
  3343. te[ 6 ] = b * c;
  3344. te[ 10 ] = a * c;
  3345. } else if ( euler.order === 'YZX' ) {
  3346. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3347. te[ 0 ] = c * e;
  3348. te[ 4 ] = bd - ac * f;
  3349. te[ 8 ] = bc * f + ad;
  3350. te[ 1 ] = f;
  3351. te[ 5 ] = a * e;
  3352. te[ 9 ] = - b * e;
  3353. te[ 2 ] = - d * e;
  3354. te[ 6 ] = ad * f + bc;
  3355. te[ 10 ] = ac - bd * f;
  3356. } else if ( euler.order === 'XZY' ) {
  3357. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3358. te[ 0 ] = c * e;
  3359. te[ 4 ] = - f;
  3360. te[ 8 ] = d * e;
  3361. te[ 1 ] = ac * f + bd;
  3362. te[ 5 ] = a * e;
  3363. te[ 9 ] = ad * f - bc;
  3364. te[ 2 ] = bc * f - ad;
  3365. te[ 6 ] = b * e;
  3366. te[ 10 ] = bd * f + ac;
  3367. }
  3368. // bottom row
  3369. te[ 3 ] = 0;
  3370. te[ 7 ] = 0;
  3371. te[ 11 ] = 0;
  3372. // last column
  3373. te[ 12 ] = 0;
  3374. te[ 13 ] = 0;
  3375. te[ 14 ] = 0;
  3376. te[ 15 ] = 1;
  3377. return this;
  3378. }
  3379. makeRotationFromQuaternion( q ) {
  3380. return this.compose( _zero, q, _one );
  3381. }
  3382. lookAt( eye, target, up ) {
  3383. const te = this.elements;
  3384. _z.subVectors( eye, target );
  3385. if ( _z.lengthSq() === 0 ) {
  3386. // eye and target are in the same position
  3387. _z.z = 1;
  3388. }
  3389. _z.normalize();
  3390. _x.crossVectors( up, _z );
  3391. if ( _x.lengthSq() === 0 ) {
  3392. // up and z are parallel
  3393. if ( Math.abs( up.z ) === 1 ) {
  3394. _z.x += 0.0001;
  3395. } else {
  3396. _z.z += 0.0001;
  3397. }
  3398. _z.normalize();
  3399. _x.crossVectors( up, _z );
  3400. }
  3401. _x.normalize();
  3402. _y.crossVectors( _z, _x );
  3403. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3404. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3405. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3406. return this;
  3407. }
  3408. multiply( m, n ) {
  3409. if ( n !== undefined ) {
  3410. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3411. return this.multiplyMatrices( m, n );
  3412. }
  3413. return this.multiplyMatrices( this, m );
  3414. }
  3415. premultiply( m ) {
  3416. return this.multiplyMatrices( m, this );
  3417. }
  3418. multiplyMatrices( a, b ) {
  3419. const ae = a.elements;
  3420. const be = b.elements;
  3421. const te = this.elements;
  3422. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3423. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3424. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3425. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3426. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3427. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3428. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3429. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3430. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3431. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3432. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3433. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3434. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3435. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3436. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3437. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3438. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3439. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3440. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3441. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3442. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3443. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3444. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3445. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3446. return this;
  3447. }
  3448. multiplyScalar( s ) {
  3449. const te = this.elements;
  3450. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3451. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3452. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3453. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3454. return this;
  3455. }
  3456. determinant() {
  3457. const te = this.elements;
  3458. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3459. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3460. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3461. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3462. //TODO: make this more efficient
  3463. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3464. return (
  3465. n41 * (
  3466. + n14 * n23 * n32
  3467. - n13 * n24 * n32
  3468. - n14 * n22 * n33
  3469. + n12 * n24 * n33
  3470. + n13 * n22 * n34
  3471. - n12 * n23 * n34
  3472. ) +
  3473. n42 * (
  3474. + n11 * n23 * n34
  3475. - n11 * n24 * n33
  3476. + n14 * n21 * n33
  3477. - n13 * n21 * n34
  3478. + n13 * n24 * n31
  3479. - n14 * n23 * n31
  3480. ) +
  3481. n43 * (
  3482. + n11 * n24 * n32
  3483. - n11 * n22 * n34
  3484. - n14 * n21 * n32
  3485. + n12 * n21 * n34
  3486. + n14 * n22 * n31
  3487. - n12 * n24 * n31
  3488. ) +
  3489. n44 * (
  3490. - n13 * n22 * n31
  3491. - n11 * n23 * n32
  3492. + n11 * n22 * n33
  3493. + n13 * n21 * n32
  3494. - n12 * n21 * n33
  3495. + n12 * n23 * n31
  3496. )
  3497. );
  3498. }
  3499. transpose() {
  3500. const te = this.elements;
  3501. let tmp;
  3502. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3503. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3504. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3505. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3506. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3507. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3508. return this;
  3509. }
  3510. setPosition( x, y, z ) {
  3511. const te = this.elements;
  3512. if ( x.isVector3 ) {
  3513. te[ 12 ] = x.x;
  3514. te[ 13 ] = x.y;
  3515. te[ 14 ] = x.z;
  3516. } else {
  3517. te[ 12 ] = x;
  3518. te[ 13 ] = y;
  3519. te[ 14 ] = z;
  3520. }
  3521. return this;
  3522. }
  3523. invert() {
  3524. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3525. const te = this.elements,
  3526. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3527. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3528. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3529. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3530. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3531. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3532. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3533. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3534. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3535. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3536. const detInv = 1 / det;
  3537. te[ 0 ] = t11 * detInv;
  3538. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3539. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3540. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3541. te[ 4 ] = t12 * detInv;
  3542. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3543. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3544. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3545. te[ 8 ] = t13 * detInv;
  3546. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3547. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3548. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3549. te[ 12 ] = t14 * detInv;
  3550. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3551. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3552. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3553. return this;
  3554. }
  3555. scale( v ) {
  3556. const te = this.elements;
  3557. const x = v.x, y = v.y, z = v.z;
  3558. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3559. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3560. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3561. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3562. return this;
  3563. }
  3564. getMaxScaleOnAxis() {
  3565. const te = this.elements;
  3566. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3567. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3568. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3569. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3570. }
  3571. makeTranslation( x, y, z ) {
  3572. this.set(
  3573. 1, 0, 0, x,
  3574. 0, 1, 0, y,
  3575. 0, 0, 1, z,
  3576. 0, 0, 0, 1
  3577. );
  3578. return this;
  3579. }
  3580. makeRotationX( theta ) {
  3581. const c = Math.cos( theta ), s = Math.sin( theta );
  3582. this.set(
  3583. 1, 0, 0, 0,
  3584. 0, c, - s, 0,
  3585. 0, s, c, 0,
  3586. 0, 0, 0, 1
  3587. );
  3588. return this;
  3589. }
  3590. makeRotationY( theta ) {
  3591. const c = Math.cos( theta ), s = Math.sin( theta );
  3592. this.set(
  3593. c, 0, s, 0,
  3594. 0, 1, 0, 0,
  3595. - s, 0, c, 0,
  3596. 0, 0, 0, 1
  3597. );
  3598. return this;
  3599. }
  3600. makeRotationZ( theta ) {
  3601. const c = Math.cos( theta ), s = Math.sin( theta );
  3602. this.set(
  3603. c, - s, 0, 0,
  3604. s, c, 0, 0,
  3605. 0, 0, 1, 0,
  3606. 0, 0, 0, 1
  3607. );
  3608. return this;
  3609. }
  3610. makeRotationAxis( axis, angle ) {
  3611. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3612. const c = Math.cos( angle );
  3613. const s = Math.sin( angle );
  3614. const t = 1 - c;
  3615. const x = axis.x, y = axis.y, z = axis.z;
  3616. const tx = t * x, ty = t * y;
  3617. this.set(
  3618. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3619. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3620. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3621. 0, 0, 0, 1
  3622. );
  3623. return this;
  3624. }
  3625. makeScale( x, y, z ) {
  3626. this.set(
  3627. x, 0, 0, 0,
  3628. 0, y, 0, 0,
  3629. 0, 0, z, 0,
  3630. 0, 0, 0, 1
  3631. );
  3632. return this;
  3633. }
  3634. makeShear( x, y, z ) {
  3635. this.set(
  3636. 1, y, z, 0,
  3637. x, 1, z, 0,
  3638. x, y, 1, 0,
  3639. 0, 0, 0, 1
  3640. );
  3641. return this;
  3642. }
  3643. compose( position, quaternion, scale ) {
  3644. const te = this.elements;
  3645. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3646. const x2 = x + x, y2 = y + y, z2 = z + z;
  3647. const xx = x * x2, xy = x * y2, xz = x * z2;
  3648. const yy = y * y2, yz = y * z2, zz = z * z2;
  3649. const wx = w * x2, wy = w * y2, wz = w * z2;
  3650. const sx = scale.x, sy = scale.y, sz = scale.z;
  3651. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3652. te[ 1 ] = ( xy + wz ) * sx;
  3653. te[ 2 ] = ( xz - wy ) * sx;
  3654. te[ 3 ] = 0;
  3655. te[ 4 ] = ( xy - wz ) * sy;
  3656. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3657. te[ 6 ] = ( yz + wx ) * sy;
  3658. te[ 7 ] = 0;
  3659. te[ 8 ] = ( xz + wy ) * sz;
  3660. te[ 9 ] = ( yz - wx ) * sz;
  3661. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3662. te[ 11 ] = 0;
  3663. te[ 12 ] = position.x;
  3664. te[ 13 ] = position.y;
  3665. te[ 14 ] = position.z;
  3666. te[ 15 ] = 1;
  3667. return this;
  3668. }
  3669. decompose( position, quaternion, scale ) {
  3670. const te = this.elements;
  3671. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3672. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3673. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3674. // if determine is negative, we need to invert one scale
  3675. const det = this.determinant();
  3676. if ( det < 0 ) sx = - sx;
  3677. position.x = te[ 12 ];
  3678. position.y = te[ 13 ];
  3679. position.z = te[ 14 ];
  3680. // scale the rotation part
  3681. _m1$2.copy( this );
  3682. const invSX = 1 / sx;
  3683. const invSY = 1 / sy;
  3684. const invSZ = 1 / sz;
  3685. _m1$2.elements[ 0 ] *= invSX;
  3686. _m1$2.elements[ 1 ] *= invSX;
  3687. _m1$2.elements[ 2 ] *= invSX;
  3688. _m1$2.elements[ 4 ] *= invSY;
  3689. _m1$2.elements[ 5 ] *= invSY;
  3690. _m1$2.elements[ 6 ] *= invSY;
  3691. _m1$2.elements[ 8 ] *= invSZ;
  3692. _m1$2.elements[ 9 ] *= invSZ;
  3693. _m1$2.elements[ 10 ] *= invSZ;
  3694. quaternion.setFromRotationMatrix( _m1$2 );
  3695. scale.x = sx;
  3696. scale.y = sy;
  3697. scale.z = sz;
  3698. return this;
  3699. }
  3700. makePerspective( left, right, top, bottom, near, far ) {
  3701. if ( far === undefined ) {
  3702. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3703. }
  3704. const te = this.elements;
  3705. const x = 2 * near / ( right - left );
  3706. const y = 2 * near / ( top - bottom );
  3707. const a = ( right + left ) / ( right - left );
  3708. const b = ( top + bottom ) / ( top - bottom );
  3709. const c = - ( far + near ) / ( far - near );
  3710. const d = - 2 * far * near / ( far - near );
  3711. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3712. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3713. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3714. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3715. return this;
  3716. }
  3717. makeOrthographic( left, right, top, bottom, near, far ) {
  3718. const te = this.elements;
  3719. const w = 1.0 / ( right - left );
  3720. const h = 1.0 / ( top - bottom );
  3721. const p = 1.0 / ( far - near );
  3722. const x = ( right + left ) * w;
  3723. const y = ( top + bottom ) * h;
  3724. const z = ( far + near ) * p;
  3725. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3726. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3727. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3728. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3729. return this;
  3730. }
  3731. equals( matrix ) {
  3732. const te = this.elements;
  3733. const me = matrix.elements;
  3734. for ( let i = 0; i < 16; i ++ ) {
  3735. if ( te[ i ] !== me[ i ] ) return false;
  3736. }
  3737. return true;
  3738. }
  3739. fromArray( array, offset = 0 ) {
  3740. for ( let i = 0; i < 16; i ++ ) {
  3741. this.elements[ i ] = array[ i + offset ];
  3742. }
  3743. return this;
  3744. }
  3745. toArray( array = [], offset = 0 ) {
  3746. const te = this.elements;
  3747. array[ offset ] = te[ 0 ];
  3748. array[ offset + 1 ] = te[ 1 ];
  3749. array[ offset + 2 ] = te[ 2 ];
  3750. array[ offset + 3 ] = te[ 3 ];
  3751. array[ offset + 4 ] = te[ 4 ];
  3752. array[ offset + 5 ] = te[ 5 ];
  3753. array[ offset + 6 ] = te[ 6 ];
  3754. array[ offset + 7 ] = te[ 7 ];
  3755. array[ offset + 8 ] = te[ 8 ];
  3756. array[ offset + 9 ] = te[ 9 ];
  3757. array[ offset + 10 ] = te[ 10 ];
  3758. array[ offset + 11 ] = te[ 11 ];
  3759. array[ offset + 12 ] = te[ 12 ];
  3760. array[ offset + 13 ] = te[ 13 ];
  3761. array[ offset + 14 ] = te[ 14 ];
  3762. array[ offset + 15 ] = te[ 15 ];
  3763. return array;
  3764. }
  3765. }
  3766. Matrix4.prototype.isMatrix4 = true;
  3767. const _v1$5 = /*@__PURE__*/ new Vector3();
  3768. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3769. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3770. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3771. const _x = /*@__PURE__*/ new Vector3();
  3772. const _y = /*@__PURE__*/ new Vector3();
  3773. const _z = /*@__PURE__*/ new Vector3();
  3774. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3775. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3776. class Euler {
  3777. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3778. this._x = x;
  3779. this._y = y;
  3780. this._z = z;
  3781. this._order = order;
  3782. }
  3783. get x() {
  3784. return this._x;
  3785. }
  3786. set x( value ) {
  3787. this._x = value;
  3788. this._onChangeCallback();
  3789. }
  3790. get y() {
  3791. return this._y;
  3792. }
  3793. set y( value ) {
  3794. this._y = value;
  3795. this._onChangeCallback();
  3796. }
  3797. get z() {
  3798. return this._z;
  3799. }
  3800. set z( value ) {
  3801. this._z = value;
  3802. this._onChangeCallback();
  3803. }
  3804. get order() {
  3805. return this._order;
  3806. }
  3807. set order( value ) {
  3808. this._order = value;
  3809. this._onChangeCallback();
  3810. }
  3811. set( x, y, z, order ) {
  3812. this._x = x;
  3813. this._y = y;
  3814. this._z = z;
  3815. this._order = order || this._order;
  3816. this._onChangeCallback();
  3817. return this;
  3818. }
  3819. clone() {
  3820. return new this.constructor( this._x, this._y, this._z, this._order );
  3821. }
  3822. copy( euler ) {
  3823. this._x = euler._x;
  3824. this._y = euler._y;
  3825. this._z = euler._z;
  3826. this._order = euler._order;
  3827. this._onChangeCallback();
  3828. return this;
  3829. }
  3830. setFromRotationMatrix( m, order, update ) {
  3831. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3832. const te = m.elements;
  3833. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3834. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3835. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3836. order = order || this._order;
  3837. switch ( order ) {
  3838. case 'XYZ':
  3839. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3840. if ( Math.abs( m13 ) < 0.9999999 ) {
  3841. this._x = Math.atan2( - m23, m33 );
  3842. this._z = Math.atan2( - m12, m11 );
  3843. } else {
  3844. this._x = Math.atan2( m32, m22 );
  3845. this._z = 0;
  3846. }
  3847. break;
  3848. case 'YXZ':
  3849. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3850. if ( Math.abs( m23 ) < 0.9999999 ) {
  3851. this._y = Math.atan2( m13, m33 );
  3852. this._z = Math.atan2( m21, m22 );
  3853. } else {
  3854. this._y = Math.atan2( - m31, m11 );
  3855. this._z = 0;
  3856. }
  3857. break;
  3858. case 'ZXY':
  3859. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3860. if ( Math.abs( m32 ) < 0.9999999 ) {
  3861. this._y = Math.atan2( - m31, m33 );
  3862. this._z = Math.atan2( - m12, m22 );
  3863. } else {
  3864. this._y = 0;
  3865. this._z = Math.atan2( m21, m11 );
  3866. }
  3867. break;
  3868. case 'ZYX':
  3869. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3870. if ( Math.abs( m31 ) < 0.9999999 ) {
  3871. this._x = Math.atan2( m32, m33 );
  3872. this._z = Math.atan2( m21, m11 );
  3873. } else {
  3874. this._x = 0;
  3875. this._z = Math.atan2( - m12, m22 );
  3876. }
  3877. break;
  3878. case 'YZX':
  3879. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3880. if ( Math.abs( m21 ) < 0.9999999 ) {
  3881. this._x = Math.atan2( - m23, m22 );
  3882. this._y = Math.atan2( - m31, m11 );
  3883. } else {
  3884. this._x = 0;
  3885. this._y = Math.atan2( m13, m33 );
  3886. }
  3887. break;
  3888. case 'XZY':
  3889. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3890. if ( Math.abs( m12 ) < 0.9999999 ) {
  3891. this._x = Math.atan2( m32, m22 );
  3892. this._y = Math.atan2( m13, m11 );
  3893. } else {
  3894. this._x = Math.atan2( - m23, m33 );
  3895. this._y = 0;
  3896. }
  3897. break;
  3898. default:
  3899. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3900. }
  3901. this._order = order;
  3902. if ( update !== false ) this._onChangeCallback();
  3903. return this;
  3904. }
  3905. setFromQuaternion( q, order, update ) {
  3906. _matrix$1.makeRotationFromQuaternion( q );
  3907. return this.setFromRotationMatrix( _matrix$1, order, update );
  3908. }
  3909. setFromVector3( v, order ) {
  3910. return this.set( v.x, v.y, v.z, order || this._order );
  3911. }
  3912. reorder( newOrder ) {
  3913. // WARNING: this discards revolution information -bhouston
  3914. _quaternion$3.setFromEuler( this );
  3915. return this.setFromQuaternion( _quaternion$3, newOrder );
  3916. }
  3917. equals( euler ) {
  3918. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3919. }
  3920. fromArray( array ) {
  3921. this._x = array[ 0 ];
  3922. this._y = array[ 1 ];
  3923. this._z = array[ 2 ];
  3924. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3925. this._onChangeCallback();
  3926. return this;
  3927. }
  3928. toArray( array = [], offset = 0 ) {
  3929. array[ offset ] = this._x;
  3930. array[ offset + 1 ] = this._y;
  3931. array[ offset + 2 ] = this._z;
  3932. array[ offset + 3 ] = this._order;
  3933. return array;
  3934. }
  3935. toVector3( optionalResult ) {
  3936. if ( optionalResult ) {
  3937. return optionalResult.set( this._x, this._y, this._z );
  3938. } else {
  3939. return new Vector3( this._x, this._y, this._z );
  3940. }
  3941. }
  3942. _onChange( callback ) {
  3943. this._onChangeCallback = callback;
  3944. return this;
  3945. }
  3946. _onChangeCallback() {}
  3947. }
  3948. Euler.prototype.isEuler = true;
  3949. Euler.DefaultOrder = 'XYZ';
  3950. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  3951. class Layers {
  3952. constructor() {
  3953. this.mask = 1 | 0;
  3954. }
  3955. set( channel ) {
  3956. this.mask = 1 << channel | 0;
  3957. }
  3958. enable( channel ) {
  3959. this.mask |= 1 << channel | 0;
  3960. }
  3961. enableAll() {
  3962. this.mask = 0xffffffff | 0;
  3963. }
  3964. toggle( channel ) {
  3965. this.mask ^= 1 << channel | 0;
  3966. }
  3967. disable( channel ) {
  3968. this.mask &= ~ ( 1 << channel | 0 );
  3969. }
  3970. disableAll() {
  3971. this.mask = 0;
  3972. }
  3973. test( layers ) {
  3974. return ( this.mask & layers.mask ) !== 0;
  3975. }
  3976. }
  3977. let _object3DId = 0;
  3978. const _v1$4 = /*@__PURE__*/ new Vector3();
  3979. const _q1 = /*@__PURE__*/ new Quaternion();
  3980. const _m1$1 = /*@__PURE__*/ new Matrix4();
  3981. const _target = /*@__PURE__*/ new Vector3();
  3982. const _position$3 = /*@__PURE__*/ new Vector3();
  3983. const _scale$2 = /*@__PURE__*/ new Vector3();
  3984. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  3985. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  3986. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  3987. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  3988. const _addedEvent = { type: 'added' };
  3989. const _removedEvent = { type: 'removed' };
  3990. class Object3D extends EventDispatcher {
  3991. constructor() {
  3992. super();
  3993. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  3994. this.uuid = generateUUID();
  3995. this.name = '';
  3996. this.type = 'Object3D';
  3997. this.parent = null;
  3998. this.children = [];
  3999. this.up = Object3D.DefaultUp.clone();
  4000. const position = new Vector3();
  4001. const rotation = new Euler();
  4002. const quaternion = new Quaternion();
  4003. const scale = new Vector3( 1, 1, 1 );
  4004. function onRotationChange() {
  4005. quaternion.setFromEuler( rotation, false );
  4006. }
  4007. function onQuaternionChange() {
  4008. rotation.setFromQuaternion( quaternion, undefined, false );
  4009. }
  4010. rotation._onChange( onRotationChange );
  4011. quaternion._onChange( onQuaternionChange );
  4012. Object.defineProperties( this, {
  4013. position: {
  4014. configurable: true,
  4015. enumerable: true,
  4016. value: position
  4017. },
  4018. rotation: {
  4019. configurable: true,
  4020. enumerable: true,
  4021. value: rotation
  4022. },
  4023. quaternion: {
  4024. configurable: true,
  4025. enumerable: true,
  4026. value: quaternion
  4027. },
  4028. scale: {
  4029. configurable: true,
  4030. enumerable: true,
  4031. value: scale
  4032. },
  4033. modelViewMatrix: {
  4034. value: new Matrix4()
  4035. },
  4036. normalMatrix: {
  4037. value: new Matrix3()
  4038. }
  4039. } );
  4040. this.matrix = new Matrix4();
  4041. this.matrixWorld = new Matrix4();
  4042. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4043. this.matrixWorldNeedsUpdate = false;
  4044. this.layers = new Layers();
  4045. this.visible = true;
  4046. this.castShadow = false;
  4047. this.receiveShadow = false;
  4048. this.frustumCulled = true;
  4049. this.renderOrder = 0;
  4050. this.animations = [];
  4051. this.userData = {};
  4052. }
  4053. onBeforeRender() {}
  4054. onAfterRender() {}
  4055. applyMatrix4( matrix ) {
  4056. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4057. this.matrix.premultiply( matrix );
  4058. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4059. }
  4060. applyQuaternion( q ) {
  4061. this.quaternion.premultiply( q );
  4062. return this;
  4063. }
  4064. setRotationFromAxisAngle( axis, angle ) {
  4065. // assumes axis is normalized
  4066. this.quaternion.setFromAxisAngle( axis, angle );
  4067. }
  4068. setRotationFromEuler( euler ) {
  4069. this.quaternion.setFromEuler( euler, true );
  4070. }
  4071. setRotationFromMatrix( m ) {
  4072. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4073. this.quaternion.setFromRotationMatrix( m );
  4074. }
  4075. setRotationFromQuaternion( q ) {
  4076. // assumes q is normalized
  4077. this.quaternion.copy( q );
  4078. }
  4079. rotateOnAxis( axis, angle ) {
  4080. // rotate object on axis in object space
  4081. // axis is assumed to be normalized
  4082. _q1.setFromAxisAngle( axis, angle );
  4083. this.quaternion.multiply( _q1 );
  4084. return this;
  4085. }
  4086. rotateOnWorldAxis( axis, angle ) {
  4087. // rotate object on axis in world space
  4088. // axis is assumed to be normalized
  4089. // method assumes no rotated parent
  4090. _q1.setFromAxisAngle( axis, angle );
  4091. this.quaternion.premultiply( _q1 );
  4092. return this;
  4093. }
  4094. rotateX( angle ) {
  4095. return this.rotateOnAxis( _xAxis, angle );
  4096. }
  4097. rotateY( angle ) {
  4098. return this.rotateOnAxis( _yAxis, angle );
  4099. }
  4100. rotateZ( angle ) {
  4101. return this.rotateOnAxis( _zAxis, angle );
  4102. }
  4103. translateOnAxis( axis, distance ) {
  4104. // translate object by distance along axis in object space
  4105. // axis is assumed to be normalized
  4106. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4107. this.position.add( _v1$4.multiplyScalar( distance ) );
  4108. return this;
  4109. }
  4110. translateX( distance ) {
  4111. return this.translateOnAxis( _xAxis, distance );
  4112. }
  4113. translateY( distance ) {
  4114. return this.translateOnAxis( _yAxis, distance );
  4115. }
  4116. translateZ( distance ) {
  4117. return this.translateOnAxis( _zAxis, distance );
  4118. }
  4119. localToWorld( vector ) {
  4120. return vector.applyMatrix4( this.matrixWorld );
  4121. }
  4122. worldToLocal( vector ) {
  4123. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4124. }
  4125. lookAt( x, y, z ) {
  4126. // This method does not support objects having non-uniformly-scaled parent(s)
  4127. if ( x.isVector3 ) {
  4128. _target.copy( x );
  4129. } else {
  4130. _target.set( x, y, z );
  4131. }
  4132. const parent = this.parent;
  4133. this.updateWorldMatrix( true, false );
  4134. _position$3.setFromMatrixPosition( this.matrixWorld );
  4135. if ( this.isCamera || this.isLight ) {
  4136. _m1$1.lookAt( _position$3, _target, this.up );
  4137. } else {
  4138. _m1$1.lookAt( _target, _position$3, this.up );
  4139. }
  4140. this.quaternion.setFromRotationMatrix( _m1$1 );
  4141. if ( parent ) {
  4142. _m1$1.extractRotation( parent.matrixWorld );
  4143. _q1.setFromRotationMatrix( _m1$1 );
  4144. this.quaternion.premultiply( _q1.invert() );
  4145. }
  4146. }
  4147. add( object ) {
  4148. if ( arguments.length > 1 ) {
  4149. for ( let i = 0; i < arguments.length; i ++ ) {
  4150. this.add( arguments[ i ] );
  4151. }
  4152. return this;
  4153. }
  4154. if ( object === this ) {
  4155. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4156. return this;
  4157. }
  4158. if ( object && object.isObject3D ) {
  4159. if ( object.parent !== null ) {
  4160. object.parent.remove( object );
  4161. }
  4162. object.parent = this;
  4163. this.children.push( object );
  4164. object.dispatchEvent( _addedEvent );
  4165. } else {
  4166. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4167. }
  4168. return this;
  4169. }
  4170. remove( object ) {
  4171. if ( arguments.length > 1 ) {
  4172. for ( let i = 0; i < arguments.length; i ++ ) {
  4173. this.remove( arguments[ i ] );
  4174. }
  4175. return this;
  4176. }
  4177. const index = this.children.indexOf( object );
  4178. if ( index !== - 1 ) {
  4179. object.parent = null;
  4180. this.children.splice( index, 1 );
  4181. object.dispatchEvent( _removedEvent );
  4182. }
  4183. return this;
  4184. }
  4185. clear() {
  4186. for ( let i = 0; i < this.children.length; i ++ ) {
  4187. const object = this.children[ i ];
  4188. object.parent = null;
  4189. object.dispatchEvent( _removedEvent );
  4190. }
  4191. this.children.length = 0;
  4192. return this;
  4193. }
  4194. attach( object ) {
  4195. // adds object as a child of this, while maintaining the object's world transform
  4196. this.updateWorldMatrix( true, false );
  4197. _m1$1.copy( this.matrixWorld ).invert();
  4198. if ( object.parent !== null ) {
  4199. object.parent.updateWorldMatrix( true, false );
  4200. _m1$1.multiply( object.parent.matrixWorld );
  4201. }
  4202. object.applyMatrix4( _m1$1 );
  4203. this.add( object );
  4204. object.updateWorldMatrix( false, true );
  4205. return this;
  4206. }
  4207. getObjectById( id ) {
  4208. return this.getObjectByProperty( 'id', id );
  4209. }
  4210. getObjectByName( name ) {
  4211. return this.getObjectByProperty( 'name', name );
  4212. }
  4213. getObjectByProperty( name, value ) {
  4214. if ( this[ name ] === value ) return this;
  4215. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4216. const child = this.children[ i ];
  4217. const object = child.getObjectByProperty( name, value );
  4218. if ( object !== undefined ) {
  4219. return object;
  4220. }
  4221. }
  4222. return undefined;
  4223. }
  4224. getWorldPosition( target ) {
  4225. if ( target === undefined ) {
  4226. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4227. target = new Vector3();
  4228. }
  4229. this.updateWorldMatrix( true, false );
  4230. return target.setFromMatrixPosition( this.matrixWorld );
  4231. }
  4232. getWorldQuaternion( target ) {
  4233. if ( target === undefined ) {
  4234. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4235. target = new Quaternion();
  4236. }
  4237. this.updateWorldMatrix( true, false );
  4238. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4239. return target;
  4240. }
  4241. getWorldScale( target ) {
  4242. if ( target === undefined ) {
  4243. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4244. target = new Vector3();
  4245. }
  4246. this.updateWorldMatrix( true, false );
  4247. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4248. return target;
  4249. }
  4250. getWorldDirection( target ) {
  4251. if ( target === undefined ) {
  4252. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4253. target = new Vector3();
  4254. }
  4255. this.updateWorldMatrix( true, false );
  4256. const e = this.matrixWorld.elements;
  4257. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4258. }
  4259. raycast() {}
  4260. traverse( callback ) {
  4261. callback( this );
  4262. const children = this.children;
  4263. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4264. children[ i ].traverse( callback );
  4265. }
  4266. }
  4267. traverseVisible( callback ) {
  4268. if ( this.visible === false ) return;
  4269. callback( this );
  4270. const children = this.children;
  4271. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4272. children[ i ].traverseVisible( callback );
  4273. }
  4274. }
  4275. traverseAncestors( callback ) {
  4276. const parent = this.parent;
  4277. if ( parent !== null ) {
  4278. callback( parent );
  4279. parent.traverseAncestors( callback );
  4280. }
  4281. }
  4282. updateMatrix() {
  4283. this.matrix.compose( this.position, this.quaternion, this.scale );
  4284. this.matrixWorldNeedsUpdate = true;
  4285. }
  4286. updateMatrixWorld( force ) {
  4287. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4288. if ( this.matrixWorldNeedsUpdate || force ) {
  4289. if ( this.parent === null ) {
  4290. this.matrixWorld.copy( this.matrix );
  4291. } else {
  4292. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4293. }
  4294. this.matrixWorldNeedsUpdate = false;
  4295. force = true;
  4296. }
  4297. // update children
  4298. const children = this.children;
  4299. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4300. children[ i ].updateMatrixWorld( force );
  4301. }
  4302. }
  4303. updateWorldMatrix( updateParents, updateChildren ) {
  4304. const parent = this.parent;
  4305. if ( updateParents === true && parent !== null ) {
  4306. parent.updateWorldMatrix( true, false );
  4307. }
  4308. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4309. if ( this.parent === null ) {
  4310. this.matrixWorld.copy( this.matrix );
  4311. } else {
  4312. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4313. }
  4314. // update children
  4315. if ( updateChildren === true ) {
  4316. const children = this.children;
  4317. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4318. children[ i ].updateWorldMatrix( false, true );
  4319. }
  4320. }
  4321. }
  4322. toJSON( meta ) {
  4323. // meta is a string when called from JSON.stringify
  4324. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4325. const output = {};
  4326. // meta is a hash used to collect geometries, materials.
  4327. // not providing it implies that this is the root object
  4328. // being serialized.
  4329. if ( isRootObject ) {
  4330. // initialize meta obj
  4331. meta = {
  4332. geometries: {},
  4333. materials: {},
  4334. textures: {},
  4335. images: {},
  4336. shapes: {},
  4337. skeletons: {},
  4338. animations: {}
  4339. };
  4340. output.metadata = {
  4341. version: 4.5,
  4342. type: 'Object',
  4343. generator: 'Object3D.toJSON'
  4344. };
  4345. }
  4346. // standard Object3D serialization
  4347. const object = {};
  4348. object.uuid = this.uuid;
  4349. object.type = this.type;
  4350. if ( this.name !== '' ) object.name = this.name;
  4351. if ( this.castShadow === true ) object.castShadow = true;
  4352. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4353. if ( this.visible === false ) object.visible = false;
  4354. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4355. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4356. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4357. object.layers = this.layers.mask;
  4358. object.matrix = this.matrix.toArray();
  4359. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4360. // object specific properties
  4361. if ( this.isInstancedMesh ) {
  4362. object.type = 'InstancedMesh';
  4363. object.count = this.count;
  4364. object.instanceMatrix = this.instanceMatrix.toJSON();
  4365. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4366. }
  4367. //
  4368. function serialize( library, element ) {
  4369. if ( library[ element.uuid ] === undefined ) {
  4370. library[ element.uuid ] = element.toJSON( meta );
  4371. }
  4372. return element.uuid;
  4373. }
  4374. if ( this.isMesh || this.isLine || this.isPoints ) {
  4375. object.geometry = serialize( meta.geometries, this.geometry );
  4376. const parameters = this.geometry.parameters;
  4377. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4378. const shapes = parameters.shapes;
  4379. if ( Array.isArray( shapes ) ) {
  4380. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4381. const shape = shapes[ i ];
  4382. serialize( meta.shapes, shape );
  4383. }
  4384. } else {
  4385. serialize( meta.shapes, shapes );
  4386. }
  4387. }
  4388. }
  4389. if ( this.isSkinnedMesh ) {
  4390. object.bindMode = this.bindMode;
  4391. object.bindMatrix = this.bindMatrix.toArray();
  4392. if ( this.skeleton !== undefined ) {
  4393. serialize( meta.skeletons, this.skeleton );
  4394. object.skeleton = this.skeleton.uuid;
  4395. }
  4396. }
  4397. if ( this.material !== undefined ) {
  4398. if ( Array.isArray( this.material ) ) {
  4399. const uuids = [];
  4400. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4401. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4402. }
  4403. object.material = uuids;
  4404. } else {
  4405. object.material = serialize( meta.materials, this.material );
  4406. }
  4407. }
  4408. //
  4409. if ( this.children.length > 0 ) {
  4410. object.children = [];
  4411. for ( let i = 0; i < this.children.length; i ++ ) {
  4412. object.children.push( this.children[ i ].toJSON( meta ).object );
  4413. }
  4414. }
  4415. //
  4416. if ( this.animations.length > 0 ) {
  4417. object.animations = [];
  4418. for ( let i = 0; i < this.animations.length; i ++ ) {
  4419. const animation = this.animations[ i ];
  4420. object.animations.push( serialize( meta.animations, animation ) );
  4421. }
  4422. }
  4423. if ( isRootObject ) {
  4424. const geometries = extractFromCache( meta.geometries );
  4425. const materials = extractFromCache( meta.materials );
  4426. const textures = extractFromCache( meta.textures );
  4427. const images = extractFromCache( meta.images );
  4428. const shapes = extractFromCache( meta.shapes );
  4429. const skeletons = extractFromCache( meta.skeletons );
  4430. const animations = extractFromCache( meta.animations );
  4431. if ( geometries.length > 0 ) output.geometries = geometries;
  4432. if ( materials.length > 0 ) output.materials = materials;
  4433. if ( textures.length > 0 ) output.textures = textures;
  4434. if ( images.length > 0 ) output.images = images;
  4435. if ( shapes.length > 0 ) output.shapes = shapes;
  4436. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4437. if ( animations.length > 0 ) output.animations = animations;
  4438. }
  4439. output.object = object;
  4440. return output;
  4441. // extract data from the cache hash
  4442. // remove metadata on each item
  4443. // and return as array
  4444. function extractFromCache( cache ) {
  4445. const values = [];
  4446. for ( const key in cache ) {
  4447. const data = cache[ key ];
  4448. delete data.metadata;
  4449. values.push( data );
  4450. }
  4451. return values;
  4452. }
  4453. }
  4454. clone( recursive ) {
  4455. return new this.constructor().copy( this, recursive );
  4456. }
  4457. copy( source, recursive = true ) {
  4458. this.name = source.name;
  4459. this.up.copy( source.up );
  4460. this.position.copy( source.position );
  4461. this.rotation.order = source.rotation.order;
  4462. this.quaternion.copy( source.quaternion );
  4463. this.scale.copy( source.scale );
  4464. this.matrix.copy( source.matrix );
  4465. this.matrixWorld.copy( source.matrixWorld );
  4466. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4467. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4468. this.layers.mask = source.layers.mask;
  4469. this.visible = source.visible;
  4470. this.castShadow = source.castShadow;
  4471. this.receiveShadow = source.receiveShadow;
  4472. this.frustumCulled = source.frustumCulled;
  4473. this.renderOrder = source.renderOrder;
  4474. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4475. if ( recursive === true ) {
  4476. for ( let i = 0; i < source.children.length; i ++ ) {
  4477. const child = source.children[ i ];
  4478. this.add( child.clone() );
  4479. }
  4480. }
  4481. return this;
  4482. }
  4483. }
  4484. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4485. Object3D.DefaultMatrixAutoUpdate = true;
  4486. Object3D.prototype.isObject3D = true;
  4487. const _vector1 = /*@__PURE__*/ new Vector3();
  4488. const _vector2$1 = /*@__PURE__*/ new Vector3();
  4489. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  4490. class Plane {
  4491. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  4492. // normal is assumed to be normalized
  4493. this.normal = normal;
  4494. this.constant = constant;
  4495. }
  4496. set( normal, constant ) {
  4497. this.normal.copy( normal );
  4498. this.constant = constant;
  4499. return this;
  4500. }
  4501. setComponents( x, y, z, w ) {
  4502. this.normal.set( x, y, z );
  4503. this.constant = w;
  4504. return this;
  4505. }
  4506. setFromNormalAndCoplanarPoint( normal, point ) {
  4507. this.normal.copy( normal );
  4508. this.constant = - point.dot( this.normal );
  4509. return this;
  4510. }
  4511. setFromCoplanarPoints( a, b, c ) {
  4512. const normal = _vector1.subVectors( c, b ).cross( _vector2$1.subVectors( a, b ) ).normalize();
  4513. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4514. this.setFromNormalAndCoplanarPoint( normal, a );
  4515. return this;
  4516. }
  4517. copy( plane ) {
  4518. this.normal.copy( plane.normal );
  4519. this.constant = plane.constant;
  4520. return this;
  4521. }
  4522. normalize() {
  4523. // Note: will lead to a divide by zero if the plane is invalid.
  4524. const inverseNormalLength = 1.0 / this.normal.length();
  4525. this.normal.multiplyScalar( inverseNormalLength );
  4526. this.constant *= inverseNormalLength;
  4527. return this;
  4528. }
  4529. negate() {
  4530. this.constant *= - 1;
  4531. this.normal.negate();
  4532. return this;
  4533. }
  4534. distanceToPoint( point ) {
  4535. return this.normal.dot( point ) + this.constant;
  4536. }
  4537. distanceToSphere( sphere ) {
  4538. return this.distanceToPoint( sphere.center ) - sphere.radius;
  4539. }
  4540. projectPoint( point, target ) {
  4541. if ( target === undefined ) {
  4542. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  4543. target = new Vector3();
  4544. }
  4545. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  4546. }
  4547. intersectLine( line, target ) {
  4548. if ( target === undefined ) {
  4549. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  4550. target = new Vector3();
  4551. }
  4552. const direction = line.delta( _vector1 );
  4553. const denominator = this.normal.dot( direction );
  4554. if ( denominator === 0 ) {
  4555. // line is coplanar, return origin
  4556. if ( this.distanceToPoint( line.start ) === 0 ) {
  4557. return target.copy( line.start );
  4558. }
  4559. // Unsure if this is the correct method to handle this case.
  4560. return null;
  4561. }
  4562. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  4563. if ( t < 0 || t > 1 ) {
  4564. return null;
  4565. }
  4566. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  4567. }
  4568. intersectsLine( line ) {
  4569. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4570. const startSign = this.distanceToPoint( line.start );
  4571. const endSign = this.distanceToPoint( line.end );
  4572. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  4573. }
  4574. intersectsBox( box ) {
  4575. return box.intersectsPlane( this );
  4576. }
  4577. intersectsSphere( sphere ) {
  4578. return sphere.intersectsPlane( this );
  4579. }
  4580. coplanarPoint( target ) {
  4581. if ( target === undefined ) {
  4582. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  4583. target = new Vector3();
  4584. }
  4585. return target.copy( this.normal ).multiplyScalar( - this.constant );
  4586. }
  4587. applyMatrix4( matrix, optionalNormalMatrix ) {
  4588. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  4589. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  4590. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  4591. this.constant = - referencePoint.dot( normal );
  4592. return this;
  4593. }
  4594. translate( offset ) {
  4595. this.constant -= offset.dot( this.normal );
  4596. return this;
  4597. }
  4598. equals( plane ) {
  4599. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4600. }
  4601. clone() {
  4602. return new this.constructor().copy( this );
  4603. }
  4604. }
  4605. Plane.prototype.isPlane = true;
  4606. const _v0$1 = /*@__PURE__*/ new Vector3();
  4607. const _v1$3 = /*@__PURE__*/ new Vector3();
  4608. const _v2$2 = /*@__PURE__*/ new Vector3();
  4609. const _v3$1 = /*@__PURE__*/ new Vector3();
  4610. const _vab = /*@__PURE__*/ new Vector3();
  4611. const _vac = /*@__PURE__*/ new Vector3();
  4612. const _vbc = /*@__PURE__*/ new Vector3();
  4613. const _vap = /*@__PURE__*/ new Vector3();
  4614. const _vbp = /*@__PURE__*/ new Vector3();
  4615. const _vcp = /*@__PURE__*/ new Vector3();
  4616. class Triangle {
  4617. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4618. this.a = a;
  4619. this.b = b;
  4620. this.c = c;
  4621. }
  4622. static getNormal( a, b, c, target ) {
  4623. if ( target === undefined ) {
  4624. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  4625. target = new Vector3();
  4626. }
  4627. target.subVectors( c, b );
  4628. _v0$1.subVectors( a, b );
  4629. target.cross( _v0$1 );
  4630. const targetLengthSq = target.lengthSq();
  4631. if ( targetLengthSq > 0 ) {
  4632. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4633. }
  4634. return target.set( 0, 0, 0 );
  4635. }
  4636. // static/instance method to calculate barycentric coordinates
  4637. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4638. static getBarycoord( point, a, b, c, target ) {
  4639. _v0$1.subVectors( c, a );
  4640. _v1$3.subVectors( b, a );
  4641. _v2$2.subVectors( point, a );
  4642. const dot00 = _v0$1.dot( _v0$1 );
  4643. const dot01 = _v0$1.dot( _v1$3 );
  4644. const dot02 = _v0$1.dot( _v2$2 );
  4645. const dot11 = _v1$3.dot( _v1$3 );
  4646. const dot12 = _v1$3.dot( _v2$2 );
  4647. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4648. if ( target === undefined ) {
  4649. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  4650. target = new Vector3();
  4651. }
  4652. // collinear or singular triangle
  4653. if ( denom === 0 ) {
  4654. // arbitrary location outside of triangle?
  4655. // not sure if this is the best idea, maybe should be returning undefined
  4656. return target.set( - 2, - 1, - 1 );
  4657. }
  4658. const invDenom = 1 / denom;
  4659. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4660. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4661. // barycentric coordinates must always sum to 1
  4662. return target.set( 1 - u - v, v, u );
  4663. }
  4664. static containsPoint( point, a, b, c ) {
  4665. this.getBarycoord( point, a, b, c, _v3$1 );
  4666. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4667. }
  4668. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4669. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4670. target.set( 0, 0 );
  4671. target.addScaledVector( uv1, _v3$1.x );
  4672. target.addScaledVector( uv2, _v3$1.y );
  4673. target.addScaledVector( uv3, _v3$1.z );
  4674. return target;
  4675. }
  4676. static isFrontFacing( a, b, c, direction ) {
  4677. _v0$1.subVectors( c, b );
  4678. _v1$3.subVectors( a, b );
  4679. // strictly front facing
  4680. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4681. }
  4682. set( a, b, c ) {
  4683. this.a.copy( a );
  4684. this.b.copy( b );
  4685. this.c.copy( c );
  4686. return this;
  4687. }
  4688. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4689. this.a.copy( points[ i0 ] );
  4690. this.b.copy( points[ i1 ] );
  4691. this.c.copy( points[ i2 ] );
  4692. return this;
  4693. }
  4694. clone() {
  4695. return new this.constructor().copy( this );
  4696. }
  4697. copy( triangle ) {
  4698. this.a.copy( triangle.a );
  4699. this.b.copy( triangle.b );
  4700. this.c.copy( triangle.c );
  4701. return this;
  4702. }
  4703. getArea() {
  4704. _v0$1.subVectors( this.c, this.b );
  4705. _v1$3.subVectors( this.a, this.b );
  4706. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4707. }
  4708. getMidpoint( target ) {
  4709. if ( target === undefined ) {
  4710. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  4711. target = new Vector3();
  4712. }
  4713. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4714. }
  4715. getNormal( target ) {
  4716. return Triangle.getNormal( this.a, this.b, this.c, target );
  4717. }
  4718. getPlane( target ) {
  4719. if ( target === undefined ) {
  4720. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  4721. target = new Plane();
  4722. }
  4723. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4724. }
  4725. getBarycoord( point, target ) {
  4726. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4727. }
  4728. getUV( point, uv1, uv2, uv3, target ) {
  4729. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4730. }
  4731. containsPoint( point ) {
  4732. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4733. }
  4734. isFrontFacing( direction ) {
  4735. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4736. }
  4737. intersectsBox( box ) {
  4738. return box.intersectsTriangle( this );
  4739. }
  4740. closestPointToPoint( p, target ) {
  4741. if ( target === undefined ) {
  4742. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  4743. target = new Vector3();
  4744. }
  4745. const a = this.a, b = this.b, c = this.c;
  4746. let v, w;
  4747. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4748. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4749. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4750. // basically, we're distinguishing which of the voronoi regions of the triangle
  4751. // the point lies in with the minimum amount of redundant computation.
  4752. _vab.subVectors( b, a );
  4753. _vac.subVectors( c, a );
  4754. _vap.subVectors( p, a );
  4755. const d1 = _vab.dot( _vap );
  4756. const d2 = _vac.dot( _vap );
  4757. if ( d1 <= 0 && d2 <= 0 ) {
  4758. // vertex region of A; barycentric coords (1, 0, 0)
  4759. return target.copy( a );
  4760. }
  4761. _vbp.subVectors( p, b );
  4762. const d3 = _vab.dot( _vbp );
  4763. const d4 = _vac.dot( _vbp );
  4764. if ( d3 >= 0 && d4 <= d3 ) {
  4765. // vertex region of B; barycentric coords (0, 1, 0)
  4766. return target.copy( b );
  4767. }
  4768. const vc = d1 * d4 - d3 * d2;
  4769. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4770. v = d1 / ( d1 - d3 );
  4771. // edge region of AB; barycentric coords (1-v, v, 0)
  4772. return target.copy( a ).addScaledVector( _vab, v );
  4773. }
  4774. _vcp.subVectors( p, c );
  4775. const d5 = _vab.dot( _vcp );
  4776. const d6 = _vac.dot( _vcp );
  4777. if ( d6 >= 0 && d5 <= d6 ) {
  4778. // vertex region of C; barycentric coords (0, 0, 1)
  4779. return target.copy( c );
  4780. }
  4781. const vb = d5 * d2 - d1 * d6;
  4782. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4783. w = d2 / ( d2 - d6 );
  4784. // edge region of AC; barycentric coords (1-w, 0, w)
  4785. return target.copy( a ).addScaledVector( _vac, w );
  4786. }
  4787. const va = d3 * d6 - d5 * d4;
  4788. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4789. _vbc.subVectors( c, b );
  4790. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4791. // edge region of BC; barycentric coords (0, 1-w, w)
  4792. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4793. }
  4794. // face region
  4795. const denom = 1 / ( va + vb + vc );
  4796. // u = va * denom
  4797. v = vb * denom;
  4798. w = vc * denom;
  4799. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4800. }
  4801. equals( triangle ) {
  4802. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4803. }
  4804. }
  4805. let materialId = 0;
  4806. class Material extends EventDispatcher {
  4807. constructor() {
  4808. super();
  4809. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4810. this.uuid = generateUUID();
  4811. this.name = '';
  4812. this.type = 'Material';
  4813. this.fog = true;
  4814. this.blending = NormalBlending;
  4815. this.side = FrontSide;
  4816. this.vertexColors = false;
  4817. this.opacity = 1;
  4818. this.transparent = false;
  4819. this.blendSrc = SrcAlphaFactor;
  4820. this.blendDst = OneMinusSrcAlphaFactor;
  4821. this.blendEquation = AddEquation;
  4822. this.blendSrcAlpha = null;
  4823. this.blendDstAlpha = null;
  4824. this.blendEquationAlpha = null;
  4825. this.depthFunc = LessEqualDepth;
  4826. this.depthTest = true;
  4827. this.depthWrite = true;
  4828. this.stencilWriteMask = 0xff;
  4829. this.stencilFunc = AlwaysStencilFunc;
  4830. this.stencilRef = 0;
  4831. this.stencilFuncMask = 0xff;
  4832. this.stencilFail = KeepStencilOp;
  4833. this.stencilZFail = KeepStencilOp;
  4834. this.stencilZPass = KeepStencilOp;
  4835. this.stencilWrite = false;
  4836. this.clippingPlanes = null;
  4837. this.clipIntersection = false;
  4838. this.clipShadows = false;
  4839. this.shadowSide = null;
  4840. this.colorWrite = true;
  4841. this.precision = null; // override the renderer's default precision for this material
  4842. this.polygonOffset = false;
  4843. this.polygonOffsetFactor = 0;
  4844. this.polygonOffsetUnits = 0;
  4845. this.dithering = false;
  4846. this.alphaTest = 0;
  4847. this.alphaToCoverage = false;
  4848. this.premultipliedAlpha = false;
  4849. this.visible = true;
  4850. this.toneMapped = true;
  4851. this.userData = {};
  4852. this.version = 0;
  4853. }
  4854. onBuild( /* shaderobject, renderer */ ) {}
  4855. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4856. customProgramCacheKey() {
  4857. return this.onBeforeCompile.toString();
  4858. }
  4859. setValues( values ) {
  4860. if ( values === undefined ) return;
  4861. for ( const key in values ) {
  4862. const newValue = values[ key ];
  4863. if ( newValue === undefined ) {
  4864. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4865. continue;
  4866. }
  4867. // for backward compatability if shading is set in the constructor
  4868. if ( key === 'shading' ) {
  4869. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4870. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4871. continue;
  4872. }
  4873. const currentValue = this[ key ];
  4874. if ( currentValue === undefined ) {
  4875. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4876. continue;
  4877. }
  4878. if ( currentValue && currentValue.isColor ) {
  4879. currentValue.set( newValue );
  4880. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4881. currentValue.copy( newValue );
  4882. } else {
  4883. this[ key ] = newValue;
  4884. }
  4885. }
  4886. }
  4887. toJSON( meta ) {
  4888. const isRoot = ( meta === undefined || typeof meta === 'string' );
  4889. if ( isRoot ) {
  4890. meta = {
  4891. textures: {},
  4892. images: {}
  4893. };
  4894. }
  4895. const data = {
  4896. metadata: {
  4897. version: 4.5,
  4898. type: 'Material',
  4899. generator: 'Material.toJSON'
  4900. }
  4901. };
  4902. // standard Material serialization
  4903. data.uuid = this.uuid;
  4904. data.type = this.type;
  4905. if ( this.name !== '' ) data.name = this.name;
  4906. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4907. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4908. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4909. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  4910. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4911. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  4912. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4913. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4914. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  4915. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  4916. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  4917. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  4918. }
  4919. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  4920. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  4921. }
  4922. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  4923. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  4924. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4925. }
  4926. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4927. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  4928. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4929. if ( this.lightMap && this.lightMap.isTexture ) {
  4930. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4931. data.lightMapIntensity = this.lightMapIntensity;
  4932. }
  4933. if ( this.aoMap && this.aoMap.isTexture ) {
  4934. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  4935. data.aoMapIntensity = this.aoMapIntensity;
  4936. }
  4937. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4938. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4939. data.bumpScale = this.bumpScale;
  4940. }
  4941. if ( this.normalMap && this.normalMap.isTexture ) {
  4942. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4943. data.normalMapType = this.normalMapType;
  4944. data.normalScale = this.normalScale.toArray();
  4945. }
  4946. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4947. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4948. data.displacementScale = this.displacementScale;
  4949. data.displacementBias = this.displacementBias;
  4950. }
  4951. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4952. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4953. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4954. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4955. if ( this.envMap && this.envMap.isTexture ) {
  4956. data.envMap = this.envMap.toJSON( meta ).uuid;
  4957. if ( this.combine !== undefined ) data.combine = this.combine;
  4958. }
  4959. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  4960. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  4961. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  4962. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4963. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4964. }
  4965. if ( this.size !== undefined ) data.size = this.size;
  4966. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  4967. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4968. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4969. if ( this.side !== FrontSide ) data.side = this.side;
  4970. if ( this.vertexColors ) data.vertexColors = true;
  4971. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4972. if ( this.transparent === true ) data.transparent = this.transparent;
  4973. data.depthFunc = this.depthFunc;
  4974. data.depthTest = this.depthTest;
  4975. data.depthWrite = this.depthWrite;
  4976. data.colorWrite = this.colorWrite;
  4977. data.stencilWrite = this.stencilWrite;
  4978. data.stencilWriteMask = this.stencilWriteMask;
  4979. data.stencilFunc = this.stencilFunc;
  4980. data.stencilRef = this.stencilRef;
  4981. data.stencilFuncMask = this.stencilFuncMask;
  4982. data.stencilFail = this.stencilFail;
  4983. data.stencilZFail = this.stencilZFail;
  4984. data.stencilZPass = this.stencilZPass;
  4985. // rotation (SpriteMaterial)
  4986. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  4987. if ( this.polygonOffset === true ) data.polygonOffset = true;
  4988. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4989. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4990. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  4991. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  4992. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  4993. if ( this.scale !== undefined ) data.scale = this.scale;
  4994. if ( this.dithering === true ) data.dithering = true;
  4995. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4996. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  4997. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4998. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4999. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5000. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5001. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5002. if ( this.morphTargets === true ) data.morphTargets = true;
  5003. if ( this.morphNormals === true ) data.morphNormals = true;
  5004. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5005. if ( this.visible === false ) data.visible = false;
  5006. if ( this.toneMapped === false ) data.toneMapped = false;
  5007. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5008. // TODO: Copied from Object3D.toJSON
  5009. function extractFromCache( cache ) {
  5010. const values = [];
  5011. for ( const key in cache ) {
  5012. const data = cache[ key ];
  5013. delete data.metadata;
  5014. values.push( data );
  5015. }
  5016. return values;
  5017. }
  5018. if ( isRoot ) {
  5019. const textures = extractFromCache( meta.textures );
  5020. const images = extractFromCache( meta.images );
  5021. if ( textures.length > 0 ) data.textures = textures;
  5022. if ( images.length > 0 ) data.images = images;
  5023. }
  5024. return data;
  5025. }
  5026. clone() {
  5027. return new this.constructor().copy( this );
  5028. }
  5029. copy( source ) {
  5030. this.name = source.name;
  5031. this.fog = source.fog;
  5032. this.blending = source.blending;
  5033. this.side = source.side;
  5034. this.vertexColors = source.vertexColors;
  5035. this.opacity = source.opacity;
  5036. this.transparent = source.transparent;
  5037. this.blendSrc = source.blendSrc;
  5038. this.blendDst = source.blendDst;
  5039. this.blendEquation = source.blendEquation;
  5040. this.blendSrcAlpha = source.blendSrcAlpha;
  5041. this.blendDstAlpha = source.blendDstAlpha;
  5042. this.blendEquationAlpha = source.blendEquationAlpha;
  5043. this.depthFunc = source.depthFunc;
  5044. this.depthTest = source.depthTest;
  5045. this.depthWrite = source.depthWrite;
  5046. this.stencilWriteMask = source.stencilWriteMask;
  5047. this.stencilFunc = source.stencilFunc;
  5048. this.stencilRef = source.stencilRef;
  5049. this.stencilFuncMask = source.stencilFuncMask;
  5050. this.stencilFail = source.stencilFail;
  5051. this.stencilZFail = source.stencilZFail;
  5052. this.stencilZPass = source.stencilZPass;
  5053. this.stencilWrite = source.stencilWrite;
  5054. const srcPlanes = source.clippingPlanes;
  5055. let dstPlanes = null;
  5056. if ( srcPlanes !== null ) {
  5057. const n = srcPlanes.length;
  5058. dstPlanes = new Array( n );
  5059. for ( let i = 0; i !== n; ++ i ) {
  5060. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5061. }
  5062. }
  5063. this.clippingPlanes = dstPlanes;
  5064. this.clipIntersection = source.clipIntersection;
  5065. this.clipShadows = source.clipShadows;
  5066. this.shadowSide = source.shadowSide;
  5067. this.colorWrite = source.colorWrite;
  5068. this.precision = source.precision;
  5069. this.polygonOffset = source.polygonOffset;
  5070. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5071. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5072. this.dithering = source.dithering;
  5073. this.alphaTest = source.alphaTest;
  5074. this.alphaToCoverage = source.alphaToCoverage;
  5075. this.premultipliedAlpha = source.premultipliedAlpha;
  5076. this.visible = source.visible;
  5077. this.toneMapped = source.toneMapped;
  5078. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5079. return this;
  5080. }
  5081. dispose() {
  5082. this.dispatchEvent( { type: 'dispose' } );
  5083. }
  5084. set needsUpdate( value ) {
  5085. if ( value === true ) this.version ++;
  5086. }
  5087. }
  5088. Material.prototype.isMaterial = true;
  5089. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5090. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5091. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5092. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5093. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5094. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5095. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5096. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5097. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5098. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5099. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5100. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5101. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5102. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5103. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5104. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5105. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5106. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5107. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5108. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5109. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5110. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5111. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5112. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5113. const _hslA = { h: 0, s: 0, l: 0 };
  5114. const _hslB = { h: 0, s: 0, l: 0 };
  5115. function hue2rgb( p, q, t ) {
  5116. if ( t < 0 ) t += 1;
  5117. if ( t > 1 ) t -= 1;
  5118. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5119. if ( t < 1 / 2 ) return q;
  5120. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5121. return p;
  5122. }
  5123. function SRGBToLinear( c ) {
  5124. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5125. }
  5126. function LinearToSRGB( c ) {
  5127. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5128. }
  5129. class Color {
  5130. constructor( r, g, b ) {
  5131. if ( g === undefined && b === undefined ) {
  5132. // r is THREE.Color, hex or string
  5133. return this.set( r );
  5134. }
  5135. return this.setRGB( r, g, b );
  5136. }
  5137. set( value ) {
  5138. if ( value && value.isColor ) {
  5139. this.copy( value );
  5140. } else if ( typeof value === 'number' ) {
  5141. this.setHex( value );
  5142. } else if ( typeof value === 'string' ) {
  5143. this.setStyle( value );
  5144. }
  5145. return this;
  5146. }
  5147. setScalar( scalar ) {
  5148. this.r = scalar;
  5149. this.g = scalar;
  5150. this.b = scalar;
  5151. return this;
  5152. }
  5153. setHex( hex ) {
  5154. hex = Math.floor( hex );
  5155. this.r = ( hex >> 16 & 255 ) / 255;
  5156. this.g = ( hex >> 8 & 255 ) / 255;
  5157. this.b = ( hex & 255 ) / 255;
  5158. return this;
  5159. }
  5160. setRGB( r, g, b ) {
  5161. this.r = r;
  5162. this.g = g;
  5163. this.b = b;
  5164. return this;
  5165. }
  5166. setHSL( h, s, l ) {
  5167. // h,s,l ranges are in 0.0 - 1.0
  5168. h = euclideanModulo( h, 1 );
  5169. s = clamp( s, 0, 1 );
  5170. l = clamp( l, 0, 1 );
  5171. if ( s === 0 ) {
  5172. this.r = this.g = this.b = l;
  5173. } else {
  5174. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5175. const q = ( 2 * l ) - p;
  5176. this.r = hue2rgb( q, p, h + 1 / 3 );
  5177. this.g = hue2rgb( q, p, h );
  5178. this.b = hue2rgb( q, p, h - 1 / 3 );
  5179. }
  5180. return this;
  5181. }
  5182. setStyle( style ) {
  5183. function handleAlpha( string ) {
  5184. if ( string === undefined ) return;
  5185. if ( parseFloat( string ) < 1 ) {
  5186. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5187. }
  5188. }
  5189. let m;
  5190. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  5191. // rgb / hsl
  5192. let color;
  5193. const name = m[ 1 ];
  5194. const components = m[ 2 ];
  5195. switch ( name ) {
  5196. case 'rgb':
  5197. case 'rgba':
  5198. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5199. // rgb(255,0,0) rgba(255,0,0,0.5)
  5200. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5201. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5202. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5203. handleAlpha( color[ 4 ] );
  5204. return this;
  5205. }
  5206. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5207. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5208. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5209. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5210. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5211. handleAlpha( color[ 4 ] );
  5212. return this;
  5213. }
  5214. break;
  5215. case 'hsl':
  5216. case 'hsla':
  5217. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5218. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5219. const h = parseFloat( color[ 1 ] ) / 360;
  5220. const s = parseInt( color[ 2 ], 10 ) / 100;
  5221. const l = parseInt( color[ 3 ], 10 ) / 100;
  5222. handleAlpha( color[ 4 ] );
  5223. return this.setHSL( h, s, l );
  5224. }
  5225. break;
  5226. }
  5227. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5228. // hex color
  5229. const hex = m[ 1 ];
  5230. const size = hex.length;
  5231. if ( size === 3 ) {
  5232. // #ff0
  5233. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5234. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5235. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5236. return this;
  5237. } else if ( size === 6 ) {
  5238. // #ff0000
  5239. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5240. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5241. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5242. return this;
  5243. }
  5244. }
  5245. if ( style && style.length > 0 ) {
  5246. return this.setColorName( style );
  5247. }
  5248. return this;
  5249. }
  5250. setColorName( style ) {
  5251. // color keywords
  5252. const hex = _colorKeywords[ style.toLowerCase() ];
  5253. if ( hex !== undefined ) {
  5254. // red
  5255. this.setHex( hex );
  5256. } else {
  5257. // unknown color
  5258. console.warn( 'THREE.Color: Unknown color ' + style );
  5259. }
  5260. return this;
  5261. }
  5262. clone() {
  5263. return new this.constructor( this.r, this.g, this.b );
  5264. }
  5265. copy( color ) {
  5266. this.r = color.r;
  5267. this.g = color.g;
  5268. this.b = color.b;
  5269. return this;
  5270. }
  5271. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5272. this.r = Math.pow( color.r, gammaFactor );
  5273. this.g = Math.pow( color.g, gammaFactor );
  5274. this.b = Math.pow( color.b, gammaFactor );
  5275. return this;
  5276. }
  5277. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5278. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5279. this.r = Math.pow( color.r, safeInverse );
  5280. this.g = Math.pow( color.g, safeInverse );
  5281. this.b = Math.pow( color.b, safeInverse );
  5282. return this;
  5283. }
  5284. convertGammaToLinear( gammaFactor ) {
  5285. this.copyGammaToLinear( this, gammaFactor );
  5286. return this;
  5287. }
  5288. convertLinearToGamma( gammaFactor ) {
  5289. this.copyLinearToGamma( this, gammaFactor );
  5290. return this;
  5291. }
  5292. copySRGBToLinear( color ) {
  5293. this.r = SRGBToLinear( color.r );
  5294. this.g = SRGBToLinear( color.g );
  5295. this.b = SRGBToLinear( color.b );
  5296. return this;
  5297. }
  5298. copyLinearToSRGB( color ) {
  5299. this.r = LinearToSRGB( color.r );
  5300. this.g = LinearToSRGB( color.g );
  5301. this.b = LinearToSRGB( color.b );
  5302. return this;
  5303. }
  5304. convertSRGBToLinear() {
  5305. this.copySRGBToLinear( this );
  5306. return this;
  5307. }
  5308. convertLinearToSRGB() {
  5309. this.copyLinearToSRGB( this );
  5310. return this;
  5311. }
  5312. getHex() {
  5313. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5314. }
  5315. getHexString() {
  5316. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5317. }
  5318. getHSL( target ) {
  5319. // h,s,l ranges are in 0.0 - 1.0
  5320. if ( target === undefined ) {
  5321. console.warn( 'THREE.Color: .getHSL() target is now required' );
  5322. target = { h: 0, s: 0, l: 0 };
  5323. }
  5324. const r = this.r, g = this.g, b = this.b;
  5325. const max = Math.max( r, g, b );
  5326. const min = Math.min( r, g, b );
  5327. let hue, saturation;
  5328. const lightness = ( min + max ) / 2.0;
  5329. if ( min === max ) {
  5330. hue = 0;
  5331. saturation = 0;
  5332. } else {
  5333. const delta = max - min;
  5334. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5335. switch ( max ) {
  5336. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5337. case g: hue = ( b - r ) / delta + 2; break;
  5338. case b: hue = ( r - g ) / delta + 4; break;
  5339. }
  5340. hue /= 6;
  5341. }
  5342. target.h = hue;
  5343. target.s = saturation;
  5344. target.l = lightness;
  5345. return target;
  5346. }
  5347. getStyle() {
  5348. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5349. }
  5350. offsetHSL( h, s, l ) {
  5351. this.getHSL( _hslA );
  5352. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5353. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5354. return this;
  5355. }
  5356. add( color ) {
  5357. this.r += color.r;
  5358. this.g += color.g;
  5359. this.b += color.b;
  5360. return this;
  5361. }
  5362. addColors( color1, color2 ) {
  5363. this.r = color1.r + color2.r;
  5364. this.g = color1.g + color2.g;
  5365. this.b = color1.b + color2.b;
  5366. return this;
  5367. }
  5368. addScalar( s ) {
  5369. this.r += s;
  5370. this.g += s;
  5371. this.b += s;
  5372. return this;
  5373. }
  5374. sub( color ) {
  5375. this.r = Math.max( 0, this.r - color.r );
  5376. this.g = Math.max( 0, this.g - color.g );
  5377. this.b = Math.max( 0, this.b - color.b );
  5378. return this;
  5379. }
  5380. multiply( color ) {
  5381. this.r *= color.r;
  5382. this.g *= color.g;
  5383. this.b *= color.b;
  5384. return this;
  5385. }
  5386. multiplyScalar( s ) {
  5387. this.r *= s;
  5388. this.g *= s;
  5389. this.b *= s;
  5390. return this;
  5391. }
  5392. lerp( color, alpha ) {
  5393. this.r += ( color.r - this.r ) * alpha;
  5394. this.g += ( color.g - this.g ) * alpha;
  5395. this.b += ( color.b - this.b ) * alpha;
  5396. return this;
  5397. }
  5398. lerpColors( color1, color2, alpha ) {
  5399. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5400. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5401. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5402. return this;
  5403. }
  5404. lerpHSL( color, alpha ) {
  5405. this.getHSL( _hslA );
  5406. color.getHSL( _hslB );
  5407. const h = lerp( _hslA.h, _hslB.h, alpha );
  5408. const s = lerp( _hslA.s, _hslB.s, alpha );
  5409. const l = lerp( _hslA.l, _hslB.l, alpha );
  5410. this.setHSL( h, s, l );
  5411. return this;
  5412. }
  5413. equals( c ) {
  5414. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5415. }
  5416. fromArray( array, offset = 0 ) {
  5417. this.r = array[ offset ];
  5418. this.g = array[ offset + 1 ];
  5419. this.b = array[ offset + 2 ];
  5420. return this;
  5421. }
  5422. toArray( array = [], offset = 0 ) {
  5423. array[ offset ] = this.r;
  5424. array[ offset + 1 ] = this.g;
  5425. array[ offset + 2 ] = this.b;
  5426. return array;
  5427. }
  5428. fromBufferAttribute( attribute, index ) {
  5429. this.r = attribute.getX( index );
  5430. this.g = attribute.getY( index );
  5431. this.b = attribute.getZ( index );
  5432. if ( attribute.normalized === true ) {
  5433. // assuming Uint8Array
  5434. this.r /= 255;
  5435. this.g /= 255;
  5436. this.b /= 255;
  5437. }
  5438. return this;
  5439. }
  5440. toJSON() {
  5441. return this.getHex();
  5442. }
  5443. }
  5444. Color.NAMES = _colorKeywords;
  5445. Color.prototype.isColor = true;
  5446. Color.prototype.r = 1;
  5447. Color.prototype.g = 1;
  5448. Color.prototype.b = 1;
  5449. /**
  5450. * parameters = {
  5451. * color: <hex>,
  5452. * opacity: <float>,
  5453. * map: new THREE.Texture( <Image> ),
  5454. *
  5455. * lightMap: new THREE.Texture( <Image> ),
  5456. * lightMapIntensity: <float>
  5457. *
  5458. * aoMap: new THREE.Texture( <Image> ),
  5459. * aoMapIntensity: <float>
  5460. *
  5461. * specularMap: new THREE.Texture( <Image> ),
  5462. *
  5463. * alphaMap: new THREE.Texture( <Image> ),
  5464. *
  5465. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5466. * combine: THREE.Multiply,
  5467. * reflectivity: <float>,
  5468. * refractionRatio: <float>,
  5469. *
  5470. * depthTest: <bool>,
  5471. * depthWrite: <bool>,
  5472. *
  5473. * wireframe: <boolean>,
  5474. * wireframeLinewidth: <float>,
  5475. *
  5476. * morphTargets: <bool>
  5477. * }
  5478. */
  5479. class MeshBasicMaterial extends Material {
  5480. constructor( parameters ) {
  5481. super();
  5482. this.type = 'MeshBasicMaterial';
  5483. this.color = new Color( 0xffffff ); // emissive
  5484. this.map = null;
  5485. this.lightMap = null;
  5486. this.lightMapIntensity = 1.0;
  5487. this.aoMap = null;
  5488. this.aoMapIntensity = 1.0;
  5489. this.specularMap = null;
  5490. this.alphaMap = null;
  5491. this.envMap = null;
  5492. this.combine = MultiplyOperation;
  5493. this.reflectivity = 1;
  5494. this.refractionRatio = 0.98;
  5495. this.wireframe = false;
  5496. this.wireframeLinewidth = 1;
  5497. this.wireframeLinecap = 'round';
  5498. this.wireframeLinejoin = 'round';
  5499. this.morphTargets = false;
  5500. this.setValues( parameters );
  5501. }
  5502. copy( source ) {
  5503. super.copy( source );
  5504. this.color.copy( source.color );
  5505. this.map = source.map;
  5506. this.lightMap = source.lightMap;
  5507. this.lightMapIntensity = source.lightMapIntensity;
  5508. this.aoMap = source.aoMap;
  5509. this.aoMapIntensity = source.aoMapIntensity;
  5510. this.specularMap = source.specularMap;
  5511. this.alphaMap = source.alphaMap;
  5512. this.envMap = source.envMap;
  5513. this.combine = source.combine;
  5514. this.reflectivity = source.reflectivity;
  5515. this.refractionRatio = source.refractionRatio;
  5516. this.wireframe = source.wireframe;
  5517. this.wireframeLinewidth = source.wireframeLinewidth;
  5518. this.wireframeLinecap = source.wireframeLinecap;
  5519. this.wireframeLinejoin = source.wireframeLinejoin;
  5520. this.morphTargets = source.morphTargets;
  5521. return this;
  5522. }
  5523. }
  5524. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5525. const _vector$9 = /*@__PURE__*/ new Vector3();
  5526. const _vector2 = /*@__PURE__*/ new Vector2();
  5527. class BufferAttribute {
  5528. constructor( array, itemSize, normalized ) {
  5529. if ( Array.isArray( array ) ) {
  5530. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5531. }
  5532. this.name = '';
  5533. this.array = array;
  5534. this.itemSize = itemSize;
  5535. this.count = array !== undefined ? array.length / itemSize : 0;
  5536. this.normalized = normalized === true;
  5537. this.usage = StaticDrawUsage;
  5538. this.updateRange = { offset: 0, count: - 1 };
  5539. this.version = 0;
  5540. }
  5541. onUploadCallback() {}
  5542. set needsUpdate( value ) {
  5543. if ( value === true ) this.version ++;
  5544. }
  5545. setUsage( value ) {
  5546. this.usage = value;
  5547. return this;
  5548. }
  5549. copy( source ) {
  5550. this.name = source.name;
  5551. this.array = new source.array.constructor( source.array );
  5552. this.itemSize = source.itemSize;
  5553. this.count = source.count;
  5554. this.normalized = source.normalized;
  5555. this.usage = source.usage;
  5556. return this;
  5557. }
  5558. copyAt( index1, attribute, index2 ) {
  5559. index1 *= this.itemSize;
  5560. index2 *= attribute.itemSize;
  5561. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5562. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5563. }
  5564. return this;
  5565. }
  5566. copyArray( array ) {
  5567. this.array.set( array );
  5568. return this;
  5569. }
  5570. copyColorsArray( colors ) {
  5571. const array = this.array;
  5572. let offset = 0;
  5573. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5574. let color = colors[ i ];
  5575. if ( color === undefined ) {
  5576. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5577. color = new Color();
  5578. }
  5579. array[ offset ++ ] = color.r;
  5580. array[ offset ++ ] = color.g;
  5581. array[ offset ++ ] = color.b;
  5582. }
  5583. return this;
  5584. }
  5585. copyVector2sArray( vectors ) {
  5586. const array = this.array;
  5587. let offset = 0;
  5588. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5589. let vector = vectors[ i ];
  5590. if ( vector === undefined ) {
  5591. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5592. vector = new Vector2();
  5593. }
  5594. array[ offset ++ ] = vector.x;
  5595. array[ offset ++ ] = vector.y;
  5596. }
  5597. return this;
  5598. }
  5599. copyVector3sArray( vectors ) {
  5600. const array = this.array;
  5601. let offset = 0;
  5602. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5603. let vector = vectors[ i ];
  5604. if ( vector === undefined ) {
  5605. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5606. vector = new Vector3();
  5607. }
  5608. array[ offset ++ ] = vector.x;
  5609. array[ offset ++ ] = vector.y;
  5610. array[ offset ++ ] = vector.z;
  5611. }
  5612. return this;
  5613. }
  5614. copyVector4sArray( vectors ) {
  5615. const array = this.array;
  5616. let offset = 0;
  5617. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5618. let vector = vectors[ i ];
  5619. if ( vector === undefined ) {
  5620. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5621. vector = new Vector4();
  5622. }
  5623. array[ offset ++ ] = vector.x;
  5624. array[ offset ++ ] = vector.y;
  5625. array[ offset ++ ] = vector.z;
  5626. array[ offset ++ ] = vector.w;
  5627. }
  5628. return this;
  5629. }
  5630. applyMatrix3( m ) {
  5631. if ( this.itemSize === 2 ) {
  5632. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5633. _vector2.fromBufferAttribute( this, i );
  5634. _vector2.applyMatrix3( m );
  5635. this.setXY( i, _vector2.x, _vector2.y );
  5636. }
  5637. } else if ( this.itemSize === 3 ) {
  5638. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5639. _vector$9.fromBufferAttribute( this, i );
  5640. _vector$9.applyMatrix3( m );
  5641. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5642. }
  5643. }
  5644. return this;
  5645. }
  5646. applyMatrix4( m ) {
  5647. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5648. _vector$9.x = this.getX( i );
  5649. _vector$9.y = this.getY( i );
  5650. _vector$9.z = this.getZ( i );
  5651. _vector$9.applyMatrix4( m );
  5652. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5653. }
  5654. return this;
  5655. }
  5656. applyNormalMatrix( m ) {
  5657. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5658. _vector$9.x = this.getX( i );
  5659. _vector$9.y = this.getY( i );
  5660. _vector$9.z = this.getZ( i );
  5661. _vector$9.applyNormalMatrix( m );
  5662. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5663. }
  5664. return this;
  5665. }
  5666. transformDirection( m ) {
  5667. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5668. _vector$9.x = this.getX( i );
  5669. _vector$9.y = this.getY( i );
  5670. _vector$9.z = this.getZ( i );
  5671. _vector$9.transformDirection( m );
  5672. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5673. }
  5674. return this;
  5675. }
  5676. set( value, offset = 0 ) {
  5677. this.array.set( value, offset );
  5678. return this;
  5679. }
  5680. getX( index ) {
  5681. return this.array[ index * this.itemSize ];
  5682. }
  5683. setX( index, x ) {
  5684. this.array[ index * this.itemSize ] = x;
  5685. return this;
  5686. }
  5687. getY( index ) {
  5688. return this.array[ index * this.itemSize + 1 ];
  5689. }
  5690. setY( index, y ) {
  5691. this.array[ index * this.itemSize + 1 ] = y;
  5692. return this;
  5693. }
  5694. getZ( index ) {
  5695. return this.array[ index * this.itemSize + 2 ];
  5696. }
  5697. setZ( index, z ) {
  5698. this.array[ index * this.itemSize + 2 ] = z;
  5699. return this;
  5700. }
  5701. getW( index ) {
  5702. return this.array[ index * this.itemSize + 3 ];
  5703. }
  5704. setW( index, w ) {
  5705. this.array[ index * this.itemSize + 3 ] = w;
  5706. return this;
  5707. }
  5708. setXY( index, x, y ) {
  5709. index *= this.itemSize;
  5710. this.array[ index + 0 ] = x;
  5711. this.array[ index + 1 ] = y;
  5712. return this;
  5713. }
  5714. setXYZ( index, x, y, z ) {
  5715. index *= this.itemSize;
  5716. this.array[ index + 0 ] = x;
  5717. this.array[ index + 1 ] = y;
  5718. this.array[ index + 2 ] = z;
  5719. return this;
  5720. }
  5721. setXYZW( index, x, y, z, w ) {
  5722. index *= this.itemSize;
  5723. this.array[ index + 0 ] = x;
  5724. this.array[ index + 1 ] = y;
  5725. this.array[ index + 2 ] = z;
  5726. this.array[ index + 3 ] = w;
  5727. return this;
  5728. }
  5729. onUpload( callback ) {
  5730. this.onUploadCallback = callback;
  5731. return this;
  5732. }
  5733. clone() {
  5734. return new this.constructor( this.array, this.itemSize ).copy( this );
  5735. }
  5736. toJSON() {
  5737. const data = {
  5738. itemSize: this.itemSize,
  5739. type: this.array.constructor.name,
  5740. array: Array.prototype.slice.call( this.array ),
  5741. normalized: this.normalized
  5742. };
  5743. if ( this.name !== '' ) data.name = this.name;
  5744. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5745. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5746. return data;
  5747. }
  5748. }
  5749. BufferAttribute.prototype.isBufferAttribute = true;
  5750. //
  5751. class Int8BufferAttribute extends BufferAttribute {
  5752. constructor( array, itemSize, normalized ) {
  5753. super( new Int8Array( array ), itemSize, normalized );
  5754. }
  5755. }
  5756. class Uint8BufferAttribute extends BufferAttribute {
  5757. constructor( array, itemSize, normalized ) {
  5758. super( new Uint8Array( array ), itemSize, normalized );
  5759. }
  5760. }
  5761. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5762. constructor( array, itemSize, normalized ) {
  5763. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5764. }
  5765. }
  5766. class Int16BufferAttribute extends BufferAttribute {
  5767. constructor( array, itemSize, normalized ) {
  5768. super( new Int16Array( array ), itemSize, normalized );
  5769. }
  5770. }
  5771. class Uint16BufferAttribute extends BufferAttribute {
  5772. constructor( array, itemSize, normalized ) {
  5773. super( new Uint16Array( array ), itemSize, normalized );
  5774. }
  5775. }
  5776. class Int32BufferAttribute extends BufferAttribute {
  5777. constructor( array, itemSize, normalized ) {
  5778. super( new Int32Array( array ), itemSize, normalized );
  5779. }
  5780. }
  5781. class Uint32BufferAttribute extends BufferAttribute {
  5782. constructor( array, itemSize, normalized ) {
  5783. super( new Uint32Array( array ), itemSize, normalized );
  5784. }
  5785. }
  5786. class Float16BufferAttribute extends BufferAttribute {
  5787. constructor( array, itemSize, normalized ) {
  5788. super( new Uint16Array( array ), itemSize, normalized );
  5789. }
  5790. }
  5791. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5792. class Float32BufferAttribute extends BufferAttribute {
  5793. constructor( array, itemSize, normalized ) {
  5794. super( new Float32Array( array ), itemSize, normalized );
  5795. }
  5796. }
  5797. class Float64BufferAttribute extends BufferAttribute {
  5798. constructor( array, itemSize, normalized ) {
  5799. super( new Float64Array( array ), itemSize, normalized );
  5800. }
  5801. }
  5802. function arrayMax( array ) {
  5803. if ( array.length === 0 ) return - Infinity;
  5804. let max = array[ 0 ];
  5805. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5806. if ( array[ i ] > max ) max = array[ i ];
  5807. }
  5808. return max;
  5809. }
  5810. const TYPED_ARRAYS = {
  5811. Int8Array: Int8Array,
  5812. Uint8Array: Uint8Array,
  5813. Uint8ClampedArray: Uint8ClampedArray,
  5814. Int16Array: Int16Array,
  5815. Uint16Array: Uint16Array,
  5816. Int32Array: Int32Array,
  5817. Uint32Array: Uint32Array,
  5818. Float32Array: Float32Array,
  5819. Float64Array: Float64Array
  5820. };
  5821. function getTypedArray( type, buffer ) {
  5822. return new TYPED_ARRAYS[ type ]( buffer );
  5823. }
  5824. let _id = 0;
  5825. const _m1 = /*@__PURE__*/ new Matrix4();
  5826. const _obj = /*@__PURE__*/ new Object3D();
  5827. const _offset = /*@__PURE__*/ new Vector3();
  5828. const _box$1 = /*@__PURE__*/ new Box3();
  5829. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5830. const _vector$8 = /*@__PURE__*/ new Vector3();
  5831. class BufferGeometry extends EventDispatcher {
  5832. constructor() {
  5833. super();
  5834. Object.defineProperty( this, 'id', { value: _id ++ } );
  5835. this.uuid = generateUUID();
  5836. this.name = '';
  5837. this.type = 'BufferGeometry';
  5838. this.index = null;
  5839. this.attributes = {};
  5840. this.morphAttributes = {};
  5841. this.morphTargetsRelative = false;
  5842. this.groups = [];
  5843. this.boundingBox = null;
  5844. this.boundingSphere = null;
  5845. this.drawRange = { start: 0, count: Infinity };
  5846. this.userData = {};
  5847. }
  5848. getIndex() {
  5849. return this.index;
  5850. }
  5851. setIndex( index ) {
  5852. if ( Array.isArray( index ) ) {
  5853. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5854. } else {
  5855. this.index = index;
  5856. }
  5857. return this;
  5858. }
  5859. getAttribute( name ) {
  5860. return this.attributes[ name ];
  5861. }
  5862. setAttribute( name, attribute ) {
  5863. this.attributes[ name ] = attribute;
  5864. return this;
  5865. }
  5866. deleteAttribute( name ) {
  5867. delete this.attributes[ name ];
  5868. return this;
  5869. }
  5870. hasAttribute( name ) {
  5871. return this.attributes[ name ] !== undefined;
  5872. }
  5873. addGroup( start, count, materialIndex = 0 ) {
  5874. this.groups.push( {
  5875. start: start,
  5876. count: count,
  5877. materialIndex: materialIndex
  5878. } );
  5879. }
  5880. clearGroups() {
  5881. this.groups = [];
  5882. }
  5883. setDrawRange( start, count ) {
  5884. this.drawRange.start = start;
  5885. this.drawRange.count = count;
  5886. }
  5887. applyMatrix4( matrix ) {
  5888. const position = this.attributes.position;
  5889. if ( position !== undefined ) {
  5890. position.applyMatrix4( matrix );
  5891. position.needsUpdate = true;
  5892. }
  5893. const normal = this.attributes.normal;
  5894. if ( normal !== undefined ) {
  5895. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5896. normal.applyNormalMatrix( normalMatrix );
  5897. normal.needsUpdate = true;
  5898. }
  5899. const tangent = this.attributes.tangent;
  5900. if ( tangent !== undefined ) {
  5901. tangent.transformDirection( matrix );
  5902. tangent.needsUpdate = true;
  5903. }
  5904. if ( this.boundingBox !== null ) {
  5905. this.computeBoundingBox();
  5906. }
  5907. if ( this.boundingSphere !== null ) {
  5908. this.computeBoundingSphere();
  5909. }
  5910. return this;
  5911. }
  5912. rotateX( angle ) {
  5913. // rotate geometry around world x-axis
  5914. _m1.makeRotationX( angle );
  5915. this.applyMatrix4( _m1 );
  5916. return this;
  5917. }
  5918. rotateY( angle ) {
  5919. // rotate geometry around world y-axis
  5920. _m1.makeRotationY( angle );
  5921. this.applyMatrix4( _m1 );
  5922. return this;
  5923. }
  5924. rotateZ( angle ) {
  5925. // rotate geometry around world z-axis
  5926. _m1.makeRotationZ( angle );
  5927. this.applyMatrix4( _m1 );
  5928. return this;
  5929. }
  5930. translate( x, y, z ) {
  5931. // translate geometry
  5932. _m1.makeTranslation( x, y, z );
  5933. this.applyMatrix4( _m1 );
  5934. return this;
  5935. }
  5936. scale( x, y, z ) {
  5937. // scale geometry
  5938. _m1.makeScale( x, y, z );
  5939. this.applyMatrix4( _m1 );
  5940. return this;
  5941. }
  5942. lookAt( vector ) {
  5943. _obj.lookAt( vector );
  5944. _obj.updateMatrix();
  5945. this.applyMatrix4( _obj.matrix );
  5946. return this;
  5947. }
  5948. center() {
  5949. this.computeBoundingBox();
  5950. this.boundingBox.getCenter( _offset ).negate();
  5951. this.translate( _offset.x, _offset.y, _offset.z );
  5952. return this;
  5953. }
  5954. setFromPoints( points ) {
  5955. const position = [];
  5956. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5957. const point = points[ i ];
  5958. position.push( point.x, point.y, point.z || 0 );
  5959. }
  5960. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5961. return this;
  5962. }
  5963. computeBoundingBox() {
  5964. if ( this.boundingBox === null ) {
  5965. this.boundingBox = new Box3();
  5966. }
  5967. const position = this.attributes.position;
  5968. const morphAttributesPosition = this.morphAttributes.position;
  5969. if ( position && position.isGLBufferAttribute ) {
  5970. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5971. this.boundingBox.set(
  5972. new Vector3( - Infinity, - Infinity, - Infinity ),
  5973. new Vector3( + Infinity, + Infinity, + Infinity )
  5974. );
  5975. return;
  5976. }
  5977. if ( position !== undefined ) {
  5978. this.boundingBox.setFromBufferAttribute( position );
  5979. // process morph attributes if present
  5980. if ( morphAttributesPosition ) {
  5981. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5982. const morphAttribute = morphAttributesPosition[ i ];
  5983. _box$1.setFromBufferAttribute( morphAttribute );
  5984. if ( this.morphTargetsRelative ) {
  5985. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5986. this.boundingBox.expandByPoint( _vector$8 );
  5987. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5988. this.boundingBox.expandByPoint( _vector$8 );
  5989. } else {
  5990. this.boundingBox.expandByPoint( _box$1.min );
  5991. this.boundingBox.expandByPoint( _box$1.max );
  5992. }
  5993. }
  5994. }
  5995. } else {
  5996. this.boundingBox.makeEmpty();
  5997. }
  5998. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5999. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6000. }
  6001. }
  6002. computeBoundingSphere() {
  6003. if ( this.boundingSphere === null ) {
  6004. this.boundingSphere = new Sphere();
  6005. }
  6006. const position = this.attributes.position;
  6007. const morphAttributesPosition = this.morphAttributes.position;
  6008. if ( position && position.isGLBufferAttribute ) {
  6009. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6010. this.boundingSphere.set( new Vector3(), Infinity );
  6011. return;
  6012. }
  6013. if ( position ) {
  6014. // first, find the center of the bounding sphere
  6015. const center = this.boundingSphere.center;
  6016. _box$1.setFromBufferAttribute( position );
  6017. // process morph attributes if present
  6018. if ( morphAttributesPosition ) {
  6019. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6020. const morphAttribute = morphAttributesPosition[ i ];
  6021. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6022. if ( this.morphTargetsRelative ) {
  6023. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6024. _box$1.expandByPoint( _vector$8 );
  6025. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6026. _box$1.expandByPoint( _vector$8 );
  6027. } else {
  6028. _box$1.expandByPoint( _boxMorphTargets.min );
  6029. _box$1.expandByPoint( _boxMorphTargets.max );
  6030. }
  6031. }
  6032. }
  6033. _box$1.getCenter( center );
  6034. // second, try to find a boundingSphere with a radius smaller than the
  6035. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6036. let maxRadiusSq = 0;
  6037. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6038. _vector$8.fromBufferAttribute( position, i );
  6039. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6040. }
  6041. // process morph attributes if present
  6042. if ( morphAttributesPosition ) {
  6043. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6044. const morphAttribute = morphAttributesPosition[ i ];
  6045. const morphTargetsRelative = this.morphTargetsRelative;
  6046. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6047. _vector$8.fromBufferAttribute( morphAttribute, j );
  6048. if ( morphTargetsRelative ) {
  6049. _offset.fromBufferAttribute( position, j );
  6050. _vector$8.add( _offset );
  6051. }
  6052. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6053. }
  6054. }
  6055. }
  6056. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6057. if ( isNaN( this.boundingSphere.radius ) ) {
  6058. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6059. }
  6060. }
  6061. }
  6062. computeFaceNormals() {
  6063. // backwards compatibility
  6064. }
  6065. computeTangents() {
  6066. const index = this.index;
  6067. const attributes = this.attributes;
  6068. // based on http://www.terathon.com/code/tangent.html
  6069. // (per vertex tangents)
  6070. if ( index === null ||
  6071. attributes.position === undefined ||
  6072. attributes.normal === undefined ||
  6073. attributes.uv === undefined ) {
  6074. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6075. return;
  6076. }
  6077. const indices = index.array;
  6078. const positions = attributes.position.array;
  6079. const normals = attributes.normal.array;
  6080. const uvs = attributes.uv.array;
  6081. const nVertices = positions.length / 3;
  6082. if ( attributes.tangent === undefined ) {
  6083. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6084. }
  6085. const tangents = attributes.tangent.array;
  6086. const tan1 = [], tan2 = [];
  6087. for ( let i = 0; i < nVertices; i ++ ) {
  6088. tan1[ i ] = new Vector3();
  6089. tan2[ i ] = new Vector3();
  6090. }
  6091. const vA = new Vector3(),
  6092. vB = new Vector3(),
  6093. vC = new Vector3(),
  6094. uvA = new Vector2(),
  6095. uvB = new Vector2(),
  6096. uvC = new Vector2(),
  6097. sdir = new Vector3(),
  6098. tdir = new Vector3();
  6099. function handleTriangle( a, b, c ) {
  6100. vA.fromArray( positions, a * 3 );
  6101. vB.fromArray( positions, b * 3 );
  6102. vC.fromArray( positions, c * 3 );
  6103. uvA.fromArray( uvs, a * 2 );
  6104. uvB.fromArray( uvs, b * 2 );
  6105. uvC.fromArray( uvs, c * 2 );
  6106. vB.sub( vA );
  6107. vC.sub( vA );
  6108. uvB.sub( uvA );
  6109. uvC.sub( uvA );
  6110. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6111. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6112. if ( ! isFinite( r ) ) return;
  6113. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6114. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6115. tan1[ a ].add( sdir );
  6116. tan1[ b ].add( sdir );
  6117. tan1[ c ].add( sdir );
  6118. tan2[ a ].add( tdir );
  6119. tan2[ b ].add( tdir );
  6120. tan2[ c ].add( tdir );
  6121. }
  6122. let groups = this.groups;
  6123. if ( groups.length === 0 ) {
  6124. groups = [ {
  6125. start: 0,
  6126. count: indices.length
  6127. } ];
  6128. }
  6129. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6130. const group = groups[ i ];
  6131. const start = group.start;
  6132. const count = group.count;
  6133. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6134. handleTriangle(
  6135. indices[ j + 0 ],
  6136. indices[ j + 1 ],
  6137. indices[ j + 2 ]
  6138. );
  6139. }
  6140. }
  6141. const tmp = new Vector3(), tmp2 = new Vector3();
  6142. const n = new Vector3(), n2 = new Vector3();
  6143. function handleVertex( v ) {
  6144. n.fromArray( normals, v * 3 );
  6145. n2.copy( n );
  6146. const t = tan1[ v ];
  6147. // Gram-Schmidt orthogonalize
  6148. tmp.copy( t );
  6149. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6150. // Calculate handedness
  6151. tmp2.crossVectors( n2, t );
  6152. const test = tmp2.dot( tan2[ v ] );
  6153. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6154. tangents[ v * 4 ] = tmp.x;
  6155. tangents[ v * 4 + 1 ] = tmp.y;
  6156. tangents[ v * 4 + 2 ] = tmp.z;
  6157. tangents[ v * 4 + 3 ] = w;
  6158. }
  6159. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6160. const group = groups[ i ];
  6161. const start = group.start;
  6162. const count = group.count;
  6163. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6164. handleVertex( indices[ j + 0 ] );
  6165. handleVertex( indices[ j + 1 ] );
  6166. handleVertex( indices[ j + 2 ] );
  6167. }
  6168. }
  6169. }
  6170. computeVertexNormals() {
  6171. const index = this.index;
  6172. const positionAttribute = this.getAttribute( 'position' );
  6173. if ( positionAttribute !== undefined ) {
  6174. let normalAttribute = this.getAttribute( 'normal' );
  6175. if ( normalAttribute === undefined ) {
  6176. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6177. this.setAttribute( 'normal', normalAttribute );
  6178. } else {
  6179. // reset existing normals to zero
  6180. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6181. normalAttribute.setXYZ( i, 0, 0, 0 );
  6182. }
  6183. }
  6184. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6185. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6186. const cb = new Vector3(), ab = new Vector3();
  6187. // indexed elements
  6188. if ( index ) {
  6189. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6190. const vA = index.getX( i + 0 );
  6191. const vB = index.getX( i + 1 );
  6192. const vC = index.getX( i + 2 );
  6193. pA.fromBufferAttribute( positionAttribute, vA );
  6194. pB.fromBufferAttribute( positionAttribute, vB );
  6195. pC.fromBufferAttribute( positionAttribute, vC );
  6196. cb.subVectors( pC, pB );
  6197. ab.subVectors( pA, pB );
  6198. cb.cross( ab );
  6199. nA.fromBufferAttribute( normalAttribute, vA );
  6200. nB.fromBufferAttribute( normalAttribute, vB );
  6201. nC.fromBufferAttribute( normalAttribute, vC );
  6202. nA.add( cb );
  6203. nB.add( cb );
  6204. nC.add( cb );
  6205. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6206. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6207. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6208. }
  6209. } else {
  6210. // non-indexed elements (unconnected triangle soup)
  6211. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6212. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6213. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6214. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6215. cb.subVectors( pC, pB );
  6216. ab.subVectors( pA, pB );
  6217. cb.cross( ab );
  6218. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6219. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6220. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6221. }
  6222. }
  6223. this.normalizeNormals();
  6224. normalAttribute.needsUpdate = true;
  6225. }
  6226. }
  6227. merge( geometry, offset ) {
  6228. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6229. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6230. return;
  6231. }
  6232. if ( offset === undefined ) {
  6233. offset = 0;
  6234. console.warn(
  6235. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6236. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6237. );
  6238. }
  6239. const attributes = this.attributes;
  6240. for ( const key in attributes ) {
  6241. if ( geometry.attributes[ key ] === undefined ) continue;
  6242. const attribute1 = attributes[ key ];
  6243. const attributeArray1 = attribute1.array;
  6244. const attribute2 = geometry.attributes[ key ];
  6245. const attributeArray2 = attribute2.array;
  6246. const attributeOffset = attribute2.itemSize * offset;
  6247. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6248. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6249. attributeArray1[ j ] = attributeArray2[ i ];
  6250. }
  6251. }
  6252. return this;
  6253. }
  6254. normalizeNormals() {
  6255. const normals = this.attributes.normal;
  6256. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6257. _vector$8.fromBufferAttribute( normals, i );
  6258. _vector$8.normalize();
  6259. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6260. }
  6261. }
  6262. toNonIndexed() {
  6263. function convertBufferAttribute( attribute, indices ) {
  6264. const array = attribute.array;
  6265. const itemSize = attribute.itemSize;
  6266. const normalized = attribute.normalized;
  6267. const array2 = new array.constructor( indices.length * itemSize );
  6268. let index = 0, index2 = 0;
  6269. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6270. index = indices[ i ] * itemSize;
  6271. for ( let j = 0; j < itemSize; j ++ ) {
  6272. array2[ index2 ++ ] = array[ index ++ ];
  6273. }
  6274. }
  6275. return new BufferAttribute( array2, itemSize, normalized );
  6276. }
  6277. //
  6278. if ( this.index === null ) {
  6279. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6280. return this;
  6281. }
  6282. const geometry2 = new BufferGeometry();
  6283. const indices = this.index.array;
  6284. const attributes = this.attributes;
  6285. // attributes
  6286. for ( const name in attributes ) {
  6287. const attribute = attributes[ name ];
  6288. const newAttribute = convertBufferAttribute( attribute, indices );
  6289. geometry2.setAttribute( name, newAttribute );
  6290. }
  6291. // morph attributes
  6292. const morphAttributes = this.morphAttributes;
  6293. for ( const name in morphAttributes ) {
  6294. const morphArray = [];
  6295. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6296. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6297. const attribute = morphAttribute[ i ];
  6298. const newAttribute = convertBufferAttribute( attribute, indices );
  6299. morphArray.push( newAttribute );
  6300. }
  6301. geometry2.morphAttributes[ name ] = morphArray;
  6302. }
  6303. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6304. // groups
  6305. const groups = this.groups;
  6306. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6307. const group = groups[ i ];
  6308. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6309. }
  6310. return geometry2;
  6311. }
  6312. toJSON() {
  6313. const data = {
  6314. metadata: {
  6315. version: 4.5,
  6316. type: 'BufferGeometry',
  6317. generator: 'BufferGeometry.toJSON'
  6318. }
  6319. };
  6320. // standard BufferGeometry serialization
  6321. data.uuid = this.uuid;
  6322. data.type = this.type;
  6323. if ( this.name !== '' ) data.name = this.name;
  6324. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6325. if ( this.parameters !== undefined ) {
  6326. const parameters = this.parameters;
  6327. for ( const key in parameters ) {
  6328. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6329. }
  6330. return data;
  6331. }
  6332. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6333. data.data = { attributes: {} };
  6334. const index = this.index;
  6335. if ( index !== null ) {
  6336. data.data.index = {
  6337. type: index.array.constructor.name,
  6338. array: Array.prototype.slice.call( index.array )
  6339. };
  6340. }
  6341. const attributes = this.attributes;
  6342. for ( const key in attributes ) {
  6343. const attribute = attributes[ key ];
  6344. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6345. }
  6346. const morphAttributes = {};
  6347. let hasMorphAttributes = false;
  6348. for ( const key in this.morphAttributes ) {
  6349. const attributeArray = this.morphAttributes[ key ];
  6350. const array = [];
  6351. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6352. const attribute = attributeArray[ i ];
  6353. array.push( attribute.toJSON( data.data ) );
  6354. }
  6355. if ( array.length > 0 ) {
  6356. morphAttributes[ key ] = array;
  6357. hasMorphAttributes = true;
  6358. }
  6359. }
  6360. if ( hasMorphAttributes ) {
  6361. data.data.morphAttributes = morphAttributes;
  6362. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6363. }
  6364. const groups = this.groups;
  6365. if ( groups.length > 0 ) {
  6366. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6367. }
  6368. const boundingSphere = this.boundingSphere;
  6369. if ( boundingSphere !== null ) {
  6370. data.data.boundingSphere = {
  6371. center: boundingSphere.center.toArray(),
  6372. radius: boundingSphere.radius
  6373. };
  6374. }
  6375. return data;
  6376. }
  6377. clone() {
  6378. /*
  6379. // Handle primitives
  6380. const parameters = this.parameters;
  6381. if ( parameters !== undefined ) {
  6382. const values = [];
  6383. for ( const key in parameters ) {
  6384. values.push( parameters[ key ] );
  6385. }
  6386. const geometry = Object.create( this.constructor.prototype );
  6387. this.constructor.apply( geometry, values );
  6388. return geometry;
  6389. }
  6390. return new this.constructor().copy( this );
  6391. */
  6392. return new BufferGeometry().copy( this );
  6393. }
  6394. copy( source ) {
  6395. // reset
  6396. this.index = null;
  6397. this.attributes = {};
  6398. this.morphAttributes = {};
  6399. this.groups = [];
  6400. this.boundingBox = null;
  6401. this.boundingSphere = null;
  6402. // used for storing cloned, shared data
  6403. const data = {};
  6404. // name
  6405. this.name = source.name;
  6406. // index
  6407. const index = source.index;
  6408. if ( index !== null ) {
  6409. this.setIndex( index.clone( data ) );
  6410. }
  6411. // attributes
  6412. const attributes = source.attributes;
  6413. for ( const name in attributes ) {
  6414. const attribute = attributes[ name ];
  6415. this.setAttribute( name, attribute.clone( data ) );
  6416. }
  6417. // morph attributes
  6418. const morphAttributes = source.morphAttributes;
  6419. for ( const name in morphAttributes ) {
  6420. const array = [];
  6421. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6422. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6423. array.push( morphAttribute[ i ].clone( data ) );
  6424. }
  6425. this.morphAttributes[ name ] = array;
  6426. }
  6427. this.morphTargetsRelative = source.morphTargetsRelative;
  6428. // groups
  6429. const groups = source.groups;
  6430. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6431. const group = groups[ i ];
  6432. this.addGroup( group.start, group.count, group.materialIndex );
  6433. }
  6434. // bounding box
  6435. const boundingBox = source.boundingBox;
  6436. if ( boundingBox !== null ) {
  6437. this.boundingBox = boundingBox.clone();
  6438. }
  6439. // bounding sphere
  6440. const boundingSphere = source.boundingSphere;
  6441. if ( boundingSphere !== null ) {
  6442. this.boundingSphere = boundingSphere.clone();
  6443. }
  6444. // draw range
  6445. this.drawRange.start = source.drawRange.start;
  6446. this.drawRange.count = source.drawRange.count;
  6447. // user data
  6448. this.userData = source.userData;
  6449. return this;
  6450. }
  6451. dispose() {
  6452. this.dispatchEvent( { type: 'dispose' } );
  6453. }
  6454. }
  6455. BufferGeometry.prototype.isBufferGeometry = true;
  6456. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6457. const _ray$2 = /*@__PURE__*/ new Ray();
  6458. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6459. const _vA$1 = /*@__PURE__*/ new Vector3();
  6460. const _vB$1 = /*@__PURE__*/ new Vector3();
  6461. const _vC$1 = /*@__PURE__*/ new Vector3();
  6462. const _tempA = /*@__PURE__*/ new Vector3();
  6463. const _tempB = /*@__PURE__*/ new Vector3();
  6464. const _tempC = /*@__PURE__*/ new Vector3();
  6465. const _morphA = /*@__PURE__*/ new Vector3();
  6466. const _morphB = /*@__PURE__*/ new Vector3();
  6467. const _morphC = /*@__PURE__*/ new Vector3();
  6468. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6469. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6470. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6471. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6472. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6473. class Mesh extends Object3D {
  6474. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6475. super();
  6476. this.type = 'Mesh';
  6477. this.geometry = geometry;
  6478. this.material = material;
  6479. this.updateMorphTargets();
  6480. }
  6481. copy( source ) {
  6482. super.copy( source );
  6483. if ( source.morphTargetInfluences !== undefined ) {
  6484. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6485. }
  6486. if ( source.morphTargetDictionary !== undefined ) {
  6487. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6488. }
  6489. this.material = source.material;
  6490. this.geometry = source.geometry;
  6491. return this;
  6492. }
  6493. updateMorphTargets() {
  6494. const geometry = this.geometry;
  6495. if ( geometry.isBufferGeometry ) {
  6496. const morphAttributes = geometry.morphAttributes;
  6497. const keys = Object.keys( morphAttributes );
  6498. if ( keys.length > 0 ) {
  6499. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6500. if ( morphAttribute !== undefined ) {
  6501. this.morphTargetInfluences = [];
  6502. this.morphTargetDictionary = {};
  6503. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6504. const name = morphAttribute[ m ].name || String( m );
  6505. this.morphTargetInfluences.push( 0 );
  6506. this.morphTargetDictionary[ name ] = m;
  6507. }
  6508. }
  6509. }
  6510. } else {
  6511. const morphTargets = geometry.morphTargets;
  6512. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6513. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6514. }
  6515. }
  6516. }
  6517. raycast( raycaster, intersects ) {
  6518. const geometry = this.geometry;
  6519. const material = this.material;
  6520. const matrixWorld = this.matrixWorld;
  6521. if ( material === undefined ) return;
  6522. // Checking boundingSphere distance to ray
  6523. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6524. _sphere$3.copy( geometry.boundingSphere );
  6525. _sphere$3.applyMatrix4( matrixWorld );
  6526. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6527. //
  6528. _inverseMatrix$2.copy( matrixWorld ).invert();
  6529. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6530. // Check boundingBox before continuing
  6531. if ( geometry.boundingBox !== null ) {
  6532. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6533. }
  6534. let intersection;
  6535. if ( geometry.isBufferGeometry ) {
  6536. const index = geometry.index;
  6537. const position = geometry.attributes.position;
  6538. const morphPosition = geometry.morphAttributes.position;
  6539. const morphTargetsRelative = geometry.morphTargetsRelative;
  6540. const uv = geometry.attributes.uv;
  6541. const uv2 = geometry.attributes.uv2;
  6542. const groups = geometry.groups;
  6543. const drawRange = geometry.drawRange;
  6544. if ( index !== null ) {
  6545. // indexed buffer geometry
  6546. if ( Array.isArray( material ) ) {
  6547. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6548. const group = groups[ i ];
  6549. const groupMaterial = material[ group.materialIndex ];
  6550. const start = Math.max( group.start, drawRange.start );
  6551. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6552. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6553. const a = index.getX( j );
  6554. const b = index.getX( j + 1 );
  6555. const c = index.getX( j + 2 );
  6556. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6557. if ( intersection ) {
  6558. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6559. intersection.face.materialIndex = group.materialIndex;
  6560. intersects.push( intersection );
  6561. }
  6562. }
  6563. }
  6564. } else {
  6565. const start = Math.max( 0, drawRange.start );
  6566. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6567. for ( let i = start, il = end; i < il; i += 3 ) {
  6568. const a = index.getX( i );
  6569. const b = index.getX( i + 1 );
  6570. const c = index.getX( i + 2 );
  6571. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6572. if ( intersection ) {
  6573. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6574. intersects.push( intersection );
  6575. }
  6576. }
  6577. }
  6578. } else if ( position !== undefined ) {
  6579. // non-indexed buffer geometry
  6580. if ( Array.isArray( material ) ) {
  6581. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6582. const group = groups[ i ];
  6583. const groupMaterial = material[ group.materialIndex ];
  6584. const start = Math.max( group.start, drawRange.start );
  6585. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6586. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6587. const a = j;
  6588. const b = j + 1;
  6589. const c = j + 2;
  6590. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6591. if ( intersection ) {
  6592. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6593. intersection.face.materialIndex = group.materialIndex;
  6594. intersects.push( intersection );
  6595. }
  6596. }
  6597. }
  6598. } else {
  6599. const start = Math.max( 0, drawRange.start );
  6600. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6601. for ( let i = start, il = end; i < il; i += 3 ) {
  6602. const a = i;
  6603. const b = i + 1;
  6604. const c = i + 2;
  6605. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6606. if ( intersection ) {
  6607. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6608. intersects.push( intersection );
  6609. }
  6610. }
  6611. }
  6612. }
  6613. } else if ( geometry.isGeometry ) {
  6614. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6615. }
  6616. }
  6617. }
  6618. Mesh.prototype.isMesh = true;
  6619. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6620. let intersect;
  6621. if ( material.side === BackSide ) {
  6622. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6623. } else {
  6624. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6625. }
  6626. if ( intersect === null ) return null;
  6627. _intersectionPointWorld.copy( point );
  6628. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6629. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6630. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6631. return {
  6632. distance: distance,
  6633. point: _intersectionPointWorld.clone(),
  6634. object: object
  6635. };
  6636. }
  6637. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6638. _vA$1.fromBufferAttribute( position, a );
  6639. _vB$1.fromBufferAttribute( position, b );
  6640. _vC$1.fromBufferAttribute( position, c );
  6641. const morphInfluences = object.morphTargetInfluences;
  6642. if ( material.morphTargets && morphPosition && morphInfluences ) {
  6643. _morphA.set( 0, 0, 0 );
  6644. _morphB.set( 0, 0, 0 );
  6645. _morphC.set( 0, 0, 0 );
  6646. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6647. const influence = morphInfluences[ i ];
  6648. const morphAttribute = morphPosition[ i ];
  6649. if ( influence === 0 ) continue;
  6650. _tempA.fromBufferAttribute( morphAttribute, a );
  6651. _tempB.fromBufferAttribute( morphAttribute, b );
  6652. _tempC.fromBufferAttribute( morphAttribute, c );
  6653. if ( morphTargetsRelative ) {
  6654. _morphA.addScaledVector( _tempA, influence );
  6655. _morphB.addScaledVector( _tempB, influence );
  6656. _morphC.addScaledVector( _tempC, influence );
  6657. } else {
  6658. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6659. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6660. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6661. }
  6662. }
  6663. _vA$1.add( _morphA );
  6664. _vB$1.add( _morphB );
  6665. _vC$1.add( _morphC );
  6666. }
  6667. if ( object.isSkinnedMesh ) {
  6668. object.boneTransform( a, _vA$1 );
  6669. object.boneTransform( b, _vB$1 );
  6670. object.boneTransform( c, _vC$1 );
  6671. }
  6672. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6673. if ( intersection ) {
  6674. if ( uv ) {
  6675. _uvA$1.fromBufferAttribute( uv, a );
  6676. _uvB$1.fromBufferAttribute( uv, b );
  6677. _uvC$1.fromBufferAttribute( uv, c );
  6678. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6679. }
  6680. if ( uv2 ) {
  6681. _uvA$1.fromBufferAttribute( uv2, a );
  6682. _uvB$1.fromBufferAttribute( uv2, b );
  6683. _uvC$1.fromBufferAttribute( uv2, c );
  6684. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6685. }
  6686. const face = {
  6687. a: a,
  6688. b: b,
  6689. c: c,
  6690. normal: new Vector3(),
  6691. materialIndex: 0
  6692. };
  6693. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6694. intersection.face = face;
  6695. }
  6696. return intersection;
  6697. }
  6698. class BoxGeometry extends BufferGeometry {
  6699. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6700. super();
  6701. this.type = 'BoxGeometry';
  6702. this.parameters = {
  6703. width: width,
  6704. height: height,
  6705. depth: depth,
  6706. widthSegments: widthSegments,
  6707. heightSegments: heightSegments,
  6708. depthSegments: depthSegments
  6709. };
  6710. const scope = this;
  6711. // segments
  6712. widthSegments = Math.floor( widthSegments );
  6713. heightSegments = Math.floor( heightSegments );
  6714. depthSegments = Math.floor( depthSegments );
  6715. // buffers
  6716. const indices = [];
  6717. const vertices = [];
  6718. const normals = [];
  6719. const uvs = [];
  6720. // helper variables
  6721. let numberOfVertices = 0;
  6722. let groupStart = 0;
  6723. // build each side of the box geometry
  6724. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6725. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6726. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6727. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6728. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6729. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6730. // build geometry
  6731. this.setIndex( indices );
  6732. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6733. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6734. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6735. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6736. const segmentWidth = width / gridX;
  6737. const segmentHeight = height / gridY;
  6738. const widthHalf = width / 2;
  6739. const heightHalf = height / 2;
  6740. const depthHalf = depth / 2;
  6741. const gridX1 = gridX + 1;
  6742. const gridY1 = gridY + 1;
  6743. let vertexCounter = 0;
  6744. let groupCount = 0;
  6745. const vector = new Vector3();
  6746. // generate vertices, normals and uvs
  6747. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6748. const y = iy * segmentHeight - heightHalf;
  6749. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6750. const x = ix * segmentWidth - widthHalf;
  6751. // set values to correct vector component
  6752. vector[ u ] = x * udir;
  6753. vector[ v ] = y * vdir;
  6754. vector[ w ] = depthHalf;
  6755. // now apply vector to vertex buffer
  6756. vertices.push( vector.x, vector.y, vector.z );
  6757. // set values to correct vector component
  6758. vector[ u ] = 0;
  6759. vector[ v ] = 0;
  6760. vector[ w ] = depth > 0 ? 1 : - 1;
  6761. // now apply vector to normal buffer
  6762. normals.push( vector.x, vector.y, vector.z );
  6763. // uvs
  6764. uvs.push( ix / gridX );
  6765. uvs.push( 1 - ( iy / gridY ) );
  6766. // counters
  6767. vertexCounter += 1;
  6768. }
  6769. }
  6770. // indices
  6771. // 1. you need three indices to draw a single face
  6772. // 2. a single segment consists of two faces
  6773. // 3. so we need to generate six (2*3) indices per segment
  6774. for ( let iy = 0; iy < gridY; iy ++ ) {
  6775. for ( let ix = 0; ix < gridX; ix ++ ) {
  6776. const a = numberOfVertices + ix + gridX1 * iy;
  6777. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6778. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6779. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6780. // faces
  6781. indices.push( a, b, d );
  6782. indices.push( b, c, d );
  6783. // increase counter
  6784. groupCount += 6;
  6785. }
  6786. }
  6787. // add a group to the geometry. this will ensure multi material support
  6788. scope.addGroup( groupStart, groupCount, materialIndex );
  6789. // calculate new start value for groups
  6790. groupStart += groupCount;
  6791. // update total number of vertices
  6792. numberOfVertices += vertexCounter;
  6793. }
  6794. }
  6795. }
  6796. /**
  6797. * Uniform Utilities
  6798. */
  6799. function cloneUniforms( src ) {
  6800. const dst = {};
  6801. for ( const u in src ) {
  6802. dst[ u ] = {};
  6803. for ( const p in src[ u ] ) {
  6804. const property = src[ u ][ p ];
  6805. if ( property && ( property.isColor ||
  6806. property.isMatrix3 || property.isMatrix4 ||
  6807. property.isVector2 || property.isVector3 || property.isVector4 ||
  6808. property.isTexture || property.isQuaternion ) ) {
  6809. dst[ u ][ p ] = property.clone();
  6810. } else if ( Array.isArray( property ) ) {
  6811. dst[ u ][ p ] = property.slice();
  6812. } else {
  6813. dst[ u ][ p ] = property;
  6814. }
  6815. }
  6816. }
  6817. return dst;
  6818. }
  6819. function mergeUniforms( uniforms ) {
  6820. const merged = {};
  6821. for ( let u = 0; u < uniforms.length; u ++ ) {
  6822. const tmp = cloneUniforms( uniforms[ u ] );
  6823. for ( const p in tmp ) {
  6824. merged[ p ] = tmp[ p ];
  6825. }
  6826. }
  6827. return merged;
  6828. }
  6829. // Legacy
  6830. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6831. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6832. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6833. /**
  6834. * parameters = {
  6835. * defines: { "label" : "value" },
  6836. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6837. *
  6838. * fragmentShader: <string>,
  6839. * vertexShader: <string>,
  6840. *
  6841. * wireframe: <boolean>,
  6842. * wireframeLinewidth: <float>,
  6843. *
  6844. * lights: <bool>,
  6845. *
  6846. * morphTargets: <bool>,
  6847. * morphNormals: <bool>
  6848. * }
  6849. */
  6850. class ShaderMaterial extends Material {
  6851. constructor( parameters ) {
  6852. super();
  6853. this.type = 'ShaderMaterial';
  6854. this.defines = {};
  6855. this.uniforms = {};
  6856. this.vertexShader = default_vertex;
  6857. this.fragmentShader = default_fragment;
  6858. this.linewidth = 1;
  6859. this.wireframe = false;
  6860. this.wireframeLinewidth = 1;
  6861. this.fog = false; // set to use scene fog
  6862. this.lights = false; // set to use scene lights
  6863. this.clipping = false; // set to use user-defined clipping planes
  6864. this.morphTargets = false; // set to use morph targets
  6865. this.morphNormals = false; // set to use morph normals
  6866. this.extensions = {
  6867. derivatives: false, // set to use derivatives
  6868. fragDepth: false, // set to use fragment depth values
  6869. drawBuffers: false, // set to use draw buffers
  6870. shaderTextureLOD: false // set to use shader texture LOD
  6871. };
  6872. // When rendered geometry doesn't include these attributes but the material does,
  6873. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6874. this.defaultAttributeValues = {
  6875. 'color': [ 1, 1, 1 ],
  6876. 'uv': [ 0, 0 ],
  6877. 'uv2': [ 0, 0 ]
  6878. };
  6879. this.index0AttributeName = undefined;
  6880. this.uniformsNeedUpdate = false;
  6881. this.glslVersion = null;
  6882. if ( parameters !== undefined ) {
  6883. if ( parameters.attributes !== undefined ) {
  6884. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6885. }
  6886. this.setValues( parameters );
  6887. }
  6888. }
  6889. copy( source ) {
  6890. super.copy( source );
  6891. this.fragmentShader = source.fragmentShader;
  6892. this.vertexShader = source.vertexShader;
  6893. this.uniforms = cloneUniforms( source.uniforms );
  6894. this.defines = Object.assign( {}, source.defines );
  6895. this.wireframe = source.wireframe;
  6896. this.wireframeLinewidth = source.wireframeLinewidth;
  6897. this.lights = source.lights;
  6898. this.clipping = source.clipping;
  6899. this.morphTargets = source.morphTargets;
  6900. this.morphNormals = source.morphNormals;
  6901. this.extensions = Object.assign( {}, source.extensions );
  6902. this.glslVersion = source.glslVersion;
  6903. return this;
  6904. }
  6905. toJSON( meta ) {
  6906. const data = super.toJSON( meta );
  6907. data.glslVersion = this.glslVersion;
  6908. data.uniforms = {};
  6909. for ( const name in this.uniforms ) {
  6910. const uniform = this.uniforms[ name ];
  6911. const value = uniform.value;
  6912. if ( value && value.isTexture ) {
  6913. data.uniforms[ name ] = {
  6914. type: 't',
  6915. value: value.toJSON( meta ).uuid
  6916. };
  6917. } else if ( value && value.isColor ) {
  6918. data.uniforms[ name ] = {
  6919. type: 'c',
  6920. value: value.getHex()
  6921. };
  6922. } else if ( value && value.isVector2 ) {
  6923. data.uniforms[ name ] = {
  6924. type: 'v2',
  6925. value: value.toArray()
  6926. };
  6927. } else if ( value && value.isVector3 ) {
  6928. data.uniforms[ name ] = {
  6929. type: 'v3',
  6930. value: value.toArray()
  6931. };
  6932. } else if ( value && value.isVector4 ) {
  6933. data.uniforms[ name ] = {
  6934. type: 'v4',
  6935. value: value.toArray()
  6936. };
  6937. } else if ( value && value.isMatrix3 ) {
  6938. data.uniforms[ name ] = {
  6939. type: 'm3',
  6940. value: value.toArray()
  6941. };
  6942. } else if ( value && value.isMatrix4 ) {
  6943. data.uniforms[ name ] = {
  6944. type: 'm4',
  6945. value: value.toArray()
  6946. };
  6947. } else {
  6948. data.uniforms[ name ] = {
  6949. value: value
  6950. };
  6951. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6952. }
  6953. }
  6954. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6955. data.vertexShader = this.vertexShader;
  6956. data.fragmentShader = this.fragmentShader;
  6957. const extensions = {};
  6958. for ( const key in this.extensions ) {
  6959. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6960. }
  6961. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6962. return data;
  6963. }
  6964. }
  6965. ShaderMaterial.prototype.isShaderMaterial = true;
  6966. class Camera extends Object3D {
  6967. constructor() {
  6968. super();
  6969. this.type = 'Camera';
  6970. this.matrixWorldInverse = new Matrix4();
  6971. this.projectionMatrix = new Matrix4();
  6972. this.projectionMatrixInverse = new Matrix4();
  6973. }
  6974. copy( source, recursive ) {
  6975. super.copy( source, recursive );
  6976. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6977. this.projectionMatrix.copy( source.projectionMatrix );
  6978. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6979. return this;
  6980. }
  6981. getWorldDirection( target ) {
  6982. if ( target === undefined ) {
  6983. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  6984. target = new Vector3();
  6985. }
  6986. this.updateWorldMatrix( true, false );
  6987. const e = this.matrixWorld.elements;
  6988. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6989. }
  6990. updateMatrixWorld( force ) {
  6991. super.updateMatrixWorld( force );
  6992. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6993. }
  6994. updateWorldMatrix( updateParents, updateChildren ) {
  6995. super.updateWorldMatrix( updateParents, updateChildren );
  6996. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6997. }
  6998. clone() {
  6999. return new this.constructor().copy( this );
  7000. }
  7001. }
  7002. Camera.prototype.isCamera = true;
  7003. class PerspectiveCamera extends Camera {
  7004. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7005. super();
  7006. this.type = 'PerspectiveCamera';
  7007. this.fov = fov;
  7008. this.zoom = 1;
  7009. this.near = near;
  7010. this.far = far;
  7011. this.focus = 10;
  7012. this.aspect = aspect;
  7013. this.view = null;
  7014. this.filmGauge = 35; // width of the film (default in millimeters)
  7015. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7016. this.updateProjectionMatrix();
  7017. }
  7018. copy( source, recursive ) {
  7019. super.copy( source, recursive );
  7020. this.fov = source.fov;
  7021. this.zoom = source.zoom;
  7022. this.near = source.near;
  7023. this.far = source.far;
  7024. this.focus = source.focus;
  7025. this.aspect = source.aspect;
  7026. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7027. this.filmGauge = source.filmGauge;
  7028. this.filmOffset = source.filmOffset;
  7029. return this;
  7030. }
  7031. /**
  7032. * Sets the FOV by focal length in respect to the current .filmGauge.
  7033. *
  7034. * The default film gauge is 35, so that the focal length can be specified for
  7035. * a 35mm (full frame) camera.
  7036. *
  7037. * Values for focal length and film gauge must have the same unit.
  7038. */
  7039. setFocalLength( focalLength ) {
  7040. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7041. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7042. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7043. this.updateProjectionMatrix();
  7044. }
  7045. /**
  7046. * Calculates the focal length from the current .fov and .filmGauge.
  7047. */
  7048. getFocalLength() {
  7049. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7050. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7051. }
  7052. getEffectiveFOV() {
  7053. return RAD2DEG * 2 * Math.atan(
  7054. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7055. }
  7056. getFilmWidth() {
  7057. // film not completely covered in portrait format (aspect < 1)
  7058. return this.filmGauge * Math.min( this.aspect, 1 );
  7059. }
  7060. getFilmHeight() {
  7061. // film not completely covered in landscape format (aspect > 1)
  7062. return this.filmGauge / Math.max( this.aspect, 1 );
  7063. }
  7064. /**
  7065. * Sets an offset in a larger frustum. This is useful for multi-window or
  7066. * multi-monitor/multi-machine setups.
  7067. *
  7068. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7069. * the monitors are in grid like this
  7070. *
  7071. * +---+---+---+
  7072. * | A | B | C |
  7073. * +---+---+---+
  7074. * | D | E | F |
  7075. * +---+---+---+
  7076. *
  7077. * then for each monitor you would call it like this
  7078. *
  7079. * const w = 1920;
  7080. * const h = 1080;
  7081. * const fullWidth = w * 3;
  7082. * const fullHeight = h * 2;
  7083. *
  7084. * --A--
  7085. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7086. * --B--
  7087. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7088. * --C--
  7089. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7090. * --D--
  7091. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7092. * --E--
  7093. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7094. * --F--
  7095. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7096. *
  7097. * Note there is no reason monitors have to be the same size or in a grid.
  7098. */
  7099. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7100. this.aspect = fullWidth / fullHeight;
  7101. if ( this.view === null ) {
  7102. this.view = {
  7103. enabled: true,
  7104. fullWidth: 1,
  7105. fullHeight: 1,
  7106. offsetX: 0,
  7107. offsetY: 0,
  7108. width: 1,
  7109. height: 1
  7110. };
  7111. }
  7112. this.view.enabled = true;
  7113. this.view.fullWidth = fullWidth;
  7114. this.view.fullHeight = fullHeight;
  7115. this.view.offsetX = x;
  7116. this.view.offsetY = y;
  7117. this.view.width = width;
  7118. this.view.height = height;
  7119. this.updateProjectionMatrix();
  7120. }
  7121. clearViewOffset() {
  7122. if ( this.view !== null ) {
  7123. this.view.enabled = false;
  7124. }
  7125. this.updateProjectionMatrix();
  7126. }
  7127. updateProjectionMatrix() {
  7128. const near = this.near;
  7129. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7130. let height = 2 * top;
  7131. let width = this.aspect * height;
  7132. let left = - 0.5 * width;
  7133. const view = this.view;
  7134. if ( this.view !== null && this.view.enabled ) {
  7135. const fullWidth = view.fullWidth,
  7136. fullHeight = view.fullHeight;
  7137. left += view.offsetX * width / fullWidth;
  7138. top -= view.offsetY * height / fullHeight;
  7139. width *= view.width / fullWidth;
  7140. height *= view.height / fullHeight;
  7141. }
  7142. const skew = this.filmOffset;
  7143. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7144. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7145. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7146. }
  7147. toJSON( meta ) {
  7148. const data = super.toJSON( meta );
  7149. data.object.fov = this.fov;
  7150. data.object.zoom = this.zoom;
  7151. data.object.near = this.near;
  7152. data.object.far = this.far;
  7153. data.object.focus = this.focus;
  7154. data.object.aspect = this.aspect;
  7155. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7156. data.object.filmGauge = this.filmGauge;
  7157. data.object.filmOffset = this.filmOffset;
  7158. return data;
  7159. }
  7160. }
  7161. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7162. const fov = 90, aspect = 1;
  7163. class CubeCamera extends Object3D {
  7164. constructor( near, far, renderTarget ) {
  7165. super();
  7166. this.type = 'CubeCamera';
  7167. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7168. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7169. return;
  7170. }
  7171. this.renderTarget = renderTarget;
  7172. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7173. cameraPX.layers = this.layers;
  7174. cameraPX.up.set( 0, - 1, 0 );
  7175. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7176. this.add( cameraPX );
  7177. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7178. cameraNX.layers = this.layers;
  7179. cameraNX.up.set( 0, - 1, 0 );
  7180. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7181. this.add( cameraNX );
  7182. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7183. cameraPY.layers = this.layers;
  7184. cameraPY.up.set( 0, 0, 1 );
  7185. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7186. this.add( cameraPY );
  7187. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7188. cameraNY.layers = this.layers;
  7189. cameraNY.up.set( 0, 0, - 1 );
  7190. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7191. this.add( cameraNY );
  7192. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7193. cameraPZ.layers = this.layers;
  7194. cameraPZ.up.set( 0, - 1, 0 );
  7195. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7196. this.add( cameraPZ );
  7197. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7198. cameraNZ.layers = this.layers;
  7199. cameraNZ.up.set( 0, - 1, 0 );
  7200. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7201. this.add( cameraNZ );
  7202. }
  7203. update( renderer, scene ) {
  7204. if ( this.parent === null ) this.updateMatrixWorld();
  7205. const renderTarget = this.renderTarget;
  7206. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7207. const currentXrEnabled = renderer.xr.enabled;
  7208. const currentRenderTarget = renderer.getRenderTarget();
  7209. renderer.xr.enabled = false;
  7210. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7211. renderTarget.texture.generateMipmaps = false;
  7212. renderer.setRenderTarget( renderTarget, 0 );
  7213. renderer.render( scene, cameraPX );
  7214. renderer.setRenderTarget( renderTarget, 1 );
  7215. renderer.render( scene, cameraNX );
  7216. renderer.setRenderTarget( renderTarget, 2 );
  7217. renderer.render( scene, cameraPY );
  7218. renderer.setRenderTarget( renderTarget, 3 );
  7219. renderer.render( scene, cameraNY );
  7220. renderer.setRenderTarget( renderTarget, 4 );
  7221. renderer.render( scene, cameraPZ );
  7222. renderTarget.texture.generateMipmaps = generateMipmaps;
  7223. renderer.setRenderTarget( renderTarget, 5 );
  7224. renderer.render( scene, cameraNZ );
  7225. renderer.setRenderTarget( currentRenderTarget );
  7226. renderer.xr.enabled = currentXrEnabled;
  7227. }
  7228. }
  7229. class CubeTexture extends Texture {
  7230. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7231. images = images !== undefined ? images : [];
  7232. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7233. format = format !== undefined ? format : RGBFormat;
  7234. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7235. // Why CubeTexture._needsFlipEnvMap is necessary:
  7236. //
  7237. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7238. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7239. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7240. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7241. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7242. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7243. this._needsFlipEnvMap = true;
  7244. this.flipY = false;
  7245. }
  7246. get images() {
  7247. return this.image;
  7248. }
  7249. set images( value ) {
  7250. this.image = value;
  7251. }
  7252. }
  7253. CubeTexture.prototype.isCubeTexture = true;
  7254. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7255. constructor( size, options, dummy ) {
  7256. if ( Number.isInteger( options ) ) {
  7257. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7258. options = dummy;
  7259. }
  7260. super( size, size, options );
  7261. options = options || {};
  7262. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7263. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7264. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7265. this.texture._needsFlipEnvMap = false;
  7266. }
  7267. fromEquirectangularTexture( renderer, texture ) {
  7268. this.texture.type = texture.type;
  7269. this.texture.format = RGBAFormat; // see #18859
  7270. this.texture.encoding = texture.encoding;
  7271. this.texture.generateMipmaps = texture.generateMipmaps;
  7272. this.texture.minFilter = texture.minFilter;
  7273. this.texture.magFilter = texture.magFilter;
  7274. const shader = {
  7275. uniforms: {
  7276. tEquirect: { value: null },
  7277. },
  7278. vertexShader: /* glsl */`
  7279. varying vec3 vWorldDirection;
  7280. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7281. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7282. }
  7283. void main() {
  7284. vWorldDirection = transformDirection( position, modelMatrix );
  7285. #include <begin_vertex>
  7286. #include <project_vertex>
  7287. }
  7288. `,
  7289. fragmentShader: /* glsl */`
  7290. uniform sampler2D tEquirect;
  7291. varying vec3 vWorldDirection;
  7292. #include <common>
  7293. void main() {
  7294. vec3 direction = normalize( vWorldDirection );
  7295. vec2 sampleUV = equirectUv( direction );
  7296. gl_FragColor = texture2D( tEquirect, sampleUV );
  7297. }
  7298. `
  7299. };
  7300. const geometry = new BoxGeometry( 5, 5, 5 );
  7301. const material = new ShaderMaterial( {
  7302. name: 'CubemapFromEquirect',
  7303. uniforms: cloneUniforms( shader.uniforms ),
  7304. vertexShader: shader.vertexShader,
  7305. fragmentShader: shader.fragmentShader,
  7306. side: BackSide,
  7307. blending: NoBlending
  7308. } );
  7309. material.uniforms.tEquirect.value = texture;
  7310. const mesh = new Mesh( geometry, material );
  7311. const currentMinFilter = texture.minFilter;
  7312. // Avoid blurred poles
  7313. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7314. const camera = new CubeCamera( 1, 10, this );
  7315. camera.update( renderer, mesh );
  7316. texture.minFilter = currentMinFilter;
  7317. mesh.geometry.dispose();
  7318. mesh.material.dispose();
  7319. return this;
  7320. }
  7321. clear( renderer, color, depth, stencil ) {
  7322. const currentRenderTarget = renderer.getRenderTarget();
  7323. for ( let i = 0; i < 6; i ++ ) {
  7324. renderer.setRenderTarget( this, i );
  7325. renderer.clear( color, depth, stencil );
  7326. }
  7327. renderer.setRenderTarget( currentRenderTarget );
  7328. }
  7329. }
  7330. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7331. class DataTexture extends Texture {
  7332. constructor( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7333. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7334. this.image = { data: data || null, width: width || 1, height: height || 1 };
  7335. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7336. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7337. this.generateMipmaps = false;
  7338. this.flipY = false;
  7339. this.unpackAlignment = 1;
  7340. this.needsUpdate = true;
  7341. }
  7342. }
  7343. DataTexture.prototype.isDataTexture = true;
  7344. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7345. const _vector$7 = /*@__PURE__*/ new Vector3();
  7346. class Frustum {
  7347. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7348. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7349. }
  7350. set( p0, p1, p2, p3, p4, p5 ) {
  7351. const planes = this.planes;
  7352. planes[ 0 ].copy( p0 );
  7353. planes[ 1 ].copy( p1 );
  7354. planes[ 2 ].copy( p2 );
  7355. planes[ 3 ].copy( p3 );
  7356. planes[ 4 ].copy( p4 );
  7357. planes[ 5 ].copy( p5 );
  7358. return this;
  7359. }
  7360. copy( frustum ) {
  7361. const planes = this.planes;
  7362. for ( let i = 0; i < 6; i ++ ) {
  7363. planes[ i ].copy( frustum.planes[ i ] );
  7364. }
  7365. return this;
  7366. }
  7367. setFromProjectionMatrix( m ) {
  7368. const planes = this.planes;
  7369. const me = m.elements;
  7370. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7371. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7372. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7373. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7374. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7375. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7376. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7377. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7378. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7379. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7380. return this;
  7381. }
  7382. intersectsObject( object ) {
  7383. const geometry = object.geometry;
  7384. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7385. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7386. return this.intersectsSphere( _sphere$2 );
  7387. }
  7388. intersectsSprite( sprite ) {
  7389. _sphere$2.center.set( 0, 0, 0 );
  7390. _sphere$2.radius = 0.7071067811865476;
  7391. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7392. return this.intersectsSphere( _sphere$2 );
  7393. }
  7394. intersectsSphere( sphere ) {
  7395. const planes = this.planes;
  7396. const center = sphere.center;
  7397. const negRadius = - sphere.radius;
  7398. for ( let i = 0; i < 6; i ++ ) {
  7399. const distance = planes[ i ].distanceToPoint( center );
  7400. if ( distance < negRadius ) {
  7401. return false;
  7402. }
  7403. }
  7404. return true;
  7405. }
  7406. intersectsBox( box ) {
  7407. const planes = this.planes;
  7408. for ( let i = 0; i < 6; i ++ ) {
  7409. const plane = planes[ i ];
  7410. // corner at max distance
  7411. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7412. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7413. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7414. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7415. return false;
  7416. }
  7417. }
  7418. return true;
  7419. }
  7420. containsPoint( point ) {
  7421. const planes = this.planes;
  7422. for ( let i = 0; i < 6; i ++ ) {
  7423. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7424. return false;
  7425. }
  7426. }
  7427. return true;
  7428. }
  7429. clone() {
  7430. return new this.constructor().copy( this );
  7431. }
  7432. }
  7433. function WebGLAnimation() {
  7434. let context = null;
  7435. let isAnimating = false;
  7436. let animationLoop = null;
  7437. let requestId = null;
  7438. function onAnimationFrame( time, frame ) {
  7439. animationLoop( time, frame );
  7440. requestId = context.requestAnimationFrame( onAnimationFrame );
  7441. }
  7442. return {
  7443. start: function () {
  7444. if ( isAnimating === true ) return;
  7445. if ( animationLoop === null ) return;
  7446. requestId = context.requestAnimationFrame( onAnimationFrame );
  7447. isAnimating = true;
  7448. },
  7449. stop: function () {
  7450. context.cancelAnimationFrame( requestId );
  7451. isAnimating = false;
  7452. },
  7453. setAnimationLoop: function ( callback ) {
  7454. animationLoop = callback;
  7455. },
  7456. setContext: function ( value ) {
  7457. context = value;
  7458. }
  7459. };
  7460. }
  7461. function WebGLAttributes( gl, capabilities ) {
  7462. const isWebGL2 = capabilities.isWebGL2;
  7463. const buffers = new WeakMap();
  7464. function createBuffer( attribute, bufferType ) {
  7465. const array = attribute.array;
  7466. const usage = attribute.usage;
  7467. const buffer = gl.createBuffer();
  7468. gl.bindBuffer( bufferType, buffer );
  7469. gl.bufferData( bufferType, array, usage );
  7470. attribute.onUploadCallback();
  7471. let type = 5126;
  7472. if ( array instanceof Float32Array ) {
  7473. type = 5126;
  7474. } else if ( array instanceof Float64Array ) {
  7475. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7476. } else if ( array instanceof Uint16Array ) {
  7477. if ( attribute.isFloat16BufferAttribute ) {
  7478. if ( isWebGL2 ) {
  7479. type = 5131;
  7480. } else {
  7481. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7482. }
  7483. } else {
  7484. type = 5123;
  7485. }
  7486. } else if ( array instanceof Int16Array ) {
  7487. type = 5122;
  7488. } else if ( array instanceof Uint32Array ) {
  7489. type = 5125;
  7490. } else if ( array instanceof Int32Array ) {
  7491. type = 5124;
  7492. } else if ( array instanceof Int8Array ) {
  7493. type = 5120;
  7494. } else if ( array instanceof Uint8Array ) {
  7495. type = 5121;
  7496. }
  7497. return {
  7498. buffer: buffer,
  7499. type: type,
  7500. bytesPerElement: array.BYTES_PER_ELEMENT,
  7501. version: attribute.version
  7502. };
  7503. }
  7504. function updateBuffer( buffer, attribute, bufferType ) {
  7505. const array = attribute.array;
  7506. const updateRange = attribute.updateRange;
  7507. gl.bindBuffer( bufferType, buffer );
  7508. if ( updateRange.count === - 1 ) {
  7509. // Not using update ranges
  7510. gl.bufferSubData( bufferType, 0, array );
  7511. } else {
  7512. if ( isWebGL2 ) {
  7513. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7514. array, updateRange.offset, updateRange.count );
  7515. } else {
  7516. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7517. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7518. }
  7519. updateRange.count = - 1; // reset range
  7520. }
  7521. }
  7522. //
  7523. function get( attribute ) {
  7524. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7525. return buffers.get( attribute );
  7526. }
  7527. function remove( attribute ) {
  7528. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7529. const data = buffers.get( attribute );
  7530. if ( data ) {
  7531. gl.deleteBuffer( data.buffer );
  7532. buffers.delete( attribute );
  7533. }
  7534. }
  7535. function update( attribute, bufferType ) {
  7536. if ( attribute.isGLBufferAttribute ) {
  7537. const cached = buffers.get( attribute );
  7538. if ( ! cached || cached.version < attribute.version ) {
  7539. buffers.set( attribute, {
  7540. buffer: attribute.buffer,
  7541. type: attribute.type,
  7542. bytesPerElement: attribute.elementSize,
  7543. version: attribute.version
  7544. } );
  7545. }
  7546. return;
  7547. }
  7548. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7549. const data = buffers.get( attribute );
  7550. if ( data === undefined ) {
  7551. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7552. } else if ( data.version < attribute.version ) {
  7553. updateBuffer( data.buffer, attribute, bufferType );
  7554. data.version = attribute.version;
  7555. }
  7556. }
  7557. return {
  7558. get: get,
  7559. remove: remove,
  7560. update: update
  7561. };
  7562. }
  7563. class PlaneGeometry extends BufferGeometry {
  7564. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7565. super();
  7566. this.type = 'PlaneGeometry';
  7567. this.parameters = {
  7568. width: width,
  7569. height: height,
  7570. widthSegments: widthSegments,
  7571. heightSegments: heightSegments
  7572. };
  7573. const width_half = width / 2;
  7574. const height_half = height / 2;
  7575. const gridX = Math.floor( widthSegments );
  7576. const gridY = Math.floor( heightSegments );
  7577. const gridX1 = gridX + 1;
  7578. const gridY1 = gridY + 1;
  7579. const segment_width = width / gridX;
  7580. const segment_height = height / gridY;
  7581. //
  7582. const indices = [];
  7583. const vertices = [];
  7584. const normals = [];
  7585. const uvs = [];
  7586. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7587. const y = iy * segment_height - height_half;
  7588. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7589. const x = ix * segment_width - width_half;
  7590. vertices.push( x, - y, 0 );
  7591. normals.push( 0, 0, 1 );
  7592. uvs.push( ix / gridX );
  7593. uvs.push( 1 - ( iy / gridY ) );
  7594. }
  7595. }
  7596. for ( let iy = 0; iy < gridY; iy ++ ) {
  7597. for ( let ix = 0; ix < gridX; ix ++ ) {
  7598. const a = ix + gridX1 * iy;
  7599. const b = ix + gridX1 * ( iy + 1 );
  7600. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7601. const d = ( ix + 1 ) + gridX1 * iy;
  7602. indices.push( a, b, d );
  7603. indices.push( b, c, d );
  7604. }
  7605. }
  7606. this.setIndex( indices );
  7607. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7608. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7609. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7610. }
  7611. }
  7612. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7613. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7614. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7615. 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.specularRoughness );\n\t#endif\n#endif";
  7616. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7617. var begin_vertex = "vec3 transformed = vec3( position );";
  7618. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7619. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\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\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_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_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * 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}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.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}\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_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7620. 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";
  7621. 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";
  7622. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7623. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7624. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7625. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7626. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7627. 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";
  7628. 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";
  7629. 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 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 max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 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}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\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}";
  7630. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7631. 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";
  7632. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7633. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7634. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7635. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7636. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7637. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  7638. 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#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\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";
  7639. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\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";
  7640. 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";
  7641. 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";
  7642. 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";
  7643. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7644. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7645. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7646. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\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";
  7647. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7648. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7649. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7650. 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 );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\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\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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 );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7651. 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 GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\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 getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.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 getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.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 getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.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 GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7652. 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 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7653. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7654. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_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_Diffuse_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)";
  7655. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7656. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, 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_Diffuse_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)";
  7657. 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.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\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 = sheen;\n#endif";
  7658. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\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.specularRoughness;\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#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_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_Diffuse_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 CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * 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}";
  7659. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef 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\tgetPointDirectLightIrradiance( 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\tgetSpotDirectLightIrradiance( 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\tgetDirectionalDirectLightIrradiance( 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 );\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 );\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";
  7660. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7661. 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";
  7662. 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";
  7663. 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";
  7664. 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";
  7665. 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";
  7666. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7667. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7668. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7669. 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";
  7670. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7671. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7672. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7673. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7674. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7675. 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;";
  7676. 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";
  7677. 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";
  7678. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7679. 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";
  7680. 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";
  7681. 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}";
  7682. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7683. 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;";
  7684. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7685. 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";
  7686. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7687. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7688. 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";
  7689. 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";
  7690. 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";
  7691. 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}";
  7692. 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";
  7693. 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";
  7694. 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";
  7695. 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";
  7696. 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";
  7697. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7698. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7699. 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; }";
  7700. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  7701. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  7702. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7703. 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";
  7704. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7705. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7706. 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";
  7707. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7708. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\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";
  7709. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7710. var background_vert = "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}";
  7711. var cube_frag = "#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}";
  7712. var cube_vert = "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}";
  7713. var depth_frag = "#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 <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}";
  7714. var depth_vert = "#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}";
  7715. var distanceRGBA_frag = "#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 <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}";
  7716. var distanceRGBA_vert = "#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}";
  7717. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7718. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7719. var linedashed_frag = "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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7720. var linedashed_vert = "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}";
  7721. var meshbasic_frag = "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 <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\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7722. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\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 <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7723. var meshlambert_frag = "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 <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_Diffuse_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_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7724. var meshlambert_vert = "#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}";
  7725. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7726. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\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\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7727. var meshtoon_frag = "#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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7728. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\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 <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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7729. var meshphong_frag = "#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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7730. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7731. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#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\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 <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_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 <lights_physical_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#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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 <transmissionmap_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 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7732. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#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\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 <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#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\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}";
  7733. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\n#include <packing>\n#include <uv_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}";
  7734. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\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 <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#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\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}";
  7735. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7736. var points_vert = "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}";
  7737. var shadow_frag = "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}";
  7738. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7739. var sprite_frag = "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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7740. var sprite_vert = "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}";
  7741. const ShaderChunk = {
  7742. alphamap_fragment: alphamap_fragment,
  7743. alphamap_pars_fragment: alphamap_pars_fragment,
  7744. alphatest_fragment: alphatest_fragment,
  7745. aomap_fragment: aomap_fragment,
  7746. aomap_pars_fragment: aomap_pars_fragment,
  7747. begin_vertex: begin_vertex,
  7748. beginnormal_vertex: beginnormal_vertex,
  7749. bsdfs: bsdfs,
  7750. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7751. clipping_planes_fragment: clipping_planes_fragment,
  7752. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7753. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7754. clipping_planes_vertex: clipping_planes_vertex,
  7755. color_fragment: color_fragment,
  7756. color_pars_fragment: color_pars_fragment,
  7757. color_pars_vertex: color_pars_vertex,
  7758. color_vertex: color_vertex,
  7759. common: common,
  7760. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7761. defaultnormal_vertex: defaultnormal_vertex,
  7762. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7763. displacementmap_vertex: displacementmap_vertex,
  7764. emissivemap_fragment: emissivemap_fragment,
  7765. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7766. encodings_fragment: encodings_fragment,
  7767. encodings_pars_fragment: encodings_pars_fragment,
  7768. envmap_fragment: envmap_fragment,
  7769. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7770. envmap_pars_fragment: envmap_pars_fragment,
  7771. envmap_pars_vertex: envmap_pars_vertex,
  7772. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7773. envmap_vertex: envmap_vertex,
  7774. fog_vertex: fog_vertex,
  7775. fog_pars_vertex: fog_pars_vertex,
  7776. fog_fragment: fog_fragment,
  7777. fog_pars_fragment: fog_pars_fragment,
  7778. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7779. lightmap_fragment: lightmap_fragment,
  7780. lightmap_pars_fragment: lightmap_pars_fragment,
  7781. lights_lambert_vertex: lights_lambert_vertex,
  7782. lights_pars_begin: lights_pars_begin,
  7783. lights_toon_fragment: lights_toon_fragment,
  7784. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7785. lights_phong_fragment: lights_phong_fragment,
  7786. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7787. lights_physical_fragment: lights_physical_fragment,
  7788. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7789. lights_fragment_begin: lights_fragment_begin,
  7790. lights_fragment_maps: lights_fragment_maps,
  7791. lights_fragment_end: lights_fragment_end,
  7792. logdepthbuf_fragment: logdepthbuf_fragment,
  7793. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7794. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7795. logdepthbuf_vertex: logdepthbuf_vertex,
  7796. map_fragment: map_fragment,
  7797. map_pars_fragment: map_pars_fragment,
  7798. map_particle_fragment: map_particle_fragment,
  7799. map_particle_pars_fragment: map_particle_pars_fragment,
  7800. metalnessmap_fragment: metalnessmap_fragment,
  7801. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7802. morphnormal_vertex: morphnormal_vertex,
  7803. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7804. morphtarget_vertex: morphtarget_vertex,
  7805. normal_fragment_begin: normal_fragment_begin,
  7806. normal_fragment_maps: normal_fragment_maps,
  7807. normalmap_pars_fragment: normalmap_pars_fragment,
  7808. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7809. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7810. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7811. packing: packing,
  7812. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7813. project_vertex: project_vertex,
  7814. dithering_fragment: dithering_fragment,
  7815. dithering_pars_fragment: dithering_pars_fragment,
  7816. roughnessmap_fragment: roughnessmap_fragment,
  7817. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7818. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7819. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7820. shadowmap_vertex: shadowmap_vertex,
  7821. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7822. skinbase_vertex: skinbase_vertex,
  7823. skinning_pars_vertex: skinning_pars_vertex,
  7824. skinning_vertex: skinning_vertex,
  7825. skinnormal_vertex: skinnormal_vertex,
  7826. specularmap_fragment: specularmap_fragment,
  7827. specularmap_pars_fragment: specularmap_pars_fragment,
  7828. tonemapping_fragment: tonemapping_fragment,
  7829. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7830. transmissionmap_fragment: transmissionmap_fragment,
  7831. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  7832. uv_pars_fragment: uv_pars_fragment,
  7833. uv_pars_vertex: uv_pars_vertex,
  7834. uv_vertex: uv_vertex,
  7835. uv2_pars_fragment: uv2_pars_fragment,
  7836. uv2_pars_vertex: uv2_pars_vertex,
  7837. uv2_vertex: uv2_vertex,
  7838. worldpos_vertex: worldpos_vertex,
  7839. background_frag: background_frag,
  7840. background_vert: background_vert,
  7841. cube_frag: cube_frag,
  7842. cube_vert: cube_vert,
  7843. depth_frag: depth_frag,
  7844. depth_vert: depth_vert,
  7845. distanceRGBA_frag: distanceRGBA_frag,
  7846. distanceRGBA_vert: distanceRGBA_vert,
  7847. equirect_frag: equirect_frag,
  7848. equirect_vert: equirect_vert,
  7849. linedashed_frag: linedashed_frag,
  7850. linedashed_vert: linedashed_vert,
  7851. meshbasic_frag: meshbasic_frag,
  7852. meshbasic_vert: meshbasic_vert,
  7853. meshlambert_frag: meshlambert_frag,
  7854. meshlambert_vert: meshlambert_vert,
  7855. meshmatcap_frag: meshmatcap_frag,
  7856. meshmatcap_vert: meshmatcap_vert,
  7857. meshtoon_frag: meshtoon_frag,
  7858. meshtoon_vert: meshtoon_vert,
  7859. meshphong_frag: meshphong_frag,
  7860. meshphong_vert: meshphong_vert,
  7861. meshphysical_frag: meshphysical_frag,
  7862. meshphysical_vert: meshphysical_vert,
  7863. normal_frag: normal_frag,
  7864. normal_vert: normal_vert,
  7865. points_frag: points_frag,
  7866. points_vert: points_vert,
  7867. shadow_frag: shadow_frag,
  7868. shadow_vert: shadow_vert,
  7869. sprite_frag: sprite_frag,
  7870. sprite_vert: sprite_vert
  7871. };
  7872. /**
  7873. * Uniforms library for shared webgl shaders
  7874. */
  7875. const UniformsLib = {
  7876. common: {
  7877. diffuse: { value: new Color( 0xffffff ) },
  7878. opacity: { value: 1.0 },
  7879. map: { value: null },
  7880. uvTransform: { value: new Matrix3() },
  7881. uv2Transform: { value: new Matrix3() },
  7882. alphaMap: { value: null },
  7883. },
  7884. specularmap: {
  7885. specularMap: { value: null },
  7886. },
  7887. envmap: {
  7888. envMap: { value: null },
  7889. flipEnvMap: { value: - 1 },
  7890. reflectivity: { value: 1.0 },
  7891. refractionRatio: { value: 0.98 },
  7892. maxMipLevel: { value: 0 }
  7893. },
  7894. aomap: {
  7895. aoMap: { value: null },
  7896. aoMapIntensity: { value: 1 }
  7897. },
  7898. lightmap: {
  7899. lightMap: { value: null },
  7900. lightMapIntensity: { value: 1 }
  7901. },
  7902. emissivemap: {
  7903. emissiveMap: { value: null }
  7904. },
  7905. bumpmap: {
  7906. bumpMap: { value: null },
  7907. bumpScale: { value: 1 }
  7908. },
  7909. normalmap: {
  7910. normalMap: { value: null },
  7911. normalScale: { value: new Vector2( 1, 1 ) }
  7912. },
  7913. displacementmap: {
  7914. displacementMap: { value: null },
  7915. displacementScale: { value: 1 },
  7916. displacementBias: { value: 0 }
  7917. },
  7918. roughnessmap: {
  7919. roughnessMap: { value: null }
  7920. },
  7921. metalnessmap: {
  7922. metalnessMap: { value: null }
  7923. },
  7924. gradientmap: {
  7925. gradientMap: { value: null }
  7926. },
  7927. fog: {
  7928. fogDensity: { value: 0.00025 },
  7929. fogNear: { value: 1 },
  7930. fogFar: { value: 2000 },
  7931. fogColor: { value: new Color( 0xffffff ) }
  7932. },
  7933. lights: {
  7934. ambientLightColor: { value: [] },
  7935. lightProbe: { value: [] },
  7936. directionalLights: { value: [], properties: {
  7937. direction: {},
  7938. color: {}
  7939. } },
  7940. directionalLightShadows: { value: [], properties: {
  7941. shadowBias: {},
  7942. shadowNormalBias: {},
  7943. shadowRadius: {},
  7944. shadowMapSize: {}
  7945. } },
  7946. directionalShadowMap: { value: [] },
  7947. directionalShadowMatrix: { value: [] },
  7948. spotLights: { value: [], properties: {
  7949. color: {},
  7950. position: {},
  7951. direction: {},
  7952. distance: {},
  7953. coneCos: {},
  7954. penumbraCos: {},
  7955. decay: {}
  7956. } },
  7957. spotLightShadows: { value: [], properties: {
  7958. shadowBias: {},
  7959. shadowNormalBias: {},
  7960. shadowRadius: {},
  7961. shadowMapSize: {}
  7962. } },
  7963. spotShadowMap: { value: [] },
  7964. spotShadowMatrix: { value: [] },
  7965. pointLights: { value: [], properties: {
  7966. color: {},
  7967. position: {},
  7968. decay: {},
  7969. distance: {}
  7970. } },
  7971. pointLightShadows: { value: [], properties: {
  7972. shadowBias: {},
  7973. shadowNormalBias: {},
  7974. shadowRadius: {},
  7975. shadowMapSize: {},
  7976. shadowCameraNear: {},
  7977. shadowCameraFar: {}
  7978. } },
  7979. pointShadowMap: { value: [] },
  7980. pointShadowMatrix: { value: [] },
  7981. hemisphereLights: { value: [], properties: {
  7982. direction: {},
  7983. skyColor: {},
  7984. groundColor: {}
  7985. } },
  7986. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7987. rectAreaLights: { value: [], properties: {
  7988. color: {},
  7989. position: {},
  7990. width: {},
  7991. height: {}
  7992. } },
  7993. ltc_1: { value: null },
  7994. ltc_2: { value: null }
  7995. },
  7996. points: {
  7997. diffuse: { value: new Color( 0xffffff ) },
  7998. opacity: { value: 1.0 },
  7999. size: { value: 1.0 },
  8000. scale: { value: 1.0 },
  8001. map: { value: null },
  8002. alphaMap: { value: null },
  8003. uvTransform: { value: new Matrix3() }
  8004. },
  8005. sprite: {
  8006. diffuse: { value: new Color( 0xffffff ) },
  8007. opacity: { value: 1.0 },
  8008. center: { value: new Vector2( 0.5, 0.5 ) },
  8009. rotation: { value: 0.0 },
  8010. map: { value: null },
  8011. alphaMap: { value: null },
  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.normal_vert,
  8164. fragmentShader: ShaderChunk.normal_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: new Color( 0x000000 ) },
  8239. transmission: { value: 0 },
  8240. transmissionMap: { value: null },
  8241. }
  8242. ] ),
  8243. vertexShader: ShaderChunk.meshphysical_vert,
  8244. fragmentShader: ShaderChunk.meshphysical_frag
  8245. };
  8246. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8247. const clearColor = new Color( 0x000000 );
  8248. let clearAlpha = 0;
  8249. let planeMesh;
  8250. let boxMesh;
  8251. let currentBackground = null;
  8252. let currentBackgroundVersion = 0;
  8253. let currentTonemapping = null;
  8254. function render( renderList, scene ) {
  8255. let forceClear = false;
  8256. let background = scene.isScene === true ? scene.background : null;
  8257. if ( background && background.isTexture ) {
  8258. background = cubemaps.get( background );
  8259. }
  8260. // Ignore background in AR
  8261. // TODO: Reconsider this.
  8262. const xr = renderer.xr;
  8263. const session = xr.getSession && xr.getSession();
  8264. if ( session && session.environmentBlendMode === 'additive' ) {
  8265. background = null;
  8266. }
  8267. if ( background === null ) {
  8268. setClear( clearColor, clearAlpha );
  8269. } else if ( background && background.isColor ) {
  8270. setClear( background, 1 );
  8271. forceClear = true;
  8272. }
  8273. if ( renderer.autoClear || forceClear ) {
  8274. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8275. }
  8276. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8277. if ( boxMesh === undefined ) {
  8278. boxMesh = new Mesh(
  8279. new BoxGeometry( 1, 1, 1 ),
  8280. new ShaderMaterial( {
  8281. name: 'BackgroundCubeMaterial',
  8282. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8283. vertexShader: ShaderLib.cube.vertexShader,
  8284. fragmentShader: ShaderLib.cube.fragmentShader,
  8285. side: BackSide,
  8286. depthTest: false,
  8287. depthWrite: false,
  8288. fog: false
  8289. } )
  8290. );
  8291. boxMesh.geometry.deleteAttribute( 'normal' );
  8292. boxMesh.geometry.deleteAttribute( 'uv' );
  8293. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8294. this.matrixWorld.copyPosition( camera.matrixWorld );
  8295. };
  8296. // enable code injection for non-built-in material
  8297. Object.defineProperty( boxMesh.material, 'envMap', {
  8298. get: function () {
  8299. return this.uniforms.envMap.value;
  8300. }
  8301. } );
  8302. objects.update( boxMesh );
  8303. }
  8304. boxMesh.material.uniforms.envMap.value = background;
  8305. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  8306. if ( currentBackground !== background ||
  8307. currentBackgroundVersion !== background.version ||
  8308. currentTonemapping !== renderer.toneMapping ) {
  8309. boxMesh.material.needsUpdate = true;
  8310. currentBackground = background;
  8311. currentBackgroundVersion = background.version;
  8312. currentTonemapping = renderer.toneMapping;
  8313. }
  8314. // push to the pre-sorted opaque render list
  8315. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8316. } else if ( background && background.isTexture ) {
  8317. if ( planeMesh === undefined ) {
  8318. planeMesh = new Mesh(
  8319. new PlaneGeometry( 2, 2 ),
  8320. new ShaderMaterial( {
  8321. name: 'BackgroundMaterial',
  8322. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8323. vertexShader: ShaderLib.background.vertexShader,
  8324. fragmentShader: ShaderLib.background.fragmentShader,
  8325. side: FrontSide,
  8326. depthTest: false,
  8327. depthWrite: false,
  8328. fog: false
  8329. } )
  8330. );
  8331. planeMesh.geometry.deleteAttribute( 'normal' );
  8332. // enable code injection for non-built-in material
  8333. Object.defineProperty( planeMesh.material, 'map', {
  8334. get: function () {
  8335. return this.uniforms.t2D.value;
  8336. }
  8337. } );
  8338. objects.update( planeMesh );
  8339. }
  8340. planeMesh.material.uniforms.t2D.value = background;
  8341. if ( background.matrixAutoUpdate === true ) {
  8342. background.updateMatrix();
  8343. }
  8344. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8345. if ( currentBackground !== background ||
  8346. currentBackgroundVersion !== background.version ||
  8347. currentTonemapping !== renderer.toneMapping ) {
  8348. planeMesh.material.needsUpdate = true;
  8349. currentBackground = background;
  8350. currentBackgroundVersion = background.version;
  8351. currentTonemapping = renderer.toneMapping;
  8352. }
  8353. // push to the pre-sorted opaque render list
  8354. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8355. }
  8356. }
  8357. function setClear( color, alpha ) {
  8358. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8359. }
  8360. return {
  8361. getClearColor: function () {
  8362. return clearColor;
  8363. },
  8364. setClearColor: function ( color, alpha = 1 ) {
  8365. clearColor.set( color );
  8366. clearAlpha = alpha;
  8367. setClear( clearColor, clearAlpha );
  8368. },
  8369. getClearAlpha: function () {
  8370. return clearAlpha;
  8371. },
  8372. setClearAlpha: function ( alpha ) {
  8373. clearAlpha = alpha;
  8374. setClear( clearColor, clearAlpha );
  8375. },
  8376. render: render
  8377. };
  8378. }
  8379. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8380. const maxVertexAttributes = gl.getParameter( 34921 );
  8381. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8382. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8383. const bindingStates = {};
  8384. const defaultState = createBindingState( null );
  8385. let currentState = defaultState;
  8386. function setup( object, material, program, geometry, index ) {
  8387. let updateBuffers = false;
  8388. if ( vaoAvailable ) {
  8389. const state = getBindingState( geometry, program, material );
  8390. if ( currentState !== state ) {
  8391. currentState = state;
  8392. bindVertexArrayObject( currentState.object );
  8393. }
  8394. updateBuffers = needsUpdate( geometry, index );
  8395. if ( updateBuffers ) saveCache( geometry, index );
  8396. } else {
  8397. const wireframe = ( material.wireframe === true );
  8398. if ( currentState.geometry !== geometry.id ||
  8399. currentState.program !== program.id ||
  8400. currentState.wireframe !== wireframe ) {
  8401. currentState.geometry = geometry.id;
  8402. currentState.program = program.id;
  8403. currentState.wireframe = wireframe;
  8404. updateBuffers = true;
  8405. }
  8406. }
  8407. if ( object.isInstancedMesh === true ) {
  8408. updateBuffers = true;
  8409. }
  8410. if ( index !== null ) {
  8411. attributes.update( index, 34963 );
  8412. }
  8413. if ( updateBuffers ) {
  8414. setupVertexAttributes( object, material, program, geometry );
  8415. if ( index !== null ) {
  8416. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8417. }
  8418. }
  8419. }
  8420. function createVertexArrayObject() {
  8421. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8422. return extension.createVertexArrayOES();
  8423. }
  8424. function bindVertexArrayObject( vao ) {
  8425. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8426. return extension.bindVertexArrayOES( vao );
  8427. }
  8428. function deleteVertexArrayObject( vao ) {
  8429. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8430. return extension.deleteVertexArrayOES( vao );
  8431. }
  8432. function getBindingState( geometry, program, material ) {
  8433. const wireframe = ( material.wireframe === true );
  8434. let programMap = bindingStates[ geometry.id ];
  8435. if ( programMap === undefined ) {
  8436. programMap = {};
  8437. bindingStates[ geometry.id ] = programMap;
  8438. }
  8439. let stateMap = programMap[ program.id ];
  8440. if ( stateMap === undefined ) {
  8441. stateMap = {};
  8442. programMap[ program.id ] = stateMap;
  8443. }
  8444. let state = stateMap[ wireframe ];
  8445. if ( state === undefined ) {
  8446. state = createBindingState( createVertexArrayObject() );
  8447. stateMap[ wireframe ] = state;
  8448. }
  8449. return state;
  8450. }
  8451. function createBindingState( vao ) {
  8452. const newAttributes = [];
  8453. const enabledAttributes = [];
  8454. const attributeDivisors = [];
  8455. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8456. newAttributes[ i ] = 0;
  8457. enabledAttributes[ i ] = 0;
  8458. attributeDivisors[ i ] = 0;
  8459. }
  8460. return {
  8461. // for backward compatibility on non-VAO support browser
  8462. geometry: null,
  8463. program: null,
  8464. wireframe: false,
  8465. newAttributes: newAttributes,
  8466. enabledAttributes: enabledAttributes,
  8467. attributeDivisors: attributeDivisors,
  8468. object: vao,
  8469. attributes: {},
  8470. index: null
  8471. };
  8472. }
  8473. function needsUpdate( geometry, index ) {
  8474. const cachedAttributes = currentState.attributes;
  8475. const geometryAttributes = geometry.attributes;
  8476. let attributesNum = 0;
  8477. for ( const key in geometryAttributes ) {
  8478. const cachedAttribute = cachedAttributes[ key ];
  8479. const geometryAttribute = geometryAttributes[ key ];
  8480. if ( cachedAttribute === undefined ) return true;
  8481. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8482. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8483. attributesNum ++;
  8484. }
  8485. if ( currentState.attributesNum !== attributesNum ) return true;
  8486. if ( currentState.index !== index ) return true;
  8487. return false;
  8488. }
  8489. function saveCache( geometry, index ) {
  8490. const cache = {};
  8491. const attributes = geometry.attributes;
  8492. let attributesNum = 0;
  8493. for ( const key in attributes ) {
  8494. const attribute = attributes[ key ];
  8495. const data = {};
  8496. data.attribute = attribute;
  8497. if ( attribute.data ) {
  8498. data.data = attribute.data;
  8499. }
  8500. cache[ key ] = data;
  8501. attributesNum ++;
  8502. }
  8503. currentState.attributes = cache;
  8504. currentState.attributesNum = attributesNum;
  8505. currentState.index = index;
  8506. }
  8507. function initAttributes() {
  8508. const newAttributes = currentState.newAttributes;
  8509. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8510. newAttributes[ i ] = 0;
  8511. }
  8512. }
  8513. function enableAttribute( attribute ) {
  8514. enableAttributeAndDivisor( attribute, 0 );
  8515. }
  8516. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8517. const newAttributes = currentState.newAttributes;
  8518. const enabledAttributes = currentState.enabledAttributes;
  8519. const attributeDivisors = currentState.attributeDivisors;
  8520. newAttributes[ attribute ] = 1;
  8521. if ( enabledAttributes[ attribute ] === 0 ) {
  8522. gl.enableVertexAttribArray( attribute );
  8523. enabledAttributes[ attribute ] = 1;
  8524. }
  8525. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8526. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8527. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8528. attributeDivisors[ attribute ] = meshPerAttribute;
  8529. }
  8530. }
  8531. function disableUnusedAttributes() {
  8532. const newAttributes = currentState.newAttributes;
  8533. const enabledAttributes = currentState.enabledAttributes;
  8534. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8535. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8536. gl.disableVertexAttribArray( i );
  8537. enabledAttributes[ i ] = 0;
  8538. }
  8539. }
  8540. }
  8541. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8542. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8543. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8544. } else {
  8545. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8546. }
  8547. }
  8548. function setupVertexAttributes( object, material, program, geometry ) {
  8549. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8550. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8551. }
  8552. initAttributes();
  8553. const geometryAttributes = geometry.attributes;
  8554. const programAttributes = program.getAttributes();
  8555. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8556. for ( const name in programAttributes ) {
  8557. const programAttribute = programAttributes[ name ];
  8558. if ( programAttribute >= 0 ) {
  8559. const geometryAttribute = geometryAttributes[ name ];
  8560. if ( geometryAttribute !== undefined ) {
  8561. const normalized = geometryAttribute.normalized;
  8562. const size = geometryAttribute.itemSize;
  8563. const attribute = attributes.get( geometryAttribute );
  8564. // TODO Attribute may not be available on context restore
  8565. if ( attribute === undefined ) continue;
  8566. const buffer = attribute.buffer;
  8567. const type = attribute.type;
  8568. const bytesPerElement = attribute.bytesPerElement;
  8569. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8570. const data = geometryAttribute.data;
  8571. const stride = data.stride;
  8572. const offset = geometryAttribute.offset;
  8573. if ( data && data.isInstancedInterleavedBuffer ) {
  8574. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  8575. if ( geometry._maxInstanceCount === undefined ) {
  8576. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8577. }
  8578. } else {
  8579. enableAttribute( programAttribute );
  8580. }
  8581. gl.bindBuffer( 34962, buffer );
  8582. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  8583. } else {
  8584. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8585. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  8586. if ( geometry._maxInstanceCount === undefined ) {
  8587. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8588. }
  8589. } else {
  8590. enableAttribute( programAttribute );
  8591. }
  8592. gl.bindBuffer( 34962, buffer );
  8593. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  8594. }
  8595. } else if ( name === 'instanceMatrix' ) {
  8596. const attribute = attributes.get( object.instanceMatrix );
  8597. // TODO Attribute may not be available on context restore
  8598. if ( attribute === undefined ) continue;
  8599. const buffer = attribute.buffer;
  8600. const type = attribute.type;
  8601. enableAttributeAndDivisor( programAttribute + 0, 1 );
  8602. enableAttributeAndDivisor( programAttribute + 1, 1 );
  8603. enableAttributeAndDivisor( programAttribute + 2, 1 );
  8604. enableAttributeAndDivisor( programAttribute + 3, 1 );
  8605. gl.bindBuffer( 34962, buffer );
  8606. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  8607. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  8608. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  8609. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  8610. } else if ( name === 'instanceColor' ) {
  8611. const attribute = attributes.get( object.instanceColor );
  8612. // TODO Attribute may not be available on context restore
  8613. if ( attribute === undefined ) continue;
  8614. const buffer = attribute.buffer;
  8615. const type = attribute.type;
  8616. enableAttributeAndDivisor( programAttribute, 1 );
  8617. gl.bindBuffer( 34962, buffer );
  8618. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  8619. } else if ( materialDefaultAttributeValues !== undefined ) {
  8620. const value = materialDefaultAttributeValues[ name ];
  8621. if ( value !== undefined ) {
  8622. switch ( value.length ) {
  8623. case 2:
  8624. gl.vertexAttrib2fv( programAttribute, value );
  8625. break;
  8626. case 3:
  8627. gl.vertexAttrib3fv( programAttribute, value );
  8628. break;
  8629. case 4:
  8630. gl.vertexAttrib4fv( programAttribute, value );
  8631. break;
  8632. default:
  8633. gl.vertexAttrib1fv( programAttribute, value );
  8634. }
  8635. }
  8636. }
  8637. }
  8638. }
  8639. disableUnusedAttributes();
  8640. }
  8641. function dispose() {
  8642. reset();
  8643. for ( const geometryId in bindingStates ) {
  8644. const programMap = bindingStates[ geometryId ];
  8645. for ( const programId in programMap ) {
  8646. const stateMap = programMap[ programId ];
  8647. for ( const wireframe in stateMap ) {
  8648. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8649. delete stateMap[ wireframe ];
  8650. }
  8651. delete programMap[ programId ];
  8652. }
  8653. delete bindingStates[ geometryId ];
  8654. }
  8655. }
  8656. function releaseStatesOfGeometry( geometry ) {
  8657. if ( bindingStates[ geometry.id ] === undefined ) return;
  8658. const programMap = bindingStates[ geometry.id ];
  8659. for ( const programId in programMap ) {
  8660. const stateMap = programMap[ programId ];
  8661. for ( const wireframe in stateMap ) {
  8662. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8663. delete stateMap[ wireframe ];
  8664. }
  8665. delete programMap[ programId ];
  8666. }
  8667. delete bindingStates[ geometry.id ];
  8668. }
  8669. function releaseStatesOfProgram( program ) {
  8670. for ( const geometryId in bindingStates ) {
  8671. const programMap = bindingStates[ geometryId ];
  8672. if ( programMap[ program.id ] === undefined ) continue;
  8673. const stateMap = programMap[ program.id ];
  8674. for ( const wireframe in stateMap ) {
  8675. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8676. delete stateMap[ wireframe ];
  8677. }
  8678. delete programMap[ program.id ];
  8679. }
  8680. }
  8681. function reset() {
  8682. resetDefaultState();
  8683. if ( currentState === defaultState ) return;
  8684. currentState = defaultState;
  8685. bindVertexArrayObject( currentState.object );
  8686. }
  8687. // for backward-compatilibity
  8688. function resetDefaultState() {
  8689. defaultState.geometry = null;
  8690. defaultState.program = null;
  8691. defaultState.wireframe = false;
  8692. }
  8693. return {
  8694. setup: setup,
  8695. reset: reset,
  8696. resetDefaultState: resetDefaultState,
  8697. dispose: dispose,
  8698. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8699. releaseStatesOfProgram: releaseStatesOfProgram,
  8700. initAttributes: initAttributes,
  8701. enableAttribute: enableAttribute,
  8702. disableUnusedAttributes: disableUnusedAttributes
  8703. };
  8704. }
  8705. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8706. const isWebGL2 = capabilities.isWebGL2;
  8707. let mode;
  8708. function setMode( value ) {
  8709. mode = value;
  8710. }
  8711. function render( start, count ) {
  8712. gl.drawArrays( mode, start, count );
  8713. info.update( count, mode, 1 );
  8714. }
  8715. function renderInstances( start, count, primcount ) {
  8716. if ( primcount === 0 ) return;
  8717. let extension, methodName;
  8718. if ( isWebGL2 ) {
  8719. extension = gl;
  8720. methodName = 'drawArraysInstanced';
  8721. } else {
  8722. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8723. methodName = 'drawArraysInstancedANGLE';
  8724. if ( extension === null ) {
  8725. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8726. return;
  8727. }
  8728. }
  8729. extension[ methodName ]( mode, start, count, primcount );
  8730. info.update( count, mode, primcount );
  8731. }
  8732. //
  8733. this.setMode = setMode;
  8734. this.render = render;
  8735. this.renderInstances = renderInstances;
  8736. }
  8737. function WebGLCapabilities( gl, extensions, parameters ) {
  8738. let maxAnisotropy;
  8739. function getMaxAnisotropy() {
  8740. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8741. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8742. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8743. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8744. } else {
  8745. maxAnisotropy = 0;
  8746. }
  8747. return maxAnisotropy;
  8748. }
  8749. function getMaxPrecision( precision ) {
  8750. if ( precision === 'highp' ) {
  8751. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8752. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8753. return 'highp';
  8754. }
  8755. precision = 'mediump';
  8756. }
  8757. if ( precision === 'mediump' ) {
  8758. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8759. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8760. return 'mediump';
  8761. }
  8762. }
  8763. return 'lowp';
  8764. }
  8765. /* eslint-disable no-undef */
  8766. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8767. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8768. /* eslint-enable no-undef */
  8769. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8770. const maxPrecision = getMaxPrecision( precision );
  8771. if ( maxPrecision !== precision ) {
  8772. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8773. precision = maxPrecision;
  8774. }
  8775. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8776. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8777. const maxTextures = gl.getParameter( 34930 );
  8778. const maxVertexTextures = gl.getParameter( 35660 );
  8779. const maxTextureSize = gl.getParameter( 3379 );
  8780. const maxCubemapSize = gl.getParameter( 34076 );
  8781. const maxAttributes = gl.getParameter( 34921 );
  8782. const maxVertexUniforms = gl.getParameter( 36347 );
  8783. const maxVaryings = gl.getParameter( 36348 );
  8784. const maxFragmentUniforms = gl.getParameter( 36349 );
  8785. const vertexTextures = maxVertexTextures > 0;
  8786. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8787. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8788. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8789. return {
  8790. isWebGL2: isWebGL2,
  8791. drawBuffers: drawBuffers,
  8792. getMaxAnisotropy: getMaxAnisotropy,
  8793. getMaxPrecision: getMaxPrecision,
  8794. precision: precision,
  8795. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8796. maxTextures: maxTextures,
  8797. maxVertexTextures: maxVertexTextures,
  8798. maxTextureSize: maxTextureSize,
  8799. maxCubemapSize: maxCubemapSize,
  8800. maxAttributes: maxAttributes,
  8801. maxVertexUniforms: maxVertexUniforms,
  8802. maxVaryings: maxVaryings,
  8803. maxFragmentUniforms: maxFragmentUniforms,
  8804. vertexTextures: vertexTextures,
  8805. floatFragmentTextures: floatFragmentTextures,
  8806. floatVertexTextures: floatVertexTextures,
  8807. maxSamples: maxSamples
  8808. };
  8809. }
  8810. function WebGLClipping( properties ) {
  8811. const scope = this;
  8812. let globalState = null,
  8813. numGlobalPlanes = 0,
  8814. localClippingEnabled = false,
  8815. renderingShadows = false;
  8816. const plane = new Plane(),
  8817. viewNormalMatrix = new Matrix3(),
  8818. uniform = { value: null, needsUpdate: false };
  8819. this.uniform = uniform;
  8820. this.numPlanes = 0;
  8821. this.numIntersection = 0;
  8822. this.init = function ( planes, enableLocalClipping, camera ) {
  8823. const enabled =
  8824. planes.length !== 0 ||
  8825. enableLocalClipping ||
  8826. // enable state of previous frame - the clipping code has to
  8827. // run another frame in order to reset the state:
  8828. numGlobalPlanes !== 0 ||
  8829. localClippingEnabled;
  8830. localClippingEnabled = enableLocalClipping;
  8831. globalState = projectPlanes( planes, camera, 0 );
  8832. numGlobalPlanes = planes.length;
  8833. return enabled;
  8834. };
  8835. this.beginShadows = function () {
  8836. renderingShadows = true;
  8837. projectPlanes( null );
  8838. };
  8839. this.endShadows = function () {
  8840. renderingShadows = false;
  8841. resetGlobalState();
  8842. };
  8843. this.setState = function ( material, camera, useCache ) {
  8844. const planes = material.clippingPlanes,
  8845. clipIntersection = material.clipIntersection,
  8846. clipShadows = material.clipShadows;
  8847. const materialProperties = properties.get( material );
  8848. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8849. // there's no local clipping
  8850. if ( renderingShadows ) {
  8851. // there's no global clipping
  8852. projectPlanes( null );
  8853. } else {
  8854. resetGlobalState();
  8855. }
  8856. } else {
  8857. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8858. lGlobal = nGlobal * 4;
  8859. let dstArray = materialProperties.clippingState || null;
  8860. uniform.value = dstArray; // ensure unique state
  8861. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8862. for ( let i = 0; i !== lGlobal; ++ i ) {
  8863. dstArray[ i ] = globalState[ i ];
  8864. }
  8865. materialProperties.clippingState = dstArray;
  8866. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8867. this.numPlanes += nGlobal;
  8868. }
  8869. };
  8870. function resetGlobalState() {
  8871. if ( uniform.value !== globalState ) {
  8872. uniform.value = globalState;
  8873. uniform.needsUpdate = numGlobalPlanes > 0;
  8874. }
  8875. scope.numPlanes = numGlobalPlanes;
  8876. scope.numIntersection = 0;
  8877. }
  8878. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8879. const nPlanes = planes !== null ? planes.length : 0;
  8880. let dstArray = null;
  8881. if ( nPlanes !== 0 ) {
  8882. dstArray = uniform.value;
  8883. if ( skipTransform !== true || dstArray === null ) {
  8884. const flatSize = dstOffset + nPlanes * 4,
  8885. viewMatrix = camera.matrixWorldInverse;
  8886. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8887. if ( dstArray === null || dstArray.length < flatSize ) {
  8888. dstArray = new Float32Array( flatSize );
  8889. }
  8890. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8891. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8892. plane.normal.toArray( dstArray, i4 );
  8893. dstArray[ i4 + 3 ] = plane.constant;
  8894. }
  8895. }
  8896. uniform.value = dstArray;
  8897. uniform.needsUpdate = true;
  8898. }
  8899. scope.numPlanes = nPlanes;
  8900. scope.numIntersection = 0;
  8901. return dstArray;
  8902. }
  8903. }
  8904. function WebGLCubeMaps( renderer ) {
  8905. let cubemaps = new WeakMap();
  8906. function mapTextureMapping( texture, mapping ) {
  8907. if ( mapping === EquirectangularReflectionMapping ) {
  8908. texture.mapping = CubeReflectionMapping;
  8909. } else if ( mapping === EquirectangularRefractionMapping ) {
  8910. texture.mapping = CubeRefractionMapping;
  8911. }
  8912. return texture;
  8913. }
  8914. function get( texture ) {
  8915. if ( texture && texture.isTexture ) {
  8916. const mapping = texture.mapping;
  8917. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8918. if ( cubemaps.has( texture ) ) {
  8919. const cubemap = cubemaps.get( texture ).texture;
  8920. return mapTextureMapping( cubemap, texture.mapping );
  8921. } else {
  8922. const image = texture.image;
  8923. if ( image && image.height > 0 ) {
  8924. const currentRenderTarget = renderer.getRenderTarget();
  8925. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8926. renderTarget.fromEquirectangularTexture( renderer, texture );
  8927. cubemaps.set( texture, renderTarget );
  8928. renderer.setRenderTarget( currentRenderTarget );
  8929. texture.addEventListener( 'dispose', onTextureDispose );
  8930. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8931. } else {
  8932. // image not yet ready. try the conversion next frame
  8933. return null;
  8934. }
  8935. }
  8936. }
  8937. }
  8938. return texture;
  8939. }
  8940. function onTextureDispose( event ) {
  8941. const texture = event.target;
  8942. texture.removeEventListener( 'dispose', onTextureDispose );
  8943. const cubemap = cubemaps.get( texture );
  8944. if ( cubemap !== undefined ) {
  8945. cubemaps.delete( texture );
  8946. cubemap.dispose();
  8947. }
  8948. }
  8949. function dispose() {
  8950. cubemaps = new WeakMap();
  8951. }
  8952. return {
  8953. get: get,
  8954. dispose: dispose
  8955. };
  8956. }
  8957. function WebGLExtensions( gl ) {
  8958. const extensions = {};
  8959. function getExtension( name ) {
  8960. if ( extensions[ name ] !== undefined ) {
  8961. return extensions[ name ];
  8962. }
  8963. let extension;
  8964. switch ( name ) {
  8965. case 'WEBGL_depth_texture':
  8966. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  8967. break;
  8968. case 'EXT_texture_filter_anisotropic':
  8969. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  8970. break;
  8971. case 'WEBGL_compressed_texture_s3tc':
  8972. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  8973. break;
  8974. case 'WEBGL_compressed_texture_pvrtc':
  8975. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  8976. break;
  8977. default:
  8978. extension = gl.getExtension( name );
  8979. }
  8980. extensions[ name ] = extension;
  8981. return extension;
  8982. }
  8983. return {
  8984. has: function ( name ) {
  8985. return getExtension( name ) !== null;
  8986. },
  8987. init: function ( capabilities ) {
  8988. if ( capabilities.isWebGL2 ) {
  8989. getExtension( 'EXT_color_buffer_float' );
  8990. } else {
  8991. getExtension( 'WEBGL_depth_texture' );
  8992. getExtension( 'OES_texture_float' );
  8993. getExtension( 'OES_texture_half_float' );
  8994. getExtension( 'OES_texture_half_float_linear' );
  8995. getExtension( 'OES_standard_derivatives' );
  8996. getExtension( 'OES_element_index_uint' );
  8997. getExtension( 'OES_vertex_array_object' );
  8998. getExtension( 'ANGLE_instanced_arrays' );
  8999. }
  9000. getExtension( 'OES_texture_float_linear' );
  9001. getExtension( 'EXT_color_buffer_half_float' );
  9002. },
  9003. get: function ( name ) {
  9004. const extension = getExtension( name );
  9005. if ( extension === null ) {
  9006. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9007. }
  9008. return extension;
  9009. }
  9010. };
  9011. }
  9012. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9013. const geometries = {};
  9014. const wireframeAttributes = new WeakMap();
  9015. function onGeometryDispose( event ) {
  9016. const geometry = event.target;
  9017. if ( geometry.index !== null ) {
  9018. attributes.remove( geometry.index );
  9019. }
  9020. for ( const name in geometry.attributes ) {
  9021. attributes.remove( geometry.attributes[ name ] );
  9022. }
  9023. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9024. delete geometries[ geometry.id ];
  9025. const attribute = wireframeAttributes.get( geometry );
  9026. if ( attribute ) {
  9027. attributes.remove( attribute );
  9028. wireframeAttributes.delete( geometry );
  9029. }
  9030. bindingStates.releaseStatesOfGeometry( geometry );
  9031. if ( geometry.isInstancedBufferGeometry === true ) {
  9032. delete geometry._maxInstanceCount;
  9033. }
  9034. //
  9035. info.memory.geometries --;
  9036. }
  9037. function get( object, geometry ) {
  9038. if ( geometries[ geometry.id ] === true ) return geometry;
  9039. geometry.addEventListener( 'dispose', onGeometryDispose );
  9040. geometries[ geometry.id ] = true;
  9041. info.memory.geometries ++;
  9042. return geometry;
  9043. }
  9044. function update( geometry ) {
  9045. const geometryAttributes = geometry.attributes;
  9046. // Updating index buffer in VAO now. See WebGLBindingStates.
  9047. for ( const name in geometryAttributes ) {
  9048. attributes.update( geometryAttributes[ name ], 34962 );
  9049. }
  9050. // morph targets
  9051. const morphAttributes = geometry.morphAttributes;
  9052. for ( const name in morphAttributes ) {
  9053. const array = morphAttributes[ name ];
  9054. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9055. attributes.update( array[ i ], 34962 );
  9056. }
  9057. }
  9058. }
  9059. function updateWireframeAttribute( geometry ) {
  9060. const indices = [];
  9061. const geometryIndex = geometry.index;
  9062. const geometryPosition = geometry.attributes.position;
  9063. let version = 0;
  9064. if ( geometryIndex !== null ) {
  9065. const array = geometryIndex.array;
  9066. version = geometryIndex.version;
  9067. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9068. const a = array[ i + 0 ];
  9069. const b = array[ i + 1 ];
  9070. const c = array[ i + 2 ];
  9071. indices.push( a, b, b, c, c, a );
  9072. }
  9073. } else {
  9074. const array = geometryPosition.array;
  9075. version = geometryPosition.version;
  9076. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9077. const a = i + 0;
  9078. const b = i + 1;
  9079. const c = i + 2;
  9080. indices.push( a, b, b, c, c, a );
  9081. }
  9082. }
  9083. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9084. attribute.version = version;
  9085. // Updating index buffer in VAO now. See WebGLBindingStates
  9086. //
  9087. const previousAttribute = wireframeAttributes.get( geometry );
  9088. if ( previousAttribute ) attributes.remove( previousAttribute );
  9089. //
  9090. wireframeAttributes.set( geometry, attribute );
  9091. }
  9092. function getWireframeAttribute( geometry ) {
  9093. const currentAttribute = wireframeAttributes.get( geometry );
  9094. if ( currentAttribute ) {
  9095. const geometryIndex = geometry.index;
  9096. if ( geometryIndex !== null ) {
  9097. // if the attribute is obsolete, create a new one
  9098. if ( currentAttribute.version < geometryIndex.version ) {
  9099. updateWireframeAttribute( geometry );
  9100. }
  9101. }
  9102. } else {
  9103. updateWireframeAttribute( geometry );
  9104. }
  9105. return wireframeAttributes.get( geometry );
  9106. }
  9107. return {
  9108. get: get,
  9109. update: update,
  9110. getWireframeAttribute: getWireframeAttribute
  9111. };
  9112. }
  9113. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9114. const isWebGL2 = capabilities.isWebGL2;
  9115. let mode;
  9116. function setMode( value ) {
  9117. mode = value;
  9118. }
  9119. let type, bytesPerElement;
  9120. function setIndex( value ) {
  9121. type = value.type;
  9122. bytesPerElement = value.bytesPerElement;
  9123. }
  9124. function render( start, count ) {
  9125. gl.drawElements( mode, count, type, start * bytesPerElement );
  9126. info.update( count, mode, 1 );
  9127. }
  9128. function renderInstances( start, count, primcount ) {
  9129. if ( primcount === 0 ) return;
  9130. let extension, methodName;
  9131. if ( isWebGL2 ) {
  9132. extension = gl;
  9133. methodName = 'drawElementsInstanced';
  9134. } else {
  9135. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9136. methodName = 'drawElementsInstancedANGLE';
  9137. if ( extension === null ) {
  9138. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9139. return;
  9140. }
  9141. }
  9142. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9143. info.update( count, mode, primcount );
  9144. }
  9145. //
  9146. this.setMode = setMode;
  9147. this.setIndex = setIndex;
  9148. this.render = render;
  9149. this.renderInstances = renderInstances;
  9150. }
  9151. function WebGLInfo( gl ) {
  9152. const memory = {
  9153. geometries: 0,
  9154. textures: 0
  9155. };
  9156. const render = {
  9157. frame: 0,
  9158. calls: 0,
  9159. triangles: 0,
  9160. points: 0,
  9161. lines: 0
  9162. };
  9163. function update( count, mode, instanceCount ) {
  9164. render.calls ++;
  9165. switch ( mode ) {
  9166. case 4:
  9167. render.triangles += instanceCount * ( count / 3 );
  9168. break;
  9169. case 1:
  9170. render.lines += instanceCount * ( count / 2 );
  9171. break;
  9172. case 3:
  9173. render.lines += instanceCount * ( count - 1 );
  9174. break;
  9175. case 2:
  9176. render.lines += instanceCount * count;
  9177. break;
  9178. case 0:
  9179. render.points += instanceCount * count;
  9180. break;
  9181. default:
  9182. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9183. break;
  9184. }
  9185. }
  9186. function reset() {
  9187. render.frame ++;
  9188. render.calls = 0;
  9189. render.triangles = 0;
  9190. render.points = 0;
  9191. render.lines = 0;
  9192. }
  9193. return {
  9194. memory: memory,
  9195. render: render,
  9196. programs: null,
  9197. autoReset: true,
  9198. reset: reset,
  9199. update: update
  9200. };
  9201. }
  9202. function numericalSort( a, b ) {
  9203. return a[ 0 ] - b[ 0 ];
  9204. }
  9205. function absNumericalSort( a, b ) {
  9206. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9207. }
  9208. function WebGLMorphtargets( gl ) {
  9209. const influencesList = {};
  9210. const morphInfluences = new Float32Array( 8 );
  9211. const workInfluences = [];
  9212. for ( let i = 0; i < 8; i ++ ) {
  9213. workInfluences[ i ] = [ i, 0 ];
  9214. }
  9215. function update( object, geometry, material, program ) {
  9216. const objectInfluences = object.morphTargetInfluences;
  9217. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9218. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9219. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9220. let influences = influencesList[ geometry.id ];
  9221. if ( influences === undefined ) {
  9222. // initialise list
  9223. influences = [];
  9224. for ( let i = 0; i < length; i ++ ) {
  9225. influences[ i ] = [ i, 0 ];
  9226. }
  9227. influencesList[ geometry.id ] = influences;
  9228. }
  9229. // Collect influences
  9230. for ( let i = 0; i < length; i ++ ) {
  9231. const influence = influences[ i ];
  9232. influence[ 0 ] = i;
  9233. influence[ 1 ] = objectInfluences[ i ];
  9234. }
  9235. influences.sort( absNumericalSort );
  9236. for ( let i = 0; i < 8; i ++ ) {
  9237. if ( i < length && influences[ i ][ 1 ] ) {
  9238. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  9239. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  9240. } else {
  9241. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  9242. workInfluences[ i ][ 1 ] = 0;
  9243. }
  9244. }
  9245. workInfluences.sort( numericalSort );
  9246. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9247. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9248. let morphInfluencesSum = 0;
  9249. for ( let i = 0; i < 8; i ++ ) {
  9250. const influence = workInfluences[ i ];
  9251. const index = influence[ 0 ];
  9252. const value = influence[ 1 ];
  9253. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  9254. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  9255. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9256. }
  9257. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  9258. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  9259. }
  9260. morphInfluences[ i ] = value;
  9261. morphInfluencesSum += value;
  9262. } else {
  9263. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  9264. geometry.deleteAttribute( 'morphTarget' + i );
  9265. }
  9266. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  9267. geometry.deleteAttribute( 'morphNormal' + i );
  9268. }
  9269. morphInfluences[ i ] = 0;
  9270. }
  9271. }
  9272. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9273. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9274. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9275. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9276. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  9277. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  9278. }
  9279. return {
  9280. update: update
  9281. };
  9282. }
  9283. function WebGLObjects( gl, geometries, attributes, info ) {
  9284. let updateMap = new WeakMap();
  9285. function update( object ) {
  9286. const frame = info.render.frame;
  9287. const geometry = object.geometry;
  9288. const buffergeometry = geometries.get( object, geometry );
  9289. // Update once per frame
  9290. if ( updateMap.get( buffergeometry ) !== frame ) {
  9291. geometries.update( buffergeometry );
  9292. updateMap.set( buffergeometry, frame );
  9293. }
  9294. if ( object.isInstancedMesh ) {
  9295. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  9296. object.addEventListener( 'dispose', onInstancedMeshDispose );
  9297. }
  9298. attributes.update( object.instanceMatrix, 34962 );
  9299. if ( object.instanceColor !== null ) {
  9300. attributes.update( object.instanceColor, 34962 );
  9301. }
  9302. }
  9303. return buffergeometry;
  9304. }
  9305. function dispose() {
  9306. updateMap = new WeakMap();
  9307. }
  9308. function onInstancedMeshDispose( event ) {
  9309. const instancedMesh = event.target;
  9310. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  9311. attributes.remove( instancedMesh.instanceMatrix );
  9312. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  9313. }
  9314. return {
  9315. update: update,
  9316. dispose: dispose
  9317. };
  9318. }
  9319. class DataTexture2DArray extends Texture {
  9320. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9321. super( null );
  9322. this.image = { data, width, height, depth };
  9323. this.magFilter = NearestFilter;
  9324. this.minFilter = NearestFilter;
  9325. this.wrapR = ClampToEdgeWrapping;
  9326. this.generateMipmaps = false;
  9327. this.flipY = false;
  9328. this.unpackAlignment = 1;
  9329. this.needsUpdate = true;
  9330. }
  9331. }
  9332. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9333. class DataTexture3D extends Texture {
  9334. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9335. // We're going to add .setXXX() methods for setting properties later.
  9336. // Users can still set in DataTexture3D directly.
  9337. //
  9338. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9339. // texture.anisotropy = 16;
  9340. //
  9341. // See #14839
  9342. super( null );
  9343. this.image = { data, width, height, depth };
  9344. this.magFilter = NearestFilter;
  9345. this.minFilter = NearestFilter;
  9346. this.wrapR = ClampToEdgeWrapping;
  9347. this.generateMipmaps = false;
  9348. this.flipY = false;
  9349. this.unpackAlignment = 1;
  9350. this.needsUpdate = true;
  9351. }
  9352. }
  9353. DataTexture3D.prototype.isDataTexture3D = true;
  9354. /**
  9355. * Uniforms of a program.
  9356. * Those form a tree structure with a special top-level container for the root,
  9357. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9358. *
  9359. *
  9360. * Properties of inner nodes including the top-level container:
  9361. *
  9362. * .seq - array of nested uniforms
  9363. * .map - nested uniforms by name
  9364. *
  9365. *
  9366. * Methods of all nodes except the top-level container:
  9367. *
  9368. * .setValue( gl, value, [textures] )
  9369. *
  9370. * uploads a uniform value(s)
  9371. * the 'textures' parameter is needed for sampler uniforms
  9372. *
  9373. *
  9374. * Static methods of the top-level container (textures factorizations):
  9375. *
  9376. * .upload( gl, seq, values, textures )
  9377. *
  9378. * sets uniforms in 'seq' to 'values[id].value'
  9379. *
  9380. * .seqWithValue( seq, values ) : filteredSeq
  9381. *
  9382. * filters 'seq' entries with corresponding entry in values
  9383. *
  9384. *
  9385. * Methods of the top-level container (textures factorizations):
  9386. *
  9387. * .setValue( gl, name, value, textures )
  9388. *
  9389. * sets uniform with name 'name' to 'value'
  9390. *
  9391. * .setOptional( gl, obj, prop )
  9392. *
  9393. * like .set for an optional property of the object
  9394. *
  9395. */
  9396. const emptyTexture = new Texture();
  9397. const emptyTexture2dArray = new DataTexture2DArray();
  9398. const emptyTexture3d = new DataTexture3D();
  9399. const emptyCubeTexture = new CubeTexture();
  9400. // --- Utilities ---
  9401. // Array Caches (provide typed arrays for temporary by size)
  9402. const arrayCacheF32 = [];
  9403. const arrayCacheI32 = [];
  9404. // Float32Array caches used for uploading Matrix uniforms
  9405. const mat4array = new Float32Array( 16 );
  9406. const mat3array = new Float32Array( 9 );
  9407. const mat2array = new Float32Array( 4 );
  9408. // Flattening for arrays of vectors and matrices
  9409. function flatten( array, nBlocks, blockSize ) {
  9410. const firstElem = array[ 0 ];
  9411. if ( firstElem <= 0 || firstElem > 0 ) return array;
  9412. // unoptimized: ! isNaN( firstElem )
  9413. // see http://jacksondunstan.com/articles/983
  9414. const n = nBlocks * blockSize;
  9415. let r = arrayCacheF32[ n ];
  9416. if ( r === undefined ) {
  9417. r = new Float32Array( n );
  9418. arrayCacheF32[ n ] = r;
  9419. }
  9420. if ( nBlocks !== 0 ) {
  9421. firstElem.toArray( r, 0 );
  9422. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  9423. offset += blockSize;
  9424. array[ i ].toArray( r, offset );
  9425. }
  9426. }
  9427. return r;
  9428. }
  9429. function arraysEqual( a, b ) {
  9430. if ( a.length !== b.length ) return false;
  9431. for ( let i = 0, l = a.length; i < l; i ++ ) {
  9432. if ( a[ i ] !== b[ i ] ) return false;
  9433. }
  9434. return true;
  9435. }
  9436. function copyArray( a, b ) {
  9437. for ( let i = 0, l = b.length; i < l; i ++ ) {
  9438. a[ i ] = b[ i ];
  9439. }
  9440. }
  9441. // Texture unit allocation
  9442. function allocTexUnits( textures, n ) {
  9443. let r = arrayCacheI32[ n ];
  9444. if ( r === undefined ) {
  9445. r = new Int32Array( n );
  9446. arrayCacheI32[ n ] = r;
  9447. }
  9448. for ( let i = 0; i !== n; ++ i ) {
  9449. r[ i ] = textures.allocateTextureUnit();
  9450. }
  9451. return r;
  9452. }
  9453. // --- Setters ---
  9454. // Note: Defining these methods externally, because they come in a bunch
  9455. // and this way their names minify.
  9456. // Single scalar
  9457. function setValueV1f( gl, v ) {
  9458. const cache = this.cache;
  9459. if ( cache[ 0 ] === v ) return;
  9460. gl.uniform1f( this.addr, v );
  9461. cache[ 0 ] = v;
  9462. }
  9463. // Single float vector (from flat array or THREE.VectorN)
  9464. function setValueV2f( gl, v ) {
  9465. const cache = this.cache;
  9466. if ( v.x !== undefined ) {
  9467. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  9468. gl.uniform2f( this.addr, v.x, v.y );
  9469. cache[ 0 ] = v.x;
  9470. cache[ 1 ] = v.y;
  9471. }
  9472. } else {
  9473. if ( arraysEqual( cache, v ) ) return;
  9474. gl.uniform2fv( this.addr, v );
  9475. copyArray( cache, v );
  9476. }
  9477. }
  9478. function setValueV3f( gl, v ) {
  9479. const cache = this.cache;
  9480. if ( v.x !== undefined ) {
  9481. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  9482. gl.uniform3f( this.addr, v.x, v.y, v.z );
  9483. cache[ 0 ] = v.x;
  9484. cache[ 1 ] = v.y;
  9485. cache[ 2 ] = v.z;
  9486. }
  9487. } else if ( v.r !== undefined ) {
  9488. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  9489. gl.uniform3f( this.addr, v.r, v.g, v.b );
  9490. cache[ 0 ] = v.r;
  9491. cache[ 1 ] = v.g;
  9492. cache[ 2 ] = v.b;
  9493. }
  9494. } else {
  9495. if ( arraysEqual( cache, v ) ) return;
  9496. gl.uniform3fv( this.addr, v );
  9497. copyArray( cache, v );
  9498. }
  9499. }
  9500. function setValueV4f( gl, v ) {
  9501. const cache = this.cache;
  9502. if ( v.x !== undefined ) {
  9503. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  9504. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  9505. cache[ 0 ] = v.x;
  9506. cache[ 1 ] = v.y;
  9507. cache[ 2 ] = v.z;
  9508. cache[ 3 ] = v.w;
  9509. }
  9510. } else {
  9511. if ( arraysEqual( cache, v ) ) return;
  9512. gl.uniform4fv( this.addr, v );
  9513. copyArray( cache, v );
  9514. }
  9515. }
  9516. // Single matrix (from flat array or THREE.MatrixN)
  9517. function setValueM2( gl, v ) {
  9518. const cache = this.cache;
  9519. const elements = v.elements;
  9520. if ( elements === undefined ) {
  9521. if ( arraysEqual( cache, v ) ) return;
  9522. gl.uniformMatrix2fv( this.addr, false, v );
  9523. copyArray( cache, v );
  9524. } else {
  9525. if ( arraysEqual( cache, elements ) ) return;
  9526. mat2array.set( elements );
  9527. gl.uniformMatrix2fv( this.addr, false, mat2array );
  9528. copyArray( cache, elements );
  9529. }
  9530. }
  9531. function setValueM3( gl, v ) {
  9532. const cache = this.cache;
  9533. const elements = v.elements;
  9534. if ( elements === undefined ) {
  9535. if ( arraysEqual( cache, v ) ) return;
  9536. gl.uniformMatrix3fv( this.addr, false, v );
  9537. copyArray( cache, v );
  9538. } else {
  9539. if ( arraysEqual( cache, elements ) ) return;
  9540. mat3array.set( elements );
  9541. gl.uniformMatrix3fv( this.addr, false, mat3array );
  9542. copyArray( cache, elements );
  9543. }
  9544. }
  9545. function setValueM4( gl, v ) {
  9546. const cache = this.cache;
  9547. const elements = v.elements;
  9548. if ( elements === undefined ) {
  9549. if ( arraysEqual( cache, v ) ) return;
  9550. gl.uniformMatrix4fv( this.addr, false, v );
  9551. copyArray( cache, v );
  9552. } else {
  9553. if ( arraysEqual( cache, elements ) ) return;
  9554. mat4array.set( elements );
  9555. gl.uniformMatrix4fv( this.addr, false, mat4array );
  9556. copyArray( cache, elements );
  9557. }
  9558. }
  9559. // Single integer / boolean
  9560. function setValueV1i( gl, v ) {
  9561. const cache = this.cache;
  9562. if ( cache[ 0 ] === v ) return;
  9563. gl.uniform1i( this.addr, v );
  9564. cache[ 0 ] = v;
  9565. }
  9566. // Single integer / boolean vector (from flat array)
  9567. function setValueV2i( gl, v ) {
  9568. const cache = this.cache;
  9569. if ( arraysEqual( cache, v ) ) return;
  9570. gl.uniform2iv( this.addr, v );
  9571. copyArray( cache, v );
  9572. }
  9573. function setValueV3i( gl, v ) {
  9574. const cache = this.cache;
  9575. if ( arraysEqual( cache, v ) ) return;
  9576. gl.uniform3iv( this.addr, v );
  9577. copyArray( cache, v );
  9578. }
  9579. function setValueV4i( gl, v ) {
  9580. const cache = this.cache;
  9581. if ( arraysEqual( cache, v ) ) return;
  9582. gl.uniform4iv( this.addr, v );
  9583. copyArray( cache, v );
  9584. }
  9585. // Single unsigned integer
  9586. function setValueV1ui( gl, v ) {
  9587. const cache = this.cache;
  9588. if ( cache[ 0 ] === v ) return;
  9589. gl.uniform1ui( this.addr, v );
  9590. cache[ 0 ] = v;
  9591. }
  9592. // Single unsigned integer vector (from flat array)
  9593. function setValueV2ui( gl, v ) {
  9594. const cache = this.cache;
  9595. if ( arraysEqual( cache, v ) ) return;
  9596. gl.uniform2uiv( this.addr, v );
  9597. copyArray( cache, v );
  9598. }
  9599. function setValueV3ui( gl, v ) {
  9600. const cache = this.cache;
  9601. if ( arraysEqual( cache, v ) ) return;
  9602. gl.uniform3uiv( this.addr, v );
  9603. copyArray( cache, v );
  9604. }
  9605. function setValueV4ui( gl, v ) {
  9606. const cache = this.cache;
  9607. if ( arraysEqual( cache, v ) ) return;
  9608. gl.uniform4uiv( this.addr, v );
  9609. copyArray( cache, v );
  9610. }
  9611. // Single texture (2D / Cube)
  9612. function setValueT1( gl, v, textures ) {
  9613. const cache = this.cache;
  9614. const unit = textures.allocateTextureUnit();
  9615. if ( cache[ 0 ] !== unit ) {
  9616. gl.uniform1i( this.addr, unit );
  9617. cache[ 0 ] = unit;
  9618. }
  9619. textures.safeSetTexture2D( v || emptyTexture, unit );
  9620. }
  9621. function setValueT3D1( gl, v, textures ) {
  9622. const cache = this.cache;
  9623. const unit = textures.allocateTextureUnit();
  9624. if ( cache[ 0 ] !== unit ) {
  9625. gl.uniform1i( this.addr, unit );
  9626. cache[ 0 ] = unit;
  9627. }
  9628. textures.setTexture3D( v || emptyTexture3d, unit );
  9629. }
  9630. function setValueT6( gl, v, textures ) {
  9631. const cache = this.cache;
  9632. const unit = textures.allocateTextureUnit();
  9633. if ( cache[ 0 ] !== unit ) {
  9634. gl.uniform1i( this.addr, unit );
  9635. cache[ 0 ] = unit;
  9636. }
  9637. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  9638. }
  9639. function setValueT2DArray1( gl, v, textures ) {
  9640. const cache = this.cache;
  9641. const unit = textures.allocateTextureUnit();
  9642. if ( cache[ 0 ] !== unit ) {
  9643. gl.uniform1i( this.addr, unit );
  9644. cache[ 0 ] = unit;
  9645. }
  9646. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  9647. }
  9648. // Helper to pick the right setter for the singular case
  9649. function getSingularSetter( type ) {
  9650. switch ( type ) {
  9651. case 0x1406: return setValueV1f; // FLOAT
  9652. case 0x8b50: return setValueV2f; // _VEC2
  9653. case 0x8b51: return setValueV3f; // _VEC3
  9654. case 0x8b52: return setValueV4f; // _VEC4
  9655. case 0x8b5a: return setValueM2; // _MAT2
  9656. case 0x8b5b: return setValueM3; // _MAT3
  9657. case 0x8b5c: return setValueM4; // _MAT4
  9658. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  9659. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  9660. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  9661. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  9662. case 0x1405: return setValueV1ui; // UINT
  9663. case 0x8dc6: return setValueV2ui; // _VEC2
  9664. case 0x8dc7: return setValueV3ui; // _VEC3
  9665. case 0x8dc8: return setValueV4ui; // _VEC4
  9666. case 0x8b5e: // SAMPLER_2D
  9667. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9668. case 0x8dca: // INT_SAMPLER_2D
  9669. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9670. case 0x8b62: // SAMPLER_2D_SHADOW
  9671. return setValueT1;
  9672. case 0x8b5f: // SAMPLER_3D
  9673. case 0x8dcb: // INT_SAMPLER_3D
  9674. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  9675. return setValueT3D1;
  9676. case 0x8b60: // SAMPLER_CUBE
  9677. case 0x8dcc: // INT_SAMPLER_CUBE
  9678. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9679. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9680. return setValueT6;
  9681. case 0x8dc1: // SAMPLER_2D_ARRAY
  9682. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  9683. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  9684. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  9685. return setValueT2DArray1;
  9686. }
  9687. }
  9688. // Array of scalars
  9689. function setValueV1fArray( gl, v ) {
  9690. gl.uniform1fv( this.addr, v );
  9691. }
  9692. // Array of vectors (from flat array or array of THREE.VectorN)
  9693. function setValueV2fArray( gl, v ) {
  9694. const data = flatten( v, this.size, 2 );
  9695. gl.uniform2fv( this.addr, data );
  9696. }
  9697. function setValueV3fArray( gl, v ) {
  9698. const data = flatten( v, this.size, 3 );
  9699. gl.uniform3fv( this.addr, data );
  9700. }
  9701. function setValueV4fArray( gl, v ) {
  9702. const data = flatten( v, this.size, 4 );
  9703. gl.uniform4fv( this.addr, data );
  9704. }
  9705. // Array of matrices (from flat array or array of THREE.MatrixN)
  9706. function setValueM2Array( gl, v ) {
  9707. const data = flatten( v, this.size, 4 );
  9708. gl.uniformMatrix2fv( this.addr, false, data );
  9709. }
  9710. function setValueM3Array( gl, v ) {
  9711. const data = flatten( v, this.size, 9 );
  9712. gl.uniformMatrix3fv( this.addr, false, data );
  9713. }
  9714. function setValueM4Array( gl, v ) {
  9715. const data = flatten( v, this.size, 16 );
  9716. gl.uniformMatrix4fv( this.addr, false, data );
  9717. }
  9718. // Array of integer / boolean
  9719. function setValueV1iArray( gl, v ) {
  9720. gl.uniform1iv( this.addr, v );
  9721. }
  9722. // Array of integer / boolean vectors (from flat array)
  9723. function setValueV2iArray( gl, v ) {
  9724. gl.uniform2iv( this.addr, v );
  9725. }
  9726. function setValueV3iArray( gl, v ) {
  9727. gl.uniform3iv( this.addr, v );
  9728. }
  9729. function setValueV4iArray( gl, v ) {
  9730. gl.uniform4iv( this.addr, v );
  9731. }
  9732. // Array of unsigned integer
  9733. function setValueV1uiArray( gl, v ) {
  9734. gl.uniform1uiv( this.addr, v );
  9735. }
  9736. // Array of unsigned integer vectors (from flat array)
  9737. function setValueV2uiArray( gl, v ) {
  9738. gl.uniform2uiv( this.addr, v );
  9739. }
  9740. function setValueV3uiArray( gl, v ) {
  9741. gl.uniform3uiv( this.addr, v );
  9742. }
  9743. function setValueV4uiArray( gl, v ) {
  9744. gl.uniform4uiv( this.addr, v );
  9745. }
  9746. // Array of textures (2D / Cube)
  9747. function setValueT1Array( gl, v, textures ) {
  9748. const n = v.length;
  9749. const units = allocTexUnits( textures, n );
  9750. gl.uniform1iv( this.addr, units );
  9751. for ( let i = 0; i !== n; ++ i ) {
  9752. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  9753. }
  9754. }
  9755. function setValueT6Array( gl, v, textures ) {
  9756. const n = v.length;
  9757. const units = allocTexUnits( textures, n );
  9758. gl.uniform1iv( this.addr, units );
  9759. for ( let i = 0; i !== n; ++ i ) {
  9760. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  9761. }
  9762. }
  9763. // Helper to pick the right setter for a pure (bottom-level) array
  9764. function getPureArraySetter( type ) {
  9765. switch ( type ) {
  9766. case 0x1406: return setValueV1fArray; // FLOAT
  9767. case 0x8b50: return setValueV2fArray; // _VEC2
  9768. case 0x8b51: return setValueV3fArray; // _VEC3
  9769. case 0x8b52: return setValueV4fArray; // _VEC4
  9770. case 0x8b5a: return setValueM2Array; // _MAT2
  9771. case 0x8b5b: return setValueM3Array; // _MAT3
  9772. case 0x8b5c: return setValueM4Array; // _MAT4
  9773. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  9774. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  9775. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  9776. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  9777. case 0x1405: return setValueV1uiArray; // UINT
  9778. case 0x8dc6: return setValueV2uiArray; // _VEC2
  9779. case 0x8dc7: return setValueV3uiArray; // _VEC3
  9780. case 0x8dc8: return setValueV4uiArray; // _VEC4
  9781. case 0x8b5e: // SAMPLER_2D
  9782. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9783. case 0x8dca: // INT_SAMPLER_2D
  9784. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9785. case 0x8b62: // SAMPLER_2D_SHADOW
  9786. return setValueT1Array;
  9787. case 0x8b60: // SAMPLER_CUBE
  9788. case 0x8dcc: // INT_SAMPLER_CUBE
  9789. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9790. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9791. return setValueT6Array;
  9792. }
  9793. }
  9794. // --- Uniform Classes ---
  9795. function SingleUniform( id, activeInfo, addr ) {
  9796. this.id = id;
  9797. this.addr = addr;
  9798. this.cache = [];
  9799. this.setValue = getSingularSetter( activeInfo.type );
  9800. // this.path = activeInfo.name; // DEBUG
  9801. }
  9802. function PureArrayUniform( id, activeInfo, addr ) {
  9803. this.id = id;
  9804. this.addr = addr;
  9805. this.cache = [];
  9806. this.size = activeInfo.size;
  9807. this.setValue = getPureArraySetter( activeInfo.type );
  9808. // this.path = activeInfo.name; // DEBUG
  9809. }
  9810. PureArrayUniform.prototype.updateCache = function ( data ) {
  9811. const cache = this.cache;
  9812. if ( data instanceof Float32Array && cache.length !== data.length ) {
  9813. this.cache = new Float32Array( data.length );
  9814. }
  9815. copyArray( cache, data );
  9816. };
  9817. function StructuredUniform( id ) {
  9818. this.id = id;
  9819. this.seq = [];
  9820. this.map = {};
  9821. }
  9822. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  9823. const seq = this.seq;
  9824. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9825. const u = seq[ i ];
  9826. u.setValue( gl, value[ u.id ], textures );
  9827. }
  9828. };
  9829. // --- Top-level ---
  9830. // Parser - builds up the property tree from the path strings
  9831. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  9832. // extracts
  9833. // - the identifier (member name or array index)
  9834. // - followed by an optional right bracket (found when array index)
  9835. // - followed by an optional left bracket or dot (type of subscript)
  9836. //
  9837. // Note: These portions can be read in a non-overlapping fashion and
  9838. // allow straightforward parsing of the hierarchy that WebGL encodes
  9839. // in the uniform names.
  9840. function addUniform( container, uniformObject ) {
  9841. container.seq.push( uniformObject );
  9842. container.map[ uniformObject.id ] = uniformObject;
  9843. }
  9844. function parseUniform( activeInfo, addr, container ) {
  9845. const path = activeInfo.name,
  9846. pathLength = path.length;
  9847. // reset RegExp object, because of the early exit of a previous run
  9848. RePathPart.lastIndex = 0;
  9849. while ( true ) {
  9850. const match = RePathPart.exec( path ),
  9851. matchEnd = RePathPart.lastIndex;
  9852. let id = match[ 1 ];
  9853. const idIsIndex = match[ 2 ] === ']',
  9854. subscript = match[ 3 ];
  9855. if ( idIsIndex ) id = id | 0; // convert to integer
  9856. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  9857. // bare name or "pure" bottom-level array "[0]" suffix
  9858. addUniform( container, subscript === undefined ?
  9859. new SingleUniform( id, activeInfo, addr ) :
  9860. new PureArrayUniform( id, activeInfo, addr ) );
  9861. break;
  9862. } else {
  9863. // step into inner node / create it in case it doesn't exist
  9864. const map = container.map;
  9865. let next = map[ id ];
  9866. if ( next === undefined ) {
  9867. next = new StructuredUniform( id );
  9868. addUniform( container, next );
  9869. }
  9870. container = next;
  9871. }
  9872. }
  9873. }
  9874. // Root Container
  9875. function WebGLUniforms( gl, program ) {
  9876. this.seq = [];
  9877. this.map = {};
  9878. const n = gl.getProgramParameter( program, 35718 );
  9879. for ( let i = 0; i < n; ++ i ) {
  9880. const info = gl.getActiveUniform( program, i ),
  9881. addr = gl.getUniformLocation( program, info.name );
  9882. parseUniform( info, addr, this );
  9883. }
  9884. }
  9885. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  9886. const u = this.map[ name ];
  9887. if ( u !== undefined ) u.setValue( gl, value, textures );
  9888. };
  9889. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  9890. const v = object[ name ];
  9891. if ( v !== undefined ) this.setValue( gl, name, v );
  9892. };
  9893. // Static interface
  9894. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  9895. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9896. const u = seq[ i ],
  9897. v = values[ u.id ];
  9898. if ( v.needsUpdate !== false ) {
  9899. // note: always updating when .needsUpdate is undefined
  9900. u.setValue( gl, v.value, textures );
  9901. }
  9902. }
  9903. };
  9904. WebGLUniforms.seqWithValue = function ( seq, values ) {
  9905. const r = [];
  9906. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9907. const u = seq[ i ];
  9908. if ( u.id in values ) r.push( u );
  9909. }
  9910. return r;
  9911. };
  9912. function WebGLShader( gl, type, string ) {
  9913. const shader = gl.createShader( type );
  9914. gl.shaderSource( shader, string );
  9915. gl.compileShader( shader );
  9916. return shader;
  9917. }
  9918. let programIdCount = 0;
  9919. function addLineNumbers( string ) {
  9920. const lines = string.split( '\n' );
  9921. for ( let i = 0; i < lines.length; i ++ ) {
  9922. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9923. }
  9924. return lines.join( '\n' );
  9925. }
  9926. function getEncodingComponents( encoding ) {
  9927. switch ( encoding ) {
  9928. case LinearEncoding:
  9929. return [ 'Linear', '( value )' ];
  9930. case sRGBEncoding:
  9931. return [ 'sRGB', '( value )' ];
  9932. case RGBEEncoding:
  9933. return [ 'RGBE', '( value )' ];
  9934. case RGBM7Encoding:
  9935. return [ 'RGBM', '( value, 7.0 )' ];
  9936. case RGBM16Encoding:
  9937. return [ 'RGBM', '( value, 16.0 )' ];
  9938. case RGBDEncoding:
  9939. return [ 'RGBD', '( value, 256.0 )' ];
  9940. case GammaEncoding:
  9941. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  9942. case LogLuvEncoding:
  9943. return [ 'LogLuv', '( value )' ];
  9944. default:
  9945. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  9946. return [ 'Linear', '( value )' ];
  9947. }
  9948. }
  9949. function getShaderErrors( gl, shader, type ) {
  9950. const status = gl.getShaderParameter( shader, 35713 );
  9951. const log = gl.getShaderInfoLog( shader ).trim();
  9952. if ( status && log === '' ) return '';
  9953. // --enable-privileged-webgl-extension
  9954. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9955. const source = gl.getShaderSource( shader );
  9956. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  9957. }
  9958. function getTexelDecodingFunction( functionName, encoding ) {
  9959. const components = getEncodingComponents( encoding );
  9960. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  9961. }
  9962. function getTexelEncodingFunction( functionName, encoding ) {
  9963. const components = getEncodingComponents( encoding );
  9964. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  9965. }
  9966. function getToneMappingFunction( functionName, toneMapping ) {
  9967. let toneMappingName;
  9968. switch ( toneMapping ) {
  9969. case LinearToneMapping:
  9970. toneMappingName = 'Linear';
  9971. break;
  9972. case ReinhardToneMapping:
  9973. toneMappingName = 'Reinhard';
  9974. break;
  9975. case CineonToneMapping:
  9976. toneMappingName = 'OptimizedCineon';
  9977. break;
  9978. case ACESFilmicToneMapping:
  9979. toneMappingName = 'ACESFilmic';
  9980. break;
  9981. case CustomToneMapping:
  9982. toneMappingName = 'Custom';
  9983. break;
  9984. default:
  9985. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  9986. toneMappingName = 'Linear';
  9987. }
  9988. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  9989. }
  9990. function generateExtensions( parameters ) {
  9991. const chunks = [
  9992. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9993. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  9994. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9995. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  9996. ];
  9997. return chunks.filter( filterEmptyLine ).join( '\n' );
  9998. }
  9999. function generateDefines( defines ) {
  10000. const chunks = [];
  10001. for ( const name in defines ) {
  10002. const value = defines[ name ];
  10003. if ( value === false ) continue;
  10004. chunks.push( '#define ' + name + ' ' + value );
  10005. }
  10006. return chunks.join( '\n' );
  10007. }
  10008. function fetchAttributeLocations( gl, program ) {
  10009. const attributes = {};
  10010. const n = gl.getProgramParameter( program, 35721 );
  10011. for ( let i = 0; i < n; i ++ ) {
  10012. const info = gl.getActiveAttrib( program, i );
  10013. const name = info.name;
  10014. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10015. attributes[ name ] = gl.getAttribLocation( program, name );
  10016. }
  10017. return attributes;
  10018. }
  10019. function filterEmptyLine( string ) {
  10020. return string !== '';
  10021. }
  10022. function replaceLightNums( string, parameters ) {
  10023. return string
  10024. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10025. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10026. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10027. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10028. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10029. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10030. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10031. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10032. }
  10033. function replaceClippingPlaneNums( string, parameters ) {
  10034. return string
  10035. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10036. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10037. }
  10038. // Resolve Includes
  10039. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10040. function resolveIncludes( string ) {
  10041. return string.replace( includePattern, includeReplacer );
  10042. }
  10043. function includeReplacer( match, include ) {
  10044. const string = ShaderChunk[ include ];
  10045. if ( string === undefined ) {
  10046. throw new Error( 'Can not resolve #include <' + include + '>' );
  10047. }
  10048. return resolveIncludes( string );
  10049. }
  10050. // Unroll Loops
  10051. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10052. 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;
  10053. function unrollLoops( string ) {
  10054. return string
  10055. .replace( unrollLoopPattern, loopReplacer )
  10056. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10057. }
  10058. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10059. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10060. return loopReplacer( match, start, end, snippet );
  10061. }
  10062. function loopReplacer( match, start, end, snippet ) {
  10063. let string = '';
  10064. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10065. string += snippet
  10066. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10067. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10068. }
  10069. return string;
  10070. }
  10071. //
  10072. function generatePrecision( parameters ) {
  10073. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10074. if ( parameters.precision === 'highp' ) {
  10075. precisionstring += '\n#define HIGH_PRECISION';
  10076. } else if ( parameters.precision === 'mediump' ) {
  10077. precisionstring += '\n#define MEDIUM_PRECISION';
  10078. } else if ( parameters.precision === 'lowp' ) {
  10079. precisionstring += '\n#define LOW_PRECISION';
  10080. }
  10081. return precisionstring;
  10082. }
  10083. function generateShadowMapTypeDefine( parameters ) {
  10084. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10085. if ( parameters.shadowMapType === PCFShadowMap ) {
  10086. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10087. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10088. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10089. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10090. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10091. }
  10092. return shadowMapTypeDefine;
  10093. }
  10094. function generateEnvMapTypeDefine( parameters ) {
  10095. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10096. if ( parameters.envMap ) {
  10097. switch ( parameters.envMapMode ) {
  10098. case CubeReflectionMapping:
  10099. case CubeRefractionMapping:
  10100. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10101. break;
  10102. case CubeUVReflectionMapping:
  10103. case CubeUVRefractionMapping:
  10104. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10105. break;
  10106. }
  10107. }
  10108. return envMapTypeDefine;
  10109. }
  10110. function generateEnvMapModeDefine( parameters ) {
  10111. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10112. if ( parameters.envMap ) {
  10113. switch ( parameters.envMapMode ) {
  10114. case CubeRefractionMapping:
  10115. case CubeUVRefractionMapping:
  10116. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10117. break;
  10118. }
  10119. }
  10120. return envMapModeDefine;
  10121. }
  10122. function generateEnvMapBlendingDefine( parameters ) {
  10123. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10124. if ( parameters.envMap ) {
  10125. switch ( parameters.combine ) {
  10126. case MultiplyOperation:
  10127. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10128. break;
  10129. case MixOperation:
  10130. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10131. break;
  10132. case AddOperation:
  10133. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10134. break;
  10135. }
  10136. }
  10137. return envMapBlendingDefine;
  10138. }
  10139. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10140. const gl = renderer.getContext();
  10141. const defines = parameters.defines;
  10142. let vertexShader = parameters.vertexShader;
  10143. let fragmentShader = parameters.fragmentShader;
  10144. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10145. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10146. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10147. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10148. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10149. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10150. const customDefines = generateDefines( defines );
  10151. const program = gl.createProgram();
  10152. let prefixVertex, prefixFragment;
  10153. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10154. if ( parameters.isRawShaderMaterial ) {
  10155. prefixVertex = [
  10156. customDefines
  10157. ].filter( filterEmptyLine ).join( '\n' );
  10158. if ( prefixVertex.length > 0 ) {
  10159. prefixVertex += '\n';
  10160. }
  10161. prefixFragment = [
  10162. customExtensions,
  10163. customDefines
  10164. ].filter( filterEmptyLine ).join( '\n' );
  10165. if ( prefixFragment.length > 0 ) {
  10166. prefixFragment += '\n';
  10167. }
  10168. } else {
  10169. prefixVertex = [
  10170. generatePrecision( parameters ),
  10171. '#define SHADER_NAME ' + parameters.shaderName,
  10172. customDefines,
  10173. parameters.instancing ? '#define USE_INSTANCING' : '',
  10174. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10175. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10176. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10177. '#define MAX_BONES ' + parameters.maxBones,
  10178. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10179. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10180. parameters.map ? '#define USE_MAP' : '',
  10181. parameters.envMap ? '#define USE_ENVMAP' : '',
  10182. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10183. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10184. parameters.aoMap ? '#define USE_AOMAP' : '',
  10185. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10186. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10187. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10188. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10189. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10190. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10191. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10192. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10193. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10194. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10195. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10196. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10197. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10198. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10199. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10200. parameters.vertexColors ? '#define USE_COLOR' : '',
  10201. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  10202. parameters.vertexUvs ? '#define USE_UV' : '',
  10203. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10204. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10205. parameters.skinning ? '#define USE_SKINNING' : '',
  10206. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10207. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10208. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10209. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10210. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10211. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10212. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10213. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10214. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10215. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10216. 'uniform mat4 modelMatrix;',
  10217. 'uniform mat4 modelViewMatrix;',
  10218. 'uniform mat4 projectionMatrix;',
  10219. 'uniform mat4 viewMatrix;',
  10220. 'uniform mat3 normalMatrix;',
  10221. 'uniform vec3 cameraPosition;',
  10222. 'uniform bool isOrthographic;',
  10223. '#ifdef USE_INSTANCING',
  10224. ' attribute mat4 instanceMatrix;',
  10225. '#endif',
  10226. '#ifdef USE_INSTANCING_COLOR',
  10227. ' attribute vec3 instanceColor;',
  10228. '#endif',
  10229. 'attribute vec3 position;',
  10230. 'attribute vec3 normal;',
  10231. 'attribute vec2 uv;',
  10232. '#ifdef USE_TANGENT',
  10233. ' attribute vec4 tangent;',
  10234. '#endif',
  10235. '#if defined( USE_COLOR_ALPHA )',
  10236. ' attribute vec4 color;',
  10237. '#elif defined( USE_COLOR )',
  10238. ' attribute vec3 color;',
  10239. '#endif',
  10240. '#ifdef USE_MORPHTARGETS',
  10241. ' attribute vec3 morphTarget0;',
  10242. ' attribute vec3 morphTarget1;',
  10243. ' attribute vec3 morphTarget2;',
  10244. ' attribute vec3 morphTarget3;',
  10245. ' #ifdef USE_MORPHNORMALS',
  10246. ' attribute vec3 morphNormal0;',
  10247. ' attribute vec3 morphNormal1;',
  10248. ' attribute vec3 morphNormal2;',
  10249. ' attribute vec3 morphNormal3;',
  10250. ' #else',
  10251. ' attribute vec3 morphTarget4;',
  10252. ' attribute vec3 morphTarget5;',
  10253. ' attribute vec3 morphTarget6;',
  10254. ' attribute vec3 morphTarget7;',
  10255. ' #endif',
  10256. '#endif',
  10257. '#ifdef USE_SKINNING',
  10258. ' attribute vec4 skinIndex;',
  10259. ' attribute vec4 skinWeight;',
  10260. '#endif',
  10261. '\n'
  10262. ].filter( filterEmptyLine ).join( '\n' );
  10263. prefixFragment = [
  10264. customExtensions,
  10265. generatePrecision( parameters ),
  10266. '#define SHADER_NAME ' + parameters.shaderName,
  10267. customDefines,
  10268. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  10269. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10270. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10271. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10272. parameters.map ? '#define USE_MAP' : '',
  10273. parameters.matcap ? '#define USE_MATCAP' : '',
  10274. parameters.envMap ? '#define USE_ENVMAP' : '',
  10275. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10276. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10277. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10278. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10279. parameters.aoMap ? '#define USE_AOMAP' : '',
  10280. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10281. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10282. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10283. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10284. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10285. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10286. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10287. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10288. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10289. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10290. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10291. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10292. parameters.sheen ? '#define USE_SHEEN' : '',
  10293. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10294. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10295. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  10296. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  10297. parameters.vertexUvs ? '#define USE_UV' : '',
  10298. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10299. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10300. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10301. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10302. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10303. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10304. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10305. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  10306. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  10307. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10308. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10309. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  10310. 'uniform mat4 viewMatrix;',
  10311. 'uniform vec3 cameraPosition;',
  10312. 'uniform bool isOrthographic;',
  10313. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  10314. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10315. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  10316. parameters.dithering ? '#define DITHERING' : '',
  10317. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  10318. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10319. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  10320. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10321. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10322. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  10323. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  10324. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  10325. '\n'
  10326. ].filter( filterEmptyLine ).join( '\n' );
  10327. }
  10328. vertexShader = resolveIncludes( vertexShader );
  10329. vertexShader = replaceLightNums( vertexShader, parameters );
  10330. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  10331. fragmentShader = resolveIncludes( fragmentShader );
  10332. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10333. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  10334. vertexShader = unrollLoops( vertexShader );
  10335. fragmentShader = unrollLoops( fragmentShader );
  10336. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  10337. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10338. versionString = '#version 300 es\n';
  10339. prefixVertex = [
  10340. '#define attribute in',
  10341. '#define varying out',
  10342. '#define texture2D texture'
  10343. ].join( '\n' ) + '\n' + prefixVertex;
  10344. prefixFragment = [
  10345. '#define varying in',
  10346. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  10347. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  10348. '#define gl_FragDepthEXT gl_FragDepth',
  10349. '#define texture2D texture',
  10350. '#define textureCube texture',
  10351. '#define texture2DProj textureProj',
  10352. '#define texture2DLodEXT textureLod',
  10353. '#define texture2DProjLodEXT textureProjLod',
  10354. '#define textureCubeLodEXT textureLod',
  10355. '#define texture2DGradEXT textureGrad',
  10356. '#define texture2DProjGradEXT textureProjGrad',
  10357. '#define textureCubeGradEXT textureGrad'
  10358. ].join( '\n' ) + '\n' + prefixFragment;
  10359. }
  10360. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10361. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  10362. // console.log( '*VERTEX*', vertexGlsl );
  10363. // console.log( '*FRAGMENT*', fragmentGlsl );
  10364. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  10365. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  10366. gl.attachShader( program, glVertexShader );
  10367. gl.attachShader( program, glFragmentShader );
  10368. // Force a particular attribute to index 0.
  10369. if ( parameters.index0AttributeName !== undefined ) {
  10370. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  10371. } else if ( parameters.morphTargets === true ) {
  10372. // programs with morphTargets displace position out of attribute 0
  10373. gl.bindAttribLocation( program, 0, 'position' );
  10374. }
  10375. gl.linkProgram( program );
  10376. // check for link errors
  10377. if ( renderer.debug.checkShaderErrors ) {
  10378. const programLog = gl.getProgramInfoLog( program ).trim();
  10379. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  10380. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  10381. let runnable = true;
  10382. let haveDiagnostics = true;
  10383. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  10384. runnable = false;
  10385. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  10386. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  10387. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  10388. } else if ( programLog !== '' ) {
  10389. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10390. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10391. haveDiagnostics = false;
  10392. }
  10393. if ( haveDiagnostics ) {
  10394. this.diagnostics = {
  10395. runnable: runnable,
  10396. programLog: programLog,
  10397. vertexShader: {
  10398. log: vertexLog,
  10399. prefix: prefixVertex
  10400. },
  10401. fragmentShader: {
  10402. log: fragmentLog,
  10403. prefix: prefixFragment
  10404. }
  10405. };
  10406. }
  10407. }
  10408. // Clean up
  10409. // Crashes in iOS9 and iOS10. #18402
  10410. // gl.detachShader( program, glVertexShader );
  10411. // gl.detachShader( program, glFragmentShader );
  10412. gl.deleteShader( glVertexShader );
  10413. gl.deleteShader( glFragmentShader );
  10414. // set up caching for uniform locations
  10415. let cachedUniforms;
  10416. this.getUniforms = function () {
  10417. if ( cachedUniforms === undefined ) {
  10418. cachedUniforms = new WebGLUniforms( gl, program );
  10419. }
  10420. return cachedUniforms;
  10421. };
  10422. // set up caching for attribute locations
  10423. let cachedAttributes;
  10424. this.getAttributes = function () {
  10425. if ( cachedAttributes === undefined ) {
  10426. cachedAttributes = fetchAttributeLocations( gl, program );
  10427. }
  10428. return cachedAttributes;
  10429. };
  10430. // free resource
  10431. this.destroy = function () {
  10432. bindingStates.releaseStatesOfProgram( this );
  10433. gl.deleteProgram( program );
  10434. this.program = undefined;
  10435. };
  10436. //
  10437. this.name = parameters.shaderName;
  10438. this.id = programIdCount ++;
  10439. this.cacheKey = cacheKey;
  10440. this.usedTimes = 1;
  10441. this.program = program;
  10442. this.vertexShader = glVertexShader;
  10443. this.fragmentShader = glFragmentShader;
  10444. return this;
  10445. }
  10446. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  10447. const programs = [];
  10448. const isWebGL2 = capabilities.isWebGL2;
  10449. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10450. const floatVertexTextures = capabilities.floatVertexTextures;
  10451. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10452. const vertexTextures = capabilities.vertexTextures;
  10453. let precision = capabilities.precision;
  10454. const shaderIDs = {
  10455. MeshDepthMaterial: 'depth',
  10456. MeshDistanceMaterial: 'distanceRGBA',
  10457. MeshNormalMaterial: 'normal',
  10458. MeshBasicMaterial: 'basic',
  10459. MeshLambertMaterial: 'lambert',
  10460. MeshPhongMaterial: 'phong',
  10461. MeshToonMaterial: 'toon',
  10462. MeshStandardMaterial: 'physical',
  10463. MeshPhysicalMaterial: 'physical',
  10464. MeshMatcapMaterial: 'matcap',
  10465. LineBasicMaterial: 'basic',
  10466. LineDashedMaterial: 'dashed',
  10467. PointsMaterial: 'points',
  10468. ShadowMaterial: 'shadow',
  10469. SpriteMaterial: 'sprite'
  10470. };
  10471. const parameterNames = [
  10472. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  10473. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  10474. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  10475. 'roughnessMap', 'metalnessMap', 'gradientMap',
  10476. 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  10477. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  10478. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha',
  10479. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  10480. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  10481. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  10482. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  10483. 'sheen', 'transmissionMap'
  10484. ];
  10485. function getMaxBones( object ) {
  10486. const skeleton = object.skeleton;
  10487. const bones = skeleton.bones;
  10488. if ( floatVertexTextures ) {
  10489. return 1024;
  10490. } else {
  10491. // default for when object is not specified
  10492. // ( for example when prebuilding shader to be used with multiple objects )
  10493. //
  10494. // - leave some extra space for other uniforms
  10495. // - limit here is ANGLE's 254 max uniform vectors
  10496. // (up to 54 should be safe)
  10497. const nVertexUniforms = maxVertexUniforms;
  10498. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10499. const maxBones = Math.min( nVertexMatrices, bones.length );
  10500. if ( maxBones < bones.length ) {
  10501. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10502. return 0;
  10503. }
  10504. return maxBones;
  10505. }
  10506. }
  10507. function getTextureEncodingFromMap( map ) {
  10508. let encoding;
  10509. if ( map && map.isTexture ) {
  10510. encoding = map.encoding;
  10511. } else if ( map && map.isWebGLRenderTarget ) {
  10512. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  10513. encoding = map.texture.encoding;
  10514. } else {
  10515. encoding = LinearEncoding;
  10516. }
  10517. return encoding;
  10518. }
  10519. function getParameters( material, lights, shadows, scene, object ) {
  10520. const fog = scene.fog;
  10521. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10522. const envMap = cubemaps.get( material.envMap || environment );
  10523. const shaderID = shaderIDs[ material.type ];
  10524. // heuristics to create shader parameters according to lights in the scene
  10525. // (not to blow over maxLights budget)
  10526. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  10527. if ( material.precision !== null ) {
  10528. precision = capabilities.getMaxPrecision( material.precision );
  10529. if ( precision !== material.precision ) {
  10530. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10531. }
  10532. }
  10533. let vertexShader, fragmentShader;
  10534. if ( shaderID ) {
  10535. const shader = ShaderLib[ shaderID ];
  10536. vertexShader = shader.vertexShader;
  10537. fragmentShader = shader.fragmentShader;
  10538. } else {
  10539. vertexShader = material.vertexShader;
  10540. fragmentShader = material.fragmentShader;
  10541. }
  10542. const currentRenderTarget = renderer.getRenderTarget();
  10543. const parameters = {
  10544. isWebGL2: isWebGL2,
  10545. shaderID: shaderID,
  10546. shaderName: material.type,
  10547. vertexShader: vertexShader,
  10548. fragmentShader: fragmentShader,
  10549. defines: material.defines,
  10550. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10551. glslVersion: material.glslVersion,
  10552. precision: precision,
  10553. instancing: object.isInstancedMesh === true,
  10554. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10555. supportsVertexTextures: vertexTextures,
  10556. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  10557. map: !! material.map,
  10558. mapEncoding: getTextureEncodingFromMap( material.map ),
  10559. matcap: !! material.matcap,
  10560. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  10561. envMap: !! envMap,
  10562. envMapMode: envMap && envMap.mapping,
  10563. envMapEncoding: getTextureEncodingFromMap( envMap ),
  10564. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  10565. lightMap: !! material.lightMap,
  10566. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  10567. aoMap: !! material.aoMap,
  10568. emissiveMap: !! material.emissiveMap,
  10569. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  10570. bumpMap: !! material.bumpMap,
  10571. normalMap: !! material.normalMap,
  10572. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10573. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10574. clearcoatMap: !! material.clearcoatMap,
  10575. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  10576. clearcoatNormalMap: !! material.clearcoatNormalMap,
  10577. displacementMap: !! material.displacementMap,
  10578. roughnessMap: !! material.roughnessMap,
  10579. metalnessMap: !! material.metalnessMap,
  10580. specularMap: !! material.specularMap,
  10581. alphaMap: !! material.alphaMap,
  10582. gradientMap: !! material.gradientMap,
  10583. sheen: !! material.sheen,
  10584. transmissionMap: !! material.transmissionMap,
  10585. combine: material.combine,
  10586. vertexTangents: ( material.normalMap && material.vertexTangents ),
  10587. vertexColors: material.vertexColors,
  10588. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10589. 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,
  10590. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  10591. fog: !! fog,
  10592. useFog: material.fog,
  10593. fogExp2: ( fog && fog.isFogExp2 ),
  10594. flatShading: !! material.flatShading,
  10595. sizeAttenuation: material.sizeAttenuation,
  10596. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10597. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10598. maxBones: maxBones,
  10599. useVertexTexture: floatVertexTextures,
  10600. morphTargets: material.morphTargets,
  10601. morphNormals: material.morphNormals,
  10602. numDirLights: lights.directional.length,
  10603. numPointLights: lights.point.length,
  10604. numSpotLights: lights.spot.length,
  10605. numRectAreaLights: lights.rectArea.length,
  10606. numHemiLights: lights.hemi.length,
  10607. numDirLightShadows: lights.directionalShadowMap.length,
  10608. numPointLightShadows: lights.pointShadowMap.length,
  10609. numSpotLightShadows: lights.spotShadowMap.length,
  10610. numClippingPlanes: clipping.numPlanes,
  10611. numClipIntersection: clipping.numIntersection,
  10612. dithering: material.dithering,
  10613. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10614. shadowMapType: renderer.shadowMap.type,
  10615. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10616. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10617. premultipliedAlpha: material.premultipliedAlpha,
  10618. alphaTest: material.alphaTest,
  10619. doubleSided: material.side === DoubleSide,
  10620. flipSided: material.side === BackSide,
  10621. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  10622. index0AttributeName: material.index0AttributeName,
  10623. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10624. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10625. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10626. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10627. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  10628. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  10629. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  10630. customProgramCacheKey: material.customProgramCacheKey()
  10631. };
  10632. return parameters;
  10633. }
  10634. function getProgramCacheKey( parameters ) {
  10635. const array = [];
  10636. if ( parameters.shaderID ) {
  10637. array.push( parameters.shaderID );
  10638. } else {
  10639. array.push( parameters.fragmentShader );
  10640. array.push( parameters.vertexShader );
  10641. }
  10642. if ( parameters.defines !== undefined ) {
  10643. for ( const name in parameters.defines ) {
  10644. array.push( name );
  10645. array.push( parameters.defines[ name ] );
  10646. }
  10647. }
  10648. if ( parameters.isRawShaderMaterial === false ) {
  10649. for ( let i = 0; i < parameterNames.length; i ++ ) {
  10650. array.push( parameters[ parameterNames[ i ] ] );
  10651. }
  10652. array.push( renderer.outputEncoding );
  10653. array.push( renderer.gammaFactor );
  10654. }
  10655. array.push( parameters.customProgramCacheKey );
  10656. return array.join();
  10657. }
  10658. function getUniforms( material ) {
  10659. const shaderID = shaderIDs[ material.type ];
  10660. let uniforms;
  10661. if ( shaderID ) {
  10662. const shader = ShaderLib[ shaderID ];
  10663. uniforms = UniformsUtils.clone( shader.uniforms );
  10664. } else {
  10665. uniforms = material.uniforms;
  10666. }
  10667. return uniforms;
  10668. }
  10669. function acquireProgram( parameters, cacheKey ) {
  10670. let program;
  10671. // Check if code has been already compiled
  10672. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  10673. const preexistingProgram = programs[ p ];
  10674. if ( preexistingProgram.cacheKey === cacheKey ) {
  10675. program = preexistingProgram;
  10676. ++ program.usedTimes;
  10677. break;
  10678. }
  10679. }
  10680. if ( program === undefined ) {
  10681. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  10682. programs.push( program );
  10683. }
  10684. return program;
  10685. }
  10686. function releaseProgram( program ) {
  10687. if ( -- program.usedTimes === 0 ) {
  10688. // Remove from unordered set
  10689. const i = programs.indexOf( program );
  10690. programs[ i ] = programs[ programs.length - 1 ];
  10691. programs.pop();
  10692. // Free WebGL resources
  10693. program.destroy();
  10694. }
  10695. }
  10696. return {
  10697. getParameters: getParameters,
  10698. getProgramCacheKey: getProgramCacheKey,
  10699. getUniforms: getUniforms,
  10700. acquireProgram: acquireProgram,
  10701. releaseProgram: releaseProgram,
  10702. // Exposed for resource monitoring & error feedback via renderer.info:
  10703. programs: programs
  10704. };
  10705. }
  10706. function WebGLProperties() {
  10707. let properties = new WeakMap();
  10708. function get( object ) {
  10709. let map = properties.get( object );
  10710. if ( map === undefined ) {
  10711. map = {};
  10712. properties.set( object, map );
  10713. }
  10714. return map;
  10715. }
  10716. function remove( object ) {
  10717. properties.delete( object );
  10718. }
  10719. function update( object, key, value ) {
  10720. properties.get( object )[ key ] = value;
  10721. }
  10722. function dispose() {
  10723. properties = new WeakMap();
  10724. }
  10725. return {
  10726. get: get,
  10727. remove: remove,
  10728. update: update,
  10729. dispose: dispose
  10730. };
  10731. }
  10732. function painterSortStable( a, b ) {
  10733. if ( a.groupOrder !== b.groupOrder ) {
  10734. return a.groupOrder - b.groupOrder;
  10735. } else if ( a.renderOrder !== b.renderOrder ) {
  10736. return a.renderOrder - b.renderOrder;
  10737. } else if ( a.program !== b.program ) {
  10738. return a.program.id - b.program.id;
  10739. } else if ( a.material.id !== b.material.id ) {
  10740. return a.material.id - b.material.id;
  10741. } else if ( a.z !== b.z ) {
  10742. return a.z - b.z;
  10743. } else {
  10744. return a.id - b.id;
  10745. }
  10746. }
  10747. function reversePainterSortStable( a, b ) {
  10748. if ( a.groupOrder !== b.groupOrder ) {
  10749. return a.groupOrder - b.groupOrder;
  10750. } else if ( a.renderOrder !== b.renderOrder ) {
  10751. return a.renderOrder - b.renderOrder;
  10752. } else if ( a.z !== b.z ) {
  10753. return b.z - a.z;
  10754. } else {
  10755. return a.id - b.id;
  10756. }
  10757. }
  10758. function WebGLRenderList( properties ) {
  10759. const renderItems = [];
  10760. let renderItemsIndex = 0;
  10761. const opaque = [];
  10762. const transparent = [];
  10763. const defaultProgram = { id: - 1 };
  10764. function init() {
  10765. renderItemsIndex = 0;
  10766. opaque.length = 0;
  10767. transparent.length = 0;
  10768. }
  10769. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  10770. let renderItem = renderItems[ renderItemsIndex ];
  10771. const materialProperties = properties.get( material );
  10772. if ( renderItem === undefined ) {
  10773. renderItem = {
  10774. id: object.id,
  10775. object: object,
  10776. geometry: geometry,
  10777. material: material,
  10778. program: materialProperties.program || defaultProgram,
  10779. groupOrder: groupOrder,
  10780. renderOrder: object.renderOrder,
  10781. z: z,
  10782. group: group
  10783. };
  10784. renderItems[ renderItemsIndex ] = renderItem;
  10785. } else {
  10786. renderItem.id = object.id;
  10787. renderItem.object = object;
  10788. renderItem.geometry = geometry;
  10789. renderItem.material = material;
  10790. renderItem.program = materialProperties.program || defaultProgram;
  10791. renderItem.groupOrder = groupOrder;
  10792. renderItem.renderOrder = object.renderOrder;
  10793. renderItem.z = z;
  10794. renderItem.group = group;
  10795. }
  10796. renderItemsIndex ++;
  10797. return renderItem;
  10798. }
  10799. function push( object, geometry, material, groupOrder, z, group ) {
  10800. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10801. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  10802. }
  10803. function unshift( object, geometry, material, groupOrder, z, group ) {
  10804. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10805. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  10806. }
  10807. function sort( customOpaqueSort, customTransparentSort ) {
  10808. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  10809. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  10810. }
  10811. function finish() {
  10812. // Clear references from inactive renderItems in the list
  10813. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  10814. const renderItem = renderItems[ i ];
  10815. if ( renderItem.id === null ) break;
  10816. renderItem.id = null;
  10817. renderItem.object = null;
  10818. renderItem.geometry = null;
  10819. renderItem.material = null;
  10820. renderItem.program = null;
  10821. renderItem.group = null;
  10822. }
  10823. }
  10824. return {
  10825. opaque: opaque,
  10826. transparent: transparent,
  10827. init: init,
  10828. push: push,
  10829. unshift: unshift,
  10830. finish: finish,
  10831. sort: sort
  10832. };
  10833. }
  10834. function WebGLRenderLists( properties ) {
  10835. let lists = new WeakMap();
  10836. function get( scene, renderCallDepth ) {
  10837. let list;
  10838. if ( lists.has( scene ) === false ) {
  10839. list = new WebGLRenderList( properties );
  10840. lists.set( scene, [ list ] );
  10841. } else {
  10842. if ( renderCallDepth >= lists.get( scene ).length ) {
  10843. list = new WebGLRenderList( properties );
  10844. lists.get( scene ).push( list );
  10845. } else {
  10846. list = lists.get( scene )[ renderCallDepth ];
  10847. }
  10848. }
  10849. return list;
  10850. }
  10851. function dispose() {
  10852. lists = new WeakMap();
  10853. }
  10854. return {
  10855. get: get,
  10856. dispose: dispose
  10857. };
  10858. }
  10859. function UniformsCache() {
  10860. const lights = {};
  10861. return {
  10862. get: function ( light ) {
  10863. if ( lights[ light.id ] !== undefined ) {
  10864. return lights[ light.id ];
  10865. }
  10866. let uniforms;
  10867. switch ( light.type ) {
  10868. case 'DirectionalLight':
  10869. uniforms = {
  10870. direction: new Vector3(),
  10871. color: new Color()
  10872. };
  10873. break;
  10874. case 'SpotLight':
  10875. uniforms = {
  10876. position: new Vector3(),
  10877. direction: new Vector3(),
  10878. color: new Color(),
  10879. distance: 0,
  10880. coneCos: 0,
  10881. penumbraCos: 0,
  10882. decay: 0
  10883. };
  10884. break;
  10885. case 'PointLight':
  10886. uniforms = {
  10887. position: new Vector3(),
  10888. color: new Color(),
  10889. distance: 0,
  10890. decay: 0
  10891. };
  10892. break;
  10893. case 'HemisphereLight':
  10894. uniforms = {
  10895. direction: new Vector3(),
  10896. skyColor: new Color(),
  10897. groundColor: new Color()
  10898. };
  10899. break;
  10900. case 'RectAreaLight':
  10901. uniforms = {
  10902. color: new Color(),
  10903. position: new Vector3(),
  10904. halfWidth: new Vector3(),
  10905. halfHeight: new Vector3()
  10906. };
  10907. break;
  10908. }
  10909. lights[ light.id ] = uniforms;
  10910. return uniforms;
  10911. }
  10912. };
  10913. }
  10914. function ShadowUniformsCache() {
  10915. const lights = {};
  10916. return {
  10917. get: function ( light ) {
  10918. if ( lights[ light.id ] !== undefined ) {
  10919. return lights[ light.id ];
  10920. }
  10921. let uniforms;
  10922. switch ( light.type ) {
  10923. case 'DirectionalLight':
  10924. uniforms = {
  10925. shadowBias: 0,
  10926. shadowNormalBias: 0,
  10927. shadowRadius: 1,
  10928. shadowMapSize: new Vector2()
  10929. };
  10930. break;
  10931. case 'SpotLight':
  10932. uniforms = {
  10933. shadowBias: 0,
  10934. shadowNormalBias: 0,
  10935. shadowRadius: 1,
  10936. shadowMapSize: new Vector2()
  10937. };
  10938. break;
  10939. case 'PointLight':
  10940. uniforms = {
  10941. shadowBias: 0,
  10942. shadowNormalBias: 0,
  10943. shadowRadius: 1,
  10944. shadowMapSize: new Vector2(),
  10945. shadowCameraNear: 1,
  10946. shadowCameraFar: 1000
  10947. };
  10948. break;
  10949. // TODO (abelnation): set RectAreaLight shadow uniforms
  10950. }
  10951. lights[ light.id ] = uniforms;
  10952. return uniforms;
  10953. }
  10954. };
  10955. }
  10956. let nextVersion = 0;
  10957. function shadowCastingLightsFirst( lightA, lightB ) {
  10958. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  10959. }
  10960. function WebGLLights( extensions, capabilities ) {
  10961. const cache = new UniformsCache();
  10962. const shadowCache = ShadowUniformsCache();
  10963. const state = {
  10964. version: 0,
  10965. hash: {
  10966. directionalLength: - 1,
  10967. pointLength: - 1,
  10968. spotLength: - 1,
  10969. rectAreaLength: - 1,
  10970. hemiLength: - 1,
  10971. numDirectionalShadows: - 1,
  10972. numPointShadows: - 1,
  10973. numSpotShadows: - 1
  10974. },
  10975. ambient: [ 0, 0, 0 ],
  10976. probe: [],
  10977. directional: [],
  10978. directionalShadow: [],
  10979. directionalShadowMap: [],
  10980. directionalShadowMatrix: [],
  10981. spot: [],
  10982. spotShadow: [],
  10983. spotShadowMap: [],
  10984. spotShadowMatrix: [],
  10985. rectArea: [],
  10986. rectAreaLTC1: null,
  10987. rectAreaLTC2: null,
  10988. point: [],
  10989. pointShadow: [],
  10990. pointShadowMap: [],
  10991. pointShadowMatrix: [],
  10992. hemi: []
  10993. };
  10994. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  10995. const vector3 = new Vector3();
  10996. const matrix4 = new Matrix4();
  10997. const matrix42 = new Matrix4();
  10998. function setup( lights ) {
  10999. let r = 0, g = 0, b = 0;
  11000. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11001. let directionalLength = 0;
  11002. let pointLength = 0;
  11003. let spotLength = 0;
  11004. let rectAreaLength = 0;
  11005. let hemiLength = 0;
  11006. let numDirectionalShadows = 0;
  11007. let numPointShadows = 0;
  11008. let numSpotShadows = 0;
  11009. lights.sort( shadowCastingLightsFirst );
  11010. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11011. const light = lights[ i ];
  11012. const color = light.color;
  11013. const intensity = light.intensity;
  11014. const distance = light.distance;
  11015. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11016. if ( light.isAmbientLight ) {
  11017. r += color.r * intensity;
  11018. g += color.g * intensity;
  11019. b += color.b * intensity;
  11020. } else if ( light.isLightProbe ) {
  11021. for ( let j = 0; j < 9; j ++ ) {
  11022. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11023. }
  11024. } else if ( light.isDirectionalLight ) {
  11025. const uniforms = cache.get( light );
  11026. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11027. if ( light.castShadow ) {
  11028. const shadow = light.shadow;
  11029. const shadowUniforms = shadowCache.get( light );
  11030. shadowUniforms.shadowBias = shadow.bias;
  11031. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11032. shadowUniforms.shadowRadius = shadow.radius;
  11033. shadowUniforms.shadowMapSize = shadow.mapSize;
  11034. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11035. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11036. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11037. numDirectionalShadows ++;
  11038. }
  11039. state.directional[ directionalLength ] = uniforms;
  11040. directionalLength ++;
  11041. } else if ( light.isSpotLight ) {
  11042. const uniforms = cache.get( light );
  11043. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11044. uniforms.color.copy( color ).multiplyScalar( intensity );
  11045. uniforms.distance = distance;
  11046. uniforms.coneCos = Math.cos( light.angle );
  11047. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11048. uniforms.decay = light.decay;
  11049. if ( light.castShadow ) {
  11050. const shadow = light.shadow;
  11051. const shadowUniforms = shadowCache.get( light );
  11052. shadowUniforms.shadowBias = shadow.bias;
  11053. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11054. shadowUniforms.shadowRadius = shadow.radius;
  11055. shadowUniforms.shadowMapSize = shadow.mapSize;
  11056. state.spotShadow[ spotLength ] = shadowUniforms;
  11057. state.spotShadowMap[ spotLength ] = shadowMap;
  11058. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11059. numSpotShadows ++;
  11060. }
  11061. state.spot[ spotLength ] = uniforms;
  11062. spotLength ++;
  11063. } else if ( light.isRectAreaLight ) {
  11064. const uniforms = cache.get( light );
  11065. // (a) intensity is the total visible light emitted
  11066. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11067. // (b) intensity is the brightness of the light
  11068. uniforms.color.copy( color ).multiplyScalar( intensity );
  11069. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11070. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11071. state.rectArea[ rectAreaLength ] = uniforms;
  11072. rectAreaLength ++;
  11073. } else if ( light.isPointLight ) {
  11074. const uniforms = cache.get( light );
  11075. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11076. uniforms.distance = light.distance;
  11077. uniforms.decay = light.decay;
  11078. if ( light.castShadow ) {
  11079. const shadow = light.shadow;
  11080. const shadowUniforms = shadowCache.get( light );
  11081. shadowUniforms.shadowBias = shadow.bias;
  11082. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11083. shadowUniforms.shadowRadius = shadow.radius;
  11084. shadowUniforms.shadowMapSize = shadow.mapSize;
  11085. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11086. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11087. state.pointShadow[ pointLength ] = shadowUniforms;
  11088. state.pointShadowMap[ pointLength ] = shadowMap;
  11089. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11090. numPointShadows ++;
  11091. }
  11092. state.point[ pointLength ] = uniforms;
  11093. pointLength ++;
  11094. } else if ( light.isHemisphereLight ) {
  11095. const uniforms = cache.get( light );
  11096. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  11097. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  11098. state.hemi[ hemiLength ] = uniforms;
  11099. hemiLength ++;
  11100. }
  11101. }
  11102. if ( rectAreaLength > 0 ) {
  11103. if ( capabilities.isWebGL2 ) {
  11104. // WebGL 2
  11105. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11106. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11107. } else {
  11108. // WebGL 1
  11109. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  11110. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11111. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11112. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  11113. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11114. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11115. } else {
  11116. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  11117. }
  11118. }
  11119. }
  11120. state.ambient[ 0 ] = r;
  11121. state.ambient[ 1 ] = g;
  11122. state.ambient[ 2 ] = b;
  11123. const hash = state.hash;
  11124. if ( hash.directionalLength !== directionalLength ||
  11125. hash.pointLength !== pointLength ||
  11126. hash.spotLength !== spotLength ||
  11127. hash.rectAreaLength !== rectAreaLength ||
  11128. hash.hemiLength !== hemiLength ||
  11129. hash.numDirectionalShadows !== numDirectionalShadows ||
  11130. hash.numPointShadows !== numPointShadows ||
  11131. hash.numSpotShadows !== numSpotShadows ) {
  11132. state.directional.length = directionalLength;
  11133. state.spot.length = spotLength;
  11134. state.rectArea.length = rectAreaLength;
  11135. state.point.length = pointLength;
  11136. state.hemi.length = hemiLength;
  11137. state.directionalShadow.length = numDirectionalShadows;
  11138. state.directionalShadowMap.length = numDirectionalShadows;
  11139. state.pointShadow.length = numPointShadows;
  11140. state.pointShadowMap.length = numPointShadows;
  11141. state.spotShadow.length = numSpotShadows;
  11142. state.spotShadowMap.length = numSpotShadows;
  11143. state.directionalShadowMatrix.length = numDirectionalShadows;
  11144. state.pointShadowMatrix.length = numPointShadows;
  11145. state.spotShadowMatrix.length = numSpotShadows;
  11146. hash.directionalLength = directionalLength;
  11147. hash.pointLength = pointLength;
  11148. hash.spotLength = spotLength;
  11149. hash.rectAreaLength = rectAreaLength;
  11150. hash.hemiLength = hemiLength;
  11151. hash.numDirectionalShadows = numDirectionalShadows;
  11152. hash.numPointShadows = numPointShadows;
  11153. hash.numSpotShadows = numSpotShadows;
  11154. state.version = nextVersion ++;
  11155. }
  11156. }
  11157. function setupView( lights, camera ) {
  11158. let directionalLength = 0;
  11159. let pointLength = 0;
  11160. let spotLength = 0;
  11161. let rectAreaLength = 0;
  11162. let hemiLength = 0;
  11163. const viewMatrix = camera.matrixWorldInverse;
  11164. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11165. const light = lights[ i ];
  11166. if ( light.isDirectionalLight ) {
  11167. const uniforms = state.directional[ directionalLength ];
  11168. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11169. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11170. uniforms.direction.sub( vector3 );
  11171. uniforms.direction.transformDirection( viewMatrix );
  11172. directionalLength ++;
  11173. } else if ( light.isSpotLight ) {
  11174. const uniforms = state.spot[ spotLength ];
  11175. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11176. uniforms.position.applyMatrix4( viewMatrix );
  11177. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11178. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11179. uniforms.direction.sub( vector3 );
  11180. uniforms.direction.transformDirection( viewMatrix );
  11181. spotLength ++;
  11182. } else if ( light.isRectAreaLight ) {
  11183. const uniforms = state.rectArea[ rectAreaLength ];
  11184. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11185. uniforms.position.applyMatrix4( viewMatrix );
  11186. // extract local rotation of light to derive width/height half vectors
  11187. matrix42.identity();
  11188. matrix4.copy( light.matrixWorld );
  11189. matrix4.premultiply( viewMatrix );
  11190. matrix42.extractRotation( matrix4 );
  11191. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11192. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11193. uniforms.halfWidth.applyMatrix4( matrix42 );
  11194. uniforms.halfHeight.applyMatrix4( matrix42 );
  11195. rectAreaLength ++;
  11196. } else if ( light.isPointLight ) {
  11197. const uniforms = state.point[ pointLength ];
  11198. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11199. uniforms.position.applyMatrix4( viewMatrix );
  11200. pointLength ++;
  11201. } else if ( light.isHemisphereLight ) {
  11202. const uniforms = state.hemi[ hemiLength ];
  11203. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11204. uniforms.direction.transformDirection( viewMatrix );
  11205. uniforms.direction.normalize();
  11206. hemiLength ++;
  11207. }
  11208. }
  11209. }
  11210. return {
  11211. setup: setup,
  11212. setupView: setupView,
  11213. state: state
  11214. };
  11215. }
  11216. function WebGLRenderState( extensions, capabilities ) {
  11217. const lights = new WebGLLights( extensions, capabilities );
  11218. const lightsArray = [];
  11219. const shadowsArray = [];
  11220. function init() {
  11221. lightsArray.length = 0;
  11222. shadowsArray.length = 0;
  11223. }
  11224. function pushLight( light ) {
  11225. lightsArray.push( light );
  11226. }
  11227. function pushShadow( shadowLight ) {
  11228. shadowsArray.push( shadowLight );
  11229. }
  11230. function setupLights() {
  11231. lights.setup( lightsArray );
  11232. }
  11233. function setupLightsView( camera ) {
  11234. lights.setupView( lightsArray, camera );
  11235. }
  11236. const state = {
  11237. lightsArray: lightsArray,
  11238. shadowsArray: shadowsArray,
  11239. lights: lights
  11240. };
  11241. return {
  11242. init: init,
  11243. state: state,
  11244. setupLights: setupLights,
  11245. setupLightsView: setupLightsView,
  11246. pushLight: pushLight,
  11247. pushShadow: pushShadow
  11248. };
  11249. }
  11250. function WebGLRenderStates( extensions, capabilities ) {
  11251. let renderStates = new WeakMap();
  11252. function get( scene, renderCallDepth = 0 ) {
  11253. let renderState;
  11254. if ( renderStates.has( scene ) === false ) {
  11255. renderState = new WebGLRenderState( extensions, capabilities );
  11256. renderStates.set( scene, [ renderState ] );
  11257. } else {
  11258. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  11259. renderState = new WebGLRenderState( extensions, capabilities );
  11260. renderStates.get( scene ).push( renderState );
  11261. } else {
  11262. renderState = renderStates.get( scene )[ renderCallDepth ];
  11263. }
  11264. }
  11265. return renderState;
  11266. }
  11267. function dispose() {
  11268. renderStates = new WeakMap();
  11269. }
  11270. return {
  11271. get: get,
  11272. dispose: dispose
  11273. };
  11274. }
  11275. /**
  11276. * parameters = {
  11277. *
  11278. * opacity: <float>,
  11279. *
  11280. * map: new THREE.Texture( <Image> ),
  11281. *
  11282. * alphaMap: new THREE.Texture( <Image> ),
  11283. *
  11284. * displacementMap: new THREE.Texture( <Image> ),
  11285. * displacementScale: <float>,
  11286. * displacementBias: <float>,
  11287. *
  11288. * wireframe: <boolean>,
  11289. * wireframeLinewidth: <float>
  11290. * }
  11291. */
  11292. class MeshDepthMaterial extends Material {
  11293. constructor( parameters ) {
  11294. super();
  11295. this.type = 'MeshDepthMaterial';
  11296. this.depthPacking = BasicDepthPacking;
  11297. this.morphTargets = false;
  11298. this.map = null;
  11299. this.alphaMap = null;
  11300. this.displacementMap = null;
  11301. this.displacementScale = 1;
  11302. this.displacementBias = 0;
  11303. this.wireframe = false;
  11304. this.wireframeLinewidth = 1;
  11305. this.fog = false;
  11306. this.setValues( parameters );
  11307. }
  11308. copy( source ) {
  11309. super.copy( source );
  11310. this.depthPacking = source.depthPacking;
  11311. this.morphTargets = source.morphTargets;
  11312. this.map = source.map;
  11313. this.alphaMap = source.alphaMap;
  11314. this.displacementMap = source.displacementMap;
  11315. this.displacementScale = source.displacementScale;
  11316. this.displacementBias = source.displacementBias;
  11317. this.wireframe = source.wireframe;
  11318. this.wireframeLinewidth = source.wireframeLinewidth;
  11319. return this;
  11320. }
  11321. }
  11322. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11323. /**
  11324. * parameters = {
  11325. *
  11326. * referencePosition: <float>,
  11327. * nearDistance: <float>,
  11328. * farDistance: <float>,
  11329. *
  11330. * morphTargets: <bool>,
  11331. *
  11332. * map: new THREE.Texture( <Image> ),
  11333. *
  11334. * alphaMap: new THREE.Texture( <Image> ),
  11335. *
  11336. * displacementMap: new THREE.Texture( <Image> ),
  11337. * displacementScale: <float>,
  11338. * displacementBias: <float>
  11339. *
  11340. * }
  11341. */
  11342. class MeshDistanceMaterial extends Material {
  11343. constructor( parameters ) {
  11344. super();
  11345. this.type = 'MeshDistanceMaterial';
  11346. this.referencePosition = new Vector3();
  11347. this.nearDistance = 1;
  11348. this.farDistance = 1000;
  11349. this.morphTargets = false;
  11350. this.map = null;
  11351. this.alphaMap = null;
  11352. this.displacementMap = null;
  11353. this.displacementScale = 1;
  11354. this.displacementBias = 0;
  11355. this.fog = false;
  11356. this.setValues( parameters );
  11357. }
  11358. copy( source ) {
  11359. super.copy( source );
  11360. this.referencePosition.copy( source.referencePosition );
  11361. this.nearDistance = source.nearDistance;
  11362. this.farDistance = source.farDistance;
  11363. this.morphTargets = source.morphTargets;
  11364. this.map = source.map;
  11365. this.alphaMap = source.alphaMap;
  11366. this.displacementMap = source.displacementMap;
  11367. this.displacementScale = source.displacementScale;
  11368. this.displacementBias = source.displacementBias;
  11369. return this;
  11370. }
  11371. }
  11372. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11373. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 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, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11374. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11375. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  11376. let _frustum = new Frustum();
  11377. const _shadowMapSize = new Vector2(),
  11378. _viewportSize = new Vector2(),
  11379. _viewport = new Vector4(),
  11380. _depthMaterials = [],
  11381. _distanceMaterials = [],
  11382. _materialCache = {},
  11383. _maxTextureSize = _capabilities.maxTextureSize;
  11384. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  11385. const shadowMaterialVertical = new ShaderMaterial( {
  11386. defines: {
  11387. SAMPLE_RATE: 2.0 / 8.0,
  11388. HALF_SAMPLE_RATE: 1.0 / 8.0
  11389. },
  11390. uniforms: {
  11391. shadow_pass: { value: null },
  11392. resolution: { value: new Vector2() },
  11393. radius: { value: 4.0 }
  11394. },
  11395. vertexShader: vsm_vert,
  11396. fragmentShader: vsm_frag
  11397. } );
  11398. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11399. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11400. const fullScreenTri = new BufferGeometry();
  11401. fullScreenTri.setAttribute(
  11402. 'position',
  11403. new BufferAttribute(
  11404. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  11405. 3
  11406. )
  11407. );
  11408. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  11409. const scope = this;
  11410. this.enabled = false;
  11411. this.autoUpdate = true;
  11412. this.needsUpdate = false;
  11413. this.type = PCFShadowMap;
  11414. this.render = function ( lights, scene, camera ) {
  11415. if ( scope.enabled === false ) return;
  11416. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  11417. if ( lights.length === 0 ) return;
  11418. const currentRenderTarget = _renderer.getRenderTarget();
  11419. const activeCubeFace = _renderer.getActiveCubeFace();
  11420. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11421. const _state = _renderer.state;
  11422. // Set GL state for depth map.
  11423. _state.setBlending( NoBlending );
  11424. _state.buffers.color.setClear( 1, 1, 1, 1 );
  11425. _state.buffers.depth.setTest( true );
  11426. _state.setScissorTest( false );
  11427. // render depth map
  11428. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  11429. const light = lights[ i ];
  11430. const shadow = light.shadow;
  11431. if ( shadow === undefined ) {
  11432. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  11433. continue;
  11434. }
  11435. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  11436. _shadowMapSize.copy( shadow.mapSize );
  11437. const shadowFrameExtents = shadow.getFrameExtents();
  11438. _shadowMapSize.multiply( shadowFrameExtents );
  11439. _viewportSize.copy( shadow.mapSize );
  11440. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  11441. if ( _shadowMapSize.x > _maxTextureSize ) {
  11442. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  11443. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11444. shadow.mapSize.x = _viewportSize.x;
  11445. }
  11446. if ( _shadowMapSize.y > _maxTextureSize ) {
  11447. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  11448. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11449. shadow.mapSize.y = _viewportSize.y;
  11450. }
  11451. }
  11452. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11453. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  11454. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11455. shadow.map.texture.name = light.name + '.shadowMap';
  11456. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11457. shadow.camera.updateProjectionMatrix();
  11458. }
  11459. if ( shadow.map === null ) {
  11460. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  11461. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11462. shadow.map.texture.name = light.name + '.shadowMap';
  11463. shadow.camera.updateProjectionMatrix();
  11464. }
  11465. _renderer.setRenderTarget( shadow.map );
  11466. _renderer.clear();
  11467. const viewportCount = shadow.getViewportCount();
  11468. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  11469. const viewport = shadow.getViewport( vp );
  11470. _viewport.set(
  11471. _viewportSize.x * viewport.x,
  11472. _viewportSize.y * viewport.y,
  11473. _viewportSize.x * viewport.z,
  11474. _viewportSize.y * viewport.w
  11475. );
  11476. _state.viewport( _viewport );
  11477. shadow.updateMatrices( light, vp );
  11478. _frustum = shadow.getFrustum();
  11479. renderObject( scene, camera, shadow.camera, light, this.type );
  11480. }
  11481. // do blur pass for VSM
  11482. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11483. VSMPass( shadow, camera );
  11484. }
  11485. shadow.needsUpdate = false;
  11486. }
  11487. scope.needsUpdate = false;
  11488. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  11489. };
  11490. function VSMPass( shadow, camera ) {
  11491. const geometry = _objects.update( fullScreenMesh );
  11492. // vertical pass
  11493. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11494. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11495. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11496. _renderer.setRenderTarget( shadow.mapPass );
  11497. _renderer.clear();
  11498. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  11499. // horizontal pass
  11500. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11501. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11502. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11503. _renderer.setRenderTarget( shadow.map );
  11504. _renderer.clear();
  11505. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  11506. }
  11507. function getDepthMaterialVariant( useMorphing ) {
  11508. const index = useMorphing << 0;
  11509. let material = _depthMaterials[ index ];
  11510. if ( material === undefined ) {
  11511. material = new MeshDepthMaterial( {
  11512. depthPacking: RGBADepthPacking,
  11513. morphTargets: useMorphing
  11514. } );
  11515. _depthMaterials[ index ] = material;
  11516. }
  11517. return material;
  11518. }
  11519. function getDistanceMaterialVariant( useMorphing ) {
  11520. const index = useMorphing << 0;
  11521. let material = _distanceMaterials[ index ];
  11522. if ( material === undefined ) {
  11523. material = new MeshDistanceMaterial( {
  11524. morphTargets: useMorphing
  11525. } );
  11526. _distanceMaterials[ index ] = material;
  11527. }
  11528. return material;
  11529. }
  11530. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  11531. let result = null;
  11532. let getMaterialVariant = getDepthMaterialVariant;
  11533. let customMaterial = object.customDepthMaterial;
  11534. if ( light.isPointLight === true ) {
  11535. getMaterialVariant = getDistanceMaterialVariant;
  11536. customMaterial = object.customDistanceMaterial;
  11537. }
  11538. if ( customMaterial === undefined ) {
  11539. let useMorphing = false;
  11540. if ( material.morphTargets === true ) {
  11541. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11542. }
  11543. result = getMaterialVariant( useMorphing );
  11544. } else {
  11545. result = customMaterial;
  11546. }
  11547. if ( _renderer.localClippingEnabled &&
  11548. material.clipShadows === true &&
  11549. material.clippingPlanes.length !== 0 ) {
  11550. // in this case we need a unique material instance reflecting the
  11551. // appropriate state
  11552. const keyA = result.uuid, keyB = material.uuid;
  11553. let materialsForVariant = _materialCache[ keyA ];
  11554. if ( materialsForVariant === undefined ) {
  11555. materialsForVariant = {};
  11556. _materialCache[ keyA ] = materialsForVariant;
  11557. }
  11558. let cachedMaterial = materialsForVariant[ keyB ];
  11559. if ( cachedMaterial === undefined ) {
  11560. cachedMaterial = result.clone();
  11561. materialsForVariant[ keyB ] = cachedMaterial;
  11562. }
  11563. result = cachedMaterial;
  11564. }
  11565. result.visible = material.visible;
  11566. result.wireframe = material.wireframe;
  11567. if ( type === VSMShadowMap ) {
  11568. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  11569. } else {
  11570. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  11571. }
  11572. result.clipShadows = material.clipShadows;
  11573. result.clippingPlanes = material.clippingPlanes;
  11574. result.clipIntersection = material.clipIntersection;
  11575. result.wireframeLinewidth = material.wireframeLinewidth;
  11576. result.linewidth = material.linewidth;
  11577. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  11578. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  11579. result.nearDistance = shadowCameraNear;
  11580. result.farDistance = shadowCameraFar;
  11581. }
  11582. return result;
  11583. }
  11584. function renderObject( object, camera, shadowCamera, light, type ) {
  11585. if ( object.visible === false ) return;
  11586. const visible = object.layers.test( camera.layers );
  11587. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  11588. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  11589. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  11590. const geometry = _objects.update( object );
  11591. const material = object.material;
  11592. if ( Array.isArray( material ) ) {
  11593. const groups = geometry.groups;
  11594. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  11595. const group = groups[ k ];
  11596. const groupMaterial = material[ group.materialIndex ];
  11597. if ( groupMaterial && groupMaterial.visible ) {
  11598. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  11599. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  11600. }
  11601. }
  11602. } else if ( material.visible ) {
  11603. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  11604. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  11605. }
  11606. }
  11607. }
  11608. const children = object.children;
  11609. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11610. renderObject( children[ i ], camera, shadowCamera, light, type );
  11611. }
  11612. }
  11613. }
  11614. function WebGLState( gl, extensions, capabilities ) {
  11615. const isWebGL2 = capabilities.isWebGL2;
  11616. function ColorBuffer() {
  11617. let locked = false;
  11618. const color = new Vector4();
  11619. let currentColorMask = null;
  11620. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  11621. return {
  11622. setMask: function ( colorMask ) {
  11623. if ( currentColorMask !== colorMask && ! locked ) {
  11624. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11625. currentColorMask = colorMask;
  11626. }
  11627. },
  11628. setLocked: function ( lock ) {
  11629. locked = lock;
  11630. },
  11631. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11632. if ( premultipliedAlpha === true ) {
  11633. r *= a; g *= a; b *= a;
  11634. }
  11635. color.set( r, g, b, a );
  11636. if ( currentColorClear.equals( color ) === false ) {
  11637. gl.clearColor( r, g, b, a );
  11638. currentColorClear.copy( color );
  11639. }
  11640. },
  11641. reset: function () {
  11642. locked = false;
  11643. currentColorMask = null;
  11644. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11645. }
  11646. };
  11647. }
  11648. function DepthBuffer() {
  11649. let locked = false;
  11650. let currentDepthMask = null;
  11651. let currentDepthFunc = null;
  11652. let currentDepthClear = null;
  11653. return {
  11654. setTest: function ( depthTest ) {
  11655. if ( depthTest ) {
  11656. enable( 2929 );
  11657. } else {
  11658. disable( 2929 );
  11659. }
  11660. },
  11661. setMask: function ( depthMask ) {
  11662. if ( currentDepthMask !== depthMask && ! locked ) {
  11663. gl.depthMask( depthMask );
  11664. currentDepthMask = depthMask;
  11665. }
  11666. },
  11667. setFunc: function ( depthFunc ) {
  11668. if ( currentDepthFunc !== depthFunc ) {
  11669. if ( depthFunc ) {
  11670. switch ( depthFunc ) {
  11671. case NeverDepth:
  11672. gl.depthFunc( 512 );
  11673. break;
  11674. case AlwaysDepth:
  11675. gl.depthFunc( 519 );
  11676. break;
  11677. case LessDepth:
  11678. gl.depthFunc( 513 );
  11679. break;
  11680. case LessEqualDepth:
  11681. gl.depthFunc( 515 );
  11682. break;
  11683. case EqualDepth:
  11684. gl.depthFunc( 514 );
  11685. break;
  11686. case GreaterEqualDepth:
  11687. gl.depthFunc( 518 );
  11688. break;
  11689. case GreaterDepth:
  11690. gl.depthFunc( 516 );
  11691. break;
  11692. case NotEqualDepth:
  11693. gl.depthFunc( 517 );
  11694. break;
  11695. default:
  11696. gl.depthFunc( 515 );
  11697. }
  11698. } else {
  11699. gl.depthFunc( 515 );
  11700. }
  11701. currentDepthFunc = depthFunc;
  11702. }
  11703. },
  11704. setLocked: function ( lock ) {
  11705. locked = lock;
  11706. },
  11707. setClear: function ( depth ) {
  11708. if ( currentDepthClear !== depth ) {
  11709. gl.clearDepth( depth );
  11710. currentDepthClear = depth;
  11711. }
  11712. },
  11713. reset: function () {
  11714. locked = false;
  11715. currentDepthMask = null;
  11716. currentDepthFunc = null;
  11717. currentDepthClear = null;
  11718. }
  11719. };
  11720. }
  11721. function StencilBuffer() {
  11722. let locked = false;
  11723. let currentStencilMask = null;
  11724. let currentStencilFunc = null;
  11725. let currentStencilRef = null;
  11726. let currentStencilFuncMask = null;
  11727. let currentStencilFail = null;
  11728. let currentStencilZFail = null;
  11729. let currentStencilZPass = null;
  11730. let currentStencilClear = null;
  11731. return {
  11732. setTest: function ( stencilTest ) {
  11733. if ( ! locked ) {
  11734. if ( stencilTest ) {
  11735. enable( 2960 );
  11736. } else {
  11737. disable( 2960 );
  11738. }
  11739. }
  11740. },
  11741. setMask: function ( stencilMask ) {
  11742. if ( currentStencilMask !== stencilMask && ! locked ) {
  11743. gl.stencilMask( stencilMask );
  11744. currentStencilMask = stencilMask;
  11745. }
  11746. },
  11747. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11748. if ( currentStencilFunc !== stencilFunc ||
  11749. currentStencilRef !== stencilRef ||
  11750. currentStencilFuncMask !== stencilMask ) {
  11751. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11752. currentStencilFunc = stencilFunc;
  11753. currentStencilRef = stencilRef;
  11754. currentStencilFuncMask = stencilMask;
  11755. }
  11756. },
  11757. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11758. if ( currentStencilFail !== stencilFail ||
  11759. currentStencilZFail !== stencilZFail ||
  11760. currentStencilZPass !== stencilZPass ) {
  11761. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11762. currentStencilFail = stencilFail;
  11763. currentStencilZFail = stencilZFail;
  11764. currentStencilZPass = stencilZPass;
  11765. }
  11766. },
  11767. setLocked: function ( lock ) {
  11768. locked = lock;
  11769. },
  11770. setClear: function ( stencil ) {
  11771. if ( currentStencilClear !== stencil ) {
  11772. gl.clearStencil( stencil );
  11773. currentStencilClear = stencil;
  11774. }
  11775. },
  11776. reset: function () {
  11777. locked = false;
  11778. currentStencilMask = null;
  11779. currentStencilFunc = null;
  11780. currentStencilRef = null;
  11781. currentStencilFuncMask = null;
  11782. currentStencilFail = null;
  11783. currentStencilZFail = null;
  11784. currentStencilZPass = null;
  11785. currentStencilClear = null;
  11786. }
  11787. };
  11788. }
  11789. //
  11790. const colorBuffer = new ColorBuffer();
  11791. const depthBuffer = new DepthBuffer();
  11792. const stencilBuffer = new StencilBuffer();
  11793. let enabledCapabilities = {};
  11794. let xrFramebuffer = null;
  11795. let currentBoundFramebuffers = {};
  11796. let currentProgram = null;
  11797. let currentBlendingEnabled = false;
  11798. let currentBlending = null;
  11799. let currentBlendEquation = null;
  11800. let currentBlendSrc = null;
  11801. let currentBlendDst = null;
  11802. let currentBlendEquationAlpha = null;
  11803. let currentBlendSrcAlpha = null;
  11804. let currentBlendDstAlpha = null;
  11805. let currentPremultipledAlpha = false;
  11806. let currentFlipSided = null;
  11807. let currentCullFace = null;
  11808. let currentLineWidth = null;
  11809. let currentPolygonOffsetFactor = null;
  11810. let currentPolygonOffsetUnits = null;
  11811. const maxTextures = gl.getParameter( 35661 );
  11812. let lineWidthAvailable = false;
  11813. let version = 0;
  11814. const glVersion = gl.getParameter( 7938 );
  11815. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  11816. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  11817. lineWidthAvailable = ( version >= 1.0 );
  11818. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  11819. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  11820. lineWidthAvailable = ( version >= 2.0 );
  11821. }
  11822. let currentTextureSlot = null;
  11823. let currentBoundTextures = {};
  11824. const currentScissor = new Vector4( 0, 0, gl.canvas.width, gl.canvas.height );
  11825. const currentViewport = new Vector4( 0, 0, gl.canvas.width, gl.canvas.height );
  11826. function createTexture( type, target, count ) {
  11827. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11828. const texture = gl.createTexture();
  11829. gl.bindTexture( type, texture );
  11830. gl.texParameteri( type, 10241, 9728 );
  11831. gl.texParameteri( type, 10240, 9728 );
  11832. for ( let i = 0; i < count; i ++ ) {
  11833. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  11834. }
  11835. return texture;
  11836. }
  11837. const emptyTextures = {};
  11838. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  11839. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  11840. // init
  11841. colorBuffer.setClear( 0, 0, 0, 1 );
  11842. depthBuffer.setClear( 1 );
  11843. stencilBuffer.setClear( 0 );
  11844. enable( 2929 );
  11845. depthBuffer.setFunc( LessEqualDepth );
  11846. setFlipSided( false );
  11847. setCullFace( CullFaceBack );
  11848. enable( 2884 );
  11849. setBlending( NoBlending );
  11850. //
  11851. function enable( id ) {
  11852. if ( enabledCapabilities[ id ] !== true ) {
  11853. gl.enable( id );
  11854. enabledCapabilities[ id ] = true;
  11855. }
  11856. }
  11857. function disable( id ) {
  11858. if ( enabledCapabilities[ id ] !== false ) {
  11859. gl.disable( id );
  11860. enabledCapabilities[ id ] = false;
  11861. }
  11862. }
  11863. function bindXRFramebuffer( framebuffer ) {
  11864. if ( framebuffer !== xrFramebuffer ) {
  11865. gl.bindFramebuffer( 36160, framebuffer );
  11866. xrFramebuffer = framebuffer;
  11867. }
  11868. }
  11869. function bindFramebuffer( target, framebuffer ) {
  11870. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  11871. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  11872. gl.bindFramebuffer( target, framebuffer );
  11873. currentBoundFramebuffers[ target ] = framebuffer;
  11874. if ( isWebGL2 ) {
  11875. // 36009 is equivalent to 36160
  11876. if ( target === 36009 ) {
  11877. currentBoundFramebuffers[ 36160 ] = framebuffer;
  11878. }
  11879. if ( target === 36160 ) {
  11880. currentBoundFramebuffers[ 36009 ] = framebuffer;
  11881. }
  11882. }
  11883. return true;
  11884. }
  11885. return false;
  11886. }
  11887. function useProgram( program ) {
  11888. if ( currentProgram !== program ) {
  11889. gl.useProgram( program );
  11890. currentProgram = program;
  11891. return true;
  11892. }
  11893. return false;
  11894. }
  11895. const equationToGL = {
  11896. [ AddEquation ]: 32774,
  11897. [ SubtractEquation ]: 32778,
  11898. [ ReverseSubtractEquation ]: 32779
  11899. };
  11900. if ( isWebGL2 ) {
  11901. equationToGL[ MinEquation ] = 32775;
  11902. equationToGL[ MaxEquation ] = 32776;
  11903. } else {
  11904. const extension = extensions.get( 'EXT_blend_minmax' );
  11905. if ( extension !== null ) {
  11906. equationToGL[ MinEquation ] = extension.MIN_EXT;
  11907. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  11908. }
  11909. }
  11910. const factorToGL = {
  11911. [ ZeroFactor ]: 0,
  11912. [ OneFactor ]: 1,
  11913. [ SrcColorFactor ]: 768,
  11914. [ SrcAlphaFactor ]: 770,
  11915. [ SrcAlphaSaturateFactor ]: 776,
  11916. [ DstColorFactor ]: 774,
  11917. [ DstAlphaFactor ]: 772,
  11918. [ OneMinusSrcColorFactor ]: 769,
  11919. [ OneMinusSrcAlphaFactor ]: 771,
  11920. [ OneMinusDstColorFactor ]: 775,
  11921. [ OneMinusDstAlphaFactor ]: 773
  11922. };
  11923. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11924. if ( blending === NoBlending ) {
  11925. if ( currentBlendingEnabled === true ) {
  11926. disable( 3042 );
  11927. currentBlendingEnabled = false;
  11928. }
  11929. return;
  11930. }
  11931. if ( currentBlendingEnabled === false ) {
  11932. enable( 3042 );
  11933. currentBlendingEnabled = true;
  11934. }
  11935. if ( blending !== CustomBlending ) {
  11936. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11937. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  11938. gl.blendEquation( 32774 );
  11939. currentBlendEquation = AddEquation;
  11940. currentBlendEquationAlpha = AddEquation;
  11941. }
  11942. if ( premultipliedAlpha ) {
  11943. switch ( blending ) {
  11944. case NormalBlending:
  11945. gl.blendFuncSeparate( 1, 771, 1, 771 );
  11946. break;
  11947. case AdditiveBlending:
  11948. gl.blendFunc( 1, 1 );
  11949. break;
  11950. case SubtractiveBlending:
  11951. gl.blendFuncSeparate( 0, 0, 769, 771 );
  11952. break;
  11953. case MultiplyBlending:
  11954. gl.blendFuncSeparate( 0, 768, 0, 770 );
  11955. break;
  11956. default:
  11957. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11958. break;
  11959. }
  11960. } else {
  11961. switch ( blending ) {
  11962. case NormalBlending:
  11963. gl.blendFuncSeparate( 770, 771, 1, 771 );
  11964. break;
  11965. case AdditiveBlending:
  11966. gl.blendFunc( 770, 1 );
  11967. break;
  11968. case SubtractiveBlending:
  11969. gl.blendFunc( 0, 769 );
  11970. break;
  11971. case MultiplyBlending:
  11972. gl.blendFunc( 0, 768 );
  11973. break;
  11974. default:
  11975. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11976. break;
  11977. }
  11978. }
  11979. currentBlendSrc = null;
  11980. currentBlendDst = null;
  11981. currentBlendSrcAlpha = null;
  11982. currentBlendDstAlpha = null;
  11983. currentBlending = blending;
  11984. currentPremultipledAlpha = premultipliedAlpha;
  11985. }
  11986. return;
  11987. }
  11988. // custom blending
  11989. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11990. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11991. blendDstAlpha = blendDstAlpha || blendDst;
  11992. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11993. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  11994. currentBlendEquation = blendEquation;
  11995. currentBlendEquationAlpha = blendEquationAlpha;
  11996. }
  11997. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11998. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  11999. currentBlendSrc = blendSrc;
  12000. currentBlendDst = blendDst;
  12001. currentBlendSrcAlpha = blendSrcAlpha;
  12002. currentBlendDstAlpha = blendDstAlpha;
  12003. }
  12004. currentBlending = blending;
  12005. currentPremultipledAlpha = null;
  12006. }
  12007. function setMaterial( material, frontFaceCW ) {
  12008. material.side === DoubleSide
  12009. ? disable( 2884 )
  12010. : enable( 2884 );
  12011. let flipSided = ( material.side === BackSide );
  12012. if ( frontFaceCW ) flipSided = ! flipSided;
  12013. setFlipSided( flipSided );
  12014. ( material.blending === NormalBlending && material.transparent === false )
  12015. ? setBlending( NoBlending )
  12016. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12017. depthBuffer.setFunc( material.depthFunc );
  12018. depthBuffer.setTest( material.depthTest );
  12019. depthBuffer.setMask( material.depthWrite );
  12020. colorBuffer.setMask( material.colorWrite );
  12021. const stencilWrite = material.stencilWrite;
  12022. stencilBuffer.setTest( stencilWrite );
  12023. if ( stencilWrite ) {
  12024. stencilBuffer.setMask( material.stencilWriteMask );
  12025. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12026. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12027. }
  12028. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12029. material.alphaToCoverage === true
  12030. ? enable( 32926 )
  12031. : disable( 32926 );
  12032. }
  12033. //
  12034. function setFlipSided( flipSided ) {
  12035. if ( currentFlipSided !== flipSided ) {
  12036. if ( flipSided ) {
  12037. gl.frontFace( 2304 );
  12038. } else {
  12039. gl.frontFace( 2305 );
  12040. }
  12041. currentFlipSided = flipSided;
  12042. }
  12043. }
  12044. function setCullFace( cullFace ) {
  12045. if ( cullFace !== CullFaceNone ) {
  12046. enable( 2884 );
  12047. if ( cullFace !== currentCullFace ) {
  12048. if ( cullFace === CullFaceBack ) {
  12049. gl.cullFace( 1029 );
  12050. } else if ( cullFace === CullFaceFront ) {
  12051. gl.cullFace( 1028 );
  12052. } else {
  12053. gl.cullFace( 1032 );
  12054. }
  12055. }
  12056. } else {
  12057. disable( 2884 );
  12058. }
  12059. currentCullFace = cullFace;
  12060. }
  12061. function setLineWidth( width ) {
  12062. if ( width !== currentLineWidth ) {
  12063. if ( lineWidthAvailable ) gl.lineWidth( width );
  12064. currentLineWidth = width;
  12065. }
  12066. }
  12067. function setPolygonOffset( polygonOffset, factor, units ) {
  12068. if ( polygonOffset ) {
  12069. enable( 32823 );
  12070. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12071. gl.polygonOffset( factor, units );
  12072. currentPolygonOffsetFactor = factor;
  12073. currentPolygonOffsetUnits = units;
  12074. }
  12075. } else {
  12076. disable( 32823 );
  12077. }
  12078. }
  12079. function setScissorTest( scissorTest ) {
  12080. if ( scissorTest ) {
  12081. enable( 3089 );
  12082. } else {
  12083. disable( 3089 );
  12084. }
  12085. }
  12086. // texture
  12087. function activeTexture( webglSlot ) {
  12088. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12089. if ( currentTextureSlot !== webglSlot ) {
  12090. gl.activeTexture( webglSlot );
  12091. currentTextureSlot = webglSlot;
  12092. }
  12093. }
  12094. function bindTexture( webglType, webglTexture ) {
  12095. if ( currentTextureSlot === null ) {
  12096. activeTexture();
  12097. }
  12098. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12099. if ( boundTexture === undefined ) {
  12100. boundTexture = { type: undefined, texture: undefined };
  12101. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12102. }
  12103. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12104. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12105. boundTexture.type = webglType;
  12106. boundTexture.texture = webglTexture;
  12107. }
  12108. }
  12109. function unbindTexture() {
  12110. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12111. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12112. gl.bindTexture( boundTexture.type, null );
  12113. boundTexture.type = undefined;
  12114. boundTexture.texture = undefined;
  12115. }
  12116. }
  12117. function compressedTexImage2D() {
  12118. try {
  12119. gl.compressedTexImage2D.apply( gl, arguments );
  12120. } catch ( error ) {
  12121. console.error( 'THREE.WebGLState:', error );
  12122. }
  12123. }
  12124. function texImage2D() {
  12125. try {
  12126. gl.texImage2D.apply( gl, arguments );
  12127. } catch ( error ) {
  12128. console.error( 'THREE.WebGLState:', error );
  12129. }
  12130. }
  12131. function texImage3D() {
  12132. try {
  12133. gl.texImage3D.apply( gl, arguments );
  12134. } catch ( error ) {
  12135. console.error( 'THREE.WebGLState:', error );
  12136. }
  12137. }
  12138. //
  12139. function scissor( scissor ) {
  12140. if ( currentScissor.equals( scissor ) === false ) {
  12141. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12142. currentScissor.copy( scissor );
  12143. }
  12144. }
  12145. function viewport( viewport ) {
  12146. if ( currentViewport.equals( viewport ) === false ) {
  12147. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12148. currentViewport.copy( viewport );
  12149. }
  12150. }
  12151. //
  12152. function reset() {
  12153. // reset state
  12154. gl.disable( 3042 );
  12155. gl.disable( 2884 );
  12156. gl.disable( 2929 );
  12157. gl.disable( 32823 );
  12158. gl.disable( 3089 );
  12159. gl.disable( 2960 );
  12160. gl.disable( 32926 );
  12161. gl.blendEquation( 32774 );
  12162. gl.blendFunc( 1, 0 );
  12163. gl.blendFuncSeparate( 1, 0, 1, 0 );
  12164. gl.colorMask( true, true, true, true );
  12165. gl.clearColor( 0, 0, 0, 0 );
  12166. gl.depthMask( true );
  12167. gl.depthFunc( 513 );
  12168. gl.clearDepth( 1 );
  12169. gl.stencilMask( 0xffffffff );
  12170. gl.stencilFunc( 519, 0, 0xffffffff );
  12171. gl.stencilOp( 7680, 7680, 7680 );
  12172. gl.clearStencil( 0 );
  12173. gl.cullFace( 1029 );
  12174. gl.frontFace( 2305 );
  12175. gl.polygonOffset( 0, 0 );
  12176. gl.activeTexture( 33984 );
  12177. gl.bindFramebuffer( 36160, null );
  12178. if ( isWebGL2 === true ) {
  12179. gl.bindFramebuffer( 36009, null );
  12180. gl.bindFramebuffer( 36008, null );
  12181. }
  12182. gl.useProgram( null );
  12183. gl.lineWidth( 1 );
  12184. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  12185. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  12186. // reset internals
  12187. enabledCapabilities = {};
  12188. currentTextureSlot = null;
  12189. currentBoundTextures = {};
  12190. xrFramebuffer = null;
  12191. currentBoundFramebuffers = {};
  12192. currentProgram = null;
  12193. currentBlendingEnabled = false;
  12194. currentBlending = null;
  12195. currentBlendEquation = null;
  12196. currentBlendSrc = null;
  12197. currentBlendDst = null;
  12198. currentBlendEquationAlpha = null;
  12199. currentBlendSrcAlpha = null;
  12200. currentBlendDstAlpha = null;
  12201. currentPremultipledAlpha = false;
  12202. currentFlipSided = null;
  12203. currentCullFace = null;
  12204. currentLineWidth = null;
  12205. currentPolygonOffsetFactor = null;
  12206. currentPolygonOffsetUnits = null;
  12207. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12208. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12209. colorBuffer.reset();
  12210. depthBuffer.reset();
  12211. stencilBuffer.reset();
  12212. }
  12213. return {
  12214. buffers: {
  12215. color: colorBuffer,
  12216. depth: depthBuffer,
  12217. stencil: stencilBuffer
  12218. },
  12219. enable: enable,
  12220. disable: disable,
  12221. bindFramebuffer: bindFramebuffer,
  12222. bindXRFramebuffer: bindXRFramebuffer,
  12223. useProgram: useProgram,
  12224. setBlending: setBlending,
  12225. setMaterial: setMaterial,
  12226. setFlipSided: setFlipSided,
  12227. setCullFace: setCullFace,
  12228. setLineWidth: setLineWidth,
  12229. setPolygonOffset: setPolygonOffset,
  12230. setScissorTest: setScissorTest,
  12231. activeTexture: activeTexture,
  12232. bindTexture: bindTexture,
  12233. unbindTexture: unbindTexture,
  12234. compressedTexImage2D: compressedTexImage2D,
  12235. texImage2D: texImage2D,
  12236. texImage3D: texImage3D,
  12237. scissor: scissor,
  12238. viewport: viewport,
  12239. reset: reset
  12240. };
  12241. }
  12242. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12243. const isWebGL2 = capabilities.isWebGL2;
  12244. const maxTextures = capabilities.maxTextures;
  12245. const maxCubemapSize = capabilities.maxCubemapSize;
  12246. const maxTextureSize = capabilities.maxTextureSize;
  12247. const maxSamples = capabilities.maxSamples;
  12248. const _videoTextures = new WeakMap();
  12249. let _canvas;
  12250. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12251. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12252. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12253. let useOffscreenCanvas = false;
  12254. try {
  12255. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12256. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12257. } catch ( err ) {
  12258. // Ignore any errors
  12259. }
  12260. function createCanvas( width, height ) {
  12261. // Use OffscreenCanvas when available. Specially needed in web workers
  12262. return useOffscreenCanvas ?
  12263. new OffscreenCanvas( width, height ) :
  12264. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  12265. }
  12266. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  12267. let scale = 1;
  12268. // handle case if texture exceeds max size
  12269. if ( image.width > maxSize || image.height > maxSize ) {
  12270. scale = maxSize / Math.max( image.width, image.height );
  12271. }
  12272. // only perform resize if necessary
  12273. if ( scale < 1 || needsPowerOfTwo === true ) {
  12274. // only perform resize for certain image types
  12275. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  12276. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  12277. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  12278. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12279. const width = floor( scale * image.width );
  12280. const height = floor( scale * image.height );
  12281. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  12282. // cube textures can't reuse the same canvas
  12283. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  12284. canvas.width = width;
  12285. canvas.height = height;
  12286. const context = canvas.getContext( '2d' );
  12287. context.drawImage( image, 0, 0, width, height );
  12288. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  12289. return canvas;
  12290. } else {
  12291. if ( 'data' in image ) {
  12292. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  12293. }
  12294. return image;
  12295. }
  12296. }
  12297. return image;
  12298. }
  12299. function isPowerOfTwo$1( image ) {
  12300. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  12301. }
  12302. function textureNeedsPowerOfTwo( texture ) {
  12303. if ( isWebGL2 ) return false;
  12304. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  12305. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  12306. }
  12307. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  12308. return texture.generateMipmaps && supportsMips &&
  12309. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12310. }
  12311. function generateMipmap( target, texture, width, height ) {
  12312. _gl.generateMipmap( target );
  12313. const textureProperties = properties.get( texture );
  12314. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height ) );
  12315. }
  12316. function getInternalFormat( internalFormatName, glFormat, glType ) {
  12317. if ( isWebGL2 === false ) return glFormat;
  12318. if ( internalFormatName !== null ) {
  12319. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  12320. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  12321. }
  12322. let internalFormat = glFormat;
  12323. if ( glFormat === 6403 ) {
  12324. if ( glType === 5126 ) internalFormat = 33326;
  12325. if ( glType === 5131 ) internalFormat = 33325;
  12326. if ( glType === 5121 ) internalFormat = 33321;
  12327. }
  12328. if ( glFormat === 6407 ) {
  12329. if ( glType === 5126 ) internalFormat = 34837;
  12330. if ( glType === 5131 ) internalFormat = 34843;
  12331. if ( glType === 5121 ) internalFormat = 32849;
  12332. }
  12333. if ( glFormat === 6408 ) {
  12334. if ( glType === 5126 ) internalFormat = 34836;
  12335. if ( glType === 5131 ) internalFormat = 34842;
  12336. if ( glType === 5121 ) internalFormat = 32856;
  12337. }
  12338. if ( internalFormat === 33325 || internalFormat === 33326 ||
  12339. internalFormat === 34842 || internalFormat === 34836 ) {
  12340. extensions.get( 'EXT_color_buffer_float' );
  12341. }
  12342. return internalFormat;
  12343. }
  12344. // Fallback filters for non-power-of-2 textures
  12345. function filterFallback( f ) {
  12346. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  12347. return 9728;
  12348. }
  12349. return 9729;
  12350. }
  12351. //
  12352. function onTextureDispose( event ) {
  12353. const texture = event.target;
  12354. texture.removeEventListener( 'dispose', onTextureDispose );
  12355. deallocateTexture( texture );
  12356. if ( texture.isVideoTexture ) {
  12357. _videoTextures.delete( texture );
  12358. }
  12359. info.memory.textures --;
  12360. }
  12361. function onRenderTargetDispose( event ) {
  12362. const renderTarget = event.target;
  12363. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12364. deallocateRenderTarget( renderTarget );
  12365. }
  12366. //
  12367. function deallocateTexture( texture ) {
  12368. const textureProperties = properties.get( texture );
  12369. if ( textureProperties.__webglInit === undefined ) return;
  12370. _gl.deleteTexture( textureProperties.__webglTexture );
  12371. properties.remove( texture );
  12372. }
  12373. function deallocateRenderTarget( renderTarget ) {
  12374. const texture = renderTarget.texture;
  12375. const renderTargetProperties = properties.get( renderTarget );
  12376. const textureProperties = properties.get( texture );
  12377. if ( ! renderTarget ) return;
  12378. if ( textureProperties.__webglTexture !== undefined ) {
  12379. _gl.deleteTexture( textureProperties.__webglTexture );
  12380. info.memory.textures --;
  12381. }
  12382. if ( renderTarget.depthTexture ) {
  12383. renderTarget.depthTexture.dispose();
  12384. }
  12385. if ( renderTarget.isWebGLCubeRenderTarget ) {
  12386. for ( let i = 0; i < 6; i ++ ) {
  12387. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  12388. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  12389. }
  12390. } else {
  12391. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  12392. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  12393. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  12394. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  12395. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  12396. }
  12397. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  12398. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  12399. const attachmentProperties = properties.get( texture[ i ] );
  12400. if ( attachmentProperties.__webglTexture ) {
  12401. _gl.deleteTexture( attachmentProperties.__webglTexture );
  12402. info.memory.textures --;
  12403. }
  12404. properties.remove( texture[ i ] );
  12405. }
  12406. }
  12407. properties.remove( texture );
  12408. properties.remove( renderTarget );
  12409. }
  12410. //
  12411. let textureUnits = 0;
  12412. function resetTextureUnits() {
  12413. textureUnits = 0;
  12414. }
  12415. function allocateTextureUnit() {
  12416. const textureUnit = textureUnits;
  12417. if ( textureUnit >= maxTextures ) {
  12418. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  12419. }
  12420. textureUnits += 1;
  12421. return textureUnit;
  12422. }
  12423. //
  12424. function setTexture2D( texture, slot ) {
  12425. const textureProperties = properties.get( texture );
  12426. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  12427. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12428. const image = texture.image;
  12429. if ( image === undefined ) {
  12430. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  12431. } else if ( image.complete === false ) {
  12432. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  12433. } else {
  12434. uploadTexture( textureProperties, texture, slot );
  12435. return;
  12436. }
  12437. }
  12438. state.activeTexture( 33984 + slot );
  12439. state.bindTexture( 3553, textureProperties.__webglTexture );
  12440. }
  12441. function setTexture2DArray( texture, slot ) {
  12442. const textureProperties = properties.get( texture );
  12443. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12444. uploadTexture( textureProperties, texture, slot );
  12445. return;
  12446. }
  12447. state.activeTexture( 33984 + slot );
  12448. state.bindTexture( 35866, textureProperties.__webglTexture );
  12449. }
  12450. function setTexture3D( texture, slot ) {
  12451. const textureProperties = properties.get( texture );
  12452. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12453. uploadTexture( textureProperties, texture, slot );
  12454. return;
  12455. }
  12456. state.activeTexture( 33984 + slot );
  12457. state.bindTexture( 32879, textureProperties.__webglTexture );
  12458. }
  12459. function setTextureCube( texture, slot ) {
  12460. const textureProperties = properties.get( texture );
  12461. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12462. uploadCubeTexture( textureProperties, texture, slot );
  12463. return;
  12464. }
  12465. state.activeTexture( 33984 + slot );
  12466. state.bindTexture( 34067, textureProperties.__webglTexture );
  12467. }
  12468. const wrappingToGL = {
  12469. [ RepeatWrapping ]: 10497,
  12470. [ ClampToEdgeWrapping ]: 33071,
  12471. [ MirroredRepeatWrapping ]: 33648
  12472. };
  12473. const filterToGL = {
  12474. [ NearestFilter ]: 9728,
  12475. [ NearestMipmapNearestFilter ]: 9984,
  12476. [ NearestMipmapLinearFilter ]: 9986,
  12477. [ LinearFilter ]: 9729,
  12478. [ LinearMipmapNearestFilter ]: 9985,
  12479. [ LinearMipmapLinearFilter ]: 9987
  12480. };
  12481. function setTextureParameters( textureType, texture, supportsMips ) {
  12482. if ( supportsMips ) {
  12483. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  12484. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  12485. if ( textureType === 32879 || textureType === 35866 ) {
  12486. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  12487. }
  12488. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  12489. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  12490. } else {
  12491. _gl.texParameteri( textureType, 10242, 33071 );
  12492. _gl.texParameteri( textureType, 10243, 33071 );
  12493. if ( textureType === 32879 || textureType === 35866 ) {
  12494. _gl.texParameteri( textureType, 32882, 33071 );
  12495. }
  12496. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  12497. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  12498. }
  12499. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  12500. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  12501. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  12502. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  12503. }
  12504. }
  12505. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  12506. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12507. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  12508. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  12509. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  12510. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  12511. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  12512. }
  12513. }
  12514. }
  12515. function initTexture( textureProperties, texture ) {
  12516. if ( textureProperties.__webglInit === undefined ) {
  12517. textureProperties.__webglInit = true;
  12518. texture.addEventListener( 'dispose', onTextureDispose );
  12519. textureProperties.__webglTexture = _gl.createTexture();
  12520. info.memory.textures ++;
  12521. }
  12522. }
  12523. function uploadTexture( textureProperties, texture, slot ) {
  12524. let textureType = 3553;
  12525. if ( texture.isDataTexture2DArray ) textureType = 35866;
  12526. if ( texture.isDataTexture3D ) textureType = 32879;
  12527. initTexture( textureProperties, texture );
  12528. state.activeTexture( 33984 + slot );
  12529. state.bindTexture( textureType, textureProperties.__webglTexture );
  12530. _gl.pixelStorei( 37440, texture.flipY );
  12531. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12532. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12533. _gl.pixelStorei( 37443, 0 );
  12534. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  12535. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  12536. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  12537. glFormat = utils.convert( texture.format );
  12538. let glType = utils.convert( texture.type ),
  12539. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12540. setTextureParameters( textureType, texture, supportsMips );
  12541. let mipmap;
  12542. const mipmaps = texture.mipmaps;
  12543. if ( texture.isDepthTexture ) {
  12544. // populate depth texture with dummy data
  12545. glInternalFormat = 6402;
  12546. if ( isWebGL2 ) {
  12547. if ( texture.type === FloatType ) {
  12548. glInternalFormat = 36012;
  12549. } else if ( texture.type === UnsignedIntType ) {
  12550. glInternalFormat = 33190;
  12551. } else if ( texture.type === UnsignedInt248Type ) {
  12552. glInternalFormat = 35056;
  12553. } else {
  12554. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  12555. }
  12556. } else {
  12557. if ( texture.type === FloatType ) {
  12558. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  12559. }
  12560. }
  12561. // validation checks for WebGL 1
  12562. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  12563. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12564. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12565. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12566. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  12567. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  12568. texture.type = UnsignedShortType;
  12569. glType = utils.convert( texture.type );
  12570. }
  12571. }
  12572. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  12573. // Depth stencil textures need the DEPTH_STENCIL internal format
  12574. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12575. glInternalFormat = 34041;
  12576. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12577. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12578. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12579. if ( texture.type !== UnsignedInt248Type ) {
  12580. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  12581. texture.type = UnsignedInt248Type;
  12582. glType = utils.convert( texture.type );
  12583. }
  12584. }
  12585. //
  12586. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  12587. } else if ( texture.isDataTexture ) {
  12588. // use manually created mipmaps if available
  12589. // if there are no manual mipmaps
  12590. // set 0 level mipmap and then use GL to generate other mipmap levels
  12591. if ( mipmaps.length > 0 && supportsMips ) {
  12592. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12593. mipmap = mipmaps[ i ];
  12594. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12595. }
  12596. texture.generateMipmaps = false;
  12597. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12598. } else {
  12599. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12600. textureProperties.__maxMipLevel = 0;
  12601. }
  12602. } else if ( texture.isCompressedTexture ) {
  12603. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12604. mipmap = mipmaps[ i ];
  12605. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12606. if ( glFormat !== null ) {
  12607. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12608. } else {
  12609. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  12610. }
  12611. } else {
  12612. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12613. }
  12614. }
  12615. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12616. } else if ( texture.isDataTexture2DArray ) {
  12617. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12618. textureProperties.__maxMipLevel = 0;
  12619. } else if ( texture.isDataTexture3D ) {
  12620. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12621. textureProperties.__maxMipLevel = 0;
  12622. } else {
  12623. // regular Texture (image, video, canvas)
  12624. // use manually created mipmaps if available
  12625. // if there are no manual mipmaps
  12626. // set 0 level mipmap and then use GL to generate other mipmap levels
  12627. if ( mipmaps.length > 0 && supportsMips ) {
  12628. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12629. mipmap = mipmaps[ i ];
  12630. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  12631. }
  12632. texture.generateMipmaps = false;
  12633. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12634. } else {
  12635. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  12636. textureProperties.__maxMipLevel = 0;
  12637. }
  12638. }
  12639. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12640. generateMipmap( textureType, texture, image.width, image.height );
  12641. }
  12642. textureProperties.__version = texture.version;
  12643. if ( texture.onUpdate ) texture.onUpdate( texture );
  12644. }
  12645. function uploadCubeTexture( textureProperties, texture, slot ) {
  12646. if ( texture.image.length !== 6 ) return;
  12647. initTexture( textureProperties, texture );
  12648. state.activeTexture( 33984 + slot );
  12649. state.bindTexture( 34067, textureProperties.__webglTexture );
  12650. _gl.pixelStorei( 37440, texture.flipY );
  12651. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12652. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12653. _gl.pixelStorei( 37443, 0 );
  12654. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  12655. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  12656. const cubeImage = [];
  12657. for ( let i = 0; i < 6; i ++ ) {
  12658. if ( ! isCompressed && ! isDataTexture ) {
  12659. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  12660. } else {
  12661. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  12662. }
  12663. }
  12664. const image = cubeImage[ 0 ],
  12665. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  12666. glFormat = utils.convert( texture.format ),
  12667. glType = utils.convert( texture.type ),
  12668. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12669. setTextureParameters( 34067, texture, supportsMips );
  12670. let mipmaps;
  12671. if ( isCompressed ) {
  12672. for ( let i = 0; i < 6; i ++ ) {
  12673. mipmaps = cubeImage[ i ].mipmaps;
  12674. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12675. const mipmap = mipmaps[ j ];
  12676. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12677. if ( glFormat !== null ) {
  12678. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12679. } else {
  12680. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  12681. }
  12682. } else {
  12683. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12684. }
  12685. }
  12686. }
  12687. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12688. } else {
  12689. mipmaps = texture.mipmaps;
  12690. for ( let i = 0; i < 6; i ++ ) {
  12691. if ( isDataTexture ) {
  12692. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  12693. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12694. const mipmap = mipmaps[ j ];
  12695. const mipmapImage = mipmap.image[ i ].image;
  12696. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  12697. }
  12698. } else {
  12699. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  12700. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12701. const mipmap = mipmaps[ j ];
  12702. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  12703. }
  12704. }
  12705. }
  12706. textureProperties.__maxMipLevel = mipmaps.length;
  12707. }
  12708. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12709. // We assume images for cube map have the same size.
  12710. generateMipmap( 34067, texture, image.width, image.height );
  12711. }
  12712. textureProperties.__version = texture.version;
  12713. if ( texture.onUpdate ) texture.onUpdate( texture );
  12714. }
  12715. // Render targets
  12716. // Setup storage for target texture and bind it to correct framebuffer
  12717. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  12718. const glFormat = utils.convert( texture.format );
  12719. const glType = utils.convert( texture.type );
  12720. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12721. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  12722. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  12723. } else {
  12724. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12725. }
  12726. state.bindFramebuffer( 36160, framebuffer );
  12727. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  12728. state.bindFramebuffer( 36160, null );
  12729. }
  12730. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12731. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  12732. _gl.bindRenderbuffer( 36161, renderbuffer );
  12733. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12734. let glInternalFormat = 33189;
  12735. if ( isMultisample ) {
  12736. const depthTexture = renderTarget.depthTexture;
  12737. if ( depthTexture && depthTexture.isDepthTexture ) {
  12738. if ( depthTexture.type === FloatType ) {
  12739. glInternalFormat = 36012;
  12740. } else if ( depthTexture.type === UnsignedIntType ) {
  12741. glInternalFormat = 33190;
  12742. }
  12743. }
  12744. const samples = getRenderTargetSamples( renderTarget );
  12745. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12746. } else {
  12747. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12748. }
  12749. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  12750. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12751. if ( isMultisample ) {
  12752. const samples = getRenderTargetSamples( renderTarget );
  12753. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  12754. } else {
  12755. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  12756. }
  12757. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  12758. } else {
  12759. // Use the first texture for MRT so far
  12760. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  12761. const glFormat = utils.convert( texture.format );
  12762. const glType = utils.convert( texture.type );
  12763. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12764. if ( isMultisample ) {
  12765. const samples = getRenderTargetSamples( renderTarget );
  12766. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12767. } else {
  12768. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12769. }
  12770. }
  12771. _gl.bindRenderbuffer( 36161, null );
  12772. }
  12773. // Setup resources for a Depth Texture for a FBO (needs an extension)
  12774. function setupDepthTexture( framebuffer, renderTarget ) {
  12775. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  12776. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  12777. state.bindFramebuffer( 36160, framebuffer );
  12778. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  12779. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  12780. }
  12781. // upload an empty depth texture with framebuffer size
  12782. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  12783. renderTarget.depthTexture.image.width !== renderTarget.width ||
  12784. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  12785. renderTarget.depthTexture.image.width = renderTarget.width;
  12786. renderTarget.depthTexture.image.height = renderTarget.height;
  12787. renderTarget.depthTexture.needsUpdate = true;
  12788. }
  12789. setTexture2D( renderTarget.depthTexture, 0 );
  12790. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  12791. if ( renderTarget.depthTexture.format === DepthFormat ) {
  12792. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  12793. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  12794. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  12795. } else {
  12796. throw new Error( 'Unknown depthTexture format' );
  12797. }
  12798. }
  12799. // Setup GL resources for a non-texture depth buffer
  12800. function setupDepthRenderbuffer( renderTarget ) {
  12801. const renderTargetProperties = properties.get( renderTarget );
  12802. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12803. if ( renderTarget.depthTexture ) {
  12804. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  12805. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  12806. } else {
  12807. if ( isCube ) {
  12808. renderTargetProperties.__webglDepthbuffer = [];
  12809. for ( let i = 0; i < 6; i ++ ) {
  12810. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  12811. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  12812. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  12813. }
  12814. } else {
  12815. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  12816. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12817. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  12818. }
  12819. }
  12820. state.bindFramebuffer( 36160, null );
  12821. }
  12822. // Set up GL resources for the render target
  12823. function setupRenderTarget( renderTarget ) {
  12824. const texture = renderTarget.texture;
  12825. const renderTargetProperties = properties.get( renderTarget );
  12826. const textureProperties = properties.get( texture );
  12827. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  12828. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  12829. textureProperties.__webglTexture = _gl.createTexture();
  12830. textureProperties.__version = texture.version;
  12831. info.memory.textures ++;
  12832. }
  12833. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12834. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  12835. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  12836. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12837. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  12838. // Handles WebGL2 RGBFormat fallback - #18858
  12839. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  12840. texture.format = RGBAFormat;
  12841. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  12842. }
  12843. // Setup framebuffer
  12844. if ( isCube ) {
  12845. renderTargetProperties.__webglFramebuffer = [];
  12846. for ( let i = 0; i < 6; i ++ ) {
  12847. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12848. }
  12849. } else {
  12850. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12851. if ( isMultipleRenderTargets ) {
  12852. if ( capabilities.drawBuffers ) {
  12853. const textures = renderTarget.texture;
  12854. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12855. const attachmentProperties = properties.get( textures[ i ] );
  12856. if ( attachmentProperties.__webglTexture === undefined ) {
  12857. attachmentProperties.__webglTexture = _gl.createTexture();
  12858. info.memory.textures ++;
  12859. }
  12860. }
  12861. } else {
  12862. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  12863. }
  12864. } else if ( isMultisample ) {
  12865. if ( isWebGL2 ) {
  12866. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12867. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12868. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  12869. const glFormat = utils.convert( texture.format );
  12870. const glType = utils.convert( texture.type );
  12871. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12872. const samples = getRenderTargetSamples( renderTarget );
  12873. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12874. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  12875. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  12876. _gl.bindRenderbuffer( 36161, null );
  12877. if ( renderTarget.depthBuffer ) {
  12878. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12879. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  12880. }
  12881. state.bindFramebuffer( 36160, null );
  12882. } else {
  12883. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12884. }
  12885. }
  12886. }
  12887. // Setup color buffer
  12888. if ( isCube ) {
  12889. state.bindTexture( 34067, textureProperties.__webglTexture );
  12890. setTextureParameters( 34067, texture, supportsMips );
  12891. for ( let i = 0; i < 6; i ++ ) {
  12892. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  12893. }
  12894. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12895. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  12896. }
  12897. state.bindTexture( 34067, null );
  12898. } else if ( isMultipleRenderTargets ) {
  12899. const textures = renderTarget.texture;
  12900. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12901. const attachment = textures[ i ];
  12902. const attachmentProperties = properties.get( attachment );
  12903. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  12904. setTextureParameters( 3553, attachment, supportsMips );
  12905. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  12906. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  12907. generateMipmap( 3553, attachment, renderTarget.width, renderTarget.height );
  12908. }
  12909. }
  12910. state.bindTexture( 3553, null );
  12911. } else {
  12912. let glTextureType = 3553;
  12913. if ( isRenderTarget3D ) {
  12914. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  12915. if ( isWebGL2 ) {
  12916. const isTexture3D = texture.isDataTexture3D;
  12917. glTextureType = isTexture3D ? 32879 : 35866;
  12918. } else {
  12919. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  12920. }
  12921. }
  12922. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  12923. setTextureParameters( glTextureType, texture, supportsMips );
  12924. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  12925. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12926. generateMipmap( 3553, texture, renderTarget.width, renderTarget.height );
  12927. }
  12928. state.bindTexture( 3553, null );
  12929. }
  12930. // Setup depth and stencil buffers
  12931. if ( renderTarget.depthBuffer ) {
  12932. setupDepthRenderbuffer( renderTarget );
  12933. }
  12934. }
  12935. function updateRenderTargetMipmap( renderTarget ) {
  12936. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  12937. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  12938. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12939. const texture = textures[ i ];
  12940. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12941. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  12942. const webglTexture = properties.get( texture ).__webglTexture;
  12943. state.bindTexture( target, webglTexture );
  12944. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  12945. state.bindTexture( target, null );
  12946. }
  12947. }
  12948. }
  12949. function updateMultisampleRenderTarget( renderTarget ) {
  12950. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  12951. if ( isWebGL2 ) {
  12952. const width = renderTarget.width;
  12953. const height = renderTarget.height;
  12954. let mask = 16384;
  12955. if ( renderTarget.depthBuffer ) mask |= 256;
  12956. if ( renderTarget.stencilBuffer ) mask |= 1024;
  12957. const renderTargetProperties = properties.get( renderTarget );
  12958. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  12959. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  12960. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  12961. state.bindFramebuffer( 36008, null );
  12962. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  12963. } else {
  12964. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12965. }
  12966. }
  12967. }
  12968. function getRenderTargetSamples( renderTarget ) {
  12969. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  12970. Math.min( maxSamples, renderTarget.samples ) : 0;
  12971. }
  12972. function updateVideoTexture( texture ) {
  12973. const frame = info.render.frame;
  12974. // Check the last frame we updated the VideoTexture
  12975. if ( _videoTextures.get( texture ) !== frame ) {
  12976. _videoTextures.set( texture, frame );
  12977. texture.update();
  12978. }
  12979. }
  12980. // backwards compatibility
  12981. let warnedTexture2D = false;
  12982. let warnedTextureCube = false;
  12983. function safeSetTexture2D( texture, slot ) {
  12984. if ( texture && texture.isWebGLRenderTarget ) {
  12985. if ( warnedTexture2D === false ) {
  12986. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  12987. warnedTexture2D = true;
  12988. }
  12989. texture = texture.texture;
  12990. }
  12991. setTexture2D( texture, slot );
  12992. }
  12993. function safeSetTextureCube( texture, slot ) {
  12994. if ( texture && texture.isWebGLCubeRenderTarget ) {
  12995. if ( warnedTextureCube === false ) {
  12996. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  12997. warnedTextureCube = true;
  12998. }
  12999. texture = texture.texture;
  13000. }
  13001. setTextureCube( texture, slot );
  13002. }
  13003. //
  13004. this.allocateTextureUnit = allocateTextureUnit;
  13005. this.resetTextureUnits = resetTextureUnits;
  13006. this.setTexture2D = setTexture2D;
  13007. this.setTexture2DArray = setTexture2DArray;
  13008. this.setTexture3D = setTexture3D;
  13009. this.setTextureCube = setTextureCube;
  13010. this.setupRenderTarget = setupRenderTarget;
  13011. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13012. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13013. this.safeSetTexture2D = safeSetTexture2D;
  13014. this.safeSetTextureCube = safeSetTextureCube;
  13015. }
  13016. function WebGLUtils( gl, extensions, capabilities ) {
  13017. const isWebGL2 = capabilities.isWebGL2;
  13018. function convert( p ) {
  13019. let extension;
  13020. if ( p === UnsignedByteType ) return 5121;
  13021. if ( p === UnsignedShort4444Type ) return 32819;
  13022. if ( p === UnsignedShort5551Type ) return 32820;
  13023. if ( p === UnsignedShort565Type ) return 33635;
  13024. if ( p === ByteType ) return 5120;
  13025. if ( p === ShortType ) return 5122;
  13026. if ( p === UnsignedShortType ) return 5123;
  13027. if ( p === IntType ) return 5124;
  13028. if ( p === UnsignedIntType ) return 5125;
  13029. if ( p === FloatType ) return 5126;
  13030. if ( p === HalfFloatType ) {
  13031. if ( isWebGL2 ) return 5131;
  13032. extension = extensions.get( 'OES_texture_half_float' );
  13033. if ( extension !== null ) {
  13034. return extension.HALF_FLOAT_OES;
  13035. } else {
  13036. return null;
  13037. }
  13038. }
  13039. if ( p === AlphaFormat ) return 6406;
  13040. if ( p === RGBFormat ) return 6407;
  13041. if ( p === RGBAFormat ) return 6408;
  13042. if ( p === LuminanceFormat ) return 6409;
  13043. if ( p === LuminanceAlphaFormat ) return 6410;
  13044. if ( p === DepthFormat ) return 6402;
  13045. if ( p === DepthStencilFormat ) return 34041;
  13046. if ( p === RedFormat ) return 6403;
  13047. // WebGL2 formats.
  13048. if ( p === RedIntegerFormat ) return 36244;
  13049. if ( p === RGFormat ) return 33319;
  13050. if ( p === RGIntegerFormat ) return 33320;
  13051. if ( p === RGBIntegerFormat ) return 36248;
  13052. if ( p === RGBAIntegerFormat ) return 36249;
  13053. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13054. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13055. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13056. if ( extension !== null ) {
  13057. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13058. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13059. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13060. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13061. } else {
  13062. return null;
  13063. }
  13064. }
  13065. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13066. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13067. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13068. if ( extension !== null ) {
  13069. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13070. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13071. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13072. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13073. } else {
  13074. return null;
  13075. }
  13076. }
  13077. if ( p === RGB_ETC1_Format ) {
  13078. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13079. if ( extension !== null ) {
  13080. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13081. } else {
  13082. return null;
  13083. }
  13084. }
  13085. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13086. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13087. if ( extension !== null ) {
  13088. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13089. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13090. }
  13091. }
  13092. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13093. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13094. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13095. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13096. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13097. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13098. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13099. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13100. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13101. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13102. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13103. if ( extension !== null ) {
  13104. // TODO Complete?
  13105. return p;
  13106. } else {
  13107. return null;
  13108. }
  13109. }
  13110. if ( p === RGBA_BPTC_Format ) {
  13111. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13112. if ( extension !== null ) {
  13113. // TODO Complete?
  13114. return p;
  13115. } else {
  13116. return null;
  13117. }
  13118. }
  13119. if ( p === UnsignedInt248Type ) {
  13120. if ( isWebGL2 ) return 34042;
  13121. extension = extensions.get( 'WEBGL_depth_texture' );
  13122. if ( extension !== null ) {
  13123. return extension.UNSIGNED_INT_24_8_WEBGL;
  13124. } else {
  13125. return null;
  13126. }
  13127. }
  13128. }
  13129. return { convert: convert };
  13130. }
  13131. class ArrayCamera extends PerspectiveCamera {
  13132. constructor( array = [] ) {
  13133. super();
  13134. this.cameras = array;
  13135. }
  13136. }
  13137. ArrayCamera.prototype.isArrayCamera = true;
  13138. class Group extends Object3D {
  13139. constructor() {
  13140. super();
  13141. this.type = 'Group';
  13142. }
  13143. }
  13144. Group.prototype.isGroup = true;
  13145. const _moveEvent = { type: 'move' };
  13146. class WebXRController {
  13147. constructor() {
  13148. this._targetRay = null;
  13149. this._grip = null;
  13150. this._hand = null;
  13151. }
  13152. getHandSpace() {
  13153. if ( this._hand === null ) {
  13154. this._hand = new Group();
  13155. this._hand.matrixAutoUpdate = false;
  13156. this._hand.visible = false;
  13157. this._hand.joints = {};
  13158. this._hand.inputState = { pinching: false };
  13159. }
  13160. return this._hand;
  13161. }
  13162. getTargetRaySpace() {
  13163. if ( this._targetRay === null ) {
  13164. this._targetRay = new Group();
  13165. this._targetRay.matrixAutoUpdate = false;
  13166. this._targetRay.visible = false;
  13167. this._targetRay.hasLinearVelocity = false;
  13168. this._targetRay.linearVelocity = new Vector3();
  13169. this._targetRay.hasAngularVelocity = false;
  13170. this._targetRay.angularVelocity = new Vector3();
  13171. }
  13172. return this._targetRay;
  13173. }
  13174. getGripSpace() {
  13175. if ( this._grip === null ) {
  13176. this._grip = new Group();
  13177. this._grip.matrixAutoUpdate = false;
  13178. this._grip.visible = false;
  13179. this._grip.hasLinearVelocity = false;
  13180. this._grip.linearVelocity = new Vector3();
  13181. this._grip.hasAngularVelocity = false;
  13182. this._grip.angularVelocity = new Vector3();
  13183. }
  13184. return this._grip;
  13185. }
  13186. dispatchEvent( event ) {
  13187. if ( this._targetRay !== null ) {
  13188. this._targetRay.dispatchEvent( event );
  13189. }
  13190. if ( this._grip !== null ) {
  13191. this._grip.dispatchEvent( event );
  13192. }
  13193. if ( this._hand !== null ) {
  13194. this._hand.dispatchEvent( event );
  13195. }
  13196. return this;
  13197. }
  13198. disconnect( inputSource ) {
  13199. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13200. if ( this._targetRay !== null ) {
  13201. this._targetRay.visible = false;
  13202. }
  13203. if ( this._grip !== null ) {
  13204. this._grip.visible = false;
  13205. }
  13206. if ( this._hand !== null ) {
  13207. this._hand.visible = false;
  13208. }
  13209. return this;
  13210. }
  13211. update( inputSource, frame, referenceSpace ) {
  13212. let inputPose = null;
  13213. let gripPose = null;
  13214. let handPose = null;
  13215. const targetRay = this._targetRay;
  13216. const grip = this._grip;
  13217. const hand = this._hand;
  13218. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13219. if ( targetRay !== null ) {
  13220. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13221. if ( inputPose !== null ) {
  13222. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13223. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13224. if ( inputPose.linearVelocity ) {
  13225. targetRay.hasLinearVelocity = true;
  13226. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13227. } else {
  13228. targetRay.hasLinearVelocity = false;
  13229. }
  13230. if ( inputPose.angularVelocity ) {
  13231. targetRay.hasAngularVelocity = true;
  13232. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13233. } else {
  13234. targetRay.hasAngularVelocity = false;
  13235. }
  13236. this.dispatchEvent( _moveEvent );
  13237. }
  13238. }
  13239. if ( hand && inputSource.hand ) {
  13240. handPose = true;
  13241. for ( const inputjoint of inputSource.hand.values() ) {
  13242. // Update the joints groups with the XRJoint poses
  13243. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13244. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13245. // The transform of this joint will be updated with the joint pose on each frame
  13246. const joint = new Group();
  13247. joint.matrixAutoUpdate = false;
  13248. joint.visible = false;
  13249. hand.joints[ inputjoint.jointName ] = joint;
  13250. // ??
  13251. hand.add( joint );
  13252. }
  13253. const joint = hand.joints[ inputjoint.jointName ];
  13254. if ( jointPose !== null ) {
  13255. joint.matrix.fromArray( jointPose.transform.matrix );
  13256. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13257. joint.jointRadius = jointPose.radius;
  13258. }
  13259. joint.visible = jointPose !== null;
  13260. }
  13261. // Custom events
  13262. // Check pinchz
  13263. const indexTip = hand.joints[ 'index-finger-tip' ];
  13264. const thumbTip = hand.joints[ 'thumb-tip' ];
  13265. const distance = indexTip.position.distanceTo( thumbTip.position );
  13266. const distanceToPinch = 0.02;
  13267. const threshold = 0.005;
  13268. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13269. hand.inputState.pinching = false;
  13270. this.dispatchEvent( {
  13271. type: 'pinchend',
  13272. handedness: inputSource.handedness,
  13273. target: this
  13274. } );
  13275. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13276. hand.inputState.pinching = true;
  13277. this.dispatchEvent( {
  13278. type: 'pinchstart',
  13279. handedness: inputSource.handedness,
  13280. target: this
  13281. } );
  13282. }
  13283. } else {
  13284. if ( grip !== null && inputSource.gripSpace ) {
  13285. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13286. if ( gripPose !== null ) {
  13287. grip.matrix.fromArray( gripPose.transform.matrix );
  13288. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13289. if ( gripPose.linearVelocity ) {
  13290. grip.hasLinearVelocity = true;
  13291. grip.linearVelocity.copy( gripPose.linearVelocity );
  13292. } else {
  13293. grip.hasLinearVelocity = false;
  13294. }
  13295. if ( gripPose.angularVelocity ) {
  13296. grip.hasAngularVelocity = true;
  13297. grip.angularVelocity.copy( gripPose.angularVelocity );
  13298. } else {
  13299. grip.hasAngularVelocity = false;
  13300. }
  13301. }
  13302. }
  13303. }
  13304. }
  13305. if ( targetRay !== null ) {
  13306. targetRay.visible = ( inputPose !== null );
  13307. }
  13308. if ( grip !== null ) {
  13309. grip.visible = ( gripPose !== null );
  13310. }
  13311. if ( hand !== null ) {
  13312. hand.visible = ( handPose !== null );
  13313. }
  13314. return this;
  13315. }
  13316. }
  13317. class WebXRManager extends EventDispatcher {
  13318. constructor( renderer, gl ) {
  13319. super();
  13320. const scope = this;
  13321. const state = renderer.state;
  13322. let session = null;
  13323. let framebufferScaleFactor = 1.0;
  13324. let referenceSpace = null;
  13325. let referenceSpaceType = 'local-floor';
  13326. let pose = null;
  13327. const controllers = [];
  13328. const inputSourcesMap = new Map();
  13329. //
  13330. const cameraL = new PerspectiveCamera();
  13331. cameraL.layers.enable( 1 );
  13332. cameraL.viewport = new Vector4();
  13333. const cameraR = new PerspectiveCamera();
  13334. cameraR.layers.enable( 2 );
  13335. cameraR.viewport = new Vector4();
  13336. const cameras = [ cameraL, cameraR ];
  13337. const cameraVR = new ArrayCamera();
  13338. cameraVR.layers.enable( 1 );
  13339. cameraVR.layers.enable( 2 );
  13340. let _currentDepthNear = null;
  13341. let _currentDepthFar = null;
  13342. //
  13343. this.enabled = false;
  13344. this.isPresenting = false;
  13345. this.getController = function ( index ) {
  13346. let controller = controllers[ index ];
  13347. if ( controller === undefined ) {
  13348. controller = new WebXRController();
  13349. controllers[ index ] = controller;
  13350. }
  13351. return controller.getTargetRaySpace();
  13352. };
  13353. this.getControllerGrip = function ( index ) {
  13354. let controller = controllers[ index ];
  13355. if ( controller === undefined ) {
  13356. controller = new WebXRController();
  13357. controllers[ index ] = controller;
  13358. }
  13359. return controller.getGripSpace();
  13360. };
  13361. this.getHand = function ( index ) {
  13362. let controller = controllers[ index ];
  13363. if ( controller === undefined ) {
  13364. controller = new WebXRController();
  13365. controllers[ index ] = controller;
  13366. }
  13367. return controller.getHandSpace();
  13368. };
  13369. //
  13370. function onSessionEvent( event ) {
  13371. const controller = inputSourcesMap.get( event.inputSource );
  13372. if ( controller ) {
  13373. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  13374. }
  13375. }
  13376. function onSessionEnd() {
  13377. inputSourcesMap.forEach( function ( controller, inputSource ) {
  13378. controller.disconnect( inputSource );
  13379. } );
  13380. inputSourcesMap.clear();
  13381. _currentDepthNear = null;
  13382. _currentDepthFar = null;
  13383. // restore framebuffer/rendering state
  13384. state.bindXRFramebuffer( null );
  13385. renderer.setRenderTarget( renderer.getRenderTarget() );
  13386. //
  13387. animation.stop();
  13388. scope.isPresenting = false;
  13389. scope.dispatchEvent( { type: 'sessionend' } );
  13390. }
  13391. this.setFramebufferScaleFactor = function ( value ) {
  13392. framebufferScaleFactor = value;
  13393. if ( scope.isPresenting === true ) {
  13394. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  13395. }
  13396. };
  13397. this.setReferenceSpaceType = function ( value ) {
  13398. referenceSpaceType = value;
  13399. if ( scope.isPresenting === true ) {
  13400. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  13401. }
  13402. };
  13403. this.getReferenceSpace = function () {
  13404. return referenceSpace;
  13405. };
  13406. this.getSession = function () {
  13407. return session;
  13408. };
  13409. this.setSession = async function ( value ) {
  13410. session = value;
  13411. if ( session !== null ) {
  13412. session.addEventListener( 'select', onSessionEvent );
  13413. session.addEventListener( 'selectstart', onSessionEvent );
  13414. session.addEventListener( 'selectend', onSessionEvent );
  13415. session.addEventListener( 'squeeze', onSessionEvent );
  13416. session.addEventListener( 'squeezestart', onSessionEvent );
  13417. session.addEventListener( 'squeezeend', onSessionEvent );
  13418. session.addEventListener( 'end', onSessionEnd );
  13419. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  13420. const attributes = gl.getContextAttributes();
  13421. if ( attributes.xrCompatible !== true ) {
  13422. await gl.makeXRCompatible();
  13423. }
  13424. const layerInit = {
  13425. antialias: attributes.antialias,
  13426. alpha: attributes.alpha,
  13427. depth: attributes.depth,
  13428. stencil: attributes.stencil,
  13429. framebufferScaleFactor: framebufferScaleFactor
  13430. };
  13431. // eslint-disable-next-line no-undef
  13432. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  13433. session.updateRenderState( { baseLayer: baseLayer } );
  13434. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  13435. animation.setContext( session );
  13436. animation.start();
  13437. scope.isPresenting = true;
  13438. scope.dispatchEvent( { type: 'sessionstart' } );
  13439. }
  13440. };
  13441. function onInputSourcesChange( event ) {
  13442. const inputSources = session.inputSources;
  13443. // Assign inputSources to available controllers
  13444. for ( let i = 0; i < controllers.length; i ++ ) {
  13445. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  13446. }
  13447. // Notify disconnected
  13448. for ( let i = 0; i < event.removed.length; i ++ ) {
  13449. const inputSource = event.removed[ i ];
  13450. const controller = inputSourcesMap.get( inputSource );
  13451. if ( controller ) {
  13452. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13453. inputSourcesMap.delete( inputSource );
  13454. }
  13455. }
  13456. // Notify connected
  13457. for ( let i = 0; i < event.added.length; i ++ ) {
  13458. const inputSource = event.added[ i ];
  13459. const controller = inputSourcesMap.get( inputSource );
  13460. if ( controller ) {
  13461. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  13462. }
  13463. }
  13464. }
  13465. //
  13466. const cameraLPos = new Vector3();
  13467. const cameraRPos = new Vector3();
  13468. /**
  13469. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13470. * the cameras' projection and world matrices have already been set.
  13471. * And that near and far planes are identical for both cameras.
  13472. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13473. */
  13474. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  13475. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  13476. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  13477. const ipd = cameraLPos.distanceTo( cameraRPos );
  13478. const projL = cameraL.projectionMatrix.elements;
  13479. const projR = cameraR.projectionMatrix.elements;
  13480. // VR systems will have identical far and near planes, and
  13481. // most likely identical top and bottom frustum extents.
  13482. // Use the left camera for these values.
  13483. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  13484. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  13485. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  13486. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  13487. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  13488. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  13489. const left = near * leftFov;
  13490. const right = near * rightFov;
  13491. // Calculate the new camera's position offset from the
  13492. // left camera. xOffset should be roughly half `ipd`.
  13493. const zOffset = ipd / ( - leftFov + rightFov );
  13494. const xOffset = zOffset * - leftFov;
  13495. // TODO: Better way to apply this offset?
  13496. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  13497. camera.translateX( xOffset );
  13498. camera.translateZ( zOffset );
  13499. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  13500. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13501. // Find the union of the frustum values of the cameras and scale
  13502. // the values so that the near plane's position does not change in world space,
  13503. // although must now be relative to the new union camera.
  13504. const near2 = near + zOffset;
  13505. const far2 = far + zOffset;
  13506. const left2 = left - xOffset;
  13507. const right2 = right + ( ipd - xOffset );
  13508. const top2 = topFov * far / far2 * near2;
  13509. const bottom2 = bottomFov * far / far2 * near2;
  13510. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  13511. }
  13512. function updateCamera( camera, parent ) {
  13513. if ( parent === null ) {
  13514. camera.matrixWorld.copy( camera.matrix );
  13515. } else {
  13516. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  13517. }
  13518. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13519. }
  13520. this.getCamera = function ( camera ) {
  13521. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13522. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13523. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  13524. // Note that the new renderState won't apply until the next frame. See #18320
  13525. session.updateRenderState( {
  13526. depthNear: cameraVR.near,
  13527. depthFar: cameraVR.far
  13528. } );
  13529. _currentDepthNear = cameraVR.near;
  13530. _currentDepthFar = cameraVR.far;
  13531. }
  13532. const parent = camera.parent;
  13533. const cameras = cameraVR.cameras;
  13534. updateCamera( cameraVR, parent );
  13535. for ( let i = 0; i < cameras.length; i ++ ) {
  13536. updateCamera( cameras[ i ], parent );
  13537. }
  13538. // update camera and its children
  13539. camera.matrixWorld.copy( cameraVR.matrixWorld );
  13540. camera.matrix.copy( cameraVR.matrix );
  13541. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  13542. const children = camera.children;
  13543. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13544. children[ i ].updateMatrixWorld( true );
  13545. }
  13546. // update projection matrix for proper view frustum culling
  13547. if ( cameras.length === 2 ) {
  13548. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  13549. } else {
  13550. // assume single camera setup (AR)
  13551. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  13552. }
  13553. return cameraVR;
  13554. };
  13555. // Animation Loop
  13556. let onAnimationFrameCallback = null;
  13557. function onAnimationFrame( time, frame ) {
  13558. pose = frame.getViewerPose( referenceSpace );
  13559. if ( pose !== null ) {
  13560. const views = pose.views;
  13561. const baseLayer = session.renderState.baseLayer;
  13562. state.bindXRFramebuffer( baseLayer.framebuffer );
  13563. let cameraVRNeedsUpdate = false;
  13564. // check if it's necessary to rebuild cameraVR's camera list
  13565. if ( views.length !== cameraVR.cameras.length ) {
  13566. cameraVR.cameras.length = 0;
  13567. cameraVRNeedsUpdate = true;
  13568. }
  13569. for ( let i = 0; i < views.length; i ++ ) {
  13570. const view = views[ i ];
  13571. const viewport = baseLayer.getViewport( view );
  13572. const camera = cameras[ i ];
  13573. camera.matrix.fromArray( view.transform.matrix );
  13574. camera.projectionMatrix.fromArray( view.projectionMatrix );
  13575. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  13576. if ( i === 0 ) {
  13577. cameraVR.matrix.copy( camera.matrix );
  13578. }
  13579. if ( cameraVRNeedsUpdate === true ) {
  13580. cameraVR.cameras.push( camera );
  13581. }
  13582. }
  13583. }
  13584. //
  13585. const inputSources = session.inputSources;
  13586. for ( let i = 0; i < controllers.length; i ++ ) {
  13587. const controller = controllers[ i ];
  13588. const inputSource = inputSources[ i ];
  13589. controller.update( inputSource, frame, referenceSpace );
  13590. }
  13591. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  13592. }
  13593. const animation = new WebGLAnimation();
  13594. animation.setAnimationLoop( onAnimationFrame );
  13595. this.setAnimationLoop = function ( callback ) {
  13596. onAnimationFrameCallback = callback;
  13597. };
  13598. this.dispose = function () {};
  13599. }
  13600. }
  13601. function WebGLMaterials( properties ) {
  13602. function refreshFogUniforms( uniforms, fog ) {
  13603. uniforms.fogColor.value.copy( fog.color );
  13604. if ( fog.isFog ) {
  13605. uniforms.fogNear.value = fog.near;
  13606. uniforms.fogFar.value = fog.far;
  13607. } else if ( fog.isFogExp2 ) {
  13608. uniforms.fogDensity.value = fog.density;
  13609. }
  13610. }
  13611. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  13612. if ( material.isMeshBasicMaterial ) {
  13613. refreshUniformsCommon( uniforms, material );
  13614. } else if ( material.isMeshLambertMaterial ) {
  13615. refreshUniformsCommon( uniforms, material );
  13616. refreshUniformsLambert( uniforms, material );
  13617. } else if ( material.isMeshToonMaterial ) {
  13618. refreshUniformsCommon( uniforms, material );
  13619. refreshUniformsToon( uniforms, material );
  13620. } else if ( material.isMeshPhongMaterial ) {
  13621. refreshUniformsCommon( uniforms, material );
  13622. refreshUniformsPhong( uniforms, material );
  13623. } else if ( material.isMeshStandardMaterial ) {
  13624. refreshUniformsCommon( uniforms, material );
  13625. if ( material.isMeshPhysicalMaterial ) {
  13626. refreshUniformsPhysical( uniforms, material );
  13627. } else {
  13628. refreshUniformsStandard( uniforms, material );
  13629. }
  13630. } else if ( material.isMeshMatcapMaterial ) {
  13631. refreshUniformsCommon( uniforms, material );
  13632. refreshUniformsMatcap( uniforms, material );
  13633. } else if ( material.isMeshDepthMaterial ) {
  13634. refreshUniformsCommon( uniforms, material );
  13635. refreshUniformsDepth( uniforms, material );
  13636. } else if ( material.isMeshDistanceMaterial ) {
  13637. refreshUniformsCommon( uniforms, material );
  13638. refreshUniformsDistance( uniforms, material );
  13639. } else if ( material.isMeshNormalMaterial ) {
  13640. refreshUniformsCommon( uniforms, material );
  13641. refreshUniformsNormal( uniforms, material );
  13642. } else if ( material.isLineBasicMaterial ) {
  13643. refreshUniformsLine( uniforms, material );
  13644. if ( material.isLineDashedMaterial ) {
  13645. refreshUniformsDash( uniforms, material );
  13646. }
  13647. } else if ( material.isPointsMaterial ) {
  13648. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  13649. } else if ( material.isSpriteMaterial ) {
  13650. refreshUniformsSprites( uniforms, material );
  13651. } else if ( material.isShadowMaterial ) {
  13652. uniforms.color.value.copy( material.color );
  13653. uniforms.opacity.value = material.opacity;
  13654. } else if ( material.isShaderMaterial ) {
  13655. material.uniformsNeedUpdate = false; // #15581
  13656. }
  13657. }
  13658. function refreshUniformsCommon( uniforms, material ) {
  13659. uniforms.opacity.value = material.opacity;
  13660. if ( material.color ) {
  13661. uniforms.diffuse.value.copy( material.color );
  13662. }
  13663. if ( material.emissive ) {
  13664. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13665. }
  13666. if ( material.map ) {
  13667. uniforms.map.value = material.map;
  13668. }
  13669. if ( material.alphaMap ) {
  13670. uniforms.alphaMap.value = material.alphaMap;
  13671. }
  13672. if ( material.specularMap ) {
  13673. uniforms.specularMap.value = material.specularMap;
  13674. }
  13675. const envMap = properties.get( material ).envMap;
  13676. if ( envMap ) {
  13677. uniforms.envMap.value = envMap;
  13678. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  13679. uniforms.reflectivity.value = material.reflectivity;
  13680. uniforms.refractionRatio.value = material.refractionRatio;
  13681. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  13682. if ( maxMipLevel !== undefined ) {
  13683. uniforms.maxMipLevel.value = maxMipLevel;
  13684. }
  13685. }
  13686. if ( material.lightMap ) {
  13687. uniforms.lightMap.value = material.lightMap;
  13688. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13689. }
  13690. if ( material.aoMap ) {
  13691. uniforms.aoMap.value = material.aoMap;
  13692. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13693. }
  13694. // uv repeat and offset setting priorities
  13695. // 1. color map
  13696. // 2. specular map
  13697. // 3. displacementMap map
  13698. // 4. normal map
  13699. // 5. bump map
  13700. // 6. roughnessMap map
  13701. // 7. metalnessMap map
  13702. // 8. alphaMap map
  13703. // 9. emissiveMap map
  13704. // 10. clearcoat map
  13705. // 11. clearcoat normal map
  13706. // 12. clearcoat roughnessMap map
  13707. let uvScaleMap;
  13708. if ( material.map ) {
  13709. uvScaleMap = material.map;
  13710. } else if ( material.specularMap ) {
  13711. uvScaleMap = material.specularMap;
  13712. } else if ( material.displacementMap ) {
  13713. uvScaleMap = material.displacementMap;
  13714. } else if ( material.normalMap ) {
  13715. uvScaleMap = material.normalMap;
  13716. } else if ( material.bumpMap ) {
  13717. uvScaleMap = material.bumpMap;
  13718. } else if ( material.roughnessMap ) {
  13719. uvScaleMap = material.roughnessMap;
  13720. } else if ( material.metalnessMap ) {
  13721. uvScaleMap = material.metalnessMap;
  13722. } else if ( material.alphaMap ) {
  13723. uvScaleMap = material.alphaMap;
  13724. } else if ( material.emissiveMap ) {
  13725. uvScaleMap = material.emissiveMap;
  13726. } else if ( material.clearcoatMap ) {
  13727. uvScaleMap = material.clearcoatMap;
  13728. } else if ( material.clearcoatNormalMap ) {
  13729. uvScaleMap = material.clearcoatNormalMap;
  13730. } else if ( material.clearcoatRoughnessMap ) {
  13731. uvScaleMap = material.clearcoatRoughnessMap;
  13732. }
  13733. if ( uvScaleMap !== undefined ) {
  13734. // backwards compatibility
  13735. if ( uvScaleMap.isWebGLRenderTarget ) {
  13736. uvScaleMap = uvScaleMap.texture;
  13737. }
  13738. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13739. uvScaleMap.updateMatrix();
  13740. }
  13741. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13742. }
  13743. // uv repeat and offset setting priorities for uv2
  13744. // 1. ao map
  13745. // 2. light map
  13746. let uv2ScaleMap;
  13747. if ( material.aoMap ) {
  13748. uv2ScaleMap = material.aoMap;
  13749. } else if ( material.lightMap ) {
  13750. uv2ScaleMap = material.lightMap;
  13751. }
  13752. if ( uv2ScaleMap !== undefined ) {
  13753. // backwards compatibility
  13754. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  13755. uv2ScaleMap = uv2ScaleMap.texture;
  13756. }
  13757. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  13758. uv2ScaleMap.updateMatrix();
  13759. }
  13760. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  13761. }
  13762. }
  13763. function refreshUniformsLine( uniforms, material ) {
  13764. uniforms.diffuse.value.copy( material.color );
  13765. uniforms.opacity.value = material.opacity;
  13766. }
  13767. function refreshUniformsDash( uniforms, material ) {
  13768. uniforms.dashSize.value = material.dashSize;
  13769. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13770. uniforms.scale.value = material.scale;
  13771. }
  13772. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  13773. uniforms.diffuse.value.copy( material.color );
  13774. uniforms.opacity.value = material.opacity;
  13775. uniforms.size.value = material.size * pixelRatio;
  13776. uniforms.scale.value = height * 0.5;
  13777. if ( material.map ) {
  13778. uniforms.map.value = material.map;
  13779. }
  13780. if ( material.alphaMap ) {
  13781. uniforms.alphaMap.value = material.alphaMap;
  13782. }
  13783. // uv repeat and offset setting priorities
  13784. // 1. color map
  13785. // 2. alpha map
  13786. let uvScaleMap;
  13787. if ( material.map ) {
  13788. uvScaleMap = material.map;
  13789. } else if ( material.alphaMap ) {
  13790. uvScaleMap = material.alphaMap;
  13791. }
  13792. if ( uvScaleMap !== undefined ) {
  13793. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13794. uvScaleMap.updateMatrix();
  13795. }
  13796. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13797. }
  13798. }
  13799. function refreshUniformsSprites( uniforms, material ) {
  13800. uniforms.diffuse.value.copy( material.color );
  13801. uniforms.opacity.value = material.opacity;
  13802. uniforms.rotation.value = material.rotation;
  13803. if ( material.map ) {
  13804. uniforms.map.value = material.map;
  13805. }
  13806. if ( material.alphaMap ) {
  13807. uniforms.alphaMap.value = material.alphaMap;
  13808. }
  13809. // uv repeat and offset setting priorities
  13810. // 1. color map
  13811. // 2. alpha map
  13812. let uvScaleMap;
  13813. if ( material.map ) {
  13814. uvScaleMap = material.map;
  13815. } else if ( material.alphaMap ) {
  13816. uvScaleMap = material.alphaMap;
  13817. }
  13818. if ( uvScaleMap !== undefined ) {
  13819. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13820. uvScaleMap.updateMatrix();
  13821. }
  13822. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13823. }
  13824. }
  13825. function refreshUniformsLambert( uniforms, material ) {
  13826. if ( material.emissiveMap ) {
  13827. uniforms.emissiveMap.value = material.emissiveMap;
  13828. }
  13829. }
  13830. function refreshUniformsPhong( uniforms, material ) {
  13831. uniforms.specular.value.copy( material.specular );
  13832. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13833. if ( material.emissiveMap ) {
  13834. uniforms.emissiveMap.value = material.emissiveMap;
  13835. }
  13836. if ( material.bumpMap ) {
  13837. uniforms.bumpMap.value = material.bumpMap;
  13838. uniforms.bumpScale.value = material.bumpScale;
  13839. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13840. }
  13841. if ( material.normalMap ) {
  13842. uniforms.normalMap.value = material.normalMap;
  13843. uniforms.normalScale.value.copy( material.normalScale );
  13844. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13845. }
  13846. if ( material.displacementMap ) {
  13847. uniforms.displacementMap.value = material.displacementMap;
  13848. uniforms.displacementScale.value = material.displacementScale;
  13849. uniforms.displacementBias.value = material.displacementBias;
  13850. }
  13851. }
  13852. function refreshUniformsToon( uniforms, material ) {
  13853. if ( material.gradientMap ) {
  13854. uniforms.gradientMap.value = material.gradientMap;
  13855. }
  13856. if ( material.emissiveMap ) {
  13857. uniforms.emissiveMap.value = material.emissiveMap;
  13858. }
  13859. if ( material.bumpMap ) {
  13860. uniforms.bumpMap.value = material.bumpMap;
  13861. uniforms.bumpScale.value = material.bumpScale;
  13862. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13863. }
  13864. if ( material.normalMap ) {
  13865. uniforms.normalMap.value = material.normalMap;
  13866. uniforms.normalScale.value.copy( material.normalScale );
  13867. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13868. }
  13869. if ( material.displacementMap ) {
  13870. uniforms.displacementMap.value = material.displacementMap;
  13871. uniforms.displacementScale.value = material.displacementScale;
  13872. uniforms.displacementBias.value = material.displacementBias;
  13873. }
  13874. }
  13875. function refreshUniformsStandard( uniforms, material ) {
  13876. uniforms.roughness.value = material.roughness;
  13877. uniforms.metalness.value = material.metalness;
  13878. if ( material.roughnessMap ) {
  13879. uniforms.roughnessMap.value = material.roughnessMap;
  13880. }
  13881. if ( material.metalnessMap ) {
  13882. uniforms.metalnessMap.value = material.metalnessMap;
  13883. }
  13884. if ( material.emissiveMap ) {
  13885. uniforms.emissiveMap.value = material.emissiveMap;
  13886. }
  13887. if ( material.bumpMap ) {
  13888. uniforms.bumpMap.value = material.bumpMap;
  13889. uniforms.bumpScale.value = material.bumpScale;
  13890. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13891. }
  13892. if ( material.normalMap ) {
  13893. uniforms.normalMap.value = material.normalMap;
  13894. uniforms.normalScale.value.copy( material.normalScale );
  13895. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13896. }
  13897. if ( material.displacementMap ) {
  13898. uniforms.displacementMap.value = material.displacementMap;
  13899. uniforms.displacementScale.value = material.displacementScale;
  13900. uniforms.displacementBias.value = material.displacementBias;
  13901. }
  13902. const envMap = properties.get( material ).envMap;
  13903. if ( envMap ) {
  13904. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13905. uniforms.envMapIntensity.value = material.envMapIntensity;
  13906. }
  13907. }
  13908. function refreshUniformsPhysical( uniforms, material ) {
  13909. refreshUniformsStandard( uniforms, material );
  13910. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13911. uniforms.clearcoat.value = material.clearcoat;
  13912. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  13913. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  13914. if ( material.clearcoatMap ) {
  13915. uniforms.clearcoatMap.value = material.clearcoatMap;
  13916. }
  13917. if ( material.clearcoatRoughnessMap ) {
  13918. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  13919. }
  13920. if ( material.clearcoatNormalMap ) {
  13921. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  13922. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  13923. if ( material.side === BackSide ) {
  13924. uniforms.clearcoatNormalScale.value.negate();
  13925. }
  13926. }
  13927. uniforms.transmission.value = material.transmission;
  13928. if ( material.transmissionMap ) {
  13929. uniforms.transmissionMap.value = material.transmissionMap;
  13930. }
  13931. }
  13932. function refreshUniformsMatcap( uniforms, material ) {
  13933. if ( material.matcap ) {
  13934. uniforms.matcap.value = material.matcap;
  13935. }
  13936. if ( material.bumpMap ) {
  13937. uniforms.bumpMap.value = material.bumpMap;
  13938. uniforms.bumpScale.value = material.bumpScale;
  13939. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13940. }
  13941. if ( material.normalMap ) {
  13942. uniforms.normalMap.value = material.normalMap;
  13943. uniforms.normalScale.value.copy( material.normalScale );
  13944. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13945. }
  13946. if ( material.displacementMap ) {
  13947. uniforms.displacementMap.value = material.displacementMap;
  13948. uniforms.displacementScale.value = material.displacementScale;
  13949. uniforms.displacementBias.value = material.displacementBias;
  13950. }
  13951. }
  13952. function refreshUniformsDepth( uniforms, material ) {
  13953. if ( material.displacementMap ) {
  13954. uniforms.displacementMap.value = material.displacementMap;
  13955. uniforms.displacementScale.value = material.displacementScale;
  13956. uniforms.displacementBias.value = material.displacementBias;
  13957. }
  13958. }
  13959. function refreshUniformsDistance( uniforms, material ) {
  13960. if ( material.displacementMap ) {
  13961. uniforms.displacementMap.value = material.displacementMap;
  13962. uniforms.displacementScale.value = material.displacementScale;
  13963. uniforms.displacementBias.value = material.displacementBias;
  13964. }
  13965. uniforms.referencePosition.value.copy( material.referencePosition );
  13966. uniforms.nearDistance.value = material.nearDistance;
  13967. uniforms.farDistance.value = material.farDistance;
  13968. }
  13969. function refreshUniformsNormal( uniforms, material ) {
  13970. if ( material.bumpMap ) {
  13971. uniforms.bumpMap.value = material.bumpMap;
  13972. uniforms.bumpScale.value = material.bumpScale;
  13973. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13974. }
  13975. if ( material.normalMap ) {
  13976. uniforms.normalMap.value = material.normalMap;
  13977. uniforms.normalScale.value.copy( material.normalScale );
  13978. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13979. }
  13980. if ( material.displacementMap ) {
  13981. uniforms.displacementMap.value = material.displacementMap;
  13982. uniforms.displacementScale.value = material.displacementScale;
  13983. uniforms.displacementBias.value = material.displacementBias;
  13984. }
  13985. }
  13986. return {
  13987. refreshFogUniforms: refreshFogUniforms,
  13988. refreshMaterialUniforms: refreshMaterialUniforms
  13989. };
  13990. }
  13991. function createCanvasElement() {
  13992. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13993. canvas.style.display = 'block';
  13994. return canvas;
  13995. }
  13996. function WebGLRenderer( parameters ) {
  13997. parameters = parameters || {};
  13998. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  13999. _context = parameters.context !== undefined ? parameters.context : null,
  14000. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14001. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14002. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14003. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14004. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14005. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14006. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14007. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14008. let currentRenderList = null;
  14009. let currentRenderState = null;
  14010. // render() can be called from within a callback triggered by another render.
  14011. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14012. const renderListStack = [];
  14013. const renderStateStack = [];
  14014. // public properties
  14015. this.domElement = _canvas;
  14016. // Debug configuration container
  14017. this.debug = {
  14018. /**
  14019. * Enables error checking and reporting when shader programs are being compiled
  14020. * @type {boolean}
  14021. */
  14022. checkShaderErrors: true
  14023. };
  14024. // clearing
  14025. this.autoClear = true;
  14026. this.autoClearColor = true;
  14027. this.autoClearDepth = true;
  14028. this.autoClearStencil = true;
  14029. // scene graph
  14030. this.sortObjects = true;
  14031. // user-defined clipping
  14032. this.clippingPlanes = [];
  14033. this.localClippingEnabled = false;
  14034. // physically based shading
  14035. this.gammaFactor = 2.0; // for backwards compatibility
  14036. this.outputEncoding = LinearEncoding;
  14037. // physical lights
  14038. this.physicallyCorrectLights = false;
  14039. // tone mapping
  14040. this.toneMapping = NoToneMapping;
  14041. this.toneMappingExposure = 1.0;
  14042. // internal properties
  14043. const _this = this;
  14044. let _isContextLost = false;
  14045. // internal state cache
  14046. let _currentActiveCubeFace = 0;
  14047. let _currentActiveMipmapLevel = 0;
  14048. let _currentRenderTarget = null;
  14049. let _currentMaterialId = - 1;
  14050. let _currentCamera = null;
  14051. const _currentViewport = new Vector4();
  14052. const _currentScissor = new Vector4();
  14053. let _currentScissorTest = null;
  14054. //
  14055. let _width = _canvas.width;
  14056. let _height = _canvas.height;
  14057. let _pixelRatio = 1;
  14058. let _opaqueSort = null;
  14059. let _transparentSort = null;
  14060. const _viewport = new Vector4( 0, 0, _width, _height );
  14061. const _scissor = new Vector4( 0, 0, _width, _height );
  14062. let _scissorTest = false;
  14063. //
  14064. const _currentDrawBuffers = [];
  14065. // frustum
  14066. const _frustum = new Frustum();
  14067. // clipping
  14068. let _clippingEnabled = false;
  14069. let _localClippingEnabled = false;
  14070. // camera matrices cache
  14071. const _projScreenMatrix = new Matrix4();
  14072. const _vector3 = new Vector3();
  14073. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  14074. function getTargetPixelRatio() {
  14075. return _currentRenderTarget === null ? _pixelRatio : 1;
  14076. }
  14077. // initialize
  14078. let _gl = _context;
  14079. function getContext( contextNames, contextAttributes ) {
  14080. for ( let i = 0; i < contextNames.length; i ++ ) {
  14081. const contextName = contextNames[ i ];
  14082. const context = _canvas.getContext( contextName, contextAttributes );
  14083. if ( context !== null ) return context;
  14084. }
  14085. return null;
  14086. }
  14087. try {
  14088. const contextAttributes = {
  14089. alpha: _alpha,
  14090. depth: _depth,
  14091. stencil: _stencil,
  14092. antialias: _antialias,
  14093. premultipliedAlpha: _premultipliedAlpha,
  14094. preserveDrawingBuffer: _preserveDrawingBuffer,
  14095. powerPreference: _powerPreference,
  14096. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14097. };
  14098. // event listeners must be registered before WebGL context is created, see #12753
  14099. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14100. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14101. if ( _gl === null ) {
  14102. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14103. if ( _this.isWebGL1Renderer === true ) {
  14104. contextNames.shift();
  14105. }
  14106. _gl = getContext( contextNames, contextAttributes );
  14107. if ( _gl === null ) {
  14108. if ( getContext( contextNames ) ) {
  14109. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14110. } else {
  14111. throw new Error( 'Error creating WebGL context.' );
  14112. }
  14113. }
  14114. }
  14115. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14116. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14117. _gl.getShaderPrecisionFormat = function () {
  14118. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14119. };
  14120. }
  14121. } catch ( error ) {
  14122. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14123. throw error;
  14124. }
  14125. let extensions, capabilities, state, info;
  14126. let properties, textures, cubemaps, attributes, geometries, objects;
  14127. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14128. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14129. let utils, bindingStates;
  14130. function initGLContext() {
  14131. extensions = new WebGLExtensions( _gl );
  14132. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14133. extensions.init( capabilities );
  14134. utils = new WebGLUtils( _gl, extensions, capabilities );
  14135. state = new WebGLState( _gl, extensions, capabilities );
  14136. _currentDrawBuffers[ 0 ] = 1029;
  14137. info = new WebGLInfo( _gl );
  14138. properties = new WebGLProperties();
  14139. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14140. cubemaps = new WebGLCubeMaps( _this );
  14141. attributes = new WebGLAttributes( _gl, capabilities );
  14142. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14143. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14144. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14145. morphtargets = new WebGLMorphtargets( _gl );
  14146. clipping = new WebGLClipping( properties );
  14147. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14148. materials = new WebGLMaterials( properties );
  14149. renderLists = new WebGLRenderLists( properties );
  14150. renderStates = new WebGLRenderStates( extensions, capabilities );
  14151. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14152. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  14153. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14154. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14155. info.programs = programCache.programs;
  14156. _this.capabilities = capabilities;
  14157. _this.extensions = extensions;
  14158. _this.properties = properties;
  14159. _this.renderLists = renderLists;
  14160. _this.shadowMap = shadowMap;
  14161. _this.state = state;
  14162. _this.info = info;
  14163. }
  14164. initGLContext();
  14165. // xr
  14166. const xr = new WebXRManager( _this, _gl );
  14167. this.xr = xr;
  14168. // API
  14169. this.getContext = function () {
  14170. return _gl;
  14171. };
  14172. this.getContextAttributes = function () {
  14173. return _gl.getContextAttributes();
  14174. };
  14175. this.forceContextLoss = function () {
  14176. const extension = extensions.get( 'WEBGL_lose_context' );
  14177. if ( extension ) extension.loseContext();
  14178. };
  14179. this.forceContextRestore = function () {
  14180. const extension = extensions.get( 'WEBGL_lose_context' );
  14181. if ( extension ) extension.restoreContext();
  14182. };
  14183. this.getPixelRatio = function () {
  14184. return _pixelRatio;
  14185. };
  14186. this.setPixelRatio = function ( value ) {
  14187. if ( value === undefined ) return;
  14188. _pixelRatio = value;
  14189. this.setSize( _width, _height, false );
  14190. };
  14191. this.getSize = function ( target ) {
  14192. if ( target === undefined ) {
  14193. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  14194. target = new Vector2();
  14195. }
  14196. return target.set( _width, _height );
  14197. };
  14198. this.setSize = function ( width, height, updateStyle ) {
  14199. if ( xr.isPresenting ) {
  14200. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14201. return;
  14202. }
  14203. _width = width;
  14204. _height = height;
  14205. _canvas.width = Math.floor( width * _pixelRatio );
  14206. _canvas.height = Math.floor( height * _pixelRatio );
  14207. if ( updateStyle !== false ) {
  14208. _canvas.style.width = width + 'px';
  14209. _canvas.style.height = height + 'px';
  14210. }
  14211. this.setViewport( 0, 0, width, height );
  14212. };
  14213. this.getDrawingBufferSize = function ( target ) {
  14214. if ( target === undefined ) {
  14215. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  14216. target = new Vector2();
  14217. }
  14218. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14219. };
  14220. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14221. _width = width;
  14222. _height = height;
  14223. _pixelRatio = pixelRatio;
  14224. _canvas.width = Math.floor( width * pixelRatio );
  14225. _canvas.height = Math.floor( height * pixelRatio );
  14226. this.setViewport( 0, 0, width, height );
  14227. };
  14228. this.getCurrentViewport = function ( target ) {
  14229. if ( target === undefined ) {
  14230. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14231. target = new Vector4();
  14232. }
  14233. return target.copy( _currentViewport );
  14234. };
  14235. this.getViewport = function ( target ) {
  14236. return target.copy( _viewport );
  14237. };
  14238. this.setViewport = function ( x, y, width, height ) {
  14239. if ( x.isVector4 ) {
  14240. _viewport.set( x.x, x.y, x.z, x.w );
  14241. } else {
  14242. _viewport.set( x, y, width, height );
  14243. }
  14244. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14245. };
  14246. this.getScissor = function ( target ) {
  14247. return target.copy( _scissor );
  14248. };
  14249. this.setScissor = function ( x, y, width, height ) {
  14250. if ( x.isVector4 ) {
  14251. _scissor.set( x.x, x.y, x.z, x.w );
  14252. } else {
  14253. _scissor.set( x, y, width, height );
  14254. }
  14255. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14256. };
  14257. this.getScissorTest = function () {
  14258. return _scissorTest;
  14259. };
  14260. this.setScissorTest = function ( boolean ) {
  14261. state.setScissorTest( _scissorTest = boolean );
  14262. };
  14263. this.setOpaqueSort = function ( method ) {
  14264. _opaqueSort = method;
  14265. };
  14266. this.setTransparentSort = function ( method ) {
  14267. _transparentSort = method;
  14268. };
  14269. // Clearing
  14270. this.getClearColor = function ( target ) {
  14271. if ( target === undefined ) {
  14272. console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
  14273. target = new Color();
  14274. }
  14275. return target.copy( background.getClearColor() );
  14276. };
  14277. this.setClearColor = function () {
  14278. background.setClearColor.apply( background, arguments );
  14279. };
  14280. this.getClearAlpha = function () {
  14281. return background.getClearAlpha();
  14282. };
  14283. this.setClearAlpha = function () {
  14284. background.setClearAlpha.apply( background, arguments );
  14285. };
  14286. this.clear = function ( color, depth, stencil ) {
  14287. let bits = 0;
  14288. if ( color === undefined || color ) bits |= 16384;
  14289. if ( depth === undefined || depth ) bits |= 256;
  14290. if ( stencil === undefined || stencil ) bits |= 1024;
  14291. _gl.clear( bits );
  14292. };
  14293. this.clearColor = function () {
  14294. this.clear( true, false, false );
  14295. };
  14296. this.clearDepth = function () {
  14297. this.clear( false, true, false );
  14298. };
  14299. this.clearStencil = function () {
  14300. this.clear( false, false, true );
  14301. };
  14302. //
  14303. this.dispose = function () {
  14304. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14305. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14306. renderLists.dispose();
  14307. renderStates.dispose();
  14308. properties.dispose();
  14309. cubemaps.dispose();
  14310. objects.dispose();
  14311. bindingStates.dispose();
  14312. xr.dispose();
  14313. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  14314. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  14315. animation.stop();
  14316. };
  14317. // Events
  14318. function onContextLost( event ) {
  14319. event.preventDefault();
  14320. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14321. _isContextLost = true;
  14322. }
  14323. function onContextRestore( /* event */ ) {
  14324. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14325. _isContextLost = false;
  14326. const infoAutoReset = info.autoReset;
  14327. const shadowMapEnabled = shadowMap.enabled;
  14328. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14329. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14330. const shadowMapType = shadowMap.type;
  14331. initGLContext();
  14332. info.autoReset = infoAutoReset;
  14333. shadowMap.enabled = shadowMapEnabled;
  14334. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14335. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14336. shadowMap.type = shadowMapType;
  14337. }
  14338. function onMaterialDispose( event ) {
  14339. const material = event.target;
  14340. material.removeEventListener( 'dispose', onMaterialDispose );
  14341. deallocateMaterial( material );
  14342. }
  14343. // Buffer deallocation
  14344. function deallocateMaterial( material ) {
  14345. releaseMaterialProgramReferences( material );
  14346. properties.remove( material );
  14347. }
  14348. function releaseMaterialProgramReferences( material ) {
  14349. const programs = properties.get( material ).programs;
  14350. if ( programs !== undefined ) {
  14351. programs.forEach( function ( program ) {
  14352. programCache.releaseProgram( program );
  14353. } );
  14354. }
  14355. }
  14356. // Buffer rendering
  14357. function renderObjectImmediate( object, program ) {
  14358. object.render( function ( object ) {
  14359. _this.renderBufferImmediate( object, program );
  14360. } );
  14361. }
  14362. this.renderBufferImmediate = function ( object, program ) {
  14363. bindingStates.initAttributes();
  14364. const buffers = properties.get( object );
  14365. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14366. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14367. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14368. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14369. const programAttributes = program.getAttributes();
  14370. if ( object.hasPositions ) {
  14371. _gl.bindBuffer( 34962, buffers.position );
  14372. _gl.bufferData( 34962, object.positionArray, 35048 );
  14373. bindingStates.enableAttribute( programAttributes.position );
  14374. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  14375. }
  14376. if ( object.hasNormals ) {
  14377. _gl.bindBuffer( 34962, buffers.normal );
  14378. _gl.bufferData( 34962, object.normalArray, 35048 );
  14379. bindingStates.enableAttribute( programAttributes.normal );
  14380. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  14381. }
  14382. if ( object.hasUvs ) {
  14383. _gl.bindBuffer( 34962, buffers.uv );
  14384. _gl.bufferData( 34962, object.uvArray, 35048 );
  14385. bindingStates.enableAttribute( programAttributes.uv );
  14386. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  14387. }
  14388. if ( object.hasColors ) {
  14389. _gl.bindBuffer( 34962, buffers.color );
  14390. _gl.bufferData( 34962, object.colorArray, 35048 );
  14391. bindingStates.enableAttribute( programAttributes.color );
  14392. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  14393. }
  14394. bindingStates.disableUnusedAttributes();
  14395. _gl.drawArrays( 4, 0, object.count );
  14396. object.count = 0;
  14397. };
  14398. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  14399. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14400. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  14401. const program = setProgram( camera, scene, material, object );
  14402. state.setMaterial( material, frontFaceCW );
  14403. //
  14404. let index = geometry.index;
  14405. const position = geometry.attributes.position;
  14406. //
  14407. if ( index === null ) {
  14408. if ( position === undefined || position.count === 0 ) return;
  14409. } else if ( index.count === 0 ) {
  14410. return;
  14411. }
  14412. //
  14413. let rangeFactor = 1;
  14414. if ( material.wireframe === true ) {
  14415. index = geometries.getWireframeAttribute( geometry );
  14416. rangeFactor = 2;
  14417. }
  14418. if ( material.morphTargets || material.morphNormals ) {
  14419. morphtargets.update( object, geometry, material, program );
  14420. }
  14421. bindingStates.setup( object, material, program, geometry, index );
  14422. let attribute;
  14423. let renderer = bufferRenderer;
  14424. if ( index !== null ) {
  14425. attribute = attributes.get( index );
  14426. renderer = indexedBufferRenderer;
  14427. renderer.setIndex( attribute );
  14428. }
  14429. //
  14430. const dataCount = ( index !== null ) ? index.count : position.count;
  14431. const rangeStart = geometry.drawRange.start * rangeFactor;
  14432. const rangeCount = geometry.drawRange.count * rangeFactor;
  14433. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14434. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14435. const drawStart = Math.max( rangeStart, groupStart );
  14436. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  14437. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  14438. if ( drawCount === 0 ) return;
  14439. //
  14440. if ( object.isMesh ) {
  14441. if ( material.wireframe === true ) {
  14442. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  14443. renderer.setMode( 1 );
  14444. } else {
  14445. renderer.setMode( 4 );
  14446. }
  14447. } else if ( object.isLine ) {
  14448. let lineWidth = material.linewidth;
  14449. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  14450. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  14451. if ( object.isLineSegments ) {
  14452. renderer.setMode( 1 );
  14453. } else if ( object.isLineLoop ) {
  14454. renderer.setMode( 2 );
  14455. } else {
  14456. renderer.setMode( 3 );
  14457. }
  14458. } else if ( object.isPoints ) {
  14459. renderer.setMode( 0 );
  14460. } else if ( object.isSprite ) {
  14461. renderer.setMode( 4 );
  14462. }
  14463. if ( object.isInstancedMesh ) {
  14464. renderer.renderInstances( drawStart, drawCount, object.count );
  14465. } else if ( geometry.isInstancedBufferGeometry ) {
  14466. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  14467. renderer.renderInstances( drawStart, drawCount, instanceCount );
  14468. } else {
  14469. renderer.render( drawStart, drawCount );
  14470. }
  14471. };
  14472. // Compile
  14473. this.compile = function ( scene, camera ) {
  14474. currentRenderState = renderStates.get( scene );
  14475. currentRenderState.init();
  14476. scene.traverseVisible( function ( object ) {
  14477. if ( object.isLight && object.layers.test( camera.layers ) ) {
  14478. currentRenderState.pushLight( object );
  14479. if ( object.castShadow ) {
  14480. currentRenderState.pushShadow( object );
  14481. }
  14482. }
  14483. } );
  14484. currentRenderState.setupLights();
  14485. scene.traverse( function ( object ) {
  14486. const material = object.material;
  14487. if ( material ) {
  14488. if ( Array.isArray( material ) ) {
  14489. for ( let i = 0; i < material.length; i ++ ) {
  14490. const material2 = material[ i ];
  14491. getProgram( material2, scene, object );
  14492. }
  14493. } else {
  14494. getProgram( material, scene, object );
  14495. }
  14496. }
  14497. } );
  14498. };
  14499. // Animation Loop
  14500. let onAnimationFrameCallback = null;
  14501. function onAnimationFrame( time ) {
  14502. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  14503. }
  14504. function onXRSessionStart() {
  14505. animation.stop();
  14506. }
  14507. function onXRSessionEnd() {
  14508. animation.start();
  14509. }
  14510. const animation = new WebGLAnimation();
  14511. animation.setAnimationLoop( onAnimationFrame );
  14512. if ( typeof window !== 'undefined' ) animation.setContext( window );
  14513. this.setAnimationLoop = function ( callback ) {
  14514. onAnimationFrameCallback = callback;
  14515. xr.setAnimationLoop( callback );
  14516. ( callback === null ) ? animation.stop() : animation.start();
  14517. };
  14518. xr.addEventListener( 'sessionstart', onXRSessionStart );
  14519. xr.addEventListener( 'sessionend', onXRSessionEnd );
  14520. // Rendering
  14521. this.render = function ( scene, camera ) {
  14522. if ( camera !== undefined && camera.isCamera !== true ) {
  14523. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14524. return;
  14525. }
  14526. if ( _isContextLost === true ) return;
  14527. // update scene graph
  14528. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14529. // update camera matrices and frustum
  14530. if ( camera.parent === null ) camera.updateMatrixWorld();
  14531. if ( xr.enabled === true && xr.isPresenting === true ) {
  14532. camera = xr.getCamera( camera );
  14533. }
  14534. //
  14535. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  14536. currentRenderState = renderStates.get( scene, renderStateStack.length );
  14537. currentRenderState.init();
  14538. renderStateStack.push( currentRenderState );
  14539. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14540. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  14541. _localClippingEnabled = this.localClippingEnabled;
  14542. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  14543. currentRenderList = renderLists.get( scene, renderListStack.length );
  14544. currentRenderList.init();
  14545. renderListStack.push( currentRenderList );
  14546. projectObject( scene, camera, 0, _this.sortObjects );
  14547. currentRenderList.finish();
  14548. if ( _this.sortObjects === true ) {
  14549. currentRenderList.sort( _opaqueSort, _transparentSort );
  14550. }
  14551. //
  14552. if ( _clippingEnabled === true ) clipping.beginShadows();
  14553. const shadowsArray = currentRenderState.state.shadowsArray;
  14554. shadowMap.render( shadowsArray, scene, camera );
  14555. currentRenderState.setupLights();
  14556. currentRenderState.setupLightsView( camera );
  14557. if ( _clippingEnabled === true ) clipping.endShadows();
  14558. //
  14559. if ( this.info.autoReset === true ) this.info.reset();
  14560. //
  14561. background.render( currentRenderList, scene );
  14562. // render scene
  14563. const opaqueObjects = currentRenderList.opaque;
  14564. const transparentObjects = currentRenderList.transparent;
  14565. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  14566. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  14567. //
  14568. if ( _currentRenderTarget !== null ) {
  14569. // Generate mipmap if we're using any kind of mipmap filtering
  14570. textures.updateRenderTargetMipmap( _currentRenderTarget );
  14571. // resolve multisample renderbuffers to a single-sample texture if necessary
  14572. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  14573. }
  14574. //
  14575. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  14576. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14577. state.buffers.depth.setTest( true );
  14578. state.buffers.depth.setMask( true );
  14579. state.buffers.color.setMask( true );
  14580. state.setPolygonOffset( false );
  14581. // _gl.finish();
  14582. bindingStates.resetDefaultState();
  14583. _currentMaterialId = - 1;
  14584. _currentCamera = null;
  14585. renderStateStack.pop();
  14586. if ( renderStateStack.length > 0 ) {
  14587. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  14588. } else {
  14589. currentRenderState = null;
  14590. }
  14591. renderListStack.pop();
  14592. if ( renderListStack.length > 0 ) {
  14593. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  14594. } else {
  14595. currentRenderList = null;
  14596. }
  14597. };
  14598. function projectObject( object, camera, groupOrder, sortObjects ) {
  14599. if ( object.visible === false ) return;
  14600. const visible = object.layers.test( camera.layers );
  14601. if ( visible ) {
  14602. if ( object.isGroup ) {
  14603. groupOrder = object.renderOrder;
  14604. } else if ( object.isLOD ) {
  14605. if ( object.autoUpdate === true ) object.update( camera );
  14606. } else if ( object.isLight ) {
  14607. currentRenderState.pushLight( object );
  14608. if ( object.castShadow ) {
  14609. currentRenderState.pushShadow( object );
  14610. }
  14611. } else if ( object.isSprite ) {
  14612. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  14613. if ( sortObjects ) {
  14614. _vector3.setFromMatrixPosition( object.matrixWorld )
  14615. .applyMatrix4( _projScreenMatrix );
  14616. }
  14617. const geometry = objects.update( object );
  14618. const material = object.material;
  14619. if ( material.visible ) {
  14620. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14621. }
  14622. }
  14623. } else if ( object.isImmediateRenderObject ) {
  14624. if ( sortObjects ) {
  14625. _vector3.setFromMatrixPosition( object.matrixWorld )
  14626. .applyMatrix4( _projScreenMatrix );
  14627. }
  14628. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  14629. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  14630. if ( object.isSkinnedMesh ) {
  14631. // update skeleton only once in a frame
  14632. if ( object.skeleton.frame !== info.render.frame ) {
  14633. object.skeleton.update();
  14634. object.skeleton.frame = info.render.frame;
  14635. }
  14636. }
  14637. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  14638. if ( sortObjects ) {
  14639. _vector3.setFromMatrixPosition( object.matrixWorld )
  14640. .applyMatrix4( _projScreenMatrix );
  14641. }
  14642. const geometry = objects.update( object );
  14643. const material = object.material;
  14644. if ( Array.isArray( material ) ) {
  14645. const groups = geometry.groups;
  14646. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14647. const group = groups[ i ];
  14648. const groupMaterial = material[ group.materialIndex ];
  14649. if ( groupMaterial && groupMaterial.visible ) {
  14650. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  14651. }
  14652. }
  14653. } else if ( material.visible ) {
  14654. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14655. }
  14656. }
  14657. }
  14658. }
  14659. const children = object.children;
  14660. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14661. projectObject( children[ i ], camera, groupOrder, sortObjects );
  14662. }
  14663. }
  14664. function renderObjects( renderList, scene, camera ) {
  14665. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14666. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  14667. const renderItem = renderList[ i ];
  14668. const object = renderItem.object;
  14669. const geometry = renderItem.geometry;
  14670. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14671. const group = renderItem.group;
  14672. if ( camera.isArrayCamera ) {
  14673. const cameras = camera.cameras;
  14674. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  14675. const camera2 = cameras[ j ];
  14676. if ( object.layers.test( camera2.layers ) ) {
  14677. state.viewport( _currentViewport.copy( camera2.viewport ) );
  14678. currentRenderState.setupLightsView( camera2 );
  14679. renderObject( object, scene, camera2, geometry, material, group );
  14680. }
  14681. }
  14682. } else {
  14683. renderObject( object, scene, camera, geometry, material, group );
  14684. }
  14685. }
  14686. }
  14687. function renderObject( object, scene, camera, geometry, material, group ) {
  14688. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  14689. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14690. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  14691. if ( object.isImmediateRenderObject ) {
  14692. const program = setProgram( camera, scene, material, object );
  14693. state.setMaterial( material );
  14694. bindingStates.reset();
  14695. renderObjectImmediate( object, program );
  14696. } else {
  14697. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  14698. }
  14699. object.onAfterRender( _this, scene, camera, geometry, material, group );
  14700. }
  14701. function getProgram( material, scene, object ) {
  14702. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14703. const materialProperties = properties.get( material );
  14704. const lights = currentRenderState.state.lights;
  14705. const shadowsArray = currentRenderState.state.shadowsArray;
  14706. const lightsStateVersion = lights.state.version;
  14707. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  14708. const programCacheKey = programCache.getProgramCacheKey( parameters );
  14709. let programs = materialProperties.programs;
  14710. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  14711. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14712. materialProperties.fog = scene.fog;
  14713. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  14714. if ( programs === undefined ) {
  14715. // new material
  14716. material.addEventListener( 'dispose', onMaterialDispose );
  14717. programs = new Map();
  14718. materialProperties.programs = programs;
  14719. }
  14720. let program = programs.get( programCacheKey );
  14721. if ( program !== undefined ) {
  14722. // early out if program and light state is identical
  14723. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  14724. updateCommonMaterialProperties( material, parameters );
  14725. return program;
  14726. }
  14727. } else {
  14728. parameters.uniforms = programCache.getUniforms( material );
  14729. material.onBuild( parameters, _this );
  14730. material.onBeforeCompile( parameters, _this );
  14731. program = programCache.acquireProgram( parameters, programCacheKey );
  14732. programs.set( programCacheKey, program );
  14733. materialProperties.uniforms = parameters.uniforms;
  14734. }
  14735. const uniforms = materialProperties.uniforms;
  14736. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  14737. uniforms.clippingPlanes = clipping.uniform;
  14738. }
  14739. updateCommonMaterialProperties( material, parameters );
  14740. // store the light setup it was created for
  14741. materialProperties.needsLights = materialNeedsLights( material );
  14742. materialProperties.lightsStateVersion = lightsStateVersion;
  14743. if ( materialProperties.needsLights ) {
  14744. // wire up the material to this renderer's lighting state
  14745. uniforms.ambientLightColor.value = lights.state.ambient;
  14746. uniforms.lightProbe.value = lights.state.probe;
  14747. uniforms.directionalLights.value = lights.state.directional;
  14748. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14749. uniforms.spotLights.value = lights.state.spot;
  14750. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14751. uniforms.rectAreaLights.value = lights.state.rectArea;
  14752. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14753. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14754. uniforms.pointLights.value = lights.state.point;
  14755. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14756. uniforms.hemisphereLights.value = lights.state.hemi;
  14757. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14758. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14759. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14760. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14761. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14762. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  14763. // TODO (abelnation): add area lights shadow info to uniforms
  14764. }
  14765. const progUniforms = program.getUniforms();
  14766. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  14767. materialProperties.currentProgram = program;
  14768. materialProperties.uniformsList = uniformsList;
  14769. return program;
  14770. }
  14771. function updateCommonMaterialProperties( material, parameters ) {
  14772. const materialProperties = properties.get( material );
  14773. materialProperties.outputEncoding = parameters.outputEncoding;
  14774. materialProperties.instancing = parameters.instancing;
  14775. materialProperties.skinning = parameters.skinning;
  14776. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14777. materialProperties.numIntersection = parameters.numClipIntersection;
  14778. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14779. }
  14780. function setProgram( camera, scene, material, object ) {
  14781. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14782. textures.resetTextureUnits();
  14783. const fog = scene.fog;
  14784. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14785. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14786. const envMap = cubemaps.get( material.envMap || environment );
  14787. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14788. const materialProperties = properties.get( material );
  14789. const lights = currentRenderState.state.lights;
  14790. if ( _clippingEnabled === true ) {
  14791. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  14792. const useCache =
  14793. camera === _currentCamera &&
  14794. material.id === _currentMaterialId;
  14795. // we might want to call this function with some ClippingGroup
  14796. // object instead of the material, once it becomes feasible
  14797. // (#8465, #8379)
  14798. clipping.setState( material, camera, useCache );
  14799. }
  14800. }
  14801. //
  14802. let needsProgramChange = false;
  14803. if ( material.version === materialProperties.__version ) {
  14804. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  14805. needsProgramChange = true;
  14806. } else if ( materialProperties.outputEncoding !== encoding ) {
  14807. needsProgramChange = true;
  14808. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  14809. needsProgramChange = true;
  14810. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  14811. needsProgramChange = true;
  14812. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  14813. needsProgramChange = true;
  14814. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  14815. needsProgramChange = true;
  14816. } else if ( materialProperties.envMap !== envMap ) {
  14817. needsProgramChange = true;
  14818. } else if ( material.fog && materialProperties.fog !== fog ) {
  14819. needsProgramChange = true;
  14820. } else if ( materialProperties.numClippingPlanes !== undefined &&
  14821. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  14822. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  14823. needsProgramChange = true;
  14824. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  14825. needsProgramChange = true;
  14826. }
  14827. } else {
  14828. needsProgramChange = true;
  14829. materialProperties.__version = material.version;
  14830. }
  14831. //
  14832. let program = materialProperties.currentProgram;
  14833. if ( needsProgramChange === true ) {
  14834. program = getProgram( material, scene, object );
  14835. }
  14836. let refreshProgram = false;
  14837. let refreshMaterial = false;
  14838. let refreshLights = false;
  14839. const p_uniforms = program.getUniforms(),
  14840. m_uniforms = materialProperties.uniforms;
  14841. if ( state.useProgram( program.program ) ) {
  14842. refreshProgram = true;
  14843. refreshMaterial = true;
  14844. refreshLights = true;
  14845. }
  14846. if ( material.id !== _currentMaterialId ) {
  14847. _currentMaterialId = material.id;
  14848. refreshMaterial = true;
  14849. }
  14850. if ( refreshProgram || _currentCamera !== camera ) {
  14851. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  14852. if ( capabilities.logarithmicDepthBuffer ) {
  14853. p_uniforms.setValue( _gl, 'logDepthBufFC',
  14854. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  14855. }
  14856. if ( _currentCamera !== camera ) {
  14857. _currentCamera = camera;
  14858. // lighting uniforms depend on the camera so enforce an update
  14859. // now, in case this material supports lights - or later, when
  14860. // the next material that does gets activated:
  14861. refreshMaterial = true; // set to true on material change
  14862. refreshLights = true; // remains set until update done
  14863. }
  14864. // load material specific uniforms
  14865. // (shader material also gets them for the sake of genericity)
  14866. if ( material.isShaderMaterial ||
  14867. material.isMeshPhongMaterial ||
  14868. material.isMeshToonMaterial ||
  14869. material.isMeshStandardMaterial ||
  14870. material.envMap ) {
  14871. const uCamPos = p_uniforms.map.cameraPosition;
  14872. if ( uCamPos !== undefined ) {
  14873. uCamPos.setValue( _gl,
  14874. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  14875. }
  14876. }
  14877. if ( material.isMeshPhongMaterial ||
  14878. material.isMeshToonMaterial ||
  14879. material.isMeshLambertMaterial ||
  14880. material.isMeshBasicMaterial ||
  14881. material.isMeshStandardMaterial ||
  14882. material.isShaderMaterial ) {
  14883. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  14884. }
  14885. if ( material.isMeshPhongMaterial ||
  14886. material.isMeshToonMaterial ||
  14887. material.isMeshLambertMaterial ||
  14888. material.isMeshBasicMaterial ||
  14889. material.isMeshStandardMaterial ||
  14890. material.isShaderMaterial ||
  14891. material.isShadowMaterial ||
  14892. object.isSkinnedMesh ) {
  14893. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  14894. }
  14895. }
  14896. // skinning uniforms must be set even if material didn't change
  14897. // auto-setting of texture unit for bone texture must go before other textures
  14898. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14899. if ( object.isSkinnedMesh ) {
  14900. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  14901. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  14902. const skeleton = object.skeleton;
  14903. if ( skeleton ) {
  14904. const bones = skeleton.bones;
  14905. if ( capabilities.floatVertexTextures ) {
  14906. if ( skeleton.boneTexture === null ) {
  14907. // layout (1 matrix = 4 pixels)
  14908. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14909. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14910. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14911. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14912. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14913. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  14914. size = ceilPowerOfTwo( size );
  14915. size = Math.max( size, 4 );
  14916. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14917. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  14918. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14919. skeleton.boneMatrices = boneMatrices;
  14920. skeleton.boneTexture = boneTexture;
  14921. skeleton.boneTextureSize = size;
  14922. }
  14923. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  14924. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  14925. } else {
  14926. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  14927. }
  14928. }
  14929. }
  14930. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  14931. materialProperties.receiveShadow = object.receiveShadow;
  14932. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  14933. }
  14934. if ( refreshMaterial ) {
  14935. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  14936. if ( materialProperties.needsLights ) {
  14937. // the current material requires lighting info
  14938. // note: all lighting uniforms are always set correctly
  14939. // they simply reference the renderer's state for their
  14940. // values
  14941. //
  14942. // use the current material's .needsUpdate flags to set
  14943. // the GL state when required
  14944. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  14945. }
  14946. // refresh uniforms common to several materials
  14947. if ( fog && material.fog ) {
  14948. materials.refreshFogUniforms( m_uniforms, fog );
  14949. }
  14950. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  14951. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14952. }
  14953. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  14954. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14955. material.uniformsNeedUpdate = false;
  14956. }
  14957. if ( material.isSpriteMaterial ) {
  14958. p_uniforms.setValue( _gl, 'center', object.center );
  14959. }
  14960. // common matrices
  14961. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  14962. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  14963. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  14964. return program;
  14965. }
  14966. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14967. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  14968. uniforms.ambientLightColor.needsUpdate = value;
  14969. uniforms.lightProbe.needsUpdate = value;
  14970. uniforms.directionalLights.needsUpdate = value;
  14971. uniforms.directionalLightShadows.needsUpdate = value;
  14972. uniforms.pointLights.needsUpdate = value;
  14973. uniforms.pointLightShadows.needsUpdate = value;
  14974. uniforms.spotLights.needsUpdate = value;
  14975. uniforms.spotLightShadows.needsUpdate = value;
  14976. uniforms.rectAreaLights.needsUpdate = value;
  14977. uniforms.hemisphereLights.needsUpdate = value;
  14978. }
  14979. function materialNeedsLights( material ) {
  14980. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  14981. material.isMeshStandardMaterial || material.isShadowMaterial ||
  14982. ( material.isShaderMaterial && material.lights === true );
  14983. }
  14984. this.getActiveCubeFace = function () {
  14985. return _currentActiveCubeFace;
  14986. };
  14987. this.getActiveMipmapLevel = function () {
  14988. return _currentActiveMipmapLevel;
  14989. };
  14990. this.getRenderTarget = function () {
  14991. return _currentRenderTarget;
  14992. };
  14993. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  14994. _currentRenderTarget = renderTarget;
  14995. _currentActiveCubeFace = activeCubeFace;
  14996. _currentActiveMipmapLevel = activeMipmapLevel;
  14997. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  14998. textures.setupRenderTarget( renderTarget );
  14999. }
  15000. let framebuffer = null;
  15001. let isCube = false;
  15002. let isRenderTarget3D = false;
  15003. if ( renderTarget ) {
  15004. const texture = renderTarget.texture;
  15005. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  15006. isRenderTarget3D = true;
  15007. }
  15008. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15009. if ( renderTarget.isWebGLCubeRenderTarget ) {
  15010. framebuffer = __webglFramebuffer[ activeCubeFace ];
  15011. isCube = true;
  15012. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15013. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  15014. } else {
  15015. framebuffer = __webglFramebuffer;
  15016. }
  15017. _currentViewport.copy( renderTarget.viewport );
  15018. _currentScissor.copy( renderTarget.scissor );
  15019. _currentScissorTest = renderTarget.scissorTest;
  15020. } else {
  15021. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  15022. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  15023. _currentScissorTest = _scissorTest;
  15024. }
  15025. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  15026. if ( framebufferBound && capabilities.drawBuffers ) {
  15027. let needsUpdate = false;
  15028. if ( renderTarget ) {
  15029. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  15030. const textures = renderTarget.texture;
  15031. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  15032. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15033. _currentDrawBuffers[ i ] = 36064 + i;
  15034. }
  15035. _currentDrawBuffers.length = textures.length;
  15036. needsUpdate = true;
  15037. }
  15038. } else {
  15039. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  15040. _currentDrawBuffers[ 0 ] = 36064;
  15041. _currentDrawBuffers.length = 1;
  15042. needsUpdate = true;
  15043. }
  15044. }
  15045. } else {
  15046. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  15047. _currentDrawBuffers[ 0 ] = 1029;
  15048. _currentDrawBuffers.length = 1;
  15049. needsUpdate = true;
  15050. }
  15051. }
  15052. if ( needsUpdate ) {
  15053. if ( capabilities.isWebGL2 ) {
  15054. _gl.drawBuffers( _currentDrawBuffers );
  15055. } else {
  15056. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  15057. }
  15058. }
  15059. }
  15060. state.viewport( _currentViewport );
  15061. state.scissor( _currentScissor );
  15062. state.setScissorTest( _currentScissorTest );
  15063. if ( isCube ) {
  15064. const textureProperties = properties.get( renderTarget.texture );
  15065. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  15066. } else if ( isRenderTarget3D ) {
  15067. const textureProperties = properties.get( renderTarget.texture );
  15068. const layer = activeCubeFace || 0;
  15069. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  15070. }
  15071. };
  15072. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  15073. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  15074. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  15075. return;
  15076. }
  15077. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15078. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  15079. framebuffer = framebuffer[ activeCubeFaceIndex ];
  15080. }
  15081. if ( framebuffer ) {
  15082. state.bindFramebuffer( 36160, framebuffer );
  15083. try {
  15084. const texture = renderTarget.texture;
  15085. const textureFormat = texture.format;
  15086. const textureType = texture.type;
  15087. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  15088. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  15089. return;
  15090. }
  15091. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  15092. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  15093. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  15094. ! halfFloatSupportedByExt ) {
  15095. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  15096. return;
  15097. }
  15098. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  15099. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15100. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  15101. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  15102. }
  15103. } else {
  15104. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  15105. }
  15106. } finally {
  15107. // restore framebuffer of current render target if necessary
  15108. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  15109. state.bindFramebuffer( 36160, framebuffer );
  15110. }
  15111. }
  15112. };
  15113. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  15114. const levelScale = Math.pow( 2, - level );
  15115. const width = Math.floor( texture.image.width * levelScale );
  15116. const height = Math.floor( texture.image.height * levelScale );
  15117. const glFormat = utils.convert( texture.format );
  15118. textures.setTexture2D( texture, 0 );
  15119. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  15120. state.unbindTexture();
  15121. };
  15122. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  15123. const width = srcTexture.image.width;
  15124. const height = srcTexture.image.height;
  15125. const glFormat = utils.convert( dstTexture.format );
  15126. const glType = utils.convert( dstTexture.type );
  15127. textures.setTexture2D( dstTexture, 0 );
  15128. // As another texture upload may have changed pixelStorei
  15129. // parameters, make sure they are correct for the dstTexture
  15130. _gl.pixelStorei( 37440, dstTexture.flipY );
  15131. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15132. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15133. if ( srcTexture.isDataTexture ) {
  15134. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  15135. } else {
  15136. if ( srcTexture.isCompressedTexture ) {
  15137. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  15138. } else {
  15139. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  15140. }
  15141. }
  15142. // Generate mipmaps only when copying level 0
  15143. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15144. state.unbindTexture();
  15145. };
  15146. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  15147. if ( _this.isWebGL1Renderer ) {
  15148. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  15149. return;
  15150. }
  15151. const { width, height, data } = srcTexture.image;
  15152. const glFormat = utils.convert( dstTexture.format );
  15153. const glType = utils.convert( dstTexture.type );
  15154. let glTarget;
  15155. if ( dstTexture.isDataTexture3D ) {
  15156. textures.setTexture3D( dstTexture, 0 );
  15157. glTarget = 32879;
  15158. } else if ( dstTexture.isDataTexture2DArray ) {
  15159. textures.setTexture2DArray( dstTexture, 0 );
  15160. glTarget = 35866;
  15161. } else {
  15162. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  15163. return;
  15164. }
  15165. _gl.pixelStorei( 37440, dstTexture.flipY );
  15166. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15167. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15168. const unpackRowLen = _gl.getParameter( 3314 );
  15169. const unpackImageHeight = _gl.getParameter( 32878 );
  15170. const unpackSkipPixels = _gl.getParameter( 3316 );
  15171. const unpackSkipRows = _gl.getParameter( 3315 );
  15172. const unpackSkipImages = _gl.getParameter( 32877 );
  15173. _gl.pixelStorei( 3314, width );
  15174. _gl.pixelStorei( 32878, height );
  15175. _gl.pixelStorei( 3316, sourceBox.min.x );
  15176. _gl.pixelStorei( 3315, sourceBox.min.y );
  15177. _gl.pixelStorei( 32877, sourceBox.min.z );
  15178. _gl.texSubImage3D(
  15179. glTarget,
  15180. level,
  15181. position.x,
  15182. position.y,
  15183. position.z,
  15184. sourceBox.max.x - sourceBox.min.x + 1,
  15185. sourceBox.max.y - sourceBox.min.y + 1,
  15186. sourceBox.max.z - sourceBox.min.z + 1,
  15187. glFormat,
  15188. glType,
  15189. data
  15190. );
  15191. _gl.pixelStorei( 3314, unpackRowLen );
  15192. _gl.pixelStorei( 32878, unpackImageHeight );
  15193. _gl.pixelStorei( 3316, unpackSkipPixels );
  15194. _gl.pixelStorei( 3315, unpackSkipRows );
  15195. _gl.pixelStorei( 32877, unpackSkipImages );
  15196. // Generate mipmaps only when copying level 0
  15197. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  15198. state.unbindTexture();
  15199. };
  15200. this.initTexture = function ( texture ) {
  15201. textures.setTexture2D( texture, 0 );
  15202. state.unbindTexture();
  15203. };
  15204. this.resetState = function () {
  15205. _currentActiveCubeFace = 0;
  15206. _currentActiveMipmapLevel = 0;
  15207. _currentRenderTarget = null;
  15208. state.reset();
  15209. bindingStates.reset();
  15210. };
  15211. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15212. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15213. }
  15214. }
  15215. class WebGL1Renderer extends WebGLRenderer {}
  15216. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15217. class FogExp2 {
  15218. constructor( color, density = 0.00025 ) {
  15219. this.name = '';
  15220. this.color = new Color( color );
  15221. this.density = density;
  15222. }
  15223. clone() {
  15224. return new FogExp2( this.color, this.density );
  15225. }
  15226. toJSON( /* meta */ ) {
  15227. return {
  15228. type: 'FogExp2',
  15229. color: this.color.getHex(),
  15230. density: this.density
  15231. };
  15232. }
  15233. }
  15234. FogExp2.prototype.isFogExp2 = true;
  15235. class Fog {
  15236. constructor( color, near = 1, far = 1000 ) {
  15237. this.name = '';
  15238. this.color = new Color( color );
  15239. this.near = near;
  15240. this.far = far;
  15241. }
  15242. clone() {
  15243. return new Fog( this.color, this.near, this.far );
  15244. }
  15245. toJSON( /* meta */ ) {
  15246. return {
  15247. type: 'Fog',
  15248. color: this.color.getHex(),
  15249. near: this.near,
  15250. far: this.far
  15251. };
  15252. }
  15253. }
  15254. Fog.prototype.isFog = true;
  15255. class Scene extends Object3D {
  15256. constructor() {
  15257. super();
  15258. this.type = 'Scene';
  15259. this.background = null;
  15260. this.environment = null;
  15261. this.fog = null;
  15262. this.overrideMaterial = null;
  15263. this.autoUpdate = true; // checked by the renderer
  15264. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15265. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15266. }
  15267. }
  15268. copy( source, recursive ) {
  15269. super.copy( source, recursive );
  15270. if ( source.background !== null ) this.background = source.background.clone();
  15271. if ( source.environment !== null ) this.environment = source.environment.clone();
  15272. if ( source.fog !== null ) this.fog = source.fog.clone();
  15273. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15274. this.autoUpdate = source.autoUpdate;
  15275. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15276. return this;
  15277. }
  15278. toJSON( meta ) {
  15279. const data = super.toJSON( meta );
  15280. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15281. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15282. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15283. return data;
  15284. }
  15285. }
  15286. Scene.prototype.isScene = true;
  15287. class InterleavedBuffer {
  15288. constructor( array, stride ) {
  15289. this.array = array;
  15290. this.stride = stride;
  15291. this.count = array !== undefined ? array.length / stride : 0;
  15292. this.usage = StaticDrawUsage;
  15293. this.updateRange = { offset: 0, count: - 1 };
  15294. this.version = 0;
  15295. this.uuid = generateUUID();
  15296. }
  15297. onUploadCallback() {}
  15298. set needsUpdate( value ) {
  15299. if ( value === true ) this.version ++;
  15300. }
  15301. setUsage( value ) {
  15302. this.usage = value;
  15303. return this;
  15304. }
  15305. copy( source ) {
  15306. this.array = new source.array.constructor( source.array );
  15307. this.count = source.count;
  15308. this.stride = source.stride;
  15309. this.usage = source.usage;
  15310. return this;
  15311. }
  15312. copyAt( index1, attribute, index2 ) {
  15313. index1 *= this.stride;
  15314. index2 *= attribute.stride;
  15315. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15316. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15317. }
  15318. return this;
  15319. }
  15320. set( value, offset = 0 ) {
  15321. this.array.set( value, offset );
  15322. return this;
  15323. }
  15324. clone( data ) {
  15325. if ( data.arrayBuffers === undefined ) {
  15326. data.arrayBuffers = {};
  15327. }
  15328. if ( this.array.buffer._uuid === undefined ) {
  15329. this.array.buffer._uuid = generateUUID();
  15330. }
  15331. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15332. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15333. }
  15334. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15335. const ib = new this.constructor( array, this.stride );
  15336. ib.setUsage( this.usage );
  15337. return ib;
  15338. }
  15339. onUpload( callback ) {
  15340. this.onUploadCallback = callback;
  15341. return this;
  15342. }
  15343. toJSON( data ) {
  15344. if ( data.arrayBuffers === undefined ) {
  15345. data.arrayBuffers = {};
  15346. }
  15347. // generate UUID for array buffer if necessary
  15348. if ( this.array.buffer._uuid === undefined ) {
  15349. this.array.buffer._uuid = generateUUID();
  15350. }
  15351. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15352. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15353. }
  15354. //
  15355. return {
  15356. uuid: this.uuid,
  15357. buffer: this.array.buffer._uuid,
  15358. type: this.array.constructor.name,
  15359. stride: this.stride
  15360. };
  15361. }
  15362. }
  15363. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15364. const _vector$6 = /*@__PURE__*/ new Vector3();
  15365. class InterleavedBufferAttribute {
  15366. constructor( interleavedBuffer, itemSize, offset, normalized ) {
  15367. this.name = '';
  15368. this.data = interleavedBuffer;
  15369. this.itemSize = itemSize;
  15370. this.offset = offset;
  15371. this.normalized = normalized === true;
  15372. }
  15373. get count() {
  15374. return this.data.count;
  15375. }
  15376. get array() {
  15377. return this.data.array;
  15378. }
  15379. set needsUpdate( value ) {
  15380. this.data.needsUpdate = value;
  15381. }
  15382. applyMatrix4( m ) {
  15383. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15384. _vector$6.x = this.getX( i );
  15385. _vector$6.y = this.getY( i );
  15386. _vector$6.z = this.getZ( i );
  15387. _vector$6.applyMatrix4( m );
  15388. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15389. }
  15390. return this;
  15391. }
  15392. applyNormalMatrix( m ) {
  15393. for ( let i = 0, l = this.count; i < l; i ++ ) {
  15394. _vector$6.x = this.getX( i );
  15395. _vector$6.y = this.getY( i );
  15396. _vector$6.z = this.getZ( i );
  15397. _vector$6.applyNormalMatrix( m );
  15398. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15399. }
  15400. return this;
  15401. }
  15402. transformDirection( m ) {
  15403. for ( let i = 0, l = this.count; i < l; i ++ ) {
  15404. _vector$6.x = this.getX( i );
  15405. _vector$6.y = this.getY( i );
  15406. _vector$6.z = this.getZ( i );
  15407. _vector$6.transformDirection( m );
  15408. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15409. }
  15410. return this;
  15411. }
  15412. setX( index, x ) {
  15413. this.data.array[ index * this.data.stride + this.offset ] = x;
  15414. return this;
  15415. }
  15416. setY( index, y ) {
  15417. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15418. return this;
  15419. }
  15420. setZ( index, z ) {
  15421. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15422. return this;
  15423. }
  15424. setW( index, w ) {
  15425. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15426. return this;
  15427. }
  15428. getX( index ) {
  15429. return this.data.array[ index * this.data.stride + this.offset ];
  15430. }
  15431. getY( index ) {
  15432. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15433. }
  15434. getZ( index ) {
  15435. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15436. }
  15437. getW( index ) {
  15438. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15439. }
  15440. setXY( index, x, y ) {
  15441. index = index * this.data.stride + this.offset;
  15442. this.data.array[ index + 0 ] = x;
  15443. this.data.array[ index + 1 ] = y;
  15444. return this;
  15445. }
  15446. setXYZ( index, x, y, z ) {
  15447. index = index * this.data.stride + this.offset;
  15448. this.data.array[ index + 0 ] = x;
  15449. this.data.array[ index + 1 ] = y;
  15450. this.data.array[ index + 2 ] = z;
  15451. return this;
  15452. }
  15453. setXYZW( index, x, y, z, w ) {
  15454. index = index * this.data.stride + this.offset;
  15455. this.data.array[ index + 0 ] = x;
  15456. this.data.array[ index + 1 ] = y;
  15457. this.data.array[ index + 2 ] = z;
  15458. this.data.array[ index + 3 ] = w;
  15459. return this;
  15460. }
  15461. clone( data ) {
  15462. if ( data === undefined ) {
  15463. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  15464. const array = [];
  15465. for ( let i = 0; i < this.count; i ++ ) {
  15466. const index = i * this.data.stride + this.offset;
  15467. for ( let j = 0; j < this.itemSize; j ++ ) {
  15468. array.push( this.data.array[ index + j ] );
  15469. }
  15470. }
  15471. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15472. } else {
  15473. if ( data.interleavedBuffers === undefined ) {
  15474. data.interleavedBuffers = {};
  15475. }
  15476. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15477. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15478. }
  15479. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15480. }
  15481. }
  15482. toJSON( data ) {
  15483. if ( data === undefined ) {
  15484. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  15485. const array = [];
  15486. for ( let i = 0; i < this.count; i ++ ) {
  15487. const index = i * this.data.stride + this.offset;
  15488. for ( let j = 0; j < this.itemSize; j ++ ) {
  15489. array.push( this.data.array[ index + j ] );
  15490. }
  15491. }
  15492. // deinterleave data and save it as an ordinary buffer attribute for now
  15493. return {
  15494. itemSize: this.itemSize,
  15495. type: this.array.constructor.name,
  15496. array: array,
  15497. normalized: this.normalized
  15498. };
  15499. } else {
  15500. // save as true interlaved attribtue
  15501. if ( data.interleavedBuffers === undefined ) {
  15502. data.interleavedBuffers = {};
  15503. }
  15504. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15505. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15506. }
  15507. return {
  15508. isInterleavedBufferAttribute: true,
  15509. itemSize: this.itemSize,
  15510. data: this.data.uuid,
  15511. offset: this.offset,
  15512. normalized: this.normalized
  15513. };
  15514. }
  15515. }
  15516. }
  15517. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15518. /**
  15519. * parameters = {
  15520. * color: <hex>,
  15521. * map: new THREE.Texture( <Image> ),
  15522. * alphaMap: new THREE.Texture( <Image> ),
  15523. * rotation: <float>,
  15524. * sizeAttenuation: <bool>
  15525. * }
  15526. */
  15527. class SpriteMaterial extends Material {
  15528. constructor( parameters ) {
  15529. super();
  15530. this.type = 'SpriteMaterial';
  15531. this.color = new Color( 0xffffff );
  15532. this.map = null;
  15533. this.alphaMap = null;
  15534. this.rotation = 0;
  15535. this.sizeAttenuation = true;
  15536. this.transparent = true;
  15537. this.setValues( parameters );
  15538. }
  15539. copy( source ) {
  15540. super.copy( source );
  15541. this.color.copy( source.color );
  15542. this.map = source.map;
  15543. this.alphaMap = source.alphaMap;
  15544. this.rotation = source.rotation;
  15545. this.sizeAttenuation = source.sizeAttenuation;
  15546. return this;
  15547. }
  15548. }
  15549. SpriteMaterial.prototype.isSpriteMaterial = true;
  15550. let _geometry;
  15551. const _intersectPoint = /*@__PURE__*/ new Vector3();
  15552. const _worldScale = /*@__PURE__*/ new Vector3();
  15553. const _mvPosition = /*@__PURE__*/ new Vector3();
  15554. const _alignedPosition = /*@__PURE__*/ new Vector2();
  15555. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  15556. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  15557. const _vA = /*@__PURE__*/ new Vector3();
  15558. const _vB = /*@__PURE__*/ new Vector3();
  15559. const _vC = /*@__PURE__*/ new Vector3();
  15560. const _uvA = /*@__PURE__*/ new Vector2();
  15561. const _uvB = /*@__PURE__*/ new Vector2();
  15562. const _uvC = /*@__PURE__*/ new Vector2();
  15563. class Sprite extends Object3D {
  15564. constructor( material ) {
  15565. super();
  15566. this.type = 'Sprite';
  15567. if ( _geometry === undefined ) {
  15568. _geometry = new BufferGeometry();
  15569. const float32Array = new Float32Array( [
  15570. - 0.5, - 0.5, 0, 0, 0,
  15571. 0.5, - 0.5, 0, 1, 0,
  15572. 0.5, 0.5, 0, 1, 1,
  15573. - 0.5, 0.5, 0, 0, 1
  15574. ] );
  15575. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  15576. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  15577. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  15578. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  15579. }
  15580. this.geometry = _geometry;
  15581. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  15582. this.center = new Vector2( 0.5, 0.5 );
  15583. }
  15584. raycast( raycaster, intersects ) {
  15585. if ( raycaster.camera === null ) {
  15586. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  15587. }
  15588. _worldScale.setFromMatrixScale( this.matrixWorld );
  15589. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  15590. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  15591. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  15592. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  15593. _worldScale.multiplyScalar( - _mvPosition.z );
  15594. }
  15595. const rotation = this.material.rotation;
  15596. let sin, cos;
  15597. if ( rotation !== 0 ) {
  15598. cos = Math.cos( rotation );
  15599. sin = Math.sin( rotation );
  15600. }
  15601. const center = this.center;
  15602. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15603. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15604. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15605. _uvA.set( 0, 0 );
  15606. _uvB.set( 1, 0 );
  15607. _uvC.set( 1, 1 );
  15608. // check first triangle
  15609. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  15610. if ( intersect === null ) {
  15611. // check second triangle
  15612. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15613. _uvB.set( 0, 1 );
  15614. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  15615. if ( intersect === null ) {
  15616. return;
  15617. }
  15618. }
  15619. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  15620. if ( distance < raycaster.near || distance > raycaster.far ) return;
  15621. intersects.push( {
  15622. distance: distance,
  15623. point: _intersectPoint.clone(),
  15624. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  15625. face: null,
  15626. object: this
  15627. } );
  15628. }
  15629. copy( source ) {
  15630. super.copy( source );
  15631. if ( source.center !== undefined ) this.center.copy( source.center );
  15632. this.material = source.material;
  15633. return this;
  15634. }
  15635. }
  15636. Sprite.prototype.isSprite = true;
  15637. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  15638. // compute position in camera space
  15639. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  15640. // to check if rotation is not zero
  15641. if ( sin !== undefined ) {
  15642. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  15643. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  15644. } else {
  15645. _rotatedPosition.copy( _alignedPosition );
  15646. }
  15647. vertexPosition.copy( mvPosition );
  15648. vertexPosition.x += _rotatedPosition.x;
  15649. vertexPosition.y += _rotatedPosition.y;
  15650. // transform to world space
  15651. vertexPosition.applyMatrix4( _viewWorldMatrix );
  15652. }
  15653. const _v1$2 = /*@__PURE__*/ new Vector3();
  15654. const _v2$1 = /*@__PURE__*/ new Vector3();
  15655. class LOD extends Object3D {
  15656. constructor() {
  15657. super();
  15658. this._currentLevel = 0;
  15659. this.type = 'LOD';
  15660. Object.defineProperties( this, {
  15661. levels: {
  15662. enumerable: true,
  15663. value: []
  15664. },
  15665. isLOD: {
  15666. value: true,
  15667. }
  15668. } );
  15669. this.autoUpdate = true;
  15670. }
  15671. copy( source ) {
  15672. super.copy( source, false );
  15673. const levels = source.levels;
  15674. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  15675. const level = levels[ i ];
  15676. this.addLevel( level.object.clone(), level.distance );
  15677. }
  15678. this.autoUpdate = source.autoUpdate;
  15679. return this;
  15680. }
  15681. addLevel( object, distance = 0 ) {
  15682. distance = Math.abs( distance );
  15683. const levels = this.levels;
  15684. let l;
  15685. for ( l = 0; l < levels.length; l ++ ) {
  15686. if ( distance < levels[ l ].distance ) {
  15687. break;
  15688. }
  15689. }
  15690. levels.splice( l, 0, { distance: distance, object: object } );
  15691. this.add( object );
  15692. return this;
  15693. }
  15694. getCurrentLevel() {
  15695. return this._currentLevel;
  15696. }
  15697. getObjectForDistance( distance ) {
  15698. const levels = this.levels;
  15699. if ( levels.length > 0 ) {
  15700. let i, l;
  15701. for ( i = 1, l = levels.length; i < l; i ++ ) {
  15702. if ( distance < levels[ i ].distance ) {
  15703. break;
  15704. }
  15705. }
  15706. return levels[ i - 1 ].object;
  15707. }
  15708. return null;
  15709. }
  15710. raycast( raycaster, intersects ) {
  15711. const levels = this.levels;
  15712. if ( levels.length > 0 ) {
  15713. _v1$2.setFromMatrixPosition( this.matrixWorld );
  15714. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  15715. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  15716. }
  15717. }
  15718. update( camera ) {
  15719. const levels = this.levels;
  15720. if ( levels.length > 1 ) {
  15721. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  15722. _v2$1.setFromMatrixPosition( this.matrixWorld );
  15723. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  15724. levels[ 0 ].object.visible = true;
  15725. let i, l;
  15726. for ( i = 1, l = levels.length; i < l; i ++ ) {
  15727. if ( distance >= levels[ i ].distance ) {
  15728. levels[ i - 1 ].object.visible = false;
  15729. levels[ i ].object.visible = true;
  15730. } else {
  15731. break;
  15732. }
  15733. }
  15734. this._currentLevel = i - 1;
  15735. for ( ; i < l; i ++ ) {
  15736. levels[ i ].object.visible = false;
  15737. }
  15738. }
  15739. }
  15740. toJSON( meta ) {
  15741. const data = super.toJSON( meta );
  15742. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  15743. data.object.levels = [];
  15744. const levels = this.levels;
  15745. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  15746. const level = levels[ i ];
  15747. data.object.levels.push( {
  15748. object: level.object.uuid,
  15749. distance: level.distance
  15750. } );
  15751. }
  15752. return data;
  15753. }
  15754. }
  15755. const _basePosition = /*@__PURE__*/ new Vector3();
  15756. const _skinIndex = /*@__PURE__*/ new Vector4();
  15757. const _skinWeight = /*@__PURE__*/ new Vector4();
  15758. const _vector$5 = /*@__PURE__*/ new Vector3();
  15759. const _matrix = /*@__PURE__*/ new Matrix4();
  15760. class SkinnedMesh extends Mesh {
  15761. constructor( geometry, material ) {
  15762. super( geometry, material );
  15763. this.type = 'SkinnedMesh';
  15764. this.bindMode = 'attached';
  15765. this.bindMatrix = new Matrix4();
  15766. this.bindMatrixInverse = new Matrix4();
  15767. }
  15768. copy( source ) {
  15769. super.copy( source );
  15770. this.bindMode = source.bindMode;
  15771. this.bindMatrix.copy( source.bindMatrix );
  15772. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  15773. this.skeleton = source.skeleton;
  15774. return this;
  15775. }
  15776. bind( skeleton, bindMatrix ) {
  15777. this.skeleton = skeleton;
  15778. if ( bindMatrix === undefined ) {
  15779. this.updateMatrixWorld( true );
  15780. this.skeleton.calculateInverses();
  15781. bindMatrix = this.matrixWorld;
  15782. }
  15783. this.bindMatrix.copy( bindMatrix );
  15784. this.bindMatrixInverse.copy( bindMatrix ).invert();
  15785. }
  15786. pose() {
  15787. this.skeleton.pose();
  15788. }
  15789. normalizeSkinWeights() {
  15790. const vector = new Vector4();
  15791. const skinWeight = this.geometry.attributes.skinWeight;
  15792. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  15793. vector.x = skinWeight.getX( i );
  15794. vector.y = skinWeight.getY( i );
  15795. vector.z = skinWeight.getZ( i );
  15796. vector.w = skinWeight.getW( i );
  15797. const scale = 1.0 / vector.manhattanLength();
  15798. if ( scale !== Infinity ) {
  15799. vector.multiplyScalar( scale );
  15800. } else {
  15801. vector.set( 1, 0, 0, 0 ); // do something reasonable
  15802. }
  15803. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  15804. }
  15805. }
  15806. updateMatrixWorld( force ) {
  15807. super.updateMatrixWorld( force );
  15808. if ( this.bindMode === 'attached' ) {
  15809. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  15810. } else if ( this.bindMode === 'detached' ) {
  15811. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  15812. } else {
  15813. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  15814. }
  15815. }
  15816. boneTransform( index, target ) {
  15817. const skeleton = this.skeleton;
  15818. const geometry = this.geometry;
  15819. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  15820. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  15821. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  15822. target.set( 0, 0, 0 );
  15823. for ( let i = 0; i < 4; i ++ ) {
  15824. const weight = _skinWeight.getComponent( i );
  15825. if ( weight !== 0 ) {
  15826. const boneIndex = _skinIndex.getComponent( i );
  15827. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  15828. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  15829. }
  15830. }
  15831. return target.applyMatrix4( this.bindMatrixInverse );
  15832. }
  15833. }
  15834. SkinnedMesh.prototype.isSkinnedMesh = true;
  15835. class Bone extends Object3D {
  15836. constructor() {
  15837. super();
  15838. this.type = 'Bone';
  15839. }
  15840. }
  15841. Bone.prototype.isBone = true;
  15842. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  15843. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  15844. class Skeleton {
  15845. constructor( bones = [], boneInverses = [] ) {
  15846. this.uuid = generateUUID();
  15847. this.bones = bones.slice( 0 );
  15848. this.boneInverses = boneInverses;
  15849. this.boneMatrices = null;
  15850. this.boneTexture = null;
  15851. this.boneTextureSize = 0;
  15852. this.frame = - 1;
  15853. this.init();
  15854. }
  15855. init() {
  15856. const bones = this.bones;
  15857. const boneInverses = this.boneInverses;
  15858. this.boneMatrices = new Float32Array( bones.length * 16 );
  15859. // calculate inverse bone matrices if necessary
  15860. if ( boneInverses.length === 0 ) {
  15861. this.calculateInverses();
  15862. } else {
  15863. // handle special case
  15864. if ( bones.length !== boneInverses.length ) {
  15865. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  15866. this.boneInverses = [];
  15867. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15868. this.boneInverses.push( new Matrix4() );
  15869. }
  15870. }
  15871. }
  15872. }
  15873. calculateInverses() {
  15874. this.boneInverses.length = 0;
  15875. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15876. const inverse = new Matrix4();
  15877. if ( this.bones[ i ] ) {
  15878. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  15879. }
  15880. this.boneInverses.push( inverse );
  15881. }
  15882. }
  15883. pose() {
  15884. // recover the bind-time world matrices
  15885. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15886. const bone = this.bones[ i ];
  15887. if ( bone ) {
  15888. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  15889. }
  15890. }
  15891. // compute the local matrices, positions, rotations and scales
  15892. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15893. const bone = this.bones[ i ];
  15894. if ( bone ) {
  15895. if ( bone.parent && bone.parent.isBone ) {
  15896. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  15897. bone.matrix.multiply( bone.matrixWorld );
  15898. } else {
  15899. bone.matrix.copy( bone.matrixWorld );
  15900. }
  15901. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  15902. }
  15903. }
  15904. }
  15905. update() {
  15906. const bones = this.bones;
  15907. const boneInverses = this.boneInverses;
  15908. const boneMatrices = this.boneMatrices;
  15909. const boneTexture = this.boneTexture;
  15910. // flatten bone matrices to array
  15911. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  15912. // compute the offset between the current and the original transform
  15913. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  15914. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  15915. _offsetMatrix.toArray( boneMatrices, i * 16 );
  15916. }
  15917. if ( boneTexture !== null ) {
  15918. boneTexture.needsUpdate = true;
  15919. }
  15920. }
  15921. clone() {
  15922. return new Skeleton( this.bones, this.boneInverses );
  15923. }
  15924. getBoneByName( name ) {
  15925. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15926. const bone = this.bones[ i ];
  15927. if ( bone.name === name ) {
  15928. return bone;
  15929. }
  15930. }
  15931. return undefined;
  15932. }
  15933. dispose( ) {
  15934. if ( this.boneTexture !== null ) {
  15935. this.boneTexture.dispose();
  15936. this.boneTexture = null;
  15937. }
  15938. }
  15939. fromJSON( json, bones ) {
  15940. this.uuid = json.uuid;
  15941. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  15942. const uuid = json.bones[ i ];
  15943. let bone = bones[ uuid ];
  15944. if ( bone === undefined ) {
  15945. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  15946. bone = new Bone();
  15947. }
  15948. this.bones.push( bone );
  15949. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  15950. }
  15951. this.init();
  15952. return this;
  15953. }
  15954. toJSON() {
  15955. const data = {
  15956. metadata: {
  15957. version: 4.5,
  15958. type: 'Skeleton',
  15959. generator: 'Skeleton.toJSON'
  15960. },
  15961. bones: [],
  15962. boneInverses: []
  15963. };
  15964. data.uuid = this.uuid;
  15965. const bones = this.bones;
  15966. const boneInverses = this.boneInverses;
  15967. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  15968. const bone = bones[ i ];
  15969. data.bones.push( bone.uuid );
  15970. const boneInverse = boneInverses[ i ];
  15971. data.boneInverses.push( boneInverse.toArray() );
  15972. }
  15973. return data;
  15974. }
  15975. }
  15976. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  15977. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  15978. const _instanceIntersects = [];
  15979. const _mesh = /*@__PURE__*/ new Mesh();
  15980. class InstancedMesh extends Mesh {
  15981. constructor( geometry, material, count ) {
  15982. super( geometry, material );
  15983. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  15984. this.instanceColor = null;
  15985. this.count = count;
  15986. this.frustumCulled = false;
  15987. }
  15988. copy( source ) {
  15989. super.copy( source );
  15990. this.instanceMatrix.copy( source.instanceMatrix );
  15991. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  15992. this.count = source.count;
  15993. return this;
  15994. }
  15995. getColorAt( index, color ) {
  15996. color.fromArray( this.instanceColor.array, index * 3 );
  15997. }
  15998. getMatrixAt( index, matrix ) {
  15999. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  16000. }
  16001. raycast( raycaster, intersects ) {
  16002. const matrixWorld = this.matrixWorld;
  16003. const raycastTimes = this.count;
  16004. _mesh.geometry = this.geometry;
  16005. _mesh.material = this.material;
  16006. if ( _mesh.material === undefined ) return;
  16007. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  16008. // calculate the world matrix for each instance
  16009. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  16010. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  16011. // the mesh represents this single instance
  16012. _mesh.matrixWorld = _instanceWorldMatrix;
  16013. _mesh.raycast( raycaster, _instanceIntersects );
  16014. // process the result of raycast
  16015. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  16016. const intersect = _instanceIntersects[ i ];
  16017. intersect.instanceId = instanceId;
  16018. intersect.object = this;
  16019. intersects.push( intersect );
  16020. }
  16021. _instanceIntersects.length = 0;
  16022. }
  16023. }
  16024. setColorAt( index, color ) {
  16025. if ( this.instanceColor === null ) {
  16026. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  16027. }
  16028. color.toArray( this.instanceColor.array, index * 3 );
  16029. }
  16030. setMatrixAt( index, matrix ) {
  16031. matrix.toArray( this.instanceMatrix.array, index * 16 );
  16032. }
  16033. updateMorphTargets() {
  16034. }
  16035. dispose() {
  16036. this.dispatchEvent( { type: 'dispose' } );
  16037. }
  16038. }
  16039. InstancedMesh.prototype.isInstancedMesh = true;
  16040. /**
  16041. * parameters = {
  16042. * color: <hex>,
  16043. * opacity: <float>,
  16044. *
  16045. * linewidth: <float>,
  16046. * linecap: "round",
  16047. * linejoin: "round"
  16048. * }
  16049. */
  16050. class LineBasicMaterial extends Material {
  16051. constructor( parameters ) {
  16052. super();
  16053. this.type = 'LineBasicMaterial';
  16054. this.color = new Color( 0xffffff );
  16055. this.linewidth = 1;
  16056. this.linecap = 'round';
  16057. this.linejoin = 'round';
  16058. this.morphTargets = false;
  16059. this.setValues( parameters );
  16060. }
  16061. copy( source ) {
  16062. super.copy( source );
  16063. this.color.copy( source.color );
  16064. this.linewidth = source.linewidth;
  16065. this.linecap = source.linecap;
  16066. this.linejoin = source.linejoin;
  16067. this.morphTargets = source.morphTargets;
  16068. return this;
  16069. }
  16070. }
  16071. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16072. const _start$1 = /*@__PURE__*/ new Vector3();
  16073. const _end$1 = /*@__PURE__*/ new Vector3();
  16074. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  16075. const _ray$1 = /*@__PURE__*/ new Ray();
  16076. const _sphere$1 = /*@__PURE__*/ new Sphere();
  16077. class Line extends Object3D {
  16078. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  16079. super();
  16080. this.type = 'Line';
  16081. this.geometry = geometry;
  16082. this.material = material;
  16083. this.updateMorphTargets();
  16084. }
  16085. copy( source ) {
  16086. super.copy( source );
  16087. this.material = source.material;
  16088. this.geometry = source.geometry;
  16089. return this;
  16090. }
  16091. computeLineDistances() {
  16092. const geometry = this.geometry;
  16093. if ( geometry.isBufferGeometry ) {
  16094. // we assume non-indexed geometry
  16095. if ( geometry.index === null ) {
  16096. const positionAttribute = geometry.attributes.position;
  16097. const lineDistances = [ 0 ];
  16098. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16099. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  16100. _end$1.fromBufferAttribute( positionAttribute, i );
  16101. lineDistances[ i ] = lineDistances[ i - 1 ];
  16102. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  16103. }
  16104. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16105. } else {
  16106. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16107. }
  16108. } else if ( geometry.isGeometry ) {
  16109. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16110. }
  16111. return this;
  16112. }
  16113. raycast( raycaster, intersects ) {
  16114. const geometry = this.geometry;
  16115. const matrixWorld = this.matrixWorld;
  16116. const threshold = raycaster.params.Line.threshold;
  16117. const drawRange = geometry.drawRange;
  16118. // Checking boundingSphere distance to ray
  16119. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16120. _sphere$1.copy( geometry.boundingSphere );
  16121. _sphere$1.applyMatrix4( matrixWorld );
  16122. _sphere$1.radius += threshold;
  16123. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  16124. //
  16125. _inverseMatrix$1.copy( matrixWorld ).invert();
  16126. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16127. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16128. const localThresholdSq = localThreshold * localThreshold;
  16129. const vStart = new Vector3();
  16130. const vEnd = new Vector3();
  16131. const interSegment = new Vector3();
  16132. const interRay = new Vector3();
  16133. const step = this.isLineSegments ? 2 : 1;
  16134. if ( geometry.isBufferGeometry ) {
  16135. const index = geometry.index;
  16136. const attributes = geometry.attributes;
  16137. const positionAttribute = attributes.position;
  16138. if ( index !== null ) {
  16139. const start = Math.max( 0, drawRange.start );
  16140. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  16141. for ( let i = start, l = end - 1; i < l; i += step ) {
  16142. const a = index.getX( i );
  16143. const b = index.getX( i + 1 );
  16144. vStart.fromBufferAttribute( positionAttribute, a );
  16145. vEnd.fromBufferAttribute( positionAttribute, b );
  16146. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16147. if ( distSq > localThresholdSq ) continue;
  16148. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16149. const distance = raycaster.ray.origin.distanceTo( interRay );
  16150. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16151. intersects.push( {
  16152. distance: distance,
  16153. // What do we want? intersection point on the ray or on the segment??
  16154. // point: raycaster.ray.at( distance ),
  16155. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16156. index: i,
  16157. face: null,
  16158. faceIndex: null,
  16159. object: this
  16160. } );
  16161. }
  16162. } else {
  16163. const start = Math.max( 0, drawRange.start );
  16164. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16165. for ( let i = start, l = end - 1; i < l; i += step ) {
  16166. vStart.fromBufferAttribute( positionAttribute, i );
  16167. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  16168. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16169. if ( distSq > localThresholdSq ) continue;
  16170. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16171. const distance = raycaster.ray.origin.distanceTo( interRay );
  16172. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16173. intersects.push( {
  16174. distance: distance,
  16175. // What do we want? intersection point on the ray or on the segment??
  16176. // point: raycaster.ray.at( distance ),
  16177. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16178. index: i,
  16179. face: null,
  16180. faceIndex: null,
  16181. object: this
  16182. } );
  16183. }
  16184. }
  16185. } else if ( geometry.isGeometry ) {
  16186. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16187. }
  16188. }
  16189. updateMorphTargets() {
  16190. const geometry = this.geometry;
  16191. if ( geometry.isBufferGeometry ) {
  16192. const morphAttributes = geometry.morphAttributes;
  16193. const keys = Object.keys( morphAttributes );
  16194. if ( keys.length > 0 ) {
  16195. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16196. if ( morphAttribute !== undefined ) {
  16197. this.morphTargetInfluences = [];
  16198. this.morphTargetDictionary = {};
  16199. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16200. const name = morphAttribute[ m ].name || String( m );
  16201. this.morphTargetInfluences.push( 0 );
  16202. this.morphTargetDictionary[ name ] = m;
  16203. }
  16204. }
  16205. }
  16206. } else {
  16207. const morphTargets = geometry.morphTargets;
  16208. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16209. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16210. }
  16211. }
  16212. }
  16213. }
  16214. Line.prototype.isLine = true;
  16215. const _start = /*@__PURE__*/ new Vector3();
  16216. const _end = /*@__PURE__*/ new Vector3();
  16217. class LineSegments extends Line {
  16218. constructor( geometry, material ) {
  16219. super( geometry, material );
  16220. this.type = 'LineSegments';
  16221. }
  16222. computeLineDistances() {
  16223. const geometry = this.geometry;
  16224. if ( geometry.isBufferGeometry ) {
  16225. // we assume non-indexed geometry
  16226. if ( geometry.index === null ) {
  16227. const positionAttribute = geometry.attributes.position;
  16228. const lineDistances = [];
  16229. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16230. _start.fromBufferAttribute( positionAttribute, i );
  16231. _end.fromBufferAttribute( positionAttribute, i + 1 );
  16232. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16233. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  16234. }
  16235. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16236. } else {
  16237. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16238. }
  16239. } else if ( geometry.isGeometry ) {
  16240. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16241. }
  16242. return this;
  16243. }
  16244. }
  16245. LineSegments.prototype.isLineSegments = true;
  16246. class LineLoop extends Line {
  16247. constructor( geometry, material ) {
  16248. super( geometry, material );
  16249. this.type = 'LineLoop';
  16250. }
  16251. }
  16252. LineLoop.prototype.isLineLoop = true;
  16253. /**
  16254. * parameters = {
  16255. * color: <hex>,
  16256. * opacity: <float>,
  16257. * map: new THREE.Texture( <Image> ),
  16258. * alphaMap: new THREE.Texture( <Image> ),
  16259. *
  16260. * size: <float>,
  16261. * sizeAttenuation: <bool>
  16262. *
  16263. * morphTargets: <bool>
  16264. * }
  16265. */
  16266. class PointsMaterial extends Material {
  16267. constructor( parameters ) {
  16268. super();
  16269. this.type = 'PointsMaterial';
  16270. this.color = new Color( 0xffffff );
  16271. this.map = null;
  16272. this.alphaMap = null;
  16273. this.size = 1;
  16274. this.sizeAttenuation = true;
  16275. this.morphTargets = false;
  16276. this.setValues( parameters );
  16277. }
  16278. copy( source ) {
  16279. super.copy( source );
  16280. this.color.copy( source.color );
  16281. this.map = source.map;
  16282. this.alphaMap = source.alphaMap;
  16283. this.size = source.size;
  16284. this.sizeAttenuation = source.sizeAttenuation;
  16285. this.morphTargets = source.morphTargets;
  16286. return this;
  16287. }
  16288. }
  16289. PointsMaterial.prototype.isPointsMaterial = true;
  16290. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  16291. const _ray = /*@__PURE__*/ new Ray();
  16292. const _sphere = /*@__PURE__*/ new Sphere();
  16293. const _position$2 = /*@__PURE__*/ new Vector3();
  16294. class Points extends Object3D {
  16295. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16296. super();
  16297. this.type = 'Points';
  16298. this.geometry = geometry;
  16299. this.material = material;
  16300. this.updateMorphTargets();
  16301. }
  16302. copy( source ) {
  16303. super.copy( source );
  16304. this.material = source.material;
  16305. this.geometry = source.geometry;
  16306. return this;
  16307. }
  16308. raycast( raycaster, intersects ) {
  16309. const geometry = this.geometry;
  16310. const matrixWorld = this.matrixWorld;
  16311. const threshold = raycaster.params.Points.threshold;
  16312. const drawRange = geometry.drawRange;
  16313. // Checking boundingSphere distance to ray
  16314. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16315. _sphere.copy( geometry.boundingSphere );
  16316. _sphere.applyMatrix4( matrixWorld );
  16317. _sphere.radius += threshold;
  16318. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  16319. //
  16320. _inverseMatrix.copy( matrixWorld ).invert();
  16321. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  16322. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16323. const localThresholdSq = localThreshold * localThreshold;
  16324. if ( geometry.isBufferGeometry ) {
  16325. const index = geometry.index;
  16326. const attributes = geometry.attributes;
  16327. const positionAttribute = attributes.position;
  16328. if ( index !== null ) {
  16329. const start = Math.max( 0, drawRange.start );
  16330. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  16331. for ( let i = start, il = end; i < il; i ++ ) {
  16332. const a = index.getX( i );
  16333. _position$2.fromBufferAttribute( positionAttribute, a );
  16334. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16335. }
  16336. } else {
  16337. const start = Math.max( 0, drawRange.start );
  16338. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16339. for ( let i = start, l = end; i < l; i ++ ) {
  16340. _position$2.fromBufferAttribute( positionAttribute, i );
  16341. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16342. }
  16343. }
  16344. } else {
  16345. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16346. }
  16347. }
  16348. updateMorphTargets() {
  16349. const geometry = this.geometry;
  16350. if ( geometry.isBufferGeometry ) {
  16351. const morphAttributes = geometry.morphAttributes;
  16352. const keys = Object.keys( morphAttributes );
  16353. if ( keys.length > 0 ) {
  16354. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16355. if ( morphAttribute !== undefined ) {
  16356. this.morphTargetInfluences = [];
  16357. this.morphTargetDictionary = {};
  16358. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16359. const name = morphAttribute[ m ].name || String( m );
  16360. this.morphTargetInfluences.push( 0 );
  16361. this.morphTargetDictionary[ name ] = m;
  16362. }
  16363. }
  16364. }
  16365. } else {
  16366. const morphTargets = geometry.morphTargets;
  16367. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16368. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16369. }
  16370. }
  16371. }
  16372. }
  16373. Points.prototype.isPoints = true;
  16374. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16375. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  16376. if ( rayPointDistanceSq < localThresholdSq ) {
  16377. const intersectPoint = new Vector3();
  16378. _ray.closestPointToPoint( point, intersectPoint );
  16379. intersectPoint.applyMatrix4( matrixWorld );
  16380. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16381. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16382. intersects.push( {
  16383. distance: distance,
  16384. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16385. point: intersectPoint,
  16386. index: index,
  16387. face: null,
  16388. object: object
  16389. } );
  16390. }
  16391. }
  16392. class VideoTexture extends Texture {
  16393. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16394. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16395. this.format = format !== undefined ? format : RGBFormat;
  16396. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16397. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16398. this.generateMipmaps = false;
  16399. const scope = this;
  16400. function updateVideo() {
  16401. scope.needsUpdate = true;
  16402. video.requestVideoFrameCallback( updateVideo );
  16403. }
  16404. if ( 'requestVideoFrameCallback' in video ) {
  16405. video.requestVideoFrameCallback( updateVideo );
  16406. }
  16407. }
  16408. clone() {
  16409. return new this.constructor( this.image ).copy( this );
  16410. }
  16411. update() {
  16412. const video = this.image;
  16413. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16414. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16415. this.needsUpdate = true;
  16416. }
  16417. }
  16418. }
  16419. VideoTexture.prototype.isVideoTexture = true;
  16420. class CompressedTexture extends Texture {
  16421. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16422. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16423. this.image = { width: width, height: height };
  16424. this.mipmaps = mipmaps;
  16425. // no flipping for cube textures
  16426. // (also flipping doesn't work for compressed textures )
  16427. this.flipY = false;
  16428. // can't generate mipmaps for compressed textures
  16429. // mips must be embedded in DDS files
  16430. this.generateMipmaps = false;
  16431. }
  16432. }
  16433. CompressedTexture.prototype.isCompressedTexture = true;
  16434. class CanvasTexture extends Texture {
  16435. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16436. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16437. this.needsUpdate = true;
  16438. }
  16439. }
  16440. CanvasTexture.prototype.isCanvasTexture = true;
  16441. class DepthTexture extends Texture {
  16442. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  16443. format = format !== undefined ? format : DepthFormat;
  16444. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16445. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16446. }
  16447. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  16448. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  16449. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16450. this.image = { width: width, height: height };
  16451. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16452. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16453. this.flipY = false;
  16454. this.generateMipmaps = false;
  16455. }
  16456. }
  16457. DepthTexture.prototype.isDepthTexture = true;
  16458. class CircleGeometry extends BufferGeometry {
  16459. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16460. super();
  16461. this.type = 'CircleGeometry';
  16462. this.parameters = {
  16463. radius: radius,
  16464. segments: segments,
  16465. thetaStart: thetaStart,
  16466. thetaLength: thetaLength
  16467. };
  16468. segments = Math.max( 3, segments );
  16469. // buffers
  16470. const indices = [];
  16471. const vertices = [];
  16472. const normals = [];
  16473. const uvs = [];
  16474. // helper variables
  16475. const vertex = new Vector3();
  16476. const uv = new Vector2();
  16477. // center point
  16478. vertices.push( 0, 0, 0 );
  16479. normals.push( 0, 0, 1 );
  16480. uvs.push( 0.5, 0.5 );
  16481. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  16482. const segment = thetaStart + s / segments * thetaLength;
  16483. // vertex
  16484. vertex.x = radius * Math.cos( segment );
  16485. vertex.y = radius * Math.sin( segment );
  16486. vertices.push( vertex.x, vertex.y, vertex.z );
  16487. // normal
  16488. normals.push( 0, 0, 1 );
  16489. // uvs
  16490. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  16491. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  16492. uvs.push( uv.x, uv.y );
  16493. }
  16494. // indices
  16495. for ( let i = 1; i <= segments; i ++ ) {
  16496. indices.push( i, i + 1, 0 );
  16497. }
  16498. // build geometry
  16499. this.setIndex( indices );
  16500. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16501. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16502. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16503. }
  16504. }
  16505. class CylinderGeometry extends BufferGeometry {
  16506. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16507. super();
  16508. this.type = 'CylinderGeometry';
  16509. this.parameters = {
  16510. radiusTop: radiusTop,
  16511. radiusBottom: radiusBottom,
  16512. height: height,
  16513. radialSegments: radialSegments,
  16514. heightSegments: heightSegments,
  16515. openEnded: openEnded,
  16516. thetaStart: thetaStart,
  16517. thetaLength: thetaLength
  16518. };
  16519. const scope = this;
  16520. radialSegments = Math.floor( radialSegments );
  16521. heightSegments = Math.floor( heightSegments );
  16522. // buffers
  16523. const indices = [];
  16524. const vertices = [];
  16525. const normals = [];
  16526. const uvs = [];
  16527. // helper variables
  16528. let index = 0;
  16529. const indexArray = [];
  16530. const halfHeight = height / 2;
  16531. let groupStart = 0;
  16532. // generate geometry
  16533. generateTorso();
  16534. if ( openEnded === false ) {
  16535. if ( radiusTop > 0 ) generateCap( true );
  16536. if ( radiusBottom > 0 ) generateCap( false );
  16537. }
  16538. // build geometry
  16539. this.setIndex( indices );
  16540. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16541. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16542. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16543. function generateTorso() {
  16544. const normal = new Vector3();
  16545. const vertex = new Vector3();
  16546. let groupCount = 0;
  16547. // this will be used to calculate the normal
  16548. const slope = ( radiusBottom - radiusTop ) / height;
  16549. // generate vertices, normals and uvs
  16550. for ( let y = 0; y <= heightSegments; y ++ ) {
  16551. const indexRow = [];
  16552. const v = y / heightSegments;
  16553. // calculate the radius of the current row
  16554. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16555. for ( let x = 0; x <= radialSegments; x ++ ) {
  16556. const u = x / radialSegments;
  16557. const theta = u * thetaLength + thetaStart;
  16558. const sinTheta = Math.sin( theta );
  16559. const cosTheta = Math.cos( theta );
  16560. // vertex
  16561. vertex.x = radius * sinTheta;
  16562. vertex.y = - v * height + halfHeight;
  16563. vertex.z = radius * cosTheta;
  16564. vertices.push( vertex.x, vertex.y, vertex.z );
  16565. // normal
  16566. normal.set( sinTheta, slope, cosTheta ).normalize();
  16567. normals.push( normal.x, normal.y, normal.z );
  16568. // uv
  16569. uvs.push( u, 1 - v );
  16570. // save index of vertex in respective row
  16571. indexRow.push( index ++ );
  16572. }
  16573. // now save vertices of the row in our index array
  16574. indexArray.push( indexRow );
  16575. }
  16576. // generate indices
  16577. for ( let x = 0; x < radialSegments; x ++ ) {
  16578. for ( let y = 0; y < heightSegments; y ++ ) {
  16579. // we use the index array to access the correct indices
  16580. const a = indexArray[ y ][ x ];
  16581. const b = indexArray[ y + 1 ][ x ];
  16582. const c = indexArray[ y + 1 ][ x + 1 ];
  16583. const d = indexArray[ y ][ x + 1 ];
  16584. // faces
  16585. indices.push( a, b, d );
  16586. indices.push( b, c, d );
  16587. // update group counter
  16588. groupCount += 6;
  16589. }
  16590. }
  16591. // add a group to the geometry. this will ensure multi material support
  16592. scope.addGroup( groupStart, groupCount, 0 );
  16593. // calculate new start value for groups
  16594. groupStart += groupCount;
  16595. }
  16596. function generateCap( top ) {
  16597. // save the index of the first center vertex
  16598. const centerIndexStart = index;
  16599. const uv = new Vector2();
  16600. const vertex = new Vector3();
  16601. let groupCount = 0;
  16602. const radius = ( top === true ) ? radiusTop : radiusBottom;
  16603. const sign = ( top === true ) ? 1 : - 1;
  16604. // first we generate the center vertex data of the cap.
  16605. // because the geometry needs one set of uvs per face,
  16606. // we must generate a center vertex per face/segment
  16607. for ( let x = 1; x <= radialSegments; x ++ ) {
  16608. // vertex
  16609. vertices.push( 0, halfHeight * sign, 0 );
  16610. // normal
  16611. normals.push( 0, sign, 0 );
  16612. // uv
  16613. uvs.push( 0.5, 0.5 );
  16614. // increase index
  16615. index ++;
  16616. }
  16617. // save the index of the last center vertex
  16618. const centerIndexEnd = index;
  16619. // now we generate the surrounding vertices, normals and uvs
  16620. for ( let x = 0; x <= radialSegments; x ++ ) {
  16621. const u = x / radialSegments;
  16622. const theta = u * thetaLength + thetaStart;
  16623. const cosTheta = Math.cos( theta );
  16624. const sinTheta = Math.sin( theta );
  16625. // vertex
  16626. vertex.x = radius * sinTheta;
  16627. vertex.y = halfHeight * sign;
  16628. vertex.z = radius * cosTheta;
  16629. vertices.push( vertex.x, vertex.y, vertex.z );
  16630. // normal
  16631. normals.push( 0, sign, 0 );
  16632. // uv
  16633. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16634. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16635. uvs.push( uv.x, uv.y );
  16636. // increase index
  16637. index ++;
  16638. }
  16639. // generate indices
  16640. for ( let x = 0; x < radialSegments; x ++ ) {
  16641. const c = centerIndexStart + x;
  16642. const i = centerIndexEnd + x;
  16643. if ( top === true ) {
  16644. // face top
  16645. indices.push( i, i + 1, c );
  16646. } else {
  16647. // face bottom
  16648. indices.push( i + 1, i, c );
  16649. }
  16650. groupCount += 3;
  16651. }
  16652. // add a group to the geometry. this will ensure multi material support
  16653. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16654. // calculate new start value for groups
  16655. groupStart += groupCount;
  16656. }
  16657. }
  16658. }
  16659. class ConeGeometry extends CylinderGeometry {
  16660. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16661. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16662. this.type = 'ConeGeometry';
  16663. this.parameters = {
  16664. radius: radius,
  16665. height: height,
  16666. radialSegments: radialSegments,
  16667. heightSegments: heightSegments,
  16668. openEnded: openEnded,
  16669. thetaStart: thetaStart,
  16670. thetaLength: thetaLength
  16671. };
  16672. }
  16673. }
  16674. class PolyhedronGeometry extends BufferGeometry {
  16675. constructor( vertices, indices, radius = 1, detail = 0 ) {
  16676. super();
  16677. this.type = 'PolyhedronGeometry';
  16678. this.parameters = {
  16679. vertices: vertices,
  16680. indices: indices,
  16681. radius: radius,
  16682. detail: detail
  16683. };
  16684. // default buffer data
  16685. const vertexBuffer = [];
  16686. const uvBuffer = [];
  16687. // the subdivision creates the vertex buffer data
  16688. subdivide( detail );
  16689. // all vertices should lie on a conceptual sphere with a given radius
  16690. applyRadius( radius );
  16691. // finally, create the uv data
  16692. generateUVs();
  16693. // build non-indexed geometry
  16694. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  16695. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  16696. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  16697. if ( detail === 0 ) {
  16698. this.computeVertexNormals(); // flat normals
  16699. } else {
  16700. this.normalizeNormals(); // smooth normals
  16701. }
  16702. // helper functions
  16703. function subdivide( detail ) {
  16704. const a = new Vector3();
  16705. const b = new Vector3();
  16706. const c = new Vector3();
  16707. // iterate over all faces and apply a subdivison with the given detail value
  16708. for ( let i = 0; i < indices.length; i += 3 ) {
  16709. // get the vertices of the face
  16710. getVertexByIndex( indices[ i + 0 ], a );
  16711. getVertexByIndex( indices[ i + 1 ], b );
  16712. getVertexByIndex( indices[ i + 2 ], c );
  16713. // perform subdivision
  16714. subdivideFace( a, b, c, detail );
  16715. }
  16716. }
  16717. function subdivideFace( a, b, c, detail ) {
  16718. const cols = detail + 1;
  16719. // we use this multidimensional array as a data structure for creating the subdivision
  16720. const v = [];
  16721. // construct all of the vertices for this subdivision
  16722. for ( let i = 0; i <= cols; i ++ ) {
  16723. v[ i ] = [];
  16724. const aj = a.clone().lerp( c, i / cols );
  16725. const bj = b.clone().lerp( c, i / cols );
  16726. const rows = cols - i;
  16727. for ( let j = 0; j <= rows; j ++ ) {
  16728. if ( j === 0 && i === cols ) {
  16729. v[ i ][ j ] = aj;
  16730. } else {
  16731. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  16732. }
  16733. }
  16734. }
  16735. // construct all of the faces
  16736. for ( let i = 0; i < cols; i ++ ) {
  16737. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  16738. const k = Math.floor( j / 2 );
  16739. if ( j % 2 === 0 ) {
  16740. pushVertex( v[ i ][ k + 1 ] );
  16741. pushVertex( v[ i + 1 ][ k ] );
  16742. pushVertex( v[ i ][ k ] );
  16743. } else {
  16744. pushVertex( v[ i ][ k + 1 ] );
  16745. pushVertex( v[ i + 1 ][ k + 1 ] );
  16746. pushVertex( v[ i + 1 ][ k ] );
  16747. }
  16748. }
  16749. }
  16750. }
  16751. function applyRadius( radius ) {
  16752. const vertex = new Vector3();
  16753. // iterate over the entire buffer and apply the radius to each vertex
  16754. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  16755. vertex.x = vertexBuffer[ i + 0 ];
  16756. vertex.y = vertexBuffer[ i + 1 ];
  16757. vertex.z = vertexBuffer[ i + 2 ];
  16758. vertex.normalize().multiplyScalar( radius );
  16759. vertexBuffer[ i + 0 ] = vertex.x;
  16760. vertexBuffer[ i + 1 ] = vertex.y;
  16761. vertexBuffer[ i + 2 ] = vertex.z;
  16762. }
  16763. }
  16764. function generateUVs() {
  16765. const vertex = new Vector3();
  16766. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  16767. vertex.x = vertexBuffer[ i + 0 ];
  16768. vertex.y = vertexBuffer[ i + 1 ];
  16769. vertex.z = vertexBuffer[ i + 2 ];
  16770. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  16771. const v = inclination( vertex ) / Math.PI + 0.5;
  16772. uvBuffer.push( u, 1 - v );
  16773. }
  16774. correctUVs();
  16775. correctSeam();
  16776. }
  16777. function correctSeam() {
  16778. // handle case when face straddles the seam, see #3269
  16779. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  16780. // uv data of a single face
  16781. const x0 = uvBuffer[ i + 0 ];
  16782. const x1 = uvBuffer[ i + 2 ];
  16783. const x2 = uvBuffer[ i + 4 ];
  16784. const max = Math.max( x0, x1, x2 );
  16785. const min = Math.min( x0, x1, x2 );
  16786. // 0.9 is somewhat arbitrary
  16787. if ( max > 0.9 && min < 0.1 ) {
  16788. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  16789. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  16790. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  16791. }
  16792. }
  16793. }
  16794. function pushVertex( vertex ) {
  16795. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  16796. }
  16797. function getVertexByIndex( index, vertex ) {
  16798. const stride = index * 3;
  16799. vertex.x = vertices[ stride + 0 ];
  16800. vertex.y = vertices[ stride + 1 ];
  16801. vertex.z = vertices[ stride + 2 ];
  16802. }
  16803. function correctUVs() {
  16804. const a = new Vector3();
  16805. const b = new Vector3();
  16806. const c = new Vector3();
  16807. const centroid = new Vector3();
  16808. const uvA = new Vector2();
  16809. const uvB = new Vector2();
  16810. const uvC = new Vector2();
  16811. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  16812. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  16813. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  16814. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  16815. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  16816. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  16817. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  16818. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  16819. const azi = azimuth( centroid );
  16820. correctUV( uvA, j + 0, a, azi );
  16821. correctUV( uvB, j + 2, b, azi );
  16822. correctUV( uvC, j + 4, c, azi );
  16823. }
  16824. }
  16825. function correctUV( uv, stride, vector, azimuth ) {
  16826. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  16827. uvBuffer[ stride ] = uv.x - 1;
  16828. }
  16829. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  16830. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  16831. }
  16832. }
  16833. // Angle around the Y axis, counter-clockwise when looking from above.
  16834. function azimuth( vector ) {
  16835. return Math.atan2( vector.z, - vector.x );
  16836. }
  16837. // Angle above the XZ plane.
  16838. function inclination( vector ) {
  16839. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  16840. }
  16841. }
  16842. }
  16843. class DodecahedronGeometry extends PolyhedronGeometry {
  16844. constructor( radius = 1, detail = 0 ) {
  16845. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  16846. const r = 1 / t;
  16847. const vertices = [
  16848. // (±1, ±1, ±1)
  16849. - 1, - 1, - 1, - 1, - 1, 1,
  16850. - 1, 1, - 1, - 1, 1, 1,
  16851. 1, - 1, - 1, 1, - 1, 1,
  16852. 1, 1, - 1, 1, 1, 1,
  16853. // (0, ±1/φ, ±φ)
  16854. 0, - r, - t, 0, - r, t,
  16855. 0, r, - t, 0, r, t,
  16856. // (±1/φ, ±φ, 0)
  16857. - r, - t, 0, - r, t, 0,
  16858. r, - t, 0, r, t, 0,
  16859. // (±φ, 0, ±1/φ)
  16860. - t, 0, - r, t, 0, - r,
  16861. - t, 0, r, t, 0, r
  16862. ];
  16863. const indices = [
  16864. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  16865. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  16866. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  16867. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  16868. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  16869. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  16870. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  16871. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  16872. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  16873. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  16874. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  16875. 1, 12, 14, 1, 14, 5, 1, 5, 9
  16876. ];
  16877. super( vertices, indices, radius, detail );
  16878. this.type = 'DodecahedronGeometry';
  16879. this.parameters = {
  16880. radius: radius,
  16881. detail: detail
  16882. };
  16883. }
  16884. }
  16885. const _v0 = new Vector3();
  16886. const _v1$1 = new Vector3();
  16887. const _normal = new Vector3();
  16888. const _triangle = new Triangle();
  16889. class EdgesGeometry extends BufferGeometry {
  16890. constructor( geometry, thresholdAngle ) {
  16891. super();
  16892. this.type = 'EdgesGeometry';
  16893. this.parameters = {
  16894. thresholdAngle: thresholdAngle
  16895. };
  16896. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16897. if ( geometry.isGeometry === true ) {
  16898. console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16899. return;
  16900. }
  16901. const precisionPoints = 4;
  16902. const precision = Math.pow( 10, precisionPoints );
  16903. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  16904. const indexAttr = geometry.getIndex();
  16905. const positionAttr = geometry.getAttribute( 'position' );
  16906. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16907. const indexArr = [ 0, 0, 0 ];
  16908. const vertKeys = [ 'a', 'b', 'c' ];
  16909. const hashes = new Array( 3 );
  16910. const edgeData = {};
  16911. const vertices = [];
  16912. for ( let i = 0; i < indexCount; i += 3 ) {
  16913. if ( indexAttr ) {
  16914. indexArr[ 0 ] = indexAttr.getX( i );
  16915. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  16916. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  16917. } else {
  16918. indexArr[ 0 ] = i;
  16919. indexArr[ 1 ] = i + 1;
  16920. indexArr[ 2 ] = i + 2;
  16921. }
  16922. const { a, b, c } = _triangle;
  16923. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  16924. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  16925. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  16926. _triangle.getNormal( _normal );
  16927. // create hashes for the edge from the vertices
  16928. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  16929. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  16930. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  16931. // skip degenerate triangles
  16932. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  16933. continue;
  16934. }
  16935. // iterate over every edge
  16936. for ( let j = 0; j < 3; j ++ ) {
  16937. // get the first and next vertex making up the edge
  16938. const jNext = ( j + 1 ) % 3;
  16939. const vecHash0 = hashes[ j ];
  16940. const vecHash1 = hashes[ jNext ];
  16941. const v0 = _triangle[ vertKeys[ j ] ];
  16942. const v1 = _triangle[ vertKeys[ jNext ] ];
  16943. const hash = `${ vecHash0 }_${ vecHash1 }`;
  16944. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  16945. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  16946. // if we found a sibling edge add it into the vertex array if
  16947. // it meets the angle threshold and delete the edge from the map.
  16948. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  16949. vertices.push( v0.x, v0.y, v0.z );
  16950. vertices.push( v1.x, v1.y, v1.z );
  16951. }
  16952. edgeData[ reverseHash ] = null;
  16953. } else if ( ! ( hash in edgeData ) ) {
  16954. // if we've already got an edge here then skip adding a new one
  16955. edgeData[ hash ] = {
  16956. index0: indexArr[ j ],
  16957. index1: indexArr[ jNext ],
  16958. normal: _normal.clone(),
  16959. };
  16960. }
  16961. }
  16962. }
  16963. // iterate over all remaining, unmatched edges and add them to the vertex array
  16964. for ( const key in edgeData ) {
  16965. if ( edgeData[ key ] ) {
  16966. const { index0, index1 } = edgeData[ key ];
  16967. _v0.fromBufferAttribute( positionAttr, index0 );
  16968. _v1$1.fromBufferAttribute( positionAttr, index1 );
  16969. vertices.push( _v0.x, _v0.y, _v0.z );
  16970. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  16971. }
  16972. }
  16973. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16974. }
  16975. }
  16976. /**
  16977. * Port from https://github.com/mapbox/earcut (v2.2.2)
  16978. */
  16979. const Earcut = {
  16980. triangulate: function ( data, holeIndices, dim ) {
  16981. dim = dim || 2;
  16982. const hasHoles = holeIndices && holeIndices.length;
  16983. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  16984. let outerNode = linkedList( data, 0, outerLen, dim, true );
  16985. const triangles = [];
  16986. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  16987. let minX, minY, maxX, maxY, x, y, invSize;
  16988. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  16989. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  16990. if ( data.length > 80 * dim ) {
  16991. minX = maxX = data[ 0 ];
  16992. minY = maxY = data[ 1 ];
  16993. for ( let i = dim; i < outerLen; i += dim ) {
  16994. x = data[ i ];
  16995. y = data[ i + 1 ];
  16996. if ( x < minX ) minX = x;
  16997. if ( y < minY ) minY = y;
  16998. if ( x > maxX ) maxX = x;
  16999. if ( y > maxY ) maxY = y;
  17000. }
  17001. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17002. invSize = Math.max( maxX - minX, maxY - minY );
  17003. invSize = invSize !== 0 ? 1 / invSize : 0;
  17004. }
  17005. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  17006. return triangles;
  17007. }
  17008. };
  17009. // create a circular doubly linked list from polygon points in the specified winding order
  17010. function linkedList( data, start, end, dim, clockwise ) {
  17011. let i, last;
  17012. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  17013. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17014. } else {
  17015. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17016. }
  17017. if ( last && equals( last, last.next ) ) {
  17018. removeNode( last );
  17019. last = last.next;
  17020. }
  17021. return last;
  17022. }
  17023. // eliminate colinear or duplicate points
  17024. function filterPoints( start, end ) {
  17025. if ( ! start ) return start;
  17026. if ( ! end ) end = start;
  17027. let p = start,
  17028. again;
  17029. do {
  17030. again = false;
  17031. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  17032. removeNode( p );
  17033. p = end = p.prev;
  17034. if ( p === p.next ) break;
  17035. again = true;
  17036. } else {
  17037. p = p.next;
  17038. }
  17039. } while ( again || p !== end );
  17040. return end;
  17041. }
  17042. // main ear slicing loop which triangulates a polygon (given as a linked list)
  17043. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  17044. if ( ! ear ) return;
  17045. // interlink polygon nodes in z-order
  17046. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  17047. let stop = ear,
  17048. prev, next;
  17049. // iterate through ears, slicing them one by one
  17050. while ( ear.prev !== ear.next ) {
  17051. prev = ear.prev;
  17052. next = ear.next;
  17053. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  17054. // cut off the triangle
  17055. triangles.push( prev.i / dim );
  17056. triangles.push( ear.i / dim );
  17057. triangles.push( next.i / dim );
  17058. removeNode( ear );
  17059. // skipping the next vertex leads to less sliver triangles
  17060. ear = next.next;
  17061. stop = next.next;
  17062. continue;
  17063. }
  17064. ear = next;
  17065. // if we looped through the whole remaining polygon and can't find any more ears
  17066. if ( ear === stop ) {
  17067. // try filtering points and slicing again
  17068. if ( ! pass ) {
  17069. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  17070. // if this didn't work, try curing all small self-intersections locally
  17071. } else if ( pass === 1 ) {
  17072. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  17073. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  17074. // as a last resort, try splitting the remaining polygon into two
  17075. } else if ( pass === 2 ) {
  17076. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  17077. }
  17078. break;
  17079. }
  17080. }
  17081. }
  17082. // check whether a polygon node forms a valid ear with adjacent nodes
  17083. function isEar( ear ) {
  17084. const a = ear.prev,
  17085. b = ear,
  17086. c = ear.next;
  17087. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17088. // now make sure we don't have other points inside the potential ear
  17089. let p = ear.next.next;
  17090. while ( p !== ear.prev ) {
  17091. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17092. area( p.prev, p, p.next ) >= 0 ) return false;
  17093. p = p.next;
  17094. }
  17095. return true;
  17096. }
  17097. function isEarHashed( ear, minX, minY, invSize ) {
  17098. const a = ear.prev,
  17099. b = ear,
  17100. c = ear.next;
  17101. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17102. // triangle bbox; min & max are calculated like this for speed
  17103. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  17104. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  17105. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  17106. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  17107. // z-order range for the current triangle bbox;
  17108. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  17109. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  17110. let p = ear.prevZ,
  17111. n = ear.nextZ;
  17112. // look for points inside the triangle in both directions
  17113. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  17114. if ( p !== ear.prev && p !== ear.next &&
  17115. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17116. area( p.prev, p, p.next ) >= 0 ) return false;
  17117. p = p.prevZ;
  17118. if ( n !== ear.prev && n !== ear.next &&
  17119. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17120. area( n.prev, n, n.next ) >= 0 ) return false;
  17121. n = n.nextZ;
  17122. }
  17123. // look for remaining points in decreasing z-order
  17124. while ( p && p.z >= minZ ) {
  17125. if ( p !== ear.prev && p !== ear.next &&
  17126. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17127. area( p.prev, p, p.next ) >= 0 ) return false;
  17128. p = p.prevZ;
  17129. }
  17130. // look for remaining points in increasing z-order
  17131. while ( n && n.z <= maxZ ) {
  17132. if ( n !== ear.prev && n !== ear.next &&
  17133. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17134. area( n.prev, n, n.next ) >= 0 ) return false;
  17135. n = n.nextZ;
  17136. }
  17137. return true;
  17138. }
  17139. // go through all polygon nodes and cure small local self-intersections
  17140. function cureLocalIntersections( start, triangles, dim ) {
  17141. let p = start;
  17142. do {
  17143. const a = p.prev,
  17144. b = p.next.next;
  17145. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  17146. triangles.push( a.i / dim );
  17147. triangles.push( p.i / dim );
  17148. triangles.push( b.i / dim );
  17149. // remove two nodes involved
  17150. removeNode( p );
  17151. removeNode( p.next );
  17152. p = start = b;
  17153. }
  17154. p = p.next;
  17155. } while ( p !== start );
  17156. return filterPoints( p );
  17157. }
  17158. // try splitting polygon into two and triangulate them independently
  17159. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  17160. // look for a valid diagonal that divides the polygon into two
  17161. let a = start;
  17162. do {
  17163. let b = a.next.next;
  17164. while ( b !== a.prev ) {
  17165. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  17166. // split the polygon in two by the diagonal
  17167. let c = splitPolygon( a, b );
  17168. // filter colinear points around the cuts
  17169. a = filterPoints( a, a.next );
  17170. c = filterPoints( c, c.next );
  17171. // run earcut on each half
  17172. earcutLinked( a, triangles, dim, minX, minY, invSize );
  17173. earcutLinked( c, triangles, dim, minX, minY, invSize );
  17174. return;
  17175. }
  17176. b = b.next;
  17177. }
  17178. a = a.next;
  17179. } while ( a !== start );
  17180. }
  17181. // link every hole into the outer loop, producing a single-ring polygon without holes
  17182. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  17183. const queue = [];
  17184. let i, len, start, end, list;
  17185. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  17186. start = holeIndices[ i ] * dim;
  17187. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  17188. list = linkedList( data, start, end, dim, false );
  17189. if ( list === list.next ) list.steiner = true;
  17190. queue.push( getLeftmost( list ) );
  17191. }
  17192. queue.sort( compareX );
  17193. // process holes from left to right
  17194. for ( i = 0; i < queue.length; i ++ ) {
  17195. eliminateHole( queue[ i ], outerNode );
  17196. outerNode = filterPoints( outerNode, outerNode.next );
  17197. }
  17198. return outerNode;
  17199. }
  17200. function compareX( a, b ) {
  17201. return a.x - b.x;
  17202. }
  17203. // find a bridge between vertices that connects hole with an outer ring and and link it
  17204. function eliminateHole( hole, outerNode ) {
  17205. outerNode = findHoleBridge( hole, outerNode );
  17206. if ( outerNode ) {
  17207. const b = splitPolygon( outerNode, hole );
  17208. // filter collinear points around the cuts
  17209. filterPoints( outerNode, outerNode.next );
  17210. filterPoints( b, b.next );
  17211. }
  17212. }
  17213. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17214. function findHoleBridge( hole, outerNode ) {
  17215. let p = outerNode;
  17216. const hx = hole.x;
  17217. const hy = hole.y;
  17218. let qx = - Infinity, m;
  17219. // find a segment intersected by a ray from the hole's leftmost point to the left;
  17220. // segment's endpoint with lesser x will be potential connection point
  17221. do {
  17222. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  17223. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  17224. if ( x <= hx && x > qx ) {
  17225. qx = x;
  17226. if ( x === hx ) {
  17227. if ( hy === p.y ) return p;
  17228. if ( hy === p.next.y ) return p.next;
  17229. }
  17230. m = p.x < p.next.x ? p : p.next;
  17231. }
  17232. }
  17233. p = p.next;
  17234. } while ( p !== outerNode );
  17235. if ( ! m ) return null;
  17236. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  17237. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17238. // if there are no points found, we have a valid connection;
  17239. // otherwise choose the point of the minimum angle with the ray as connection point
  17240. const stop = m,
  17241. mx = m.x,
  17242. my = m.y;
  17243. let tanMin = Infinity, tan;
  17244. p = m;
  17245. do {
  17246. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  17247. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  17248. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  17249. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  17250. m = p;
  17251. tanMin = tan;
  17252. }
  17253. }
  17254. p = p.next;
  17255. } while ( p !== stop );
  17256. return m;
  17257. }
  17258. // whether sector in vertex m contains sector in vertex p in the same coordinates
  17259. function sectorContainsSector( m, p ) {
  17260. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  17261. }
  17262. // interlink polygon nodes in z-order
  17263. function indexCurve( start, minX, minY, invSize ) {
  17264. let p = start;
  17265. do {
  17266. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  17267. p.prevZ = p.prev;
  17268. p.nextZ = p.next;
  17269. p = p.next;
  17270. } while ( p !== start );
  17271. p.prevZ.nextZ = null;
  17272. p.prevZ = null;
  17273. sortLinked( p );
  17274. }
  17275. // Simon Tatham's linked list merge sort algorithm
  17276. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17277. function sortLinked( list ) {
  17278. let i, p, q, e, tail, numMerges, pSize, qSize,
  17279. inSize = 1;
  17280. do {
  17281. p = list;
  17282. list = null;
  17283. tail = null;
  17284. numMerges = 0;
  17285. while ( p ) {
  17286. numMerges ++;
  17287. q = p;
  17288. pSize = 0;
  17289. for ( i = 0; i < inSize; i ++ ) {
  17290. pSize ++;
  17291. q = q.nextZ;
  17292. if ( ! q ) break;
  17293. }
  17294. qSize = inSize;
  17295. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  17296. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  17297. e = p;
  17298. p = p.nextZ;
  17299. pSize --;
  17300. } else {
  17301. e = q;
  17302. q = q.nextZ;
  17303. qSize --;
  17304. }
  17305. if ( tail ) tail.nextZ = e;
  17306. else list = e;
  17307. e.prevZ = tail;
  17308. tail = e;
  17309. }
  17310. p = q;
  17311. }
  17312. tail.nextZ = null;
  17313. inSize *= 2;
  17314. } while ( numMerges > 1 );
  17315. return list;
  17316. }
  17317. // z-order of a point given coords and inverse of the longer side of data bbox
  17318. function zOrder( x, y, minX, minY, invSize ) {
  17319. // coords are transformed into non-negative 15-bit integer range
  17320. x = 32767 * ( x - minX ) * invSize;
  17321. y = 32767 * ( y - minY ) * invSize;
  17322. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  17323. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  17324. x = ( x | ( x << 2 ) ) & 0x33333333;
  17325. x = ( x | ( x << 1 ) ) & 0x55555555;
  17326. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  17327. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  17328. y = ( y | ( y << 2 ) ) & 0x33333333;
  17329. y = ( y | ( y << 1 ) ) & 0x55555555;
  17330. return x | ( y << 1 );
  17331. }
  17332. // find the leftmost node of a polygon ring
  17333. function getLeftmost( start ) {
  17334. let p = start,
  17335. leftmost = start;
  17336. do {
  17337. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  17338. p = p.next;
  17339. } while ( p !== start );
  17340. return leftmost;
  17341. }
  17342. // check if a point lies within a convex triangle
  17343. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  17344. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  17345. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  17346. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  17347. }
  17348. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17349. function isValidDiagonal( a, b ) {
  17350. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  17351. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  17352. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  17353. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  17354. }
  17355. // signed area of a triangle
  17356. function area( p, q, r ) {
  17357. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  17358. }
  17359. // check if two points are equal
  17360. function equals( p1, p2 ) {
  17361. return p1.x === p2.x && p1.y === p2.y;
  17362. }
  17363. // check if two segments intersect
  17364. function intersects( p1, q1, p2, q2 ) {
  17365. const o1 = sign( area( p1, q1, p2 ) );
  17366. const o2 = sign( area( p1, q1, q2 ) );
  17367. const o3 = sign( area( p2, q2, p1 ) );
  17368. const o4 = sign( area( p2, q2, q1 ) );
  17369. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  17370. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17371. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17372. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17373. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17374. return false;
  17375. }
  17376. // for collinear points p, q, r, check if point q lies on segment pr
  17377. function onSegment( p, q, r ) {
  17378. 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 );
  17379. }
  17380. function sign( num ) {
  17381. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  17382. }
  17383. // check if a polygon diagonal intersects any polygon segments
  17384. function intersectsPolygon( a, b ) {
  17385. let p = a;
  17386. do {
  17387. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  17388. intersects( p, p.next, a, b ) ) return true;
  17389. p = p.next;
  17390. } while ( p !== a );
  17391. return false;
  17392. }
  17393. // check if a polygon diagonal is locally inside the polygon
  17394. function locallyInside( a, b ) {
  17395. return area( a.prev, a, a.next ) < 0 ?
  17396. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  17397. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  17398. }
  17399. // check if the middle point of a polygon diagonal is inside the polygon
  17400. function middleInside( a, b ) {
  17401. let p = a,
  17402. inside = false;
  17403. const px = ( a.x + b.x ) / 2,
  17404. py = ( a.y + b.y ) / 2;
  17405. do {
  17406. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  17407. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  17408. inside = ! inside;
  17409. p = p.next;
  17410. } while ( p !== a );
  17411. return inside;
  17412. }
  17413. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17414. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17415. function splitPolygon( a, b ) {
  17416. const a2 = new Node( a.i, a.x, a.y ),
  17417. b2 = new Node( b.i, b.x, b.y ),
  17418. an = a.next,
  17419. bp = b.prev;
  17420. a.next = b;
  17421. b.prev = a;
  17422. a2.next = an;
  17423. an.prev = a2;
  17424. b2.next = a2;
  17425. a2.prev = b2;
  17426. bp.next = b2;
  17427. b2.prev = bp;
  17428. return b2;
  17429. }
  17430. // create a node and optionally link it with previous one (in a circular doubly linked list)
  17431. function insertNode( i, x, y, last ) {
  17432. const p = new Node( i, x, y );
  17433. if ( ! last ) {
  17434. p.prev = p;
  17435. p.next = p;
  17436. } else {
  17437. p.next = last.next;
  17438. p.prev = last;
  17439. last.next.prev = p;
  17440. last.next = p;
  17441. }
  17442. return p;
  17443. }
  17444. function removeNode( p ) {
  17445. p.next.prev = p.prev;
  17446. p.prev.next = p.next;
  17447. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  17448. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  17449. }
  17450. function Node( i, x, y ) {
  17451. // vertex index in coordinates array
  17452. this.i = i;
  17453. // vertex coordinates
  17454. this.x = x;
  17455. this.y = y;
  17456. // previous and next vertex nodes in a polygon ring
  17457. this.prev = null;
  17458. this.next = null;
  17459. // z-order curve value
  17460. this.z = null;
  17461. // previous and next nodes in z-order
  17462. this.prevZ = null;
  17463. this.nextZ = null;
  17464. // indicates whether this is a steiner point
  17465. this.steiner = false;
  17466. }
  17467. function signedArea( data, start, end, dim ) {
  17468. let sum = 0;
  17469. for ( let i = start, j = end - dim; i < end; i += dim ) {
  17470. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  17471. j = i;
  17472. }
  17473. return sum;
  17474. }
  17475. class ShapeUtils {
  17476. // calculate area of the contour polygon
  17477. static area( contour ) {
  17478. const n = contour.length;
  17479. let a = 0.0;
  17480. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  17481. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17482. }
  17483. return a * 0.5;
  17484. }
  17485. static isClockWise( pts ) {
  17486. return ShapeUtils.area( pts ) < 0;
  17487. }
  17488. static triangulateShape( contour, holes ) {
  17489. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17490. const holeIndices = []; // array of hole indices
  17491. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17492. removeDupEndPts( contour );
  17493. addContour( vertices, contour );
  17494. //
  17495. let holeIndex = contour.length;
  17496. holes.forEach( removeDupEndPts );
  17497. for ( let i = 0; i < holes.length; i ++ ) {
  17498. holeIndices.push( holeIndex );
  17499. holeIndex += holes[ i ].length;
  17500. addContour( vertices, holes[ i ] );
  17501. }
  17502. //
  17503. const triangles = Earcut.triangulate( vertices, holeIndices );
  17504. //
  17505. for ( let i = 0; i < triangles.length; i += 3 ) {
  17506. faces.push( triangles.slice( i, i + 3 ) );
  17507. }
  17508. return faces;
  17509. }
  17510. }
  17511. function removeDupEndPts( points ) {
  17512. const l = points.length;
  17513. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17514. points.pop();
  17515. }
  17516. }
  17517. function addContour( vertices, contour ) {
  17518. for ( let i = 0; i < contour.length; i ++ ) {
  17519. vertices.push( contour[ i ].x );
  17520. vertices.push( contour[ i ].y );
  17521. }
  17522. }
  17523. /**
  17524. * Creates extruded geometry from a path shape.
  17525. *
  17526. * parameters = {
  17527. *
  17528. * curveSegments: <int>, // number of points on the curves
  17529. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17530. * depth: <float>, // Depth to extrude the shape
  17531. *
  17532. * bevelEnabled: <bool>, // turn on bevel
  17533. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17534. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17535. * bevelOffset: <float>, // how far from shape outline does bevel start
  17536. * bevelSegments: <int>, // number of bevel layers
  17537. *
  17538. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17539. *
  17540. * UVGenerator: <Object> // object that provides UV generator functions
  17541. *
  17542. * }
  17543. */
  17544. class ExtrudeGeometry extends BufferGeometry {
  17545. constructor( shapes, options ) {
  17546. super();
  17547. this.type = 'ExtrudeGeometry';
  17548. this.parameters = {
  17549. shapes: shapes,
  17550. options: options
  17551. };
  17552. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  17553. const scope = this;
  17554. const verticesArray = [];
  17555. const uvArray = [];
  17556. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  17557. const shape = shapes[ i ];
  17558. addShape( shape );
  17559. }
  17560. // build geometry
  17561. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  17562. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  17563. this.computeVertexNormals();
  17564. // functions
  17565. function addShape( shape ) {
  17566. const placeholder = [];
  17567. // options
  17568. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17569. const steps = options.steps !== undefined ? options.steps : 1;
  17570. let depth = options.depth !== undefined ? options.depth : 100;
  17571. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17572. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17573. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17574. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17575. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17576. const extrudePath = options.extrudePath;
  17577. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  17578. // deprecated options
  17579. if ( options.amount !== undefined ) {
  17580. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  17581. depth = options.amount;
  17582. }
  17583. //
  17584. let extrudePts, extrudeByPath = false;
  17585. let splineTube, binormal, normal, position2;
  17586. if ( extrudePath ) {
  17587. extrudePts = extrudePath.getSpacedPoints( steps );
  17588. extrudeByPath = true;
  17589. bevelEnabled = false; // bevels not supported for path extrusion
  17590. // SETUP TNB variables
  17591. // TODO1 - have a .isClosed in spline?
  17592. splineTube = extrudePath.computeFrenetFrames( steps, false );
  17593. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17594. binormal = new Vector3();
  17595. normal = new Vector3();
  17596. position2 = new Vector3();
  17597. }
  17598. // Safeguards if bevels are not enabled
  17599. if ( ! bevelEnabled ) {
  17600. bevelSegments = 0;
  17601. bevelThickness = 0;
  17602. bevelSize = 0;
  17603. bevelOffset = 0;
  17604. }
  17605. // Variables initialization
  17606. const shapePoints = shape.extractPoints( curveSegments );
  17607. let vertices = shapePoints.shape;
  17608. const holes = shapePoints.holes;
  17609. const reverse = ! ShapeUtils.isClockWise( vertices );
  17610. if ( reverse ) {
  17611. vertices = vertices.reverse();
  17612. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17613. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17614. const ahole = holes[ h ];
  17615. if ( ShapeUtils.isClockWise( ahole ) ) {
  17616. holes[ h ] = ahole.reverse();
  17617. }
  17618. }
  17619. }
  17620. const faces = ShapeUtils.triangulateShape( vertices, holes );
  17621. /* Vertices */
  17622. const contour = vertices; // vertices has all points but contour has only points of circumference
  17623. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17624. const ahole = holes[ h ];
  17625. vertices = vertices.concat( ahole );
  17626. }
  17627. function scalePt2( pt, vec, size ) {
  17628. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  17629. return vec.clone().multiplyScalar( size ).add( pt );
  17630. }
  17631. const vlen = vertices.length, flen = faces.length;
  17632. // Find directions for point movement
  17633. function getBevelVec( inPt, inPrev, inNext ) {
  17634. // computes for inPt the corresponding point inPt' on a new contour
  17635. // shifted by 1 unit (length of normalized vector) to the left
  17636. // if we walk along contour clockwise, this new contour is outside the old one
  17637. //
  17638. // inPt' is the intersection of the two lines parallel to the two
  17639. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17640. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17641. // good reading for geometry algorithms (here: line-line intersection)
  17642. // http://geomalgorithms.com/a05-_intersect-1.html
  17643. const v_prev_x = inPt.x - inPrev.x,
  17644. v_prev_y = inPt.y - inPrev.y;
  17645. const v_next_x = inNext.x - inPt.x,
  17646. v_next_y = inNext.y - inPt.y;
  17647. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  17648. // check for collinear edges
  17649. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  17650. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  17651. // not collinear
  17652. // length of vectors for normalizing
  17653. const v_prev_len = Math.sqrt( v_prev_lensq );
  17654. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  17655. // shift adjacent points by unit vectors to the left
  17656. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  17657. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  17658. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  17659. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  17660. // scaling factor for v_prev to intersection point
  17661. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  17662. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  17663. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  17664. // vector from inPt to intersection point
  17665. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  17666. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  17667. // Don't normalize!, otherwise sharp corners become ugly
  17668. // but prevent crazy spikes
  17669. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  17670. if ( v_trans_lensq <= 2 ) {
  17671. return new Vector2( v_trans_x, v_trans_y );
  17672. } else {
  17673. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  17674. }
  17675. } else {
  17676. // handle special case of collinear edges
  17677. let direction_eq = false; // assumes: opposite
  17678. if ( v_prev_x > Number.EPSILON ) {
  17679. if ( v_next_x > Number.EPSILON ) {
  17680. direction_eq = true;
  17681. }
  17682. } else {
  17683. if ( v_prev_x < - Number.EPSILON ) {
  17684. if ( v_next_x < - Number.EPSILON ) {
  17685. direction_eq = true;
  17686. }
  17687. } else {
  17688. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  17689. direction_eq = true;
  17690. }
  17691. }
  17692. }
  17693. if ( direction_eq ) {
  17694. // console.log("Warning: lines are a straight sequence");
  17695. v_trans_x = - v_prev_y;
  17696. v_trans_y = v_prev_x;
  17697. shrink_by = Math.sqrt( v_prev_lensq );
  17698. } else {
  17699. // console.log("Warning: lines are a straight spike");
  17700. v_trans_x = v_prev_x;
  17701. v_trans_y = v_prev_y;
  17702. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  17703. }
  17704. }
  17705. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  17706. }
  17707. const contourMovements = [];
  17708. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17709. if ( j === il ) j = 0;
  17710. if ( k === il ) k = 0;
  17711. // (j)---(i)---(k)
  17712. // console.log('i,j,k', i, j , k)
  17713. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  17714. }
  17715. const holesMovements = [];
  17716. let oneHoleMovements, verticesMovements = contourMovements.concat();
  17717. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17718. const ahole = holes[ h ];
  17719. oneHoleMovements = [];
  17720. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17721. if ( j === il ) j = 0;
  17722. if ( k === il ) k = 0;
  17723. // (j)---(i)---(k)
  17724. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  17725. }
  17726. holesMovements.push( oneHoleMovements );
  17727. verticesMovements = verticesMovements.concat( oneHoleMovements );
  17728. }
  17729. // Loop bevelSegments, 1 for the front, 1 for the back
  17730. for ( let b = 0; b < bevelSegments; b ++ ) {
  17731. //for ( b = bevelSegments; b > 0; b -- ) {
  17732. const t = b / bevelSegments;
  17733. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  17734. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  17735. // contract shape
  17736. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  17737. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17738. v( vert.x, vert.y, - z );
  17739. }
  17740. // expand holes
  17741. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17742. const ahole = holes[ h ];
  17743. oneHoleMovements = holesMovements[ h ];
  17744. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  17745. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17746. v( vert.x, vert.y, - z );
  17747. }
  17748. }
  17749. }
  17750. const bs = bevelSize + bevelOffset;
  17751. // Back facing vertices
  17752. for ( let i = 0; i < vlen; i ++ ) {
  17753. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17754. if ( ! extrudeByPath ) {
  17755. v( vert.x, vert.y, 0 );
  17756. } else {
  17757. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17758. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  17759. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  17760. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  17761. v( position2.x, position2.y, position2.z );
  17762. }
  17763. }
  17764. // Add stepped vertices...
  17765. // Including front facing vertices
  17766. for ( let s = 1; s <= steps; s ++ ) {
  17767. for ( let i = 0; i < vlen; i ++ ) {
  17768. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17769. if ( ! extrudeByPath ) {
  17770. v( vert.x, vert.y, depth / steps * s );
  17771. } else {
  17772. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17773. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  17774. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  17775. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  17776. v( position2.x, position2.y, position2.z );
  17777. }
  17778. }
  17779. }
  17780. // Add bevel segments planes
  17781. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17782. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  17783. const t = b / bevelSegments;
  17784. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  17785. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  17786. // contract shape
  17787. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  17788. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17789. v( vert.x, vert.y, depth + z );
  17790. }
  17791. // expand holes
  17792. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17793. const ahole = holes[ h ];
  17794. oneHoleMovements = holesMovements[ h ];
  17795. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  17796. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17797. if ( ! extrudeByPath ) {
  17798. v( vert.x, vert.y, depth + z );
  17799. } else {
  17800. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  17801. }
  17802. }
  17803. }
  17804. }
  17805. /* Faces */
  17806. // Top and bottom faces
  17807. buildLidFaces();
  17808. // Sides faces
  17809. buildSideFaces();
  17810. ///// Internal functions
  17811. function buildLidFaces() {
  17812. const start = verticesArray.length / 3;
  17813. if ( bevelEnabled ) {
  17814. let layer = 0; // steps + 1
  17815. let offset = vlen * layer;
  17816. // Bottom faces
  17817. for ( let i = 0; i < flen; i ++ ) {
  17818. const face = faces[ i ];
  17819. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  17820. }
  17821. layer = steps + bevelSegments * 2;
  17822. offset = vlen * layer;
  17823. // Top faces
  17824. for ( let i = 0; i < flen; i ++ ) {
  17825. const face = faces[ i ];
  17826. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  17827. }
  17828. } else {
  17829. // Bottom faces
  17830. for ( let i = 0; i < flen; i ++ ) {
  17831. const face = faces[ i ];
  17832. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  17833. }
  17834. // Top faces
  17835. for ( let i = 0; i < flen; i ++ ) {
  17836. const face = faces[ i ];
  17837. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  17838. }
  17839. }
  17840. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  17841. }
  17842. // Create faces for the z-sides of the shape
  17843. function buildSideFaces() {
  17844. const start = verticesArray.length / 3;
  17845. let layeroffset = 0;
  17846. sidewalls( contour, layeroffset );
  17847. layeroffset += contour.length;
  17848. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17849. const ahole = holes[ h ];
  17850. sidewalls( ahole, layeroffset );
  17851. //, true
  17852. layeroffset += ahole.length;
  17853. }
  17854. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  17855. }
  17856. function sidewalls( contour, layeroffset ) {
  17857. let i = contour.length;
  17858. while ( -- i >= 0 ) {
  17859. const j = i;
  17860. let k = i - 1;
  17861. if ( k < 0 ) k = contour.length - 1;
  17862. //console.log('b', i,j, i-1, k,vertices.length);
  17863. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  17864. const slen1 = vlen * s;
  17865. const slen2 = vlen * ( s + 1 );
  17866. const a = layeroffset + j + slen1,
  17867. b = layeroffset + k + slen1,
  17868. c = layeroffset + k + slen2,
  17869. d = layeroffset + j + slen2;
  17870. f4( a, b, c, d );
  17871. }
  17872. }
  17873. }
  17874. function v( x, y, z ) {
  17875. placeholder.push( x );
  17876. placeholder.push( y );
  17877. placeholder.push( z );
  17878. }
  17879. function f3( a, b, c ) {
  17880. addVertex( a );
  17881. addVertex( b );
  17882. addVertex( c );
  17883. const nextIndex = verticesArray.length / 3;
  17884. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  17885. addUV( uvs[ 0 ] );
  17886. addUV( uvs[ 1 ] );
  17887. addUV( uvs[ 2 ] );
  17888. }
  17889. function f4( a, b, c, d ) {
  17890. addVertex( a );
  17891. addVertex( b );
  17892. addVertex( d );
  17893. addVertex( b );
  17894. addVertex( c );
  17895. addVertex( d );
  17896. const nextIndex = verticesArray.length / 3;
  17897. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  17898. addUV( uvs[ 0 ] );
  17899. addUV( uvs[ 1 ] );
  17900. addUV( uvs[ 3 ] );
  17901. addUV( uvs[ 1 ] );
  17902. addUV( uvs[ 2 ] );
  17903. addUV( uvs[ 3 ] );
  17904. }
  17905. function addVertex( index ) {
  17906. verticesArray.push( placeholder[ index * 3 + 0 ] );
  17907. verticesArray.push( placeholder[ index * 3 + 1 ] );
  17908. verticesArray.push( placeholder[ index * 3 + 2 ] );
  17909. }
  17910. function addUV( vector2 ) {
  17911. uvArray.push( vector2.x );
  17912. uvArray.push( vector2.y );
  17913. }
  17914. }
  17915. }
  17916. toJSON() {
  17917. const data = BufferGeometry.prototype.toJSON.call( this );
  17918. const shapes = this.parameters.shapes;
  17919. const options = this.parameters.options;
  17920. return toJSON$1( shapes, options, data );
  17921. }
  17922. }
  17923. const WorldUVGenerator = {
  17924. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  17925. const a_x = vertices[ indexA * 3 ];
  17926. const a_y = vertices[ indexA * 3 + 1 ];
  17927. const b_x = vertices[ indexB * 3 ];
  17928. const b_y = vertices[ indexB * 3 + 1 ];
  17929. const c_x = vertices[ indexC * 3 ];
  17930. const c_y = vertices[ indexC * 3 + 1 ];
  17931. return [
  17932. new Vector2( a_x, a_y ),
  17933. new Vector2( b_x, b_y ),
  17934. new Vector2( c_x, c_y )
  17935. ];
  17936. },
  17937. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  17938. const a_x = vertices[ indexA * 3 ];
  17939. const a_y = vertices[ indexA * 3 + 1 ];
  17940. const a_z = vertices[ indexA * 3 + 2 ];
  17941. const b_x = vertices[ indexB * 3 ];
  17942. const b_y = vertices[ indexB * 3 + 1 ];
  17943. const b_z = vertices[ indexB * 3 + 2 ];
  17944. const c_x = vertices[ indexC * 3 ];
  17945. const c_y = vertices[ indexC * 3 + 1 ];
  17946. const c_z = vertices[ indexC * 3 + 2 ];
  17947. const d_x = vertices[ indexD * 3 ];
  17948. const d_y = vertices[ indexD * 3 + 1 ];
  17949. const d_z = vertices[ indexD * 3 + 2 ];
  17950. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  17951. return [
  17952. new Vector2( a_x, 1 - a_z ),
  17953. new Vector2( b_x, 1 - b_z ),
  17954. new Vector2( c_x, 1 - c_z ),
  17955. new Vector2( d_x, 1 - d_z )
  17956. ];
  17957. } else {
  17958. return [
  17959. new Vector2( a_y, 1 - a_z ),
  17960. new Vector2( b_y, 1 - b_z ),
  17961. new Vector2( c_y, 1 - c_z ),
  17962. new Vector2( d_y, 1 - d_z )
  17963. ];
  17964. }
  17965. }
  17966. };
  17967. function toJSON$1( shapes, options, data ) {
  17968. data.shapes = [];
  17969. if ( Array.isArray( shapes ) ) {
  17970. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  17971. const shape = shapes[ i ];
  17972. data.shapes.push( shape.uuid );
  17973. }
  17974. } else {
  17975. data.shapes.push( shapes.uuid );
  17976. }
  17977. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  17978. return data;
  17979. }
  17980. class IcosahedronGeometry extends PolyhedronGeometry {
  17981. constructor( radius = 1, detail = 0 ) {
  17982. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17983. const vertices = [
  17984. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  17985. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  17986. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  17987. ];
  17988. const indices = [
  17989. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  17990. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  17991. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  17992. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  17993. ];
  17994. super( vertices, indices, radius, detail );
  17995. this.type = 'IcosahedronGeometry';
  17996. this.parameters = {
  17997. radius: radius,
  17998. detail: detail
  17999. };
  18000. }
  18001. }
  18002. class LatheGeometry extends BufferGeometry {
  18003. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  18004. super();
  18005. this.type = 'LatheGeometry';
  18006. this.parameters = {
  18007. points: points,
  18008. segments: segments,
  18009. phiStart: phiStart,
  18010. phiLength: phiLength
  18011. };
  18012. segments = Math.floor( segments );
  18013. // clamp phiLength so it's in range of [ 0, 2PI ]
  18014. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  18015. // buffers
  18016. const indices = [];
  18017. const vertices = [];
  18018. const uvs = [];
  18019. // helper variables
  18020. const inverseSegments = 1.0 / segments;
  18021. const vertex = new Vector3();
  18022. const uv = new Vector2();
  18023. // generate vertices and uvs
  18024. for ( let i = 0; i <= segments; i ++ ) {
  18025. const phi = phiStart + i * inverseSegments * phiLength;
  18026. const sin = Math.sin( phi );
  18027. const cos = Math.cos( phi );
  18028. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  18029. // vertex
  18030. vertex.x = points[ j ].x * sin;
  18031. vertex.y = points[ j ].y;
  18032. vertex.z = points[ j ].x * cos;
  18033. vertices.push( vertex.x, vertex.y, vertex.z );
  18034. // uv
  18035. uv.x = i / segments;
  18036. uv.y = j / ( points.length - 1 );
  18037. uvs.push( uv.x, uv.y );
  18038. }
  18039. }
  18040. // indices
  18041. for ( let i = 0; i < segments; i ++ ) {
  18042. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  18043. const base = j + i * points.length;
  18044. const a = base;
  18045. const b = base + points.length;
  18046. const c = base + points.length + 1;
  18047. const d = base + 1;
  18048. // faces
  18049. indices.push( a, b, d );
  18050. indices.push( b, c, d );
  18051. }
  18052. }
  18053. // build geometry
  18054. this.setIndex( indices );
  18055. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18056. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18057. // generate normals
  18058. this.computeVertexNormals();
  18059. // if the geometry is closed, we need to average the normals along the seam.
  18060. // because the corresponding vertices are identical (but still have different UVs).
  18061. if ( phiLength === Math.PI * 2 ) {
  18062. const normals = this.attributes.normal.array;
  18063. const n1 = new Vector3();
  18064. const n2 = new Vector3();
  18065. const n = new Vector3();
  18066. // this is the buffer offset for the last line of vertices
  18067. const base = segments * points.length * 3;
  18068. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  18069. // select the normal of the vertex in the first line
  18070. n1.x = normals[ j + 0 ];
  18071. n1.y = normals[ j + 1 ];
  18072. n1.z = normals[ j + 2 ];
  18073. // select the normal of the vertex in the last line
  18074. n2.x = normals[ base + j + 0 ];
  18075. n2.y = normals[ base + j + 1 ];
  18076. n2.z = normals[ base + j + 2 ];
  18077. // average normals
  18078. n.addVectors( n1, n2 ).normalize();
  18079. // assign the new values to both normals
  18080. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  18081. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  18082. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  18083. }
  18084. }
  18085. }
  18086. }
  18087. class OctahedronGeometry extends PolyhedronGeometry {
  18088. constructor( radius = 1, detail = 0 ) {
  18089. const vertices = [
  18090. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  18091. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  18092. ];
  18093. const indices = [
  18094. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  18095. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  18096. 1, 3, 4, 1, 4, 2
  18097. ];
  18098. super( vertices, indices, radius, detail );
  18099. this.type = 'OctahedronGeometry';
  18100. this.parameters = {
  18101. radius: radius,
  18102. detail: detail
  18103. };
  18104. }
  18105. }
  18106. /**
  18107. * Parametric Surfaces Geometry
  18108. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18109. */
  18110. class ParametricGeometry extends BufferGeometry {
  18111. constructor( func, slices, stacks ) {
  18112. super();
  18113. this.type = 'ParametricGeometry';
  18114. this.parameters = {
  18115. func: func,
  18116. slices: slices,
  18117. stacks: stacks
  18118. };
  18119. // buffers
  18120. const indices = [];
  18121. const vertices = [];
  18122. const normals = [];
  18123. const uvs = [];
  18124. const EPS = 0.00001;
  18125. const normal = new Vector3();
  18126. const p0 = new Vector3(), p1 = new Vector3();
  18127. const pu = new Vector3(), pv = new Vector3();
  18128. if ( func.length < 3 ) {
  18129. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  18130. }
  18131. // generate vertices, normals and uvs
  18132. const sliceCount = slices + 1;
  18133. for ( let i = 0; i <= stacks; i ++ ) {
  18134. const v = i / stacks;
  18135. for ( let j = 0; j <= slices; j ++ ) {
  18136. const u = j / slices;
  18137. // vertex
  18138. func( u, v, p0 );
  18139. vertices.push( p0.x, p0.y, p0.z );
  18140. // normal
  18141. // approximate tangent vectors via finite differences
  18142. if ( u - EPS >= 0 ) {
  18143. func( u - EPS, v, p1 );
  18144. pu.subVectors( p0, p1 );
  18145. } else {
  18146. func( u + EPS, v, p1 );
  18147. pu.subVectors( p1, p0 );
  18148. }
  18149. if ( v - EPS >= 0 ) {
  18150. func( u, v - EPS, p1 );
  18151. pv.subVectors( p0, p1 );
  18152. } else {
  18153. func( u, v + EPS, p1 );
  18154. pv.subVectors( p1, p0 );
  18155. }
  18156. // cross product of tangent vectors returns surface normal
  18157. normal.crossVectors( pu, pv ).normalize();
  18158. normals.push( normal.x, normal.y, normal.z );
  18159. // uv
  18160. uvs.push( u, v );
  18161. }
  18162. }
  18163. // generate indices
  18164. for ( let i = 0; i < stacks; i ++ ) {
  18165. for ( let j = 0; j < slices; j ++ ) {
  18166. const a = i * sliceCount + j;
  18167. const b = i * sliceCount + j + 1;
  18168. const c = ( i + 1 ) * sliceCount + j + 1;
  18169. const d = ( i + 1 ) * sliceCount + j;
  18170. // faces one and two
  18171. indices.push( a, b, d );
  18172. indices.push( b, c, d );
  18173. }
  18174. }
  18175. // build geometry
  18176. this.setIndex( indices );
  18177. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18178. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18179. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18180. }
  18181. }
  18182. class RingGeometry extends BufferGeometry {
  18183. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18184. super();
  18185. this.type = 'RingGeometry';
  18186. this.parameters = {
  18187. innerRadius: innerRadius,
  18188. outerRadius: outerRadius,
  18189. thetaSegments: thetaSegments,
  18190. phiSegments: phiSegments,
  18191. thetaStart: thetaStart,
  18192. thetaLength: thetaLength
  18193. };
  18194. thetaSegments = Math.max( 3, thetaSegments );
  18195. phiSegments = Math.max( 1, phiSegments );
  18196. // buffers
  18197. const indices = [];
  18198. const vertices = [];
  18199. const normals = [];
  18200. const uvs = [];
  18201. // some helper variables
  18202. let radius = innerRadius;
  18203. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  18204. const vertex = new Vector3();
  18205. const uv = new Vector2();
  18206. // generate vertices, normals and uvs
  18207. for ( let j = 0; j <= phiSegments; j ++ ) {
  18208. for ( let i = 0; i <= thetaSegments; i ++ ) {
  18209. // values are generate from the inside of the ring to the outside
  18210. const segment = thetaStart + i / thetaSegments * thetaLength;
  18211. // vertex
  18212. vertex.x = radius * Math.cos( segment );
  18213. vertex.y = radius * Math.sin( segment );
  18214. vertices.push( vertex.x, vertex.y, vertex.z );
  18215. // normal
  18216. normals.push( 0, 0, 1 );
  18217. // uv
  18218. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  18219. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  18220. uvs.push( uv.x, uv.y );
  18221. }
  18222. // increase the radius for next row of vertices
  18223. radius += radiusStep;
  18224. }
  18225. // indices
  18226. for ( let j = 0; j < phiSegments; j ++ ) {
  18227. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  18228. for ( let i = 0; i < thetaSegments; i ++ ) {
  18229. const segment = i + thetaSegmentLevel;
  18230. const a = segment;
  18231. const b = segment + thetaSegments + 1;
  18232. const c = segment + thetaSegments + 2;
  18233. const d = segment + 1;
  18234. // faces
  18235. indices.push( a, b, d );
  18236. indices.push( b, c, d );
  18237. }
  18238. }
  18239. // build geometry
  18240. this.setIndex( indices );
  18241. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18242. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18243. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18244. }
  18245. }
  18246. class ShapeGeometry extends BufferGeometry {
  18247. constructor( shapes, curveSegments = 12 ) {
  18248. super();
  18249. this.type = 'ShapeGeometry';
  18250. this.parameters = {
  18251. shapes: shapes,
  18252. curveSegments: curveSegments
  18253. };
  18254. // buffers
  18255. const indices = [];
  18256. const vertices = [];
  18257. const normals = [];
  18258. const uvs = [];
  18259. // helper variables
  18260. let groupStart = 0;
  18261. let groupCount = 0;
  18262. // allow single and array values for "shapes" parameter
  18263. if ( Array.isArray( shapes ) === false ) {
  18264. addShape( shapes );
  18265. } else {
  18266. for ( let i = 0; i < shapes.length; i ++ ) {
  18267. addShape( shapes[ i ] );
  18268. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  18269. groupStart += groupCount;
  18270. groupCount = 0;
  18271. }
  18272. }
  18273. // build geometry
  18274. this.setIndex( indices );
  18275. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18276. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18277. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18278. // helper functions
  18279. function addShape( shape ) {
  18280. const indexOffset = vertices.length / 3;
  18281. const points = shape.extractPoints( curveSegments );
  18282. let shapeVertices = points.shape;
  18283. const shapeHoles = points.holes;
  18284. // check direction of vertices
  18285. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  18286. shapeVertices = shapeVertices.reverse();
  18287. }
  18288. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  18289. const shapeHole = shapeHoles[ i ];
  18290. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  18291. shapeHoles[ i ] = shapeHole.reverse();
  18292. }
  18293. }
  18294. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  18295. // join vertices of inner and outer paths to a single array
  18296. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  18297. const shapeHole = shapeHoles[ i ];
  18298. shapeVertices = shapeVertices.concat( shapeHole );
  18299. }
  18300. // vertices, normals, uvs
  18301. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  18302. const vertex = shapeVertices[ i ];
  18303. vertices.push( vertex.x, vertex.y, 0 );
  18304. normals.push( 0, 0, 1 );
  18305. uvs.push( vertex.x, vertex.y ); // world uvs
  18306. }
  18307. // incides
  18308. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  18309. const face = faces[ i ];
  18310. const a = face[ 0 ] + indexOffset;
  18311. const b = face[ 1 ] + indexOffset;
  18312. const c = face[ 2 ] + indexOffset;
  18313. indices.push( a, b, c );
  18314. groupCount += 3;
  18315. }
  18316. }
  18317. }
  18318. toJSON() {
  18319. const data = BufferGeometry.prototype.toJSON.call( this );
  18320. const shapes = this.parameters.shapes;
  18321. return toJSON( shapes, data );
  18322. }
  18323. }
  18324. function toJSON( shapes, data ) {
  18325. data.shapes = [];
  18326. if ( Array.isArray( shapes ) ) {
  18327. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18328. const shape = shapes[ i ];
  18329. data.shapes.push( shape.uuid );
  18330. }
  18331. } else {
  18332. data.shapes.push( shapes.uuid );
  18333. }
  18334. return data;
  18335. }
  18336. class SphereGeometry extends BufferGeometry {
  18337. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  18338. super();
  18339. this.type = 'SphereGeometry';
  18340. this.parameters = {
  18341. radius: radius,
  18342. widthSegments: widthSegments,
  18343. heightSegments: heightSegments,
  18344. phiStart: phiStart,
  18345. phiLength: phiLength,
  18346. thetaStart: thetaStart,
  18347. thetaLength: thetaLength
  18348. };
  18349. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  18350. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  18351. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  18352. let index = 0;
  18353. const grid = [];
  18354. const vertex = new Vector3();
  18355. const normal = new Vector3();
  18356. // buffers
  18357. const indices = [];
  18358. const vertices = [];
  18359. const normals = [];
  18360. const uvs = [];
  18361. // generate vertices, normals and uvs
  18362. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  18363. const verticesRow = [];
  18364. const v = iy / heightSegments;
  18365. // special case for the poles
  18366. let uOffset = 0;
  18367. if ( iy == 0 && thetaStart == 0 ) {
  18368. uOffset = 0.5 / widthSegments;
  18369. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  18370. uOffset = - 0.5 / widthSegments;
  18371. }
  18372. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  18373. const u = ix / widthSegments;
  18374. // vertex
  18375. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18376. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18377. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18378. vertices.push( vertex.x, vertex.y, vertex.z );
  18379. // normal
  18380. normal.copy( vertex ).normalize();
  18381. normals.push( normal.x, normal.y, normal.z );
  18382. // uv
  18383. uvs.push( u + uOffset, 1 - v );
  18384. verticesRow.push( index ++ );
  18385. }
  18386. grid.push( verticesRow );
  18387. }
  18388. // indices
  18389. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  18390. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  18391. const a = grid[ iy ][ ix + 1 ];
  18392. const b = grid[ iy ][ ix ];
  18393. const c = grid[ iy + 1 ][ ix ];
  18394. const d = grid[ iy + 1 ][ ix + 1 ];
  18395. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  18396. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  18397. }
  18398. }
  18399. // build geometry
  18400. this.setIndex( indices );
  18401. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18402. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18403. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18404. }
  18405. }
  18406. class TetrahedronGeometry extends PolyhedronGeometry {
  18407. constructor( radius = 1, detail = 0 ) {
  18408. const vertices = [
  18409. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  18410. ];
  18411. const indices = [
  18412. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  18413. ];
  18414. super( vertices, indices, radius, detail );
  18415. this.type = 'TetrahedronGeometry';
  18416. this.parameters = {
  18417. radius: radius,
  18418. detail: detail
  18419. };
  18420. }
  18421. }
  18422. /**
  18423. * Text = 3D Text
  18424. *
  18425. * parameters = {
  18426. * font: <THREE.Font>, // font
  18427. *
  18428. * size: <float>, // size of the text
  18429. * height: <float>, // thickness to extrude text
  18430. * curveSegments: <int>, // number of points on the curves
  18431. *
  18432. * bevelEnabled: <bool>, // turn on bevel
  18433. * bevelThickness: <float>, // how deep into text bevel goes
  18434. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18435. * bevelOffset: <float> // how far from text outline does bevel start
  18436. * }
  18437. */
  18438. class TextGeometry extends ExtrudeGeometry {
  18439. constructor( text, parameters = {} ) {
  18440. const font = parameters.font;
  18441. if ( ! ( font && font.isFont ) ) {
  18442. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  18443. return new BufferGeometry();
  18444. }
  18445. const shapes = font.generateShapes( text, parameters.size );
  18446. // translate parameters to ExtrudeGeometry API
  18447. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  18448. // defaults
  18449. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18450. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18451. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18452. super( shapes, parameters );
  18453. this.type = 'TextGeometry';
  18454. }
  18455. }
  18456. class TorusGeometry extends BufferGeometry {
  18457. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  18458. super();
  18459. this.type = 'TorusGeometry';
  18460. this.parameters = {
  18461. radius: radius,
  18462. tube: tube,
  18463. radialSegments: radialSegments,
  18464. tubularSegments: tubularSegments,
  18465. arc: arc
  18466. };
  18467. radialSegments = Math.floor( radialSegments );
  18468. tubularSegments = Math.floor( tubularSegments );
  18469. // buffers
  18470. const indices = [];
  18471. const vertices = [];
  18472. const normals = [];
  18473. const uvs = [];
  18474. // helper variables
  18475. const center = new Vector3();
  18476. const vertex = new Vector3();
  18477. const normal = new Vector3();
  18478. // generate vertices, normals and uvs
  18479. for ( let j = 0; j <= radialSegments; j ++ ) {
  18480. for ( let i = 0; i <= tubularSegments; i ++ ) {
  18481. const u = i / tubularSegments * arc;
  18482. const v = j / radialSegments * Math.PI * 2;
  18483. // vertex
  18484. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  18485. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  18486. vertex.z = tube * Math.sin( v );
  18487. vertices.push( vertex.x, vertex.y, vertex.z );
  18488. // normal
  18489. center.x = radius * Math.cos( u );
  18490. center.y = radius * Math.sin( u );
  18491. normal.subVectors( vertex, center ).normalize();
  18492. normals.push( normal.x, normal.y, normal.z );
  18493. // uv
  18494. uvs.push( i / tubularSegments );
  18495. uvs.push( j / radialSegments );
  18496. }
  18497. }
  18498. // generate indices
  18499. for ( let j = 1; j <= radialSegments; j ++ ) {
  18500. for ( let i = 1; i <= tubularSegments; i ++ ) {
  18501. // indices
  18502. const a = ( tubularSegments + 1 ) * j + i - 1;
  18503. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18504. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  18505. const d = ( tubularSegments + 1 ) * j + i;
  18506. // faces
  18507. indices.push( a, b, d );
  18508. indices.push( b, c, d );
  18509. }
  18510. }
  18511. // build geometry
  18512. this.setIndex( indices );
  18513. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18514. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18515. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18516. }
  18517. }
  18518. class TorusKnotGeometry extends BufferGeometry {
  18519. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  18520. super();
  18521. this.type = 'TorusKnotGeometry';
  18522. this.parameters = {
  18523. radius: radius,
  18524. tube: tube,
  18525. tubularSegments: tubularSegments,
  18526. radialSegments: radialSegments,
  18527. p: p,
  18528. q: q
  18529. };
  18530. tubularSegments = Math.floor( tubularSegments );
  18531. radialSegments = Math.floor( radialSegments );
  18532. // buffers
  18533. const indices = [];
  18534. const vertices = [];
  18535. const normals = [];
  18536. const uvs = [];
  18537. // helper variables
  18538. const vertex = new Vector3();
  18539. const normal = new Vector3();
  18540. const P1 = new Vector3();
  18541. const P2 = new Vector3();
  18542. const B = new Vector3();
  18543. const T = new Vector3();
  18544. const N = new Vector3();
  18545. // generate vertices, normals and uvs
  18546. for ( let i = 0; i <= tubularSegments; ++ i ) {
  18547. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18548. const u = i / tubularSegments * p * Math.PI * 2;
  18549. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  18550. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18551. calculatePositionOnCurve( u, p, q, radius, P1 );
  18552. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  18553. // calculate orthonormal basis
  18554. T.subVectors( P2, P1 );
  18555. N.addVectors( P2, P1 );
  18556. B.crossVectors( T, N );
  18557. N.crossVectors( B, T );
  18558. // normalize B, N. T can be ignored, we don't use it
  18559. B.normalize();
  18560. N.normalize();
  18561. for ( let j = 0; j <= radialSegments; ++ j ) {
  18562. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18563. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18564. const v = j / radialSegments * Math.PI * 2;
  18565. const cx = - tube * Math.cos( v );
  18566. const cy = tube * Math.sin( v );
  18567. // now calculate the final vertex position.
  18568. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18569. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  18570. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  18571. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  18572. vertices.push( vertex.x, vertex.y, vertex.z );
  18573. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  18574. normal.subVectors( vertex, P1 ).normalize();
  18575. normals.push( normal.x, normal.y, normal.z );
  18576. // uv
  18577. uvs.push( i / tubularSegments );
  18578. uvs.push( j / radialSegments );
  18579. }
  18580. }
  18581. // generate indices
  18582. for ( let j = 1; j <= tubularSegments; j ++ ) {
  18583. for ( let i = 1; i <= radialSegments; i ++ ) {
  18584. // indices
  18585. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  18586. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  18587. const c = ( radialSegments + 1 ) * j + i;
  18588. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  18589. // faces
  18590. indices.push( a, b, d );
  18591. indices.push( b, c, d );
  18592. }
  18593. }
  18594. // build geometry
  18595. this.setIndex( indices );
  18596. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18597. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18598. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18599. // this function calculates the current position on the torus curve
  18600. function calculatePositionOnCurve( u, p, q, radius, position ) {
  18601. const cu = Math.cos( u );
  18602. const su = Math.sin( u );
  18603. const quOverP = q / p * u;
  18604. const cs = Math.cos( quOverP );
  18605. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  18606. position.y = radius * ( 2 + cs ) * su * 0.5;
  18607. position.z = radius * Math.sin( quOverP ) * 0.5;
  18608. }
  18609. }
  18610. }
  18611. class TubeGeometry extends BufferGeometry {
  18612. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  18613. super();
  18614. this.type = 'TubeGeometry';
  18615. this.parameters = {
  18616. path: path,
  18617. tubularSegments: tubularSegments,
  18618. radius: radius,
  18619. radialSegments: radialSegments,
  18620. closed: closed
  18621. };
  18622. const frames = path.computeFrenetFrames( tubularSegments, closed );
  18623. // expose internals
  18624. this.tangents = frames.tangents;
  18625. this.normals = frames.normals;
  18626. this.binormals = frames.binormals;
  18627. // helper variables
  18628. const vertex = new Vector3();
  18629. const normal = new Vector3();
  18630. const uv = new Vector2();
  18631. let P = new Vector3();
  18632. // buffer
  18633. const vertices = [];
  18634. const normals = [];
  18635. const uvs = [];
  18636. const indices = [];
  18637. // create buffer data
  18638. generateBufferData();
  18639. // build geometry
  18640. this.setIndex( indices );
  18641. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18642. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18643. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18644. // functions
  18645. function generateBufferData() {
  18646. for ( let i = 0; i < tubularSegments; i ++ ) {
  18647. generateSegment( i );
  18648. }
  18649. // if the geometry is not closed, generate the last row of vertices and normals
  18650. // at the regular position on the given path
  18651. //
  18652. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18653. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  18654. // uvs are generated in a separate function.
  18655. // this makes it easy compute correct values for closed geometries
  18656. generateUVs();
  18657. // finally create faces
  18658. generateIndices();
  18659. }
  18660. function generateSegment( i ) {
  18661. // we use getPointAt to sample evenly distributed points from the given path
  18662. P = path.getPointAt( i / tubularSegments, P );
  18663. // retrieve corresponding normal and binormal
  18664. const N = frames.normals[ i ];
  18665. const B = frames.binormals[ i ];
  18666. // generate normals and vertices for the current segment
  18667. for ( let j = 0; j <= radialSegments; j ++ ) {
  18668. const v = j / radialSegments * Math.PI * 2;
  18669. const sin = Math.sin( v );
  18670. const cos = - Math.cos( v );
  18671. // normal
  18672. normal.x = ( cos * N.x + sin * B.x );
  18673. normal.y = ( cos * N.y + sin * B.y );
  18674. normal.z = ( cos * N.z + sin * B.z );
  18675. normal.normalize();
  18676. normals.push( normal.x, normal.y, normal.z );
  18677. // vertex
  18678. vertex.x = P.x + radius * normal.x;
  18679. vertex.y = P.y + radius * normal.y;
  18680. vertex.z = P.z + radius * normal.z;
  18681. vertices.push( vertex.x, vertex.y, vertex.z );
  18682. }
  18683. }
  18684. function generateIndices() {
  18685. for ( let j = 1; j <= tubularSegments; j ++ ) {
  18686. for ( let i = 1; i <= radialSegments; i ++ ) {
  18687. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  18688. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  18689. const c = ( radialSegments + 1 ) * j + i;
  18690. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  18691. // faces
  18692. indices.push( a, b, d );
  18693. indices.push( b, c, d );
  18694. }
  18695. }
  18696. }
  18697. function generateUVs() {
  18698. for ( let i = 0; i <= tubularSegments; i ++ ) {
  18699. for ( let j = 0; j <= radialSegments; j ++ ) {
  18700. uv.x = i / tubularSegments;
  18701. uv.y = j / radialSegments;
  18702. uvs.push( uv.x, uv.y );
  18703. }
  18704. }
  18705. }
  18706. }
  18707. toJSON() {
  18708. const data = BufferGeometry.prototype.toJSON.call( this );
  18709. data.path = this.parameters.path.toJSON();
  18710. return data;
  18711. }
  18712. }
  18713. class WireframeGeometry extends BufferGeometry {
  18714. constructor( geometry ) {
  18715. super();
  18716. this.type = 'WireframeGeometry';
  18717. if ( geometry.isGeometry === true ) {
  18718. console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18719. return;
  18720. }
  18721. // buffer
  18722. const vertices = [];
  18723. // helper variables
  18724. const edge = [ 0, 0 ], edges = {};
  18725. const vertex = new Vector3();
  18726. if ( geometry.index !== null ) {
  18727. // indexed BufferGeometry
  18728. const position = geometry.attributes.position;
  18729. const indices = geometry.index;
  18730. let groups = geometry.groups;
  18731. if ( groups.length === 0 ) {
  18732. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  18733. }
  18734. // create a data structure that contains all eges without duplicates
  18735. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  18736. const group = groups[ o ];
  18737. const start = group.start;
  18738. const count = group.count;
  18739. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  18740. for ( let j = 0; j < 3; j ++ ) {
  18741. const edge1 = indices.getX( i + j );
  18742. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  18743. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  18744. edge[ 1 ] = Math.max( edge1, edge2 );
  18745. const key = edge[ 0 ] + ',' + edge[ 1 ];
  18746. if ( edges[ key ] === undefined ) {
  18747. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  18748. }
  18749. }
  18750. }
  18751. }
  18752. // generate vertices
  18753. for ( const key in edges ) {
  18754. const e = edges[ key ];
  18755. vertex.fromBufferAttribute( position, e.index1 );
  18756. vertices.push( vertex.x, vertex.y, vertex.z );
  18757. vertex.fromBufferAttribute( position, e.index2 );
  18758. vertices.push( vertex.x, vertex.y, vertex.z );
  18759. }
  18760. } else {
  18761. // non-indexed BufferGeometry
  18762. const position = geometry.attributes.position;
  18763. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  18764. for ( let j = 0; j < 3; j ++ ) {
  18765. // three edges per triangle, an edge is represented as (index1, index2)
  18766. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18767. const index1 = 3 * i + j;
  18768. vertex.fromBufferAttribute( position, index1 );
  18769. vertices.push( vertex.x, vertex.y, vertex.z );
  18770. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  18771. vertex.fromBufferAttribute( position, index2 );
  18772. vertices.push( vertex.x, vertex.y, vertex.z );
  18773. }
  18774. }
  18775. }
  18776. // build geometry
  18777. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18778. }
  18779. }
  18780. var Geometries = /*#__PURE__*/Object.freeze({
  18781. __proto__: null,
  18782. BoxGeometry: BoxGeometry,
  18783. BoxBufferGeometry: BoxGeometry,
  18784. CircleGeometry: CircleGeometry,
  18785. CircleBufferGeometry: CircleGeometry,
  18786. ConeGeometry: ConeGeometry,
  18787. ConeBufferGeometry: ConeGeometry,
  18788. CylinderGeometry: CylinderGeometry,
  18789. CylinderBufferGeometry: CylinderGeometry,
  18790. DodecahedronGeometry: DodecahedronGeometry,
  18791. DodecahedronBufferGeometry: DodecahedronGeometry,
  18792. EdgesGeometry: EdgesGeometry,
  18793. ExtrudeGeometry: ExtrudeGeometry,
  18794. ExtrudeBufferGeometry: ExtrudeGeometry,
  18795. IcosahedronGeometry: IcosahedronGeometry,
  18796. IcosahedronBufferGeometry: IcosahedronGeometry,
  18797. LatheGeometry: LatheGeometry,
  18798. LatheBufferGeometry: LatheGeometry,
  18799. OctahedronGeometry: OctahedronGeometry,
  18800. OctahedronBufferGeometry: OctahedronGeometry,
  18801. ParametricGeometry: ParametricGeometry,
  18802. ParametricBufferGeometry: ParametricGeometry,
  18803. PlaneGeometry: PlaneGeometry,
  18804. PlaneBufferGeometry: PlaneGeometry,
  18805. PolyhedronGeometry: PolyhedronGeometry,
  18806. PolyhedronBufferGeometry: PolyhedronGeometry,
  18807. RingGeometry: RingGeometry,
  18808. RingBufferGeometry: RingGeometry,
  18809. ShapeGeometry: ShapeGeometry,
  18810. ShapeBufferGeometry: ShapeGeometry,
  18811. SphereGeometry: SphereGeometry,
  18812. SphereBufferGeometry: SphereGeometry,
  18813. TetrahedronGeometry: TetrahedronGeometry,
  18814. TetrahedronBufferGeometry: TetrahedronGeometry,
  18815. TextGeometry: TextGeometry,
  18816. TextBufferGeometry: TextGeometry,
  18817. TorusGeometry: TorusGeometry,
  18818. TorusBufferGeometry: TorusGeometry,
  18819. TorusKnotGeometry: TorusKnotGeometry,
  18820. TorusKnotBufferGeometry: TorusKnotGeometry,
  18821. TubeGeometry: TubeGeometry,
  18822. TubeBufferGeometry: TubeGeometry,
  18823. WireframeGeometry: WireframeGeometry
  18824. });
  18825. /**
  18826. * parameters = {
  18827. * color: <THREE.Color>
  18828. * }
  18829. */
  18830. class ShadowMaterial extends Material {
  18831. constructor( parameters ) {
  18832. super();
  18833. this.type = 'ShadowMaterial';
  18834. this.color = new Color( 0x000000 );
  18835. this.transparent = true;
  18836. this.setValues( parameters );
  18837. }
  18838. copy( source ) {
  18839. super.copy( source );
  18840. this.color.copy( source.color );
  18841. return this;
  18842. }
  18843. }
  18844. ShadowMaterial.prototype.isShadowMaterial = true;
  18845. class RawShaderMaterial extends ShaderMaterial {
  18846. constructor( parameters ) {
  18847. super( parameters );
  18848. this.type = 'RawShaderMaterial';
  18849. }
  18850. }
  18851. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18852. /**
  18853. * parameters = {
  18854. * color: <hex>,
  18855. * roughness: <float>,
  18856. * metalness: <float>,
  18857. * opacity: <float>,
  18858. *
  18859. * map: new THREE.Texture( <Image> ),
  18860. *
  18861. * lightMap: new THREE.Texture( <Image> ),
  18862. * lightMapIntensity: <float>
  18863. *
  18864. * aoMap: new THREE.Texture( <Image> ),
  18865. * aoMapIntensity: <float>
  18866. *
  18867. * emissive: <hex>,
  18868. * emissiveIntensity: <float>
  18869. * emissiveMap: new THREE.Texture( <Image> ),
  18870. *
  18871. * bumpMap: new THREE.Texture( <Image> ),
  18872. * bumpScale: <float>,
  18873. *
  18874. * normalMap: new THREE.Texture( <Image> ),
  18875. * normalMapType: THREE.TangentSpaceNormalMap,
  18876. * normalScale: <Vector2>,
  18877. *
  18878. * displacementMap: new THREE.Texture( <Image> ),
  18879. * displacementScale: <float>,
  18880. * displacementBias: <float>,
  18881. *
  18882. * roughnessMap: new THREE.Texture( <Image> ),
  18883. *
  18884. * metalnessMap: new THREE.Texture( <Image> ),
  18885. *
  18886. * alphaMap: new THREE.Texture( <Image> ),
  18887. *
  18888. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18889. * envMapIntensity: <float>
  18890. *
  18891. * refractionRatio: <float>,
  18892. *
  18893. * wireframe: <boolean>,
  18894. * wireframeLinewidth: <float>,
  18895. *
  18896. * morphTargets: <bool>,
  18897. * morphNormals: <bool>,
  18898. *
  18899. * flatShading: <bool>
  18900. * }
  18901. */
  18902. class MeshStandardMaterial extends Material {
  18903. constructor( parameters ) {
  18904. super();
  18905. this.defines = { 'STANDARD': '' };
  18906. this.type = 'MeshStandardMaterial';
  18907. this.color = new Color( 0xffffff ); // diffuse
  18908. this.roughness = 1.0;
  18909. this.metalness = 0.0;
  18910. this.map = null;
  18911. this.lightMap = null;
  18912. this.lightMapIntensity = 1.0;
  18913. this.aoMap = null;
  18914. this.aoMapIntensity = 1.0;
  18915. this.emissive = new Color( 0x000000 );
  18916. this.emissiveIntensity = 1.0;
  18917. this.emissiveMap = null;
  18918. this.bumpMap = null;
  18919. this.bumpScale = 1;
  18920. this.normalMap = null;
  18921. this.normalMapType = TangentSpaceNormalMap;
  18922. this.normalScale = new Vector2( 1, 1 );
  18923. this.displacementMap = null;
  18924. this.displacementScale = 1;
  18925. this.displacementBias = 0;
  18926. this.roughnessMap = null;
  18927. this.metalnessMap = null;
  18928. this.alphaMap = null;
  18929. this.envMap = null;
  18930. this.envMapIntensity = 1.0;
  18931. this.refractionRatio = 0.98;
  18932. this.wireframe = false;
  18933. this.wireframeLinewidth = 1;
  18934. this.wireframeLinecap = 'round';
  18935. this.wireframeLinejoin = 'round';
  18936. this.morphTargets = false;
  18937. this.morphNormals = false;
  18938. this.flatShading = false;
  18939. this.vertexTangents = false;
  18940. this.setValues( parameters );
  18941. }
  18942. copy( source ) {
  18943. super.copy( source );
  18944. this.defines = { 'STANDARD': '' };
  18945. this.color.copy( source.color );
  18946. this.roughness = source.roughness;
  18947. this.metalness = source.metalness;
  18948. this.map = source.map;
  18949. this.lightMap = source.lightMap;
  18950. this.lightMapIntensity = source.lightMapIntensity;
  18951. this.aoMap = source.aoMap;
  18952. this.aoMapIntensity = source.aoMapIntensity;
  18953. this.emissive.copy( source.emissive );
  18954. this.emissiveMap = source.emissiveMap;
  18955. this.emissiveIntensity = source.emissiveIntensity;
  18956. this.bumpMap = source.bumpMap;
  18957. this.bumpScale = source.bumpScale;
  18958. this.normalMap = source.normalMap;
  18959. this.normalMapType = source.normalMapType;
  18960. this.normalScale.copy( source.normalScale );
  18961. this.displacementMap = source.displacementMap;
  18962. this.displacementScale = source.displacementScale;
  18963. this.displacementBias = source.displacementBias;
  18964. this.roughnessMap = source.roughnessMap;
  18965. this.metalnessMap = source.metalnessMap;
  18966. this.alphaMap = source.alphaMap;
  18967. this.envMap = source.envMap;
  18968. this.envMapIntensity = source.envMapIntensity;
  18969. this.refractionRatio = source.refractionRatio;
  18970. this.wireframe = source.wireframe;
  18971. this.wireframeLinewidth = source.wireframeLinewidth;
  18972. this.wireframeLinecap = source.wireframeLinecap;
  18973. this.wireframeLinejoin = source.wireframeLinejoin;
  18974. this.morphTargets = source.morphTargets;
  18975. this.morphNormals = source.morphNormals;
  18976. this.flatShading = source.flatShading;
  18977. this.vertexTangents = source.vertexTangents;
  18978. return this;
  18979. }
  18980. }
  18981. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18982. /**
  18983. * parameters = {
  18984. * clearcoat: <float>,
  18985. * clearcoatMap: new THREE.Texture( <Image> ),
  18986. * clearcoatRoughness: <float>,
  18987. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18988. * clearcoatNormalScale: <Vector2>,
  18989. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18990. *
  18991. * reflectivity: <float>,
  18992. * ior: <float>,
  18993. *
  18994. * sheen: <Color>,
  18995. *
  18996. * transmission: <float>,
  18997. * transmissionMap: new THREE.Texture( <Image> )
  18998. * }
  18999. */
  19000. class MeshPhysicalMaterial extends MeshStandardMaterial {
  19001. constructor( parameters ) {
  19002. super();
  19003. this.defines = {
  19004. 'STANDARD': '',
  19005. 'PHYSICAL': ''
  19006. };
  19007. this.type = 'MeshPhysicalMaterial';
  19008. this.clearcoat = 0.0;
  19009. this.clearcoatMap = null;
  19010. this.clearcoatRoughness = 0.0;
  19011. this.clearcoatRoughnessMap = null;
  19012. this.clearcoatNormalScale = new Vector2( 1, 1 );
  19013. this.clearcoatNormalMap = null;
  19014. this.reflectivity = 0.5; // maps to F0 = 0.04
  19015. Object.defineProperty( this, 'ior', {
  19016. get: function () {
  19017. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  19018. },
  19019. set: function ( ior ) {
  19020. this.reflectivity = clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  19021. }
  19022. } );
  19023. this.sheen = null; // null will disable sheen bsdf
  19024. this.transmission = 0.0;
  19025. this.transmissionMap = null;
  19026. this.setValues( parameters );
  19027. }
  19028. copy( source ) {
  19029. super.copy( source );
  19030. this.defines = {
  19031. 'STANDARD': '',
  19032. 'PHYSICAL': ''
  19033. };
  19034. this.clearcoat = source.clearcoat;
  19035. this.clearcoatMap = source.clearcoatMap;
  19036. this.clearcoatRoughness = source.clearcoatRoughness;
  19037. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19038. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19039. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  19040. this.reflectivity = source.reflectivity;
  19041. if ( source.sheen ) {
  19042. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  19043. } else {
  19044. this.sheen = null;
  19045. }
  19046. this.transmission = source.transmission;
  19047. this.transmissionMap = source.transmissionMap;
  19048. return this;
  19049. }
  19050. }
  19051. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19052. /**
  19053. * parameters = {
  19054. * color: <hex>,
  19055. * specular: <hex>,
  19056. * shininess: <float>,
  19057. * opacity: <float>,
  19058. *
  19059. * map: new THREE.Texture( <Image> ),
  19060. *
  19061. * lightMap: new THREE.Texture( <Image> ),
  19062. * lightMapIntensity: <float>
  19063. *
  19064. * aoMap: new THREE.Texture( <Image> ),
  19065. * aoMapIntensity: <float>
  19066. *
  19067. * emissive: <hex>,
  19068. * emissiveIntensity: <float>
  19069. * emissiveMap: new THREE.Texture( <Image> ),
  19070. *
  19071. * bumpMap: new THREE.Texture( <Image> ),
  19072. * bumpScale: <float>,
  19073. *
  19074. * normalMap: new THREE.Texture( <Image> ),
  19075. * normalMapType: THREE.TangentSpaceNormalMap,
  19076. * normalScale: <Vector2>,
  19077. *
  19078. * displacementMap: new THREE.Texture( <Image> ),
  19079. * displacementScale: <float>,
  19080. * displacementBias: <float>,
  19081. *
  19082. * specularMap: new THREE.Texture( <Image> ),
  19083. *
  19084. * alphaMap: new THREE.Texture( <Image> ),
  19085. *
  19086. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19087. * combine: THREE.MultiplyOperation,
  19088. * reflectivity: <float>,
  19089. * refractionRatio: <float>,
  19090. *
  19091. * wireframe: <boolean>,
  19092. * wireframeLinewidth: <float>,
  19093. *
  19094. * morphTargets: <bool>,
  19095. * morphNormals: <bool>,
  19096. *
  19097. * flatShading: <bool>
  19098. * }
  19099. */
  19100. class MeshPhongMaterial extends Material {
  19101. constructor( parameters ) {
  19102. super();
  19103. this.type = 'MeshPhongMaterial';
  19104. this.color = new Color( 0xffffff ); // diffuse
  19105. this.specular = new Color( 0x111111 );
  19106. this.shininess = 30;
  19107. this.map = null;
  19108. this.lightMap = null;
  19109. this.lightMapIntensity = 1.0;
  19110. this.aoMap = null;
  19111. this.aoMapIntensity = 1.0;
  19112. this.emissive = new Color( 0x000000 );
  19113. this.emissiveIntensity = 1.0;
  19114. this.emissiveMap = null;
  19115. this.bumpMap = null;
  19116. this.bumpScale = 1;
  19117. this.normalMap = null;
  19118. this.normalMapType = TangentSpaceNormalMap;
  19119. this.normalScale = new Vector2( 1, 1 );
  19120. this.displacementMap = null;
  19121. this.displacementScale = 1;
  19122. this.displacementBias = 0;
  19123. this.specularMap = null;
  19124. this.alphaMap = null;
  19125. this.envMap = null;
  19126. this.combine = MultiplyOperation;
  19127. this.reflectivity = 1;
  19128. this.refractionRatio = 0.98;
  19129. this.wireframe = false;
  19130. this.wireframeLinewidth = 1;
  19131. this.wireframeLinecap = 'round';
  19132. this.wireframeLinejoin = 'round';
  19133. this.morphTargets = false;
  19134. this.morphNormals = false;
  19135. this.flatShading = false;
  19136. this.setValues( parameters );
  19137. }
  19138. copy( source ) {
  19139. super.copy( source );
  19140. this.color.copy( source.color );
  19141. this.specular.copy( source.specular );
  19142. this.shininess = source.shininess;
  19143. this.map = source.map;
  19144. this.lightMap = source.lightMap;
  19145. this.lightMapIntensity = source.lightMapIntensity;
  19146. this.aoMap = source.aoMap;
  19147. this.aoMapIntensity = source.aoMapIntensity;
  19148. this.emissive.copy( source.emissive );
  19149. this.emissiveMap = source.emissiveMap;
  19150. this.emissiveIntensity = source.emissiveIntensity;
  19151. this.bumpMap = source.bumpMap;
  19152. this.bumpScale = source.bumpScale;
  19153. this.normalMap = source.normalMap;
  19154. this.normalMapType = source.normalMapType;
  19155. this.normalScale.copy( source.normalScale );
  19156. this.displacementMap = source.displacementMap;
  19157. this.displacementScale = source.displacementScale;
  19158. this.displacementBias = source.displacementBias;
  19159. this.specularMap = source.specularMap;
  19160. this.alphaMap = source.alphaMap;
  19161. this.envMap = source.envMap;
  19162. this.combine = source.combine;
  19163. this.reflectivity = source.reflectivity;
  19164. this.refractionRatio = source.refractionRatio;
  19165. this.wireframe = source.wireframe;
  19166. this.wireframeLinewidth = source.wireframeLinewidth;
  19167. this.wireframeLinecap = source.wireframeLinecap;
  19168. this.wireframeLinejoin = source.wireframeLinejoin;
  19169. this.morphTargets = source.morphTargets;
  19170. this.morphNormals = source.morphNormals;
  19171. this.flatShading = source.flatShading;
  19172. return this;
  19173. }
  19174. }
  19175. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19176. /**
  19177. * parameters = {
  19178. * color: <hex>,
  19179. *
  19180. * map: new THREE.Texture( <Image> ),
  19181. * gradientMap: new THREE.Texture( <Image> ),
  19182. *
  19183. * lightMap: new THREE.Texture( <Image> ),
  19184. * lightMapIntensity: <float>
  19185. *
  19186. * aoMap: new THREE.Texture( <Image> ),
  19187. * aoMapIntensity: <float>
  19188. *
  19189. * emissive: <hex>,
  19190. * emissiveIntensity: <float>
  19191. * emissiveMap: new THREE.Texture( <Image> ),
  19192. *
  19193. * bumpMap: new THREE.Texture( <Image> ),
  19194. * bumpScale: <float>,
  19195. *
  19196. * normalMap: new THREE.Texture( <Image> ),
  19197. * normalMapType: THREE.TangentSpaceNormalMap,
  19198. * normalScale: <Vector2>,
  19199. *
  19200. * displacementMap: new THREE.Texture( <Image> ),
  19201. * displacementScale: <float>,
  19202. * displacementBias: <float>,
  19203. *
  19204. * alphaMap: new THREE.Texture( <Image> ),
  19205. *
  19206. * wireframe: <boolean>,
  19207. * wireframeLinewidth: <float>,
  19208. *
  19209. * morphTargets: <bool>,
  19210. * morphNormals: <bool>
  19211. * }
  19212. */
  19213. class MeshToonMaterial extends Material {
  19214. constructor( parameters ) {
  19215. super();
  19216. this.defines = { 'TOON': '' };
  19217. this.type = 'MeshToonMaterial';
  19218. this.color = new Color( 0xffffff );
  19219. this.map = null;
  19220. this.gradientMap = null;
  19221. this.lightMap = null;
  19222. this.lightMapIntensity = 1.0;
  19223. this.aoMap = null;
  19224. this.aoMapIntensity = 1.0;
  19225. this.emissive = new Color( 0x000000 );
  19226. this.emissiveIntensity = 1.0;
  19227. this.emissiveMap = null;
  19228. this.bumpMap = null;
  19229. this.bumpScale = 1;
  19230. this.normalMap = null;
  19231. this.normalMapType = TangentSpaceNormalMap;
  19232. this.normalScale = new Vector2( 1, 1 );
  19233. this.displacementMap = null;
  19234. this.displacementScale = 1;
  19235. this.displacementBias = 0;
  19236. this.alphaMap = null;
  19237. this.wireframe = false;
  19238. this.wireframeLinewidth = 1;
  19239. this.wireframeLinecap = 'round';
  19240. this.wireframeLinejoin = 'round';
  19241. this.morphTargets = false;
  19242. this.morphNormals = false;
  19243. this.setValues( parameters );
  19244. }
  19245. copy( source ) {
  19246. super.copy( source );
  19247. this.color.copy( source.color );
  19248. this.map = source.map;
  19249. this.gradientMap = source.gradientMap;
  19250. this.lightMap = source.lightMap;
  19251. this.lightMapIntensity = source.lightMapIntensity;
  19252. this.aoMap = source.aoMap;
  19253. this.aoMapIntensity = source.aoMapIntensity;
  19254. this.emissive.copy( source.emissive );
  19255. this.emissiveMap = source.emissiveMap;
  19256. this.emissiveIntensity = source.emissiveIntensity;
  19257. this.bumpMap = source.bumpMap;
  19258. this.bumpScale = source.bumpScale;
  19259. this.normalMap = source.normalMap;
  19260. this.normalMapType = source.normalMapType;
  19261. this.normalScale.copy( source.normalScale );
  19262. this.displacementMap = source.displacementMap;
  19263. this.displacementScale = source.displacementScale;
  19264. this.displacementBias = source.displacementBias;
  19265. this.alphaMap = source.alphaMap;
  19266. this.wireframe = source.wireframe;
  19267. this.wireframeLinewidth = source.wireframeLinewidth;
  19268. this.wireframeLinecap = source.wireframeLinecap;
  19269. this.wireframeLinejoin = source.wireframeLinejoin;
  19270. this.morphTargets = source.morphTargets;
  19271. this.morphNormals = source.morphNormals;
  19272. return this;
  19273. }
  19274. }
  19275. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19276. /**
  19277. * parameters = {
  19278. * opacity: <float>,
  19279. *
  19280. * bumpMap: new THREE.Texture( <Image> ),
  19281. * bumpScale: <float>,
  19282. *
  19283. * normalMap: new THREE.Texture( <Image> ),
  19284. * normalMapType: THREE.TangentSpaceNormalMap,
  19285. * normalScale: <Vector2>,
  19286. *
  19287. * displacementMap: new THREE.Texture( <Image> ),
  19288. * displacementScale: <float>,
  19289. * displacementBias: <float>,
  19290. *
  19291. * wireframe: <boolean>,
  19292. * wireframeLinewidth: <float>
  19293. *
  19294. * morphTargets: <bool>,
  19295. * morphNormals: <bool>,
  19296. *
  19297. * flatShading: <bool>
  19298. * }
  19299. */
  19300. class MeshNormalMaterial extends Material {
  19301. constructor( parameters ) {
  19302. super();
  19303. this.type = 'MeshNormalMaterial';
  19304. this.bumpMap = null;
  19305. this.bumpScale = 1;
  19306. this.normalMap = null;
  19307. this.normalMapType = TangentSpaceNormalMap;
  19308. this.normalScale = new Vector2( 1, 1 );
  19309. this.displacementMap = null;
  19310. this.displacementScale = 1;
  19311. this.displacementBias = 0;
  19312. this.wireframe = false;
  19313. this.wireframeLinewidth = 1;
  19314. this.fog = false;
  19315. this.morphTargets = false;
  19316. this.morphNormals = false;
  19317. this.flatShading = false;
  19318. this.setValues( parameters );
  19319. }
  19320. copy( source ) {
  19321. super.copy( source );
  19322. this.bumpMap = source.bumpMap;
  19323. this.bumpScale = source.bumpScale;
  19324. this.normalMap = source.normalMap;
  19325. this.normalMapType = source.normalMapType;
  19326. this.normalScale.copy( source.normalScale );
  19327. this.displacementMap = source.displacementMap;
  19328. this.displacementScale = source.displacementScale;
  19329. this.displacementBias = source.displacementBias;
  19330. this.wireframe = source.wireframe;
  19331. this.wireframeLinewidth = source.wireframeLinewidth;
  19332. this.morphTargets = source.morphTargets;
  19333. this.morphNormals = source.morphNormals;
  19334. this.flatShading = source.flatShading;
  19335. return this;
  19336. }
  19337. }
  19338. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19339. /**
  19340. * parameters = {
  19341. * color: <hex>,
  19342. * opacity: <float>,
  19343. *
  19344. * map: new THREE.Texture( <Image> ),
  19345. *
  19346. * lightMap: new THREE.Texture( <Image> ),
  19347. * lightMapIntensity: <float>
  19348. *
  19349. * aoMap: new THREE.Texture( <Image> ),
  19350. * aoMapIntensity: <float>
  19351. *
  19352. * emissive: <hex>,
  19353. * emissiveIntensity: <float>
  19354. * emissiveMap: new THREE.Texture( <Image> ),
  19355. *
  19356. * specularMap: new THREE.Texture( <Image> ),
  19357. *
  19358. * alphaMap: new THREE.Texture( <Image> ),
  19359. *
  19360. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19361. * combine: THREE.Multiply,
  19362. * reflectivity: <float>,
  19363. * refractionRatio: <float>,
  19364. *
  19365. * wireframe: <boolean>,
  19366. * wireframeLinewidth: <float>,
  19367. *
  19368. * morphTargets: <bool>,
  19369. * morphNormals: <bool>
  19370. * }
  19371. */
  19372. class MeshLambertMaterial extends Material {
  19373. constructor( parameters ) {
  19374. super();
  19375. this.type = 'MeshLambertMaterial';
  19376. this.color = new Color( 0xffffff ); // diffuse
  19377. this.map = null;
  19378. this.lightMap = null;
  19379. this.lightMapIntensity = 1.0;
  19380. this.aoMap = null;
  19381. this.aoMapIntensity = 1.0;
  19382. this.emissive = new Color( 0x000000 );
  19383. this.emissiveIntensity = 1.0;
  19384. this.emissiveMap = null;
  19385. this.specularMap = null;
  19386. this.alphaMap = null;
  19387. this.envMap = null;
  19388. this.combine = MultiplyOperation;
  19389. this.reflectivity = 1;
  19390. this.refractionRatio = 0.98;
  19391. this.wireframe = false;
  19392. this.wireframeLinewidth = 1;
  19393. this.wireframeLinecap = 'round';
  19394. this.wireframeLinejoin = 'round';
  19395. this.morphTargets = false;
  19396. this.morphNormals = false;
  19397. this.setValues( parameters );
  19398. }
  19399. copy( source ) {
  19400. super.copy( source );
  19401. this.color.copy( source.color );
  19402. this.map = source.map;
  19403. this.lightMap = source.lightMap;
  19404. this.lightMapIntensity = source.lightMapIntensity;
  19405. this.aoMap = source.aoMap;
  19406. this.aoMapIntensity = source.aoMapIntensity;
  19407. this.emissive.copy( source.emissive );
  19408. this.emissiveMap = source.emissiveMap;
  19409. this.emissiveIntensity = source.emissiveIntensity;
  19410. this.specularMap = source.specularMap;
  19411. this.alphaMap = source.alphaMap;
  19412. this.envMap = source.envMap;
  19413. this.combine = source.combine;
  19414. this.reflectivity = source.reflectivity;
  19415. this.refractionRatio = source.refractionRatio;
  19416. this.wireframe = source.wireframe;
  19417. this.wireframeLinewidth = source.wireframeLinewidth;
  19418. this.wireframeLinecap = source.wireframeLinecap;
  19419. this.wireframeLinejoin = source.wireframeLinejoin;
  19420. this.morphTargets = source.morphTargets;
  19421. this.morphNormals = source.morphNormals;
  19422. return this;
  19423. }
  19424. }
  19425. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19426. /**
  19427. * parameters = {
  19428. * color: <hex>,
  19429. * opacity: <float>,
  19430. *
  19431. * matcap: new THREE.Texture( <Image> ),
  19432. *
  19433. * map: new THREE.Texture( <Image> ),
  19434. *
  19435. * bumpMap: new THREE.Texture( <Image> ),
  19436. * bumpScale: <float>,
  19437. *
  19438. * normalMap: new THREE.Texture( <Image> ),
  19439. * normalMapType: THREE.TangentSpaceNormalMap,
  19440. * normalScale: <Vector2>,
  19441. *
  19442. * displacementMap: new THREE.Texture( <Image> ),
  19443. * displacementScale: <float>,
  19444. * displacementBias: <float>,
  19445. *
  19446. * alphaMap: new THREE.Texture( <Image> ),
  19447. *
  19448. * morphTargets: <bool>,
  19449. * morphNormals: <bool>
  19450. *
  19451. * flatShading: <bool>
  19452. * }
  19453. */
  19454. class MeshMatcapMaterial extends Material {
  19455. constructor( parameters ) {
  19456. super();
  19457. this.defines = { 'MATCAP': '' };
  19458. this.type = 'MeshMatcapMaterial';
  19459. this.color = new Color( 0xffffff ); // diffuse
  19460. this.matcap = null;
  19461. this.map = null;
  19462. this.bumpMap = null;
  19463. this.bumpScale = 1;
  19464. this.normalMap = null;
  19465. this.normalMapType = TangentSpaceNormalMap;
  19466. this.normalScale = new Vector2( 1, 1 );
  19467. this.displacementMap = null;
  19468. this.displacementScale = 1;
  19469. this.displacementBias = 0;
  19470. this.alphaMap = null;
  19471. this.morphTargets = false;
  19472. this.morphNormals = false;
  19473. this.flatShading = false;
  19474. this.setValues( parameters );
  19475. }
  19476. copy( source ) {
  19477. super.copy( source );
  19478. this.defines = { 'MATCAP': '' };
  19479. this.color.copy( source.color );
  19480. this.matcap = source.matcap;
  19481. this.map = source.map;
  19482. this.bumpMap = source.bumpMap;
  19483. this.bumpScale = source.bumpScale;
  19484. this.normalMap = source.normalMap;
  19485. this.normalMapType = source.normalMapType;
  19486. this.normalScale.copy( source.normalScale );
  19487. this.displacementMap = source.displacementMap;
  19488. this.displacementScale = source.displacementScale;
  19489. this.displacementBias = source.displacementBias;
  19490. this.alphaMap = source.alphaMap;
  19491. this.morphTargets = source.morphTargets;
  19492. this.morphNormals = source.morphNormals;
  19493. this.flatShading = source.flatShading;
  19494. return this;
  19495. }
  19496. }
  19497. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19498. /**
  19499. * parameters = {
  19500. * color: <hex>,
  19501. * opacity: <float>,
  19502. *
  19503. * linewidth: <float>,
  19504. *
  19505. * scale: <float>,
  19506. * dashSize: <float>,
  19507. * gapSize: <float>
  19508. * }
  19509. */
  19510. class LineDashedMaterial extends LineBasicMaterial {
  19511. constructor( parameters ) {
  19512. super();
  19513. this.type = 'LineDashedMaterial';
  19514. this.scale = 1;
  19515. this.dashSize = 3;
  19516. this.gapSize = 1;
  19517. this.setValues( parameters );
  19518. }
  19519. copy( source ) {
  19520. super.copy( source );
  19521. this.scale = source.scale;
  19522. this.dashSize = source.dashSize;
  19523. this.gapSize = source.gapSize;
  19524. return this;
  19525. }
  19526. }
  19527. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19528. var Materials = /*#__PURE__*/Object.freeze({
  19529. __proto__: null,
  19530. ShadowMaterial: ShadowMaterial,
  19531. SpriteMaterial: SpriteMaterial,
  19532. RawShaderMaterial: RawShaderMaterial,
  19533. ShaderMaterial: ShaderMaterial,
  19534. PointsMaterial: PointsMaterial,
  19535. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19536. MeshStandardMaterial: MeshStandardMaterial,
  19537. MeshPhongMaterial: MeshPhongMaterial,
  19538. MeshToonMaterial: MeshToonMaterial,
  19539. MeshNormalMaterial: MeshNormalMaterial,
  19540. MeshLambertMaterial: MeshLambertMaterial,
  19541. MeshDepthMaterial: MeshDepthMaterial,
  19542. MeshDistanceMaterial: MeshDistanceMaterial,
  19543. MeshBasicMaterial: MeshBasicMaterial,
  19544. MeshMatcapMaterial: MeshMatcapMaterial,
  19545. LineDashedMaterial: LineDashedMaterial,
  19546. LineBasicMaterial: LineBasicMaterial,
  19547. Material: Material
  19548. });
  19549. const AnimationUtils = {
  19550. // same as Array.prototype.slice, but also works on typed arrays
  19551. arraySlice: function ( array, from, to ) {
  19552. if ( AnimationUtils.isTypedArray( array ) ) {
  19553. // in ios9 array.subarray(from, undefined) will return empty array
  19554. // but array.subarray(from) or array.subarray(from, len) is correct
  19555. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  19556. }
  19557. return array.slice( from, to );
  19558. },
  19559. // converts an array to a specific type
  19560. convertArray: function ( array, type, forceClone ) {
  19561. if ( ! array || // let 'undefined' and 'null' pass
  19562. ! forceClone && array.constructor === type ) return array;
  19563. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  19564. return new type( array ); // create typed array
  19565. }
  19566. return Array.prototype.slice.call( array ); // create Array
  19567. },
  19568. isTypedArray: function ( object ) {
  19569. return ArrayBuffer.isView( object ) &&
  19570. ! ( object instanceof DataView );
  19571. },
  19572. // returns an array by which times and values can be sorted
  19573. getKeyframeOrder: function ( times ) {
  19574. function compareTime( i, j ) {
  19575. return times[ i ] - times[ j ];
  19576. }
  19577. const n = times.length;
  19578. const result = new Array( n );
  19579. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  19580. result.sort( compareTime );
  19581. return result;
  19582. },
  19583. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19584. sortedArray: function ( values, stride, order ) {
  19585. const nValues = values.length;
  19586. const result = new values.constructor( nValues );
  19587. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  19588. const srcOffset = order[ i ] * stride;
  19589. for ( let j = 0; j !== stride; ++ j ) {
  19590. result[ dstOffset ++ ] = values[ srcOffset + j ];
  19591. }
  19592. }
  19593. return result;
  19594. },
  19595. // function for parsing AOS keyframe formats
  19596. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  19597. let i = 1, key = jsonKeys[ 0 ];
  19598. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  19599. key = jsonKeys[ i ++ ];
  19600. }
  19601. if ( key === undefined ) return; // no data
  19602. let value = key[ valuePropertyName ];
  19603. if ( value === undefined ) return; // no data
  19604. if ( Array.isArray( value ) ) {
  19605. do {
  19606. value = key[ valuePropertyName ];
  19607. if ( value !== undefined ) {
  19608. times.push( key.time );
  19609. values.push.apply( values, value ); // push all elements
  19610. }
  19611. key = jsonKeys[ i ++ ];
  19612. } while ( key !== undefined );
  19613. } else if ( value.toArray !== undefined ) {
  19614. // ...assume THREE.Math-ish
  19615. do {
  19616. value = key[ valuePropertyName ];
  19617. if ( value !== undefined ) {
  19618. times.push( key.time );
  19619. value.toArray( values, values.length );
  19620. }
  19621. key = jsonKeys[ i ++ ];
  19622. } while ( key !== undefined );
  19623. } else {
  19624. // otherwise push as-is
  19625. do {
  19626. value = key[ valuePropertyName ];
  19627. if ( value !== undefined ) {
  19628. times.push( key.time );
  19629. values.push( value );
  19630. }
  19631. key = jsonKeys[ i ++ ];
  19632. } while ( key !== undefined );
  19633. }
  19634. },
  19635. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  19636. const clip = sourceClip.clone();
  19637. clip.name = name;
  19638. const tracks = [];
  19639. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19640. const track = clip.tracks[ i ];
  19641. const valueSize = track.getValueSize();
  19642. const times = [];
  19643. const values = [];
  19644. for ( let j = 0; j < track.times.length; ++ j ) {
  19645. const frame = track.times[ j ] * fps;
  19646. if ( frame < startFrame || frame >= endFrame ) continue;
  19647. times.push( track.times[ j ] );
  19648. for ( let k = 0; k < valueSize; ++ k ) {
  19649. values.push( track.values[ j * valueSize + k ] );
  19650. }
  19651. }
  19652. if ( times.length === 0 ) continue;
  19653. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  19654. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  19655. tracks.push( track );
  19656. }
  19657. clip.tracks = tracks;
  19658. // find minimum .times value across all tracks in the trimmed clip
  19659. let minStartTime = Infinity;
  19660. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19661. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  19662. minStartTime = clip.tracks[ i ].times[ 0 ];
  19663. }
  19664. }
  19665. // shift all tracks such that clip begins at t=0
  19666. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19667. clip.tracks[ i ].shift( - 1 * minStartTime );
  19668. }
  19669. clip.resetDuration();
  19670. return clip;
  19671. },
  19672. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  19673. if ( fps <= 0 ) fps = 30;
  19674. const numTracks = referenceClip.tracks.length;
  19675. const referenceTime = referenceFrame / fps;
  19676. // Make each track's values relative to the values at the reference frame
  19677. for ( let i = 0; i < numTracks; ++ i ) {
  19678. const referenceTrack = referenceClip.tracks[ i ];
  19679. const referenceTrackType = referenceTrack.ValueTypeName;
  19680. // Skip this track if it's non-numeric
  19681. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  19682. // Find the track in the target clip whose name and type matches the reference track
  19683. const targetTrack = targetClip.tracks.find( function ( track ) {
  19684. return track.name === referenceTrack.name
  19685. && track.ValueTypeName === referenceTrackType;
  19686. } );
  19687. if ( targetTrack === undefined ) continue;
  19688. let referenceOffset = 0;
  19689. const referenceValueSize = referenceTrack.getValueSize();
  19690. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  19691. referenceOffset = referenceValueSize / 3;
  19692. }
  19693. let targetOffset = 0;
  19694. const targetValueSize = targetTrack.getValueSize();
  19695. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  19696. targetOffset = targetValueSize / 3;
  19697. }
  19698. const lastIndex = referenceTrack.times.length - 1;
  19699. let referenceValue;
  19700. // Find the value to subtract out of the track
  19701. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  19702. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19703. const startIndex = referenceOffset;
  19704. const endIndex = referenceValueSize - referenceOffset;
  19705. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  19706. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  19707. // Reference frame is after the last keyframe, so just use the last keyframe
  19708. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19709. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19710. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  19711. } else {
  19712. // Interpolate to the reference value
  19713. const interpolant = referenceTrack.createInterpolant();
  19714. const startIndex = referenceOffset;
  19715. const endIndex = referenceValueSize - referenceOffset;
  19716. interpolant.evaluate( referenceTime );
  19717. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  19718. }
  19719. // Conjugate the quaternion
  19720. if ( referenceTrackType === 'quaternion' ) {
  19721. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  19722. referenceQuat.toArray( referenceValue );
  19723. }
  19724. // Subtract the reference value from all of the track values
  19725. const numTimes = targetTrack.times.length;
  19726. for ( let j = 0; j < numTimes; ++ j ) {
  19727. const valueStart = j * targetValueSize + targetOffset;
  19728. if ( referenceTrackType === 'quaternion' ) {
  19729. // Multiply the conjugate for quaternion track types
  19730. Quaternion.multiplyQuaternionsFlat(
  19731. targetTrack.values,
  19732. valueStart,
  19733. referenceValue,
  19734. 0,
  19735. targetTrack.values,
  19736. valueStart
  19737. );
  19738. } else {
  19739. const valueEnd = targetValueSize - targetOffset * 2;
  19740. // Subtract each value for all other numeric track types
  19741. for ( let k = 0; k < valueEnd; ++ k ) {
  19742. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  19743. }
  19744. }
  19745. }
  19746. }
  19747. targetClip.blendMode = AdditiveAnimationBlendMode;
  19748. return targetClip;
  19749. }
  19750. };
  19751. /**
  19752. * Abstract base class of interpolants over parametric samples.
  19753. *
  19754. * The parameter domain is one dimensional, typically the time or a path
  19755. * along a curve defined by the data.
  19756. *
  19757. * The sample values can have any dimensionality and derived classes may
  19758. * apply special interpretations to the data.
  19759. *
  19760. * This class provides the interval seek in a Template Method, deferring
  19761. * the actual interpolation to derived classes.
  19762. *
  19763. * Time complexity is O(1) for linear access crossing at most two points
  19764. * and O(log N) for random access, where N is the number of positions.
  19765. *
  19766. * References:
  19767. *
  19768. * http://www.oodesign.com/template-method-pattern.html
  19769. *
  19770. */
  19771. class Interpolant {
  19772. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19773. this.parameterPositions = parameterPositions;
  19774. this._cachedIndex = 0;
  19775. this.resultBuffer = resultBuffer !== undefined ?
  19776. resultBuffer : new sampleValues.constructor( sampleSize );
  19777. this.sampleValues = sampleValues;
  19778. this.valueSize = sampleSize;
  19779. this.settings = null;
  19780. this.DefaultSettings_ = {};
  19781. }
  19782. evaluate( t ) {
  19783. const pp = this.parameterPositions;
  19784. let i1 = this._cachedIndex,
  19785. t1 = pp[ i1 ],
  19786. t0 = pp[ i1 - 1 ];
  19787. validate_interval: {
  19788. seek: {
  19789. let right;
  19790. linear_scan: {
  19791. //- See http://jsperf.com/comparison-to-undefined/3
  19792. //- slower code:
  19793. //-
  19794. //- if ( t >= t1 || t1 === undefined ) {
  19795. forward_scan: if ( ! ( t < t1 ) ) {
  19796. for ( let giveUpAt = i1 + 2; ; ) {
  19797. if ( t1 === undefined ) {
  19798. if ( t < t0 ) break forward_scan;
  19799. // after end
  19800. i1 = pp.length;
  19801. this._cachedIndex = i1;
  19802. return this.afterEnd_( i1 - 1, t, t0 );
  19803. }
  19804. if ( i1 === giveUpAt ) break; // this loop
  19805. t0 = t1;
  19806. t1 = pp[ ++ i1 ];
  19807. if ( t < t1 ) {
  19808. // we have arrived at the sought interval
  19809. break seek;
  19810. }
  19811. }
  19812. // prepare binary search on the right side of the index
  19813. right = pp.length;
  19814. break linear_scan;
  19815. }
  19816. //- slower code:
  19817. //- if ( t < t0 || t0 === undefined ) {
  19818. if ( ! ( t >= t0 ) ) {
  19819. // looping?
  19820. const t1global = pp[ 1 ];
  19821. if ( t < t1global ) {
  19822. i1 = 2; // + 1, using the scan for the details
  19823. t0 = t1global;
  19824. }
  19825. // linear reverse scan
  19826. for ( let giveUpAt = i1 - 2; ; ) {
  19827. if ( t0 === undefined ) {
  19828. // before start
  19829. this._cachedIndex = 0;
  19830. return this.beforeStart_( 0, t, t1 );
  19831. }
  19832. if ( i1 === giveUpAt ) break; // this loop
  19833. t1 = t0;
  19834. t0 = pp[ -- i1 - 1 ];
  19835. if ( t >= t0 ) {
  19836. // we have arrived at the sought interval
  19837. break seek;
  19838. }
  19839. }
  19840. // prepare binary search on the left side of the index
  19841. right = i1;
  19842. i1 = 0;
  19843. break linear_scan;
  19844. }
  19845. // the interval is valid
  19846. break validate_interval;
  19847. } // linear scan
  19848. // binary search
  19849. while ( i1 < right ) {
  19850. const mid = ( i1 + right ) >>> 1;
  19851. if ( t < pp[ mid ] ) {
  19852. right = mid;
  19853. } else {
  19854. i1 = mid + 1;
  19855. }
  19856. }
  19857. t1 = pp[ i1 ];
  19858. t0 = pp[ i1 - 1 ];
  19859. // check boundary cases, again
  19860. if ( t0 === undefined ) {
  19861. this._cachedIndex = 0;
  19862. return this.beforeStart_( 0, t, t1 );
  19863. }
  19864. if ( t1 === undefined ) {
  19865. i1 = pp.length;
  19866. this._cachedIndex = i1;
  19867. return this.afterEnd_( i1 - 1, t0, t );
  19868. }
  19869. } // seek
  19870. this._cachedIndex = i1;
  19871. this.intervalChanged_( i1, t0, t1 );
  19872. } // validate_interval
  19873. return this.interpolate_( i1, t0, t, t1 );
  19874. }
  19875. getSettings_() {
  19876. return this.settings || this.DefaultSettings_;
  19877. }
  19878. copySampleValue_( index ) {
  19879. // copies a sample value to the result buffer
  19880. const result = this.resultBuffer,
  19881. values = this.sampleValues,
  19882. stride = this.valueSize,
  19883. offset = index * stride;
  19884. for ( let i = 0; i !== stride; ++ i ) {
  19885. result[ i ] = values[ offset + i ];
  19886. }
  19887. return result;
  19888. }
  19889. // Template methods for derived classes:
  19890. interpolate_( /* i1, t0, t, t1 */ ) {
  19891. throw new Error( 'call to abstract method' );
  19892. // implementations shall return this.resultBuffer
  19893. }
  19894. intervalChanged_( /* i1, t0, t1 */ ) {
  19895. // empty
  19896. }
  19897. }
  19898. // ALIAS DEFINITIONS
  19899. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19900. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19901. /**
  19902. * Fast and simple cubic spline interpolant.
  19903. *
  19904. * It was derived from a Hermitian construction setting the first derivative
  19905. * at each sample position to the linear slope between neighboring positions
  19906. * over their parameter interval.
  19907. */
  19908. class CubicInterpolant extends Interpolant {
  19909. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19910. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  19911. this._weightPrev = - 0;
  19912. this._offsetPrev = - 0;
  19913. this._weightNext = - 0;
  19914. this._offsetNext = - 0;
  19915. this.DefaultSettings_ = {
  19916. endingStart: ZeroCurvatureEnding,
  19917. endingEnd: ZeroCurvatureEnding
  19918. };
  19919. }
  19920. intervalChanged_( i1, t0, t1 ) {
  19921. const pp = this.parameterPositions;
  19922. let iPrev = i1 - 2,
  19923. iNext = i1 + 1,
  19924. tPrev = pp[ iPrev ],
  19925. tNext = pp[ iNext ];
  19926. if ( tPrev === undefined ) {
  19927. switch ( this.getSettings_().endingStart ) {
  19928. case ZeroSlopeEnding:
  19929. // f'(t0) = 0
  19930. iPrev = i1;
  19931. tPrev = 2 * t0 - t1;
  19932. break;
  19933. case WrapAroundEnding:
  19934. // use the other end of the curve
  19935. iPrev = pp.length - 2;
  19936. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  19937. break;
  19938. default: // ZeroCurvatureEnding
  19939. // f''(t0) = 0 a.k.a. Natural Spline
  19940. iPrev = i1;
  19941. tPrev = t1;
  19942. }
  19943. }
  19944. if ( tNext === undefined ) {
  19945. switch ( this.getSettings_().endingEnd ) {
  19946. case ZeroSlopeEnding:
  19947. // f'(tN) = 0
  19948. iNext = i1;
  19949. tNext = 2 * t1 - t0;
  19950. break;
  19951. case WrapAroundEnding:
  19952. // use the other end of the curve
  19953. iNext = 1;
  19954. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  19955. break;
  19956. default: // ZeroCurvatureEnding
  19957. // f''(tN) = 0, a.k.a. Natural Spline
  19958. iNext = i1 - 1;
  19959. tNext = t0;
  19960. }
  19961. }
  19962. const halfDt = ( t1 - t0 ) * 0.5,
  19963. stride = this.valueSize;
  19964. this._weightPrev = halfDt / ( t0 - tPrev );
  19965. this._weightNext = halfDt / ( tNext - t1 );
  19966. this._offsetPrev = iPrev * stride;
  19967. this._offsetNext = iNext * stride;
  19968. }
  19969. interpolate_( i1, t0, t, t1 ) {
  19970. const result = this.resultBuffer,
  19971. values = this.sampleValues,
  19972. stride = this.valueSize,
  19973. o1 = i1 * stride, o0 = o1 - stride,
  19974. oP = this._offsetPrev, oN = this._offsetNext,
  19975. wP = this._weightPrev, wN = this._weightNext,
  19976. p = ( t - t0 ) / ( t1 - t0 ),
  19977. pp = p * p,
  19978. ppp = pp * p;
  19979. // evaluate polynomials
  19980. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  19981. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  19982. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  19983. const sN = wN * ppp - wN * pp;
  19984. // combine data linearly
  19985. for ( let i = 0; i !== stride; ++ i ) {
  19986. result[ i ] =
  19987. sP * values[ oP + i ] +
  19988. s0 * values[ o0 + i ] +
  19989. s1 * values[ o1 + i ] +
  19990. sN * values[ oN + i ];
  19991. }
  19992. return result;
  19993. }
  19994. }
  19995. class LinearInterpolant extends Interpolant {
  19996. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19997. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  19998. }
  19999. interpolate_( i1, t0, t, t1 ) {
  20000. const result = this.resultBuffer,
  20001. values = this.sampleValues,
  20002. stride = this.valueSize,
  20003. offset1 = i1 * stride,
  20004. offset0 = offset1 - stride,
  20005. weight1 = ( t - t0 ) / ( t1 - t0 ),
  20006. weight0 = 1 - weight1;
  20007. for ( let i = 0; i !== stride; ++ i ) {
  20008. result[ i ] =
  20009. values[ offset0 + i ] * weight0 +
  20010. values[ offset1 + i ] * weight1;
  20011. }
  20012. return result;
  20013. }
  20014. }
  20015. /**
  20016. *
  20017. * Interpolant that evaluates to the sample value at the position preceeding
  20018. * the parameter.
  20019. */
  20020. class DiscreteInterpolant extends Interpolant {
  20021. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20022. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  20023. }
  20024. interpolate_( i1 /*, t0, t, t1 */ ) {
  20025. return this.copySampleValue_( i1 - 1 );
  20026. }
  20027. }
  20028. class KeyframeTrack {
  20029. constructor( name, times, values, interpolation ) {
  20030. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  20031. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  20032. this.name = name;
  20033. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  20034. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  20035. this.setInterpolation( interpolation || this.DefaultInterpolation );
  20036. }
  20037. // Serialization (in static context, because of constructor invocation
  20038. // and automatic invocation of .toJSON):
  20039. static toJSON( track ) {
  20040. const trackType = track.constructor;
  20041. let json;
  20042. // derived classes can define a static toJSON method
  20043. if ( trackType.toJSON !== this.toJSON ) {
  20044. json = trackType.toJSON( track );
  20045. } else {
  20046. // by default, we assume the data can be serialized as-is
  20047. json = {
  20048. 'name': track.name,
  20049. 'times': AnimationUtils.convertArray( track.times, Array ),
  20050. 'values': AnimationUtils.convertArray( track.values, Array )
  20051. };
  20052. const interpolation = track.getInterpolation();
  20053. if ( interpolation !== track.DefaultInterpolation ) {
  20054. json.interpolation = interpolation;
  20055. }
  20056. }
  20057. json.type = track.ValueTypeName; // mandatory
  20058. return json;
  20059. }
  20060. InterpolantFactoryMethodDiscrete( result ) {
  20061. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  20062. }
  20063. InterpolantFactoryMethodLinear( result ) {
  20064. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  20065. }
  20066. InterpolantFactoryMethodSmooth( result ) {
  20067. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  20068. }
  20069. setInterpolation( interpolation ) {
  20070. let factoryMethod;
  20071. switch ( interpolation ) {
  20072. case InterpolateDiscrete:
  20073. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20074. break;
  20075. case InterpolateLinear:
  20076. factoryMethod = this.InterpolantFactoryMethodLinear;
  20077. break;
  20078. case InterpolateSmooth:
  20079. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20080. break;
  20081. }
  20082. if ( factoryMethod === undefined ) {
  20083. const message = 'unsupported interpolation for ' +
  20084. this.ValueTypeName + ' keyframe track named ' + this.name;
  20085. if ( this.createInterpolant === undefined ) {
  20086. // fall back to default, unless the default itself is messed up
  20087. if ( interpolation !== this.DefaultInterpolation ) {
  20088. this.setInterpolation( this.DefaultInterpolation );
  20089. } else {
  20090. throw new Error( message ); // fatal, in this case
  20091. }
  20092. }
  20093. console.warn( 'THREE.KeyframeTrack:', message );
  20094. return this;
  20095. }
  20096. this.createInterpolant = factoryMethod;
  20097. return this;
  20098. }
  20099. getInterpolation() {
  20100. switch ( this.createInterpolant ) {
  20101. case this.InterpolantFactoryMethodDiscrete:
  20102. return InterpolateDiscrete;
  20103. case this.InterpolantFactoryMethodLinear:
  20104. return InterpolateLinear;
  20105. case this.InterpolantFactoryMethodSmooth:
  20106. return InterpolateSmooth;
  20107. }
  20108. }
  20109. getValueSize() {
  20110. return this.values.length / this.times.length;
  20111. }
  20112. // move all keyframes either forwards or backwards in time
  20113. shift( timeOffset ) {
  20114. if ( timeOffset !== 0.0 ) {
  20115. const times = this.times;
  20116. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  20117. times[ i ] += timeOffset;
  20118. }
  20119. }
  20120. return this;
  20121. }
  20122. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20123. scale( timeScale ) {
  20124. if ( timeScale !== 1.0 ) {
  20125. const times = this.times;
  20126. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  20127. times[ i ] *= timeScale;
  20128. }
  20129. }
  20130. return this;
  20131. }
  20132. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20133. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20134. trim( startTime, endTime ) {
  20135. const times = this.times,
  20136. nKeys = times.length;
  20137. let from = 0,
  20138. to = nKeys - 1;
  20139. while ( from !== nKeys && times[ from ] < startTime ) {
  20140. ++ from;
  20141. }
  20142. while ( to !== - 1 && times[ to ] > endTime ) {
  20143. -- to;
  20144. }
  20145. ++ to; // inclusive -> exclusive bound
  20146. if ( from !== 0 || to !== nKeys ) {
  20147. // empty tracks are forbidden, so keep at least one keyframe
  20148. if ( from >= to ) {
  20149. to = Math.max( to, 1 );
  20150. from = to - 1;
  20151. }
  20152. const stride = this.getValueSize();
  20153. this.times = AnimationUtils.arraySlice( times, from, to );
  20154. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  20155. }
  20156. return this;
  20157. }
  20158. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20159. validate() {
  20160. let valid = true;
  20161. const valueSize = this.getValueSize();
  20162. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  20163. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  20164. valid = false;
  20165. }
  20166. const times = this.times,
  20167. values = this.values,
  20168. nKeys = times.length;
  20169. if ( nKeys === 0 ) {
  20170. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  20171. valid = false;
  20172. }
  20173. let prevTime = null;
  20174. for ( let i = 0; i !== nKeys; i ++ ) {
  20175. const currTime = times[ i ];
  20176. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  20177. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  20178. valid = false;
  20179. break;
  20180. }
  20181. if ( prevTime !== null && prevTime > currTime ) {
  20182. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  20183. valid = false;
  20184. break;
  20185. }
  20186. prevTime = currTime;
  20187. }
  20188. if ( values !== undefined ) {
  20189. if ( AnimationUtils.isTypedArray( values ) ) {
  20190. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  20191. const value = values[ i ];
  20192. if ( isNaN( value ) ) {
  20193. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  20194. valid = false;
  20195. break;
  20196. }
  20197. }
  20198. }
  20199. }
  20200. return valid;
  20201. }
  20202. // removes equivalent sequential keys as common in morph target sequences
  20203. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20204. optimize() {
  20205. // times or values may be shared with other tracks, so overwriting is unsafe
  20206. const times = AnimationUtils.arraySlice( this.times ),
  20207. values = AnimationUtils.arraySlice( this.values ),
  20208. stride = this.getValueSize(),
  20209. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20210. lastIndex = times.length - 1;
  20211. let writeIndex = 1;
  20212. for ( let i = 1; i < lastIndex; ++ i ) {
  20213. let keep = false;
  20214. const time = times[ i ];
  20215. const timeNext = times[ i + 1 ];
  20216. // remove adjacent keyframes scheduled at the same time
  20217. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  20218. if ( ! smoothInterpolation ) {
  20219. // remove unnecessary keyframes same as their neighbors
  20220. const offset = i * stride,
  20221. offsetP = offset - stride,
  20222. offsetN = offset + stride;
  20223. for ( let j = 0; j !== stride; ++ j ) {
  20224. const value = values[ offset + j ];
  20225. if ( value !== values[ offsetP + j ] ||
  20226. value !== values[ offsetN + j ] ) {
  20227. keep = true;
  20228. break;
  20229. }
  20230. }
  20231. } else {
  20232. keep = true;
  20233. }
  20234. }
  20235. // in-place compaction
  20236. if ( keep ) {
  20237. if ( i !== writeIndex ) {
  20238. times[ writeIndex ] = times[ i ];
  20239. const readOffset = i * stride,
  20240. writeOffset = writeIndex * stride;
  20241. for ( let j = 0; j !== stride; ++ j ) {
  20242. values[ writeOffset + j ] = values[ readOffset + j ];
  20243. }
  20244. }
  20245. ++ writeIndex;
  20246. }
  20247. }
  20248. // flush last keyframe (compaction looks ahead)
  20249. if ( lastIndex > 0 ) {
  20250. times[ writeIndex ] = times[ lastIndex ];
  20251. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  20252. values[ writeOffset + j ] = values[ readOffset + j ];
  20253. }
  20254. ++ writeIndex;
  20255. }
  20256. if ( writeIndex !== times.length ) {
  20257. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  20258. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  20259. } else {
  20260. this.times = times;
  20261. this.values = values;
  20262. }
  20263. return this;
  20264. }
  20265. clone() {
  20266. const times = AnimationUtils.arraySlice( this.times, 0 );
  20267. const values = AnimationUtils.arraySlice( this.values, 0 );
  20268. const TypedKeyframeTrack = this.constructor;
  20269. const track = new TypedKeyframeTrack( this.name, times, values );
  20270. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20271. track.createInterpolant = this.createInterpolant;
  20272. return track;
  20273. }
  20274. }
  20275. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20276. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20277. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20278. /**
  20279. * A Track of Boolean keyframe values.
  20280. */
  20281. class BooleanKeyframeTrack extends KeyframeTrack {}
  20282. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20283. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20284. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20285. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20286. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20287. /**
  20288. * A Track of keyframe values that represent color.
  20289. */
  20290. class ColorKeyframeTrack extends KeyframeTrack {}
  20291. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  20292. /**
  20293. * A Track of numeric keyframe values.
  20294. */
  20295. class NumberKeyframeTrack extends KeyframeTrack {}
  20296. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  20297. /**
  20298. * Spherical linear unit quaternion interpolant.
  20299. */
  20300. class QuaternionLinearInterpolant extends Interpolant {
  20301. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20302. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  20303. }
  20304. interpolate_( i1, t0, t, t1 ) {
  20305. const result = this.resultBuffer,
  20306. values = this.sampleValues,
  20307. stride = this.valueSize,
  20308. alpha = ( t - t0 ) / ( t1 - t0 );
  20309. let offset = i1 * stride;
  20310. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  20311. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  20312. }
  20313. return result;
  20314. }
  20315. }
  20316. /**
  20317. * A Track of quaternion keyframe values.
  20318. */
  20319. class QuaternionKeyframeTrack extends KeyframeTrack {
  20320. InterpolantFactoryMethodLinear( result ) {
  20321. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  20322. }
  20323. }
  20324. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  20325. // ValueBufferType is inherited
  20326. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20327. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20328. /**
  20329. * A Track that interpolates Strings
  20330. */
  20331. class StringKeyframeTrack extends KeyframeTrack {}
  20332. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20333. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20334. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20335. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20336. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20337. /**
  20338. * A Track of vectored keyframe values.
  20339. */
  20340. class VectorKeyframeTrack extends KeyframeTrack {}
  20341. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  20342. class AnimationClip {
  20343. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  20344. this.name = name;
  20345. this.tracks = tracks;
  20346. this.duration = duration;
  20347. this.blendMode = blendMode;
  20348. this.uuid = generateUUID();
  20349. // this means it should figure out its duration by scanning the tracks
  20350. if ( this.duration < 0 ) {
  20351. this.resetDuration();
  20352. }
  20353. }
  20354. static parse( json ) {
  20355. const tracks = [],
  20356. jsonTracks = json.tracks,
  20357. frameTime = 1.0 / ( json.fps || 1.0 );
  20358. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  20359. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  20360. }
  20361. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  20362. clip.uuid = json.uuid;
  20363. return clip;
  20364. }
  20365. static toJSON( clip ) {
  20366. const tracks = [],
  20367. clipTracks = clip.tracks;
  20368. const json = {
  20369. 'name': clip.name,
  20370. 'duration': clip.duration,
  20371. 'tracks': tracks,
  20372. 'uuid': clip.uuid,
  20373. 'blendMode': clip.blendMode
  20374. };
  20375. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  20376. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  20377. }
  20378. return json;
  20379. }
  20380. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  20381. const numMorphTargets = morphTargetSequence.length;
  20382. const tracks = [];
  20383. for ( let i = 0; i < numMorphTargets; i ++ ) {
  20384. let times = [];
  20385. let values = [];
  20386. times.push(
  20387. ( i + numMorphTargets - 1 ) % numMorphTargets,
  20388. i,
  20389. ( i + 1 ) % numMorphTargets );
  20390. values.push( 0, 1, 0 );
  20391. const order = AnimationUtils.getKeyframeOrder( times );
  20392. times = AnimationUtils.sortedArray( times, 1, order );
  20393. values = AnimationUtils.sortedArray( values, 1, order );
  20394. // if there is a key at the first frame, duplicate it as the
  20395. // last frame as well for perfect loop.
  20396. if ( ! noLoop && times[ 0 ] === 0 ) {
  20397. times.push( numMorphTargets );
  20398. values.push( values[ 0 ] );
  20399. }
  20400. tracks.push(
  20401. new NumberKeyframeTrack(
  20402. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  20403. times, values
  20404. ).scale( 1.0 / fps ) );
  20405. }
  20406. return new this( name, - 1, tracks );
  20407. }
  20408. static findByName( objectOrClipArray, name ) {
  20409. let clipArray = objectOrClipArray;
  20410. if ( ! Array.isArray( objectOrClipArray ) ) {
  20411. const o = objectOrClipArray;
  20412. clipArray = o.geometry && o.geometry.animations || o.animations;
  20413. }
  20414. for ( let i = 0; i < clipArray.length; i ++ ) {
  20415. if ( clipArray[ i ].name === name ) {
  20416. return clipArray[ i ];
  20417. }
  20418. }
  20419. return null;
  20420. }
  20421. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  20422. const animationToMorphTargets = {};
  20423. // tested with https://regex101.com/ on trick sequences
  20424. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20425. const pattern = /^([\w-]*?)([\d]+)$/;
  20426. // sort morph target names into animation groups based
  20427. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20428. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  20429. const morphTarget = morphTargets[ i ];
  20430. const parts = morphTarget.name.match( pattern );
  20431. if ( parts && parts.length > 1 ) {
  20432. const name = parts[ 1 ];
  20433. let animationMorphTargets = animationToMorphTargets[ name ];
  20434. if ( ! animationMorphTargets ) {
  20435. animationToMorphTargets[ name ] = animationMorphTargets = [];
  20436. }
  20437. animationMorphTargets.push( morphTarget );
  20438. }
  20439. }
  20440. const clips = [];
  20441. for ( const name in animationToMorphTargets ) {
  20442. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  20443. }
  20444. return clips;
  20445. }
  20446. // parse the animation.hierarchy format
  20447. static parseAnimation( animation, bones ) {
  20448. if ( ! animation ) {
  20449. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  20450. return null;
  20451. }
  20452. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  20453. // only return track if there are actually keys.
  20454. if ( animationKeys.length !== 0 ) {
  20455. const times = [];
  20456. const values = [];
  20457. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  20458. // empty keys are filtered out, so check again
  20459. if ( times.length !== 0 ) {
  20460. destTracks.push( new trackType( trackName, times, values ) );
  20461. }
  20462. }
  20463. };
  20464. const tracks = [];
  20465. const clipName = animation.name || 'default';
  20466. const fps = animation.fps || 30;
  20467. const blendMode = animation.blendMode;
  20468. // automatic length determination in AnimationClip.
  20469. let duration = animation.length || - 1;
  20470. const hierarchyTracks = animation.hierarchy || [];
  20471. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  20472. const animationKeys = hierarchyTracks[ h ].keys;
  20473. // skip empty tracks
  20474. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  20475. // process morph targets
  20476. if ( animationKeys[ 0 ].morphTargets ) {
  20477. // figure out all morph targets used in this track
  20478. const morphTargetNames = {};
  20479. let k;
  20480. for ( k = 0; k < animationKeys.length; k ++ ) {
  20481. if ( animationKeys[ k ].morphTargets ) {
  20482. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  20483. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  20484. }
  20485. }
  20486. }
  20487. // create a track for each morph target with all zero
  20488. // morphTargetInfluences except for the keys in which
  20489. // the morphTarget is named.
  20490. for ( const morphTargetName in morphTargetNames ) {
  20491. const times = [];
  20492. const values = [];
  20493. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  20494. const animationKey = animationKeys[ k ];
  20495. times.push( animationKey.time );
  20496. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  20497. }
  20498. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  20499. }
  20500. duration = morphTargetNames.length * ( fps || 1.0 );
  20501. } else {
  20502. // ...assume skeletal animation
  20503. const boneName = '.bones[' + bones[ h ].name + ']';
  20504. addNonemptyTrack(
  20505. VectorKeyframeTrack, boneName + '.position',
  20506. animationKeys, 'pos', tracks );
  20507. addNonemptyTrack(
  20508. QuaternionKeyframeTrack, boneName + '.quaternion',
  20509. animationKeys, 'rot', tracks );
  20510. addNonemptyTrack(
  20511. VectorKeyframeTrack, boneName + '.scale',
  20512. animationKeys, 'scl', tracks );
  20513. }
  20514. }
  20515. if ( tracks.length === 0 ) {
  20516. return null;
  20517. }
  20518. const clip = new this( clipName, duration, tracks, blendMode );
  20519. return clip;
  20520. }
  20521. resetDuration() {
  20522. const tracks = this.tracks;
  20523. let duration = 0;
  20524. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  20525. const track = this.tracks[ i ];
  20526. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  20527. }
  20528. this.duration = duration;
  20529. return this;
  20530. }
  20531. trim() {
  20532. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20533. this.tracks[ i ].trim( 0, this.duration );
  20534. }
  20535. return this;
  20536. }
  20537. validate() {
  20538. let valid = true;
  20539. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20540. valid = valid && this.tracks[ i ].validate();
  20541. }
  20542. return valid;
  20543. }
  20544. optimize() {
  20545. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20546. this.tracks[ i ].optimize();
  20547. }
  20548. return this;
  20549. }
  20550. clone() {
  20551. const tracks = [];
  20552. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20553. tracks.push( this.tracks[ i ].clone() );
  20554. }
  20555. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  20556. }
  20557. toJSON() {
  20558. return this.constructor.toJSON( this );
  20559. }
  20560. }
  20561. function getTrackTypeForValueTypeName( typeName ) {
  20562. switch ( typeName.toLowerCase() ) {
  20563. case 'scalar':
  20564. case 'double':
  20565. case 'float':
  20566. case 'number':
  20567. case 'integer':
  20568. return NumberKeyframeTrack;
  20569. case 'vector':
  20570. case 'vector2':
  20571. case 'vector3':
  20572. case 'vector4':
  20573. return VectorKeyframeTrack;
  20574. case 'color':
  20575. return ColorKeyframeTrack;
  20576. case 'quaternion':
  20577. return QuaternionKeyframeTrack;
  20578. case 'bool':
  20579. case 'boolean':
  20580. return BooleanKeyframeTrack;
  20581. case 'string':
  20582. return StringKeyframeTrack;
  20583. }
  20584. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  20585. }
  20586. function parseKeyframeTrack( json ) {
  20587. if ( json.type === undefined ) {
  20588. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  20589. }
  20590. const trackType = getTrackTypeForValueTypeName( json.type );
  20591. if ( json.times === undefined ) {
  20592. const times = [], values = [];
  20593. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  20594. json.times = times;
  20595. json.values = values;
  20596. }
  20597. // derived classes can define a static parse method
  20598. if ( trackType.parse !== undefined ) {
  20599. return trackType.parse( json );
  20600. } else {
  20601. // by default, we assume a constructor compatible with the base
  20602. return new trackType( json.name, json.times, json.values, json.interpolation );
  20603. }
  20604. }
  20605. const Cache = {
  20606. enabled: false,
  20607. files: {},
  20608. add: function ( key, file ) {
  20609. if ( this.enabled === false ) return;
  20610. // console.log( 'THREE.Cache', 'Adding key:', key );
  20611. this.files[ key ] = file;
  20612. },
  20613. get: function ( key ) {
  20614. if ( this.enabled === false ) return;
  20615. // console.log( 'THREE.Cache', 'Checking key:', key );
  20616. return this.files[ key ];
  20617. },
  20618. remove: function ( key ) {
  20619. delete this.files[ key ];
  20620. },
  20621. clear: function () {
  20622. this.files = {};
  20623. }
  20624. };
  20625. class LoadingManager {
  20626. constructor( onLoad, onProgress, onError ) {
  20627. const scope = this;
  20628. let isLoading = false;
  20629. let itemsLoaded = 0;
  20630. let itemsTotal = 0;
  20631. let urlModifier = undefined;
  20632. const handlers = [];
  20633. // Refer to #5689 for the reason why we don't set .onStart
  20634. // in the constructor
  20635. this.onStart = undefined;
  20636. this.onLoad = onLoad;
  20637. this.onProgress = onProgress;
  20638. this.onError = onError;
  20639. this.itemStart = function ( url ) {
  20640. itemsTotal ++;
  20641. if ( isLoading === false ) {
  20642. if ( scope.onStart !== undefined ) {
  20643. scope.onStart( url, itemsLoaded, itemsTotal );
  20644. }
  20645. }
  20646. isLoading = true;
  20647. };
  20648. this.itemEnd = function ( url ) {
  20649. itemsLoaded ++;
  20650. if ( scope.onProgress !== undefined ) {
  20651. scope.onProgress( url, itemsLoaded, itemsTotal );
  20652. }
  20653. if ( itemsLoaded === itemsTotal ) {
  20654. isLoading = false;
  20655. if ( scope.onLoad !== undefined ) {
  20656. scope.onLoad();
  20657. }
  20658. }
  20659. };
  20660. this.itemError = function ( url ) {
  20661. if ( scope.onError !== undefined ) {
  20662. scope.onError( url );
  20663. }
  20664. };
  20665. this.resolveURL = function ( url ) {
  20666. if ( urlModifier ) {
  20667. return urlModifier( url );
  20668. }
  20669. return url;
  20670. };
  20671. this.setURLModifier = function ( transform ) {
  20672. urlModifier = transform;
  20673. return this;
  20674. };
  20675. this.addHandler = function ( regex, loader ) {
  20676. handlers.push( regex, loader );
  20677. return this;
  20678. };
  20679. this.removeHandler = function ( regex ) {
  20680. const index = handlers.indexOf( regex );
  20681. if ( index !== - 1 ) {
  20682. handlers.splice( index, 2 );
  20683. }
  20684. return this;
  20685. };
  20686. this.getHandler = function ( file ) {
  20687. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  20688. const regex = handlers[ i ];
  20689. const loader = handlers[ i + 1 ];
  20690. if ( regex.global ) regex.lastIndex = 0; // see #17920
  20691. if ( regex.test( file ) ) {
  20692. return loader;
  20693. }
  20694. }
  20695. return null;
  20696. };
  20697. }
  20698. }
  20699. const DefaultLoadingManager = new LoadingManager();
  20700. class Loader {
  20701. constructor( manager ) {
  20702. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20703. this.crossOrigin = 'anonymous';
  20704. this.withCredentials = false;
  20705. this.path = '';
  20706. this.resourcePath = '';
  20707. this.requestHeader = {};
  20708. }
  20709. load( /* url, onLoad, onProgress, onError */ ) {}
  20710. loadAsync( url, onProgress ) {
  20711. const scope = this;
  20712. return new Promise( function ( resolve, reject ) {
  20713. scope.load( url, resolve, onProgress, reject );
  20714. } );
  20715. }
  20716. parse( /* data */ ) {}
  20717. setCrossOrigin( crossOrigin ) {
  20718. this.crossOrigin = crossOrigin;
  20719. return this;
  20720. }
  20721. setWithCredentials( value ) {
  20722. this.withCredentials = value;
  20723. return this;
  20724. }
  20725. setPath( path ) {
  20726. this.path = path;
  20727. return this;
  20728. }
  20729. setResourcePath( resourcePath ) {
  20730. this.resourcePath = resourcePath;
  20731. return this;
  20732. }
  20733. setRequestHeader( requestHeader ) {
  20734. this.requestHeader = requestHeader;
  20735. return this;
  20736. }
  20737. }
  20738. const loading = {};
  20739. class FileLoader extends Loader {
  20740. constructor( manager ) {
  20741. super( manager );
  20742. }
  20743. load( url, onLoad, onProgress, onError ) {
  20744. if ( url === undefined ) url = '';
  20745. if ( this.path !== undefined ) url = this.path + url;
  20746. url = this.manager.resolveURL( url );
  20747. const scope = this;
  20748. const cached = Cache.get( url );
  20749. if ( cached !== undefined ) {
  20750. scope.manager.itemStart( url );
  20751. setTimeout( function () {
  20752. if ( onLoad ) onLoad( cached );
  20753. scope.manager.itemEnd( url );
  20754. }, 0 );
  20755. return cached;
  20756. }
  20757. // Check if request is duplicate
  20758. if ( loading[ url ] !== undefined ) {
  20759. loading[ url ].push( {
  20760. onLoad: onLoad,
  20761. onProgress: onProgress,
  20762. onError: onError
  20763. } );
  20764. return;
  20765. }
  20766. // Check for data: URI
  20767. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20768. const dataUriRegexResult = url.match( dataUriRegex );
  20769. let request;
  20770. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20771. if ( dataUriRegexResult ) {
  20772. const mimeType = dataUriRegexResult[ 1 ];
  20773. const isBase64 = !! dataUriRegexResult[ 2 ];
  20774. let data = dataUriRegexResult[ 3 ];
  20775. data = decodeURIComponent( data );
  20776. if ( isBase64 ) data = atob( data );
  20777. try {
  20778. let response;
  20779. const responseType = ( this.responseType || '' ).toLowerCase();
  20780. switch ( responseType ) {
  20781. case 'arraybuffer':
  20782. case 'blob':
  20783. const view = new Uint8Array( data.length );
  20784. for ( let i = 0; i < data.length; i ++ ) {
  20785. view[ i ] = data.charCodeAt( i );
  20786. }
  20787. if ( responseType === 'blob' ) {
  20788. response = new Blob( [ view.buffer ], { type: mimeType } );
  20789. } else {
  20790. response = view.buffer;
  20791. }
  20792. break;
  20793. case 'document':
  20794. const parser = new DOMParser();
  20795. response = parser.parseFromString( data, mimeType );
  20796. break;
  20797. case 'json':
  20798. response = JSON.parse( data );
  20799. break;
  20800. default: // 'text' or other
  20801. response = data;
  20802. break;
  20803. }
  20804. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20805. setTimeout( function () {
  20806. if ( onLoad ) onLoad( response );
  20807. scope.manager.itemEnd( url );
  20808. }, 0 );
  20809. } catch ( error ) {
  20810. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20811. setTimeout( function () {
  20812. if ( onError ) onError( error );
  20813. scope.manager.itemError( url );
  20814. scope.manager.itemEnd( url );
  20815. }, 0 );
  20816. }
  20817. } else {
  20818. // Initialise array for duplicate requests
  20819. loading[ url ] = [];
  20820. loading[ url ].push( {
  20821. onLoad: onLoad,
  20822. onProgress: onProgress,
  20823. onError: onError
  20824. } );
  20825. request = new XMLHttpRequest();
  20826. request.open( 'GET', url, true );
  20827. request.addEventListener( 'load', function ( event ) {
  20828. const response = this.response;
  20829. const callbacks = loading[ url ];
  20830. delete loading[ url ];
  20831. if ( this.status === 200 || this.status === 0 ) {
  20832. // Some browsers return HTTP Status 0 when using non-http protocol
  20833. // e.g. 'file://' or 'data://'. Handle as success.
  20834. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  20835. // Add to cache only on HTTP success, so that we do not cache
  20836. // error response bodies as proper responses to requests.
  20837. Cache.add( url, response );
  20838. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20839. const callback = callbacks[ i ];
  20840. if ( callback.onLoad ) callback.onLoad( response );
  20841. }
  20842. scope.manager.itemEnd( url );
  20843. } else {
  20844. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20845. const callback = callbacks[ i ];
  20846. if ( callback.onError ) callback.onError( event );
  20847. }
  20848. scope.manager.itemError( url );
  20849. scope.manager.itemEnd( url );
  20850. }
  20851. }, false );
  20852. request.addEventListener( 'progress', function ( event ) {
  20853. const callbacks = loading[ url ];
  20854. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20855. const callback = callbacks[ i ];
  20856. if ( callback.onProgress ) callback.onProgress( event );
  20857. }
  20858. }, false );
  20859. request.addEventListener( 'error', function ( event ) {
  20860. const callbacks = loading[ url ];
  20861. delete loading[ url ];
  20862. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20863. const callback = callbacks[ i ];
  20864. if ( callback.onError ) callback.onError( event );
  20865. }
  20866. scope.manager.itemError( url );
  20867. scope.manager.itemEnd( url );
  20868. }, false );
  20869. request.addEventListener( 'abort', function ( event ) {
  20870. const callbacks = loading[ url ];
  20871. delete loading[ url ];
  20872. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20873. const callback = callbacks[ i ];
  20874. if ( callback.onError ) callback.onError( event );
  20875. }
  20876. scope.manager.itemError( url );
  20877. scope.manager.itemEnd( url );
  20878. }, false );
  20879. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  20880. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  20881. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  20882. for ( const header in this.requestHeader ) {
  20883. request.setRequestHeader( header, this.requestHeader[ header ] );
  20884. }
  20885. request.send( null );
  20886. }
  20887. scope.manager.itemStart( url );
  20888. return request;
  20889. }
  20890. setResponseType( value ) {
  20891. this.responseType = value;
  20892. return this;
  20893. }
  20894. setMimeType( value ) {
  20895. this.mimeType = value;
  20896. return this;
  20897. }
  20898. }
  20899. class AnimationLoader extends Loader {
  20900. constructor( manager ) {
  20901. super( manager );
  20902. }
  20903. load( url, onLoad, onProgress, onError ) {
  20904. const scope = this;
  20905. const loader = new FileLoader( this.manager );
  20906. loader.setPath( this.path );
  20907. loader.setRequestHeader( this.requestHeader );
  20908. loader.setWithCredentials( this.withCredentials );
  20909. loader.load( url, function ( text ) {
  20910. try {
  20911. onLoad( scope.parse( JSON.parse( text ) ) );
  20912. } catch ( e ) {
  20913. if ( onError ) {
  20914. onError( e );
  20915. } else {
  20916. console.error( e );
  20917. }
  20918. scope.manager.itemError( url );
  20919. }
  20920. }, onProgress, onError );
  20921. }
  20922. parse( json ) {
  20923. const animations = [];
  20924. for ( let i = 0; i < json.length; i ++ ) {
  20925. const clip = AnimationClip.parse( json[ i ] );
  20926. animations.push( clip );
  20927. }
  20928. return animations;
  20929. }
  20930. }
  20931. /**
  20932. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20933. *
  20934. * Sub classes have to implement the parse() method which will be used in load().
  20935. */
  20936. class CompressedTextureLoader extends Loader {
  20937. constructor( manager ) {
  20938. super( manager );
  20939. }
  20940. load( url, onLoad, onProgress, onError ) {
  20941. const scope = this;
  20942. const images = [];
  20943. const texture = new CompressedTexture();
  20944. const loader = new FileLoader( this.manager );
  20945. loader.setPath( this.path );
  20946. loader.setResponseType( 'arraybuffer' );
  20947. loader.setRequestHeader( this.requestHeader );
  20948. loader.setWithCredentials( scope.withCredentials );
  20949. let loaded = 0;
  20950. function loadTexture( i ) {
  20951. loader.load( url[ i ], function ( buffer ) {
  20952. const texDatas = scope.parse( buffer, true );
  20953. images[ i ] = {
  20954. width: texDatas.width,
  20955. height: texDatas.height,
  20956. format: texDatas.format,
  20957. mipmaps: texDatas.mipmaps
  20958. };
  20959. loaded += 1;
  20960. if ( loaded === 6 ) {
  20961. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  20962. texture.image = images;
  20963. texture.format = texDatas.format;
  20964. texture.needsUpdate = true;
  20965. if ( onLoad ) onLoad( texture );
  20966. }
  20967. }, onProgress, onError );
  20968. }
  20969. if ( Array.isArray( url ) ) {
  20970. for ( let i = 0, il = url.length; i < il; ++ i ) {
  20971. loadTexture( i );
  20972. }
  20973. } else {
  20974. // compressed cubemap texture stored in a single DDS file
  20975. loader.load( url, function ( buffer ) {
  20976. const texDatas = scope.parse( buffer, true );
  20977. if ( texDatas.isCubemap ) {
  20978. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20979. for ( let f = 0; f < faces; f ++ ) {
  20980. images[ f ] = { mipmaps: [] };
  20981. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  20982. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  20983. images[ f ].format = texDatas.format;
  20984. images[ f ].width = texDatas.width;
  20985. images[ f ].height = texDatas.height;
  20986. }
  20987. }
  20988. texture.image = images;
  20989. } else {
  20990. texture.image.width = texDatas.width;
  20991. texture.image.height = texDatas.height;
  20992. texture.mipmaps = texDatas.mipmaps;
  20993. }
  20994. if ( texDatas.mipmapCount === 1 ) {
  20995. texture.minFilter = LinearFilter;
  20996. }
  20997. texture.format = texDatas.format;
  20998. texture.needsUpdate = true;
  20999. if ( onLoad ) onLoad( texture );
  21000. }, onProgress, onError );
  21001. }
  21002. return texture;
  21003. }
  21004. }
  21005. class ImageLoader extends Loader {
  21006. constructor( manager ) {
  21007. super( manager );
  21008. }
  21009. load( url, onLoad, onProgress, onError ) {
  21010. if ( this.path !== undefined ) url = this.path + url;
  21011. url = this.manager.resolveURL( url );
  21012. const scope = this;
  21013. const cached = Cache.get( url );
  21014. if ( cached !== undefined ) {
  21015. scope.manager.itemStart( url );
  21016. setTimeout( function () {
  21017. if ( onLoad ) onLoad( cached );
  21018. scope.manager.itemEnd( url );
  21019. }, 0 );
  21020. return cached;
  21021. }
  21022. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  21023. function onImageLoad() {
  21024. image.removeEventListener( 'load', onImageLoad, false );
  21025. image.removeEventListener( 'error', onImageError, false );
  21026. Cache.add( url, this );
  21027. if ( onLoad ) onLoad( this );
  21028. scope.manager.itemEnd( url );
  21029. }
  21030. function onImageError( event ) {
  21031. image.removeEventListener( 'load', onImageLoad, false );
  21032. image.removeEventListener( 'error', onImageError, false );
  21033. if ( onError ) onError( event );
  21034. scope.manager.itemError( url );
  21035. scope.manager.itemEnd( url );
  21036. }
  21037. image.addEventListener( 'load', onImageLoad, false );
  21038. image.addEventListener( 'error', onImageError, false );
  21039. if ( url.substr( 0, 5 ) !== 'data:' ) {
  21040. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  21041. }
  21042. scope.manager.itemStart( url );
  21043. image.src = url;
  21044. return image;
  21045. }
  21046. }
  21047. class CubeTextureLoader extends Loader {
  21048. constructor( manager ) {
  21049. super( manager );
  21050. }
  21051. load( urls, onLoad, onProgress, onError ) {
  21052. const texture = new CubeTexture();
  21053. const loader = new ImageLoader( this.manager );
  21054. loader.setCrossOrigin( this.crossOrigin );
  21055. loader.setPath( this.path );
  21056. let loaded = 0;
  21057. function loadTexture( i ) {
  21058. loader.load( urls[ i ], function ( image ) {
  21059. texture.images[ i ] = image;
  21060. loaded ++;
  21061. if ( loaded === 6 ) {
  21062. texture.needsUpdate = true;
  21063. if ( onLoad ) onLoad( texture );
  21064. }
  21065. }, undefined, onError );
  21066. }
  21067. for ( let i = 0; i < urls.length; ++ i ) {
  21068. loadTexture( i );
  21069. }
  21070. return texture;
  21071. }
  21072. }
  21073. /**
  21074. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21075. *
  21076. * Sub classes have to implement the parse() method which will be used in load().
  21077. */
  21078. class DataTextureLoader extends Loader {
  21079. constructor( manager ) {
  21080. super( manager );
  21081. }
  21082. load( url, onLoad, onProgress, onError ) {
  21083. const scope = this;
  21084. const texture = new DataTexture();
  21085. const loader = new FileLoader( this.manager );
  21086. loader.setResponseType( 'arraybuffer' );
  21087. loader.setRequestHeader( this.requestHeader );
  21088. loader.setPath( this.path );
  21089. loader.setWithCredentials( scope.withCredentials );
  21090. loader.load( url, function ( buffer ) {
  21091. const texData = scope.parse( buffer );
  21092. if ( ! texData ) return;
  21093. if ( texData.image !== undefined ) {
  21094. texture.image = texData.image;
  21095. } else if ( texData.data !== undefined ) {
  21096. texture.image.width = texData.width;
  21097. texture.image.height = texData.height;
  21098. texture.image.data = texData.data;
  21099. }
  21100. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21101. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21102. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21103. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  21104. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21105. if ( texData.encoding !== undefined ) {
  21106. texture.encoding = texData.encoding;
  21107. }
  21108. if ( texData.flipY !== undefined ) {
  21109. texture.flipY = texData.flipY;
  21110. }
  21111. if ( texData.format !== undefined ) {
  21112. texture.format = texData.format;
  21113. }
  21114. if ( texData.type !== undefined ) {
  21115. texture.type = texData.type;
  21116. }
  21117. if ( texData.mipmaps !== undefined ) {
  21118. texture.mipmaps = texData.mipmaps;
  21119. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  21120. }
  21121. if ( texData.mipmapCount === 1 ) {
  21122. texture.minFilter = LinearFilter;
  21123. }
  21124. if ( texData.generateMipmaps !== undefined ) {
  21125. texture.generateMipmaps = texData.generateMipmaps;
  21126. }
  21127. texture.needsUpdate = true;
  21128. if ( onLoad ) onLoad( texture, texData );
  21129. }, onProgress, onError );
  21130. return texture;
  21131. }
  21132. }
  21133. class TextureLoader extends Loader {
  21134. constructor( manager ) {
  21135. super( manager );
  21136. }
  21137. load( url, onLoad, onProgress, onError ) {
  21138. const texture = new Texture();
  21139. const loader = new ImageLoader( this.manager );
  21140. loader.setCrossOrigin( this.crossOrigin );
  21141. loader.setPath( this.path );
  21142. loader.load( url, function ( image ) {
  21143. texture.image = image;
  21144. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  21145. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  21146. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  21147. texture.needsUpdate = true;
  21148. if ( onLoad !== undefined ) {
  21149. onLoad( texture );
  21150. }
  21151. }, onProgress, onError );
  21152. return texture;
  21153. }
  21154. }
  21155. /**
  21156. * Extensible curve object.
  21157. *
  21158. * Some common of curve methods:
  21159. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  21160. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  21161. * .getPoints(), .getSpacedPoints()
  21162. * .getLength()
  21163. * .updateArcLengths()
  21164. *
  21165. * This following curves inherit from THREE.Curve:
  21166. *
  21167. * -- 2D curves --
  21168. * THREE.ArcCurve
  21169. * THREE.CubicBezierCurve
  21170. * THREE.EllipseCurve
  21171. * THREE.LineCurve
  21172. * THREE.QuadraticBezierCurve
  21173. * THREE.SplineCurve
  21174. *
  21175. * -- 3D curves --
  21176. * THREE.CatmullRomCurve3
  21177. * THREE.CubicBezierCurve3
  21178. * THREE.LineCurve3
  21179. * THREE.QuadraticBezierCurve3
  21180. *
  21181. * A series of curves can be represented as a THREE.CurvePath.
  21182. *
  21183. **/
  21184. class Curve {
  21185. constructor() {
  21186. this.type = 'Curve';
  21187. this.arcLengthDivisions = 200;
  21188. }
  21189. // Virtual base class method to overwrite and implement in subclasses
  21190. // - t [0 .. 1]
  21191. getPoint( /* t, optionalTarget */ ) {
  21192. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  21193. return null;
  21194. }
  21195. // Get point at relative position in curve according to arc length
  21196. // - u [0 .. 1]
  21197. getPointAt( u, optionalTarget ) {
  21198. const t = this.getUtoTmapping( u );
  21199. return this.getPoint( t, optionalTarget );
  21200. }
  21201. // Get sequence of points using getPoint( t )
  21202. getPoints( divisions = 5 ) {
  21203. const points = [];
  21204. for ( let d = 0; d <= divisions; d ++ ) {
  21205. points.push( this.getPoint( d / divisions ) );
  21206. }
  21207. return points;
  21208. }
  21209. // Get sequence of points using getPointAt( u )
  21210. getSpacedPoints( divisions = 5 ) {
  21211. const points = [];
  21212. for ( let d = 0; d <= divisions; d ++ ) {
  21213. points.push( this.getPointAt( d / divisions ) );
  21214. }
  21215. return points;
  21216. }
  21217. // Get total curve arc length
  21218. getLength() {
  21219. const lengths = this.getLengths();
  21220. return lengths[ lengths.length - 1 ];
  21221. }
  21222. // Get list of cumulative segment lengths
  21223. getLengths( divisions = this.arcLengthDivisions ) {
  21224. if ( this.cacheArcLengths &&
  21225. ( this.cacheArcLengths.length === divisions + 1 ) &&
  21226. ! this.needsUpdate ) {
  21227. return this.cacheArcLengths;
  21228. }
  21229. this.needsUpdate = false;
  21230. const cache = [];
  21231. let current, last = this.getPoint( 0 );
  21232. let sum = 0;
  21233. cache.push( 0 );
  21234. for ( let p = 1; p <= divisions; p ++ ) {
  21235. current = this.getPoint( p / divisions );
  21236. sum += current.distanceTo( last );
  21237. cache.push( sum );
  21238. last = current;
  21239. }
  21240. this.cacheArcLengths = cache;
  21241. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21242. }
  21243. updateArcLengths() {
  21244. this.needsUpdate = true;
  21245. this.getLengths();
  21246. }
  21247. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21248. getUtoTmapping( u, distance ) {
  21249. const arcLengths = this.getLengths();
  21250. let i = 0;
  21251. const il = arcLengths.length;
  21252. let targetArcLength; // The targeted u distance value to get
  21253. if ( distance ) {
  21254. targetArcLength = distance;
  21255. } else {
  21256. targetArcLength = u * arcLengths[ il - 1 ];
  21257. }
  21258. // binary search for the index with largest value smaller than target u distance
  21259. let low = 0, high = il - 1, comparison;
  21260. while ( low <= high ) {
  21261. 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
  21262. comparison = arcLengths[ i ] - targetArcLength;
  21263. if ( comparison < 0 ) {
  21264. low = i + 1;
  21265. } else if ( comparison > 0 ) {
  21266. high = i - 1;
  21267. } else {
  21268. high = i;
  21269. break;
  21270. // DONE
  21271. }
  21272. }
  21273. i = high;
  21274. if ( arcLengths[ i ] === targetArcLength ) {
  21275. return i / ( il - 1 );
  21276. }
  21277. // we could get finer grain at lengths, or use simple interpolation between two points
  21278. const lengthBefore = arcLengths[ i ];
  21279. const lengthAfter = arcLengths[ i + 1 ];
  21280. const segmentLength = lengthAfter - lengthBefore;
  21281. // determine where we are between the 'before' and 'after' points
  21282. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21283. // add that fractional amount to t
  21284. const t = ( i + segmentFraction ) / ( il - 1 );
  21285. return t;
  21286. }
  21287. // Returns a unit vector tangent at t
  21288. // In case any sub curve does not implement its tangent derivation,
  21289. // 2 points a small delta apart will be used to find its gradient
  21290. // which seems to give a reasonable approximation
  21291. getTangent( t, optionalTarget ) {
  21292. const delta = 0.0001;
  21293. let t1 = t - delta;
  21294. let t2 = t + delta;
  21295. // Capping in case of danger
  21296. if ( t1 < 0 ) t1 = 0;
  21297. if ( t2 > 1 ) t2 = 1;
  21298. const pt1 = this.getPoint( t1 );
  21299. const pt2 = this.getPoint( t2 );
  21300. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  21301. tangent.copy( pt2 ).sub( pt1 ).normalize();
  21302. return tangent;
  21303. }
  21304. getTangentAt( u, optionalTarget ) {
  21305. const t = this.getUtoTmapping( u );
  21306. return this.getTangent( t, optionalTarget );
  21307. }
  21308. computeFrenetFrames( segments, closed ) {
  21309. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21310. const normal = new Vector3();
  21311. const tangents = [];
  21312. const normals = [];
  21313. const binormals = [];
  21314. const vec = new Vector3();
  21315. const mat = new Matrix4();
  21316. // compute the tangent vectors for each segment on the curve
  21317. for ( let i = 0; i <= segments; i ++ ) {
  21318. const u = i / segments;
  21319. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  21320. tangents[ i ].normalize();
  21321. }
  21322. // select an initial normal vector perpendicular to the first tangent vector,
  21323. // and in the direction of the minimum tangent xyz component
  21324. normals[ 0 ] = new Vector3();
  21325. binormals[ 0 ] = new Vector3();
  21326. let min = Number.MAX_VALUE;
  21327. const tx = Math.abs( tangents[ 0 ].x );
  21328. const ty = Math.abs( tangents[ 0 ].y );
  21329. const tz = Math.abs( tangents[ 0 ].z );
  21330. if ( tx <= min ) {
  21331. min = tx;
  21332. normal.set( 1, 0, 0 );
  21333. }
  21334. if ( ty <= min ) {
  21335. min = ty;
  21336. normal.set( 0, 1, 0 );
  21337. }
  21338. if ( tz <= min ) {
  21339. normal.set( 0, 0, 1 );
  21340. }
  21341. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21342. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21343. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21344. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21345. for ( let i = 1; i <= segments; i ++ ) {
  21346. normals[ i ] = normals[ i - 1 ].clone();
  21347. binormals[ i ] = binormals[ i - 1 ].clone();
  21348. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21349. if ( vec.length() > Number.EPSILON ) {
  21350. vec.normalize();
  21351. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21352. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21353. }
  21354. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21355. }
  21356. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21357. if ( closed === true ) {
  21358. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21359. theta /= segments;
  21360. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21361. theta = - theta;
  21362. }
  21363. for ( let i = 1; i <= segments; i ++ ) {
  21364. // twist a little...
  21365. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21366. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21367. }
  21368. }
  21369. return {
  21370. tangents: tangents,
  21371. normals: normals,
  21372. binormals: binormals
  21373. };
  21374. }
  21375. clone() {
  21376. return new this.constructor().copy( this );
  21377. }
  21378. copy( source ) {
  21379. this.arcLengthDivisions = source.arcLengthDivisions;
  21380. return this;
  21381. }
  21382. toJSON() {
  21383. const data = {
  21384. metadata: {
  21385. version: 4.5,
  21386. type: 'Curve',
  21387. generator: 'Curve.toJSON'
  21388. }
  21389. };
  21390. data.arcLengthDivisions = this.arcLengthDivisions;
  21391. data.type = this.type;
  21392. return data;
  21393. }
  21394. fromJSON( json ) {
  21395. this.arcLengthDivisions = json.arcLengthDivisions;
  21396. return this;
  21397. }
  21398. }
  21399. class EllipseCurve extends Curve {
  21400. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  21401. super();
  21402. this.type = 'EllipseCurve';
  21403. this.aX = aX;
  21404. this.aY = aY;
  21405. this.xRadius = xRadius;
  21406. this.yRadius = yRadius;
  21407. this.aStartAngle = aStartAngle;
  21408. this.aEndAngle = aEndAngle;
  21409. this.aClockwise = aClockwise;
  21410. this.aRotation = aRotation;
  21411. }
  21412. getPoint( t, optionalTarget ) {
  21413. const point = optionalTarget || new Vector2();
  21414. const twoPi = Math.PI * 2;
  21415. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21416. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21417. // ensures that deltaAngle is 0 .. 2 PI
  21418. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21419. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21420. if ( deltaAngle < Number.EPSILON ) {
  21421. if ( samePoints ) {
  21422. deltaAngle = 0;
  21423. } else {
  21424. deltaAngle = twoPi;
  21425. }
  21426. }
  21427. if ( this.aClockwise === true && ! samePoints ) {
  21428. if ( deltaAngle === twoPi ) {
  21429. deltaAngle = - twoPi;
  21430. } else {
  21431. deltaAngle = deltaAngle - twoPi;
  21432. }
  21433. }
  21434. const angle = this.aStartAngle + t * deltaAngle;
  21435. let x = this.aX + this.xRadius * Math.cos( angle );
  21436. let y = this.aY + this.yRadius * Math.sin( angle );
  21437. if ( this.aRotation !== 0 ) {
  21438. const cos = Math.cos( this.aRotation );
  21439. const sin = Math.sin( this.aRotation );
  21440. const tx = x - this.aX;
  21441. const ty = y - this.aY;
  21442. // Rotate the point about the center of the ellipse.
  21443. x = tx * cos - ty * sin + this.aX;
  21444. y = tx * sin + ty * cos + this.aY;
  21445. }
  21446. return point.set( x, y );
  21447. }
  21448. copy( source ) {
  21449. super.copy( source );
  21450. this.aX = source.aX;
  21451. this.aY = source.aY;
  21452. this.xRadius = source.xRadius;
  21453. this.yRadius = source.yRadius;
  21454. this.aStartAngle = source.aStartAngle;
  21455. this.aEndAngle = source.aEndAngle;
  21456. this.aClockwise = source.aClockwise;
  21457. this.aRotation = source.aRotation;
  21458. return this;
  21459. }
  21460. toJSON() {
  21461. const data = super.toJSON();
  21462. data.aX = this.aX;
  21463. data.aY = this.aY;
  21464. data.xRadius = this.xRadius;
  21465. data.yRadius = this.yRadius;
  21466. data.aStartAngle = this.aStartAngle;
  21467. data.aEndAngle = this.aEndAngle;
  21468. data.aClockwise = this.aClockwise;
  21469. data.aRotation = this.aRotation;
  21470. return data;
  21471. }
  21472. fromJSON( json ) {
  21473. super.fromJSON( json );
  21474. this.aX = json.aX;
  21475. this.aY = json.aY;
  21476. this.xRadius = json.xRadius;
  21477. this.yRadius = json.yRadius;
  21478. this.aStartAngle = json.aStartAngle;
  21479. this.aEndAngle = json.aEndAngle;
  21480. this.aClockwise = json.aClockwise;
  21481. this.aRotation = json.aRotation;
  21482. return this;
  21483. }
  21484. }
  21485. EllipseCurve.prototype.isEllipseCurve = true;
  21486. class ArcCurve extends EllipseCurve {
  21487. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21488. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21489. this.type = 'ArcCurve';
  21490. }
  21491. }
  21492. ArcCurve.prototype.isArcCurve = true;
  21493. /**
  21494. * Centripetal CatmullRom Curve - which is useful for avoiding
  21495. * cusps and self-intersections in non-uniform catmull rom curves.
  21496. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21497. *
  21498. * curve.type accepts centripetal(default), chordal and catmullrom
  21499. * curve.tension is used for catmullrom which defaults to 0.5
  21500. */
  21501. /*
  21502. Based on an optimized c++ solution in
  21503. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21504. - http://ideone.com/NoEbVM
  21505. This CubicPoly class could be used for reusing some variables and calculations,
  21506. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21507. which can be placed in CurveUtils.
  21508. */
  21509. function CubicPoly() {
  21510. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  21511. /*
  21512. * Compute coefficients for a cubic polynomial
  21513. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21514. * such that
  21515. * p(0) = x0, p(1) = x1
  21516. * and
  21517. * p'(0) = t0, p'(1) = t1.
  21518. */
  21519. function init( x0, x1, t0, t1 ) {
  21520. c0 = x0;
  21521. c1 = t0;
  21522. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21523. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21524. }
  21525. return {
  21526. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  21527. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21528. },
  21529. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21530. // compute tangents when parameterized in [t1,t2]
  21531. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21532. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21533. // rescale tangents for parametrization in [0,1]
  21534. t1 *= dt1;
  21535. t2 *= dt1;
  21536. init( x1, x2, t1, t2 );
  21537. },
  21538. calc: function ( t ) {
  21539. const t2 = t * t;
  21540. const t3 = t2 * t;
  21541. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21542. }
  21543. };
  21544. }
  21545. //
  21546. const tmp = new Vector3();
  21547. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  21548. class CatmullRomCurve3 extends Curve {
  21549. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  21550. super();
  21551. this.type = 'CatmullRomCurve3';
  21552. this.points = points;
  21553. this.closed = closed;
  21554. this.curveType = curveType;
  21555. this.tension = tension;
  21556. }
  21557. getPoint( t, optionalTarget = new Vector3() ) {
  21558. const point = optionalTarget;
  21559. const points = this.points;
  21560. const l = points.length;
  21561. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21562. let intPoint = Math.floor( p );
  21563. let weight = p - intPoint;
  21564. if ( this.closed ) {
  21565. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  21566. } else if ( weight === 0 && intPoint === l - 1 ) {
  21567. intPoint = l - 2;
  21568. weight = 1;
  21569. }
  21570. let p0, p3; // 4 points (p1 & p2 defined below)
  21571. if ( this.closed || intPoint > 0 ) {
  21572. p0 = points[ ( intPoint - 1 ) % l ];
  21573. } else {
  21574. // extrapolate first point
  21575. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21576. p0 = tmp;
  21577. }
  21578. const p1 = points[ intPoint % l ];
  21579. const p2 = points[ ( intPoint + 1 ) % l ];
  21580. if ( this.closed || intPoint + 2 < l ) {
  21581. p3 = points[ ( intPoint + 2 ) % l ];
  21582. } else {
  21583. // extrapolate last point
  21584. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21585. p3 = tmp;
  21586. }
  21587. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  21588. // init Centripetal / Chordal Catmull-Rom
  21589. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21590. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21591. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21592. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21593. // safety check for repeated points
  21594. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21595. if ( dt0 < 1e-4 ) dt0 = dt1;
  21596. if ( dt2 < 1e-4 ) dt2 = dt1;
  21597. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21598. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21599. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21600. } else if ( this.curveType === 'catmullrom' ) {
  21601. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  21602. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  21603. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  21604. }
  21605. point.set(
  21606. px.calc( weight ),
  21607. py.calc( weight ),
  21608. pz.calc( weight )
  21609. );
  21610. return point;
  21611. }
  21612. copy( source ) {
  21613. super.copy( source );
  21614. this.points = [];
  21615. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21616. const point = source.points[ i ];
  21617. this.points.push( point.clone() );
  21618. }
  21619. this.closed = source.closed;
  21620. this.curveType = source.curveType;
  21621. this.tension = source.tension;
  21622. return this;
  21623. }
  21624. toJSON() {
  21625. const data = super.toJSON();
  21626. data.points = [];
  21627. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21628. const point = this.points[ i ];
  21629. data.points.push( point.toArray() );
  21630. }
  21631. data.closed = this.closed;
  21632. data.curveType = this.curveType;
  21633. data.tension = this.tension;
  21634. return data;
  21635. }
  21636. fromJSON( json ) {
  21637. super.fromJSON( json );
  21638. this.points = [];
  21639. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21640. const point = json.points[ i ];
  21641. this.points.push( new Vector3().fromArray( point ) );
  21642. }
  21643. this.closed = json.closed;
  21644. this.curveType = json.curveType;
  21645. this.tension = json.tension;
  21646. return this;
  21647. }
  21648. }
  21649. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21650. /**
  21651. * Bezier Curves formulas obtained from
  21652. * http://en.wikipedia.org/wiki/Bézier_curve
  21653. */
  21654. function CatmullRom( t, p0, p1, p2, p3 ) {
  21655. const v0 = ( p2 - p0 ) * 0.5;
  21656. const v1 = ( p3 - p1 ) * 0.5;
  21657. const t2 = t * t;
  21658. const t3 = t * t2;
  21659. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21660. }
  21661. //
  21662. function QuadraticBezierP0( t, p ) {
  21663. const k = 1 - t;
  21664. return k * k * p;
  21665. }
  21666. function QuadraticBezierP1( t, p ) {
  21667. return 2 * ( 1 - t ) * t * p;
  21668. }
  21669. function QuadraticBezierP2( t, p ) {
  21670. return t * t * p;
  21671. }
  21672. function QuadraticBezier( t, p0, p1, p2 ) {
  21673. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  21674. QuadraticBezierP2( t, p2 );
  21675. }
  21676. //
  21677. function CubicBezierP0( t, p ) {
  21678. const k = 1 - t;
  21679. return k * k * k * p;
  21680. }
  21681. function CubicBezierP1( t, p ) {
  21682. const k = 1 - t;
  21683. return 3 * k * k * t * p;
  21684. }
  21685. function CubicBezierP2( t, p ) {
  21686. return 3 * ( 1 - t ) * t * t * p;
  21687. }
  21688. function CubicBezierP3( t, p ) {
  21689. return t * t * t * p;
  21690. }
  21691. function CubicBezier( t, p0, p1, p2, p3 ) {
  21692. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21693. CubicBezierP3( t, p3 );
  21694. }
  21695. class CubicBezierCurve extends Curve {
  21696. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21697. super();
  21698. this.type = 'CubicBezierCurve';
  21699. this.v0 = v0;
  21700. this.v1 = v1;
  21701. this.v2 = v2;
  21702. this.v3 = v3;
  21703. }
  21704. getPoint( t, optionalTarget = new Vector2() ) {
  21705. const point = optionalTarget;
  21706. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21707. point.set(
  21708. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21709. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21710. );
  21711. return point;
  21712. }
  21713. copy( source ) {
  21714. super.copy( source );
  21715. this.v0.copy( source.v0 );
  21716. this.v1.copy( source.v1 );
  21717. this.v2.copy( source.v2 );
  21718. this.v3.copy( source.v3 );
  21719. return this;
  21720. }
  21721. toJSON() {
  21722. const data = super.toJSON();
  21723. data.v0 = this.v0.toArray();
  21724. data.v1 = this.v1.toArray();
  21725. data.v2 = this.v2.toArray();
  21726. data.v3 = this.v3.toArray();
  21727. return data;
  21728. }
  21729. fromJSON( json ) {
  21730. super.fromJSON( json );
  21731. this.v0.fromArray( json.v0 );
  21732. this.v1.fromArray( json.v1 );
  21733. this.v2.fromArray( json.v2 );
  21734. this.v3.fromArray( json.v3 );
  21735. return this;
  21736. }
  21737. }
  21738. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21739. class CubicBezierCurve3 extends Curve {
  21740. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21741. super();
  21742. this.type = 'CubicBezierCurve3';
  21743. this.v0 = v0;
  21744. this.v1 = v1;
  21745. this.v2 = v2;
  21746. this.v3 = v3;
  21747. }
  21748. getPoint( t, optionalTarget = new Vector3() ) {
  21749. const point = optionalTarget;
  21750. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21751. point.set(
  21752. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21753. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21754. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21755. );
  21756. return point;
  21757. }
  21758. copy( source ) {
  21759. super.copy( source );
  21760. this.v0.copy( source.v0 );
  21761. this.v1.copy( source.v1 );
  21762. this.v2.copy( source.v2 );
  21763. this.v3.copy( source.v3 );
  21764. return this;
  21765. }
  21766. toJSON() {
  21767. const data = super.toJSON();
  21768. data.v0 = this.v0.toArray();
  21769. data.v1 = this.v1.toArray();
  21770. data.v2 = this.v2.toArray();
  21771. data.v3 = this.v3.toArray();
  21772. return data;
  21773. }
  21774. fromJSON( json ) {
  21775. super.fromJSON( json );
  21776. this.v0.fromArray( json.v0 );
  21777. this.v1.fromArray( json.v1 );
  21778. this.v2.fromArray( json.v2 );
  21779. this.v3.fromArray( json.v3 );
  21780. return this;
  21781. }
  21782. }
  21783. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21784. class LineCurve extends Curve {
  21785. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21786. super();
  21787. this.type = 'LineCurve';
  21788. this.v1 = v1;
  21789. this.v2 = v2;
  21790. }
  21791. getPoint( t, optionalTarget = new Vector2() ) {
  21792. const point = optionalTarget;
  21793. if ( t === 1 ) {
  21794. point.copy( this.v2 );
  21795. } else {
  21796. point.copy( this.v2 ).sub( this.v1 );
  21797. point.multiplyScalar( t ).add( this.v1 );
  21798. }
  21799. return point;
  21800. }
  21801. // Line curve is linear, so we can overwrite default getPointAt
  21802. getPointAt( u, optionalTarget ) {
  21803. return this.getPoint( u, optionalTarget );
  21804. }
  21805. getTangent( t, optionalTarget ) {
  21806. const tangent = optionalTarget || new Vector2();
  21807. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  21808. return tangent;
  21809. }
  21810. copy( source ) {
  21811. super.copy( source );
  21812. this.v1.copy( source.v1 );
  21813. this.v2.copy( source.v2 );
  21814. return this;
  21815. }
  21816. toJSON() {
  21817. const data = super.toJSON();
  21818. data.v1 = this.v1.toArray();
  21819. data.v2 = this.v2.toArray();
  21820. return data;
  21821. }
  21822. fromJSON( json ) {
  21823. super.fromJSON( json );
  21824. this.v1.fromArray( json.v1 );
  21825. this.v2.fromArray( json.v2 );
  21826. return this;
  21827. }
  21828. }
  21829. LineCurve.prototype.isLineCurve = true;
  21830. class LineCurve3 extends Curve {
  21831. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21832. super();
  21833. this.type = 'LineCurve3';
  21834. this.isLineCurve3 = true;
  21835. this.v1 = v1;
  21836. this.v2 = v2;
  21837. }
  21838. getPoint( t, optionalTarget = new Vector3() ) {
  21839. const point = optionalTarget;
  21840. if ( t === 1 ) {
  21841. point.copy( this.v2 );
  21842. } else {
  21843. point.copy( this.v2 ).sub( this.v1 );
  21844. point.multiplyScalar( t ).add( this.v1 );
  21845. }
  21846. return point;
  21847. }
  21848. // Line curve is linear, so we can overwrite default getPointAt
  21849. getPointAt( u, optionalTarget ) {
  21850. return this.getPoint( u, optionalTarget );
  21851. }
  21852. copy( source ) {
  21853. super.copy( source );
  21854. this.v1.copy( source.v1 );
  21855. this.v2.copy( source.v2 );
  21856. return this;
  21857. }
  21858. toJSON() {
  21859. const data = super.toJSON();
  21860. data.v1 = this.v1.toArray();
  21861. data.v2 = this.v2.toArray();
  21862. return data;
  21863. }
  21864. fromJSON( json ) {
  21865. super.fromJSON( json );
  21866. this.v1.fromArray( json.v1 );
  21867. this.v2.fromArray( json.v2 );
  21868. return this;
  21869. }
  21870. }
  21871. class QuadraticBezierCurve extends Curve {
  21872. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21873. super();
  21874. this.type = 'QuadraticBezierCurve';
  21875. this.v0 = v0;
  21876. this.v1 = v1;
  21877. this.v2 = v2;
  21878. }
  21879. getPoint( t, optionalTarget = new Vector2() ) {
  21880. const point = optionalTarget;
  21881. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21882. point.set(
  21883. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21884. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21885. );
  21886. return point;
  21887. }
  21888. copy( source ) {
  21889. super.copy( source );
  21890. this.v0.copy( source.v0 );
  21891. this.v1.copy( source.v1 );
  21892. this.v2.copy( source.v2 );
  21893. return this;
  21894. }
  21895. toJSON() {
  21896. const data = super.toJSON();
  21897. data.v0 = this.v0.toArray();
  21898. data.v1 = this.v1.toArray();
  21899. data.v2 = this.v2.toArray();
  21900. return data;
  21901. }
  21902. fromJSON( json ) {
  21903. super.fromJSON( json );
  21904. this.v0.fromArray( json.v0 );
  21905. this.v1.fromArray( json.v1 );
  21906. this.v2.fromArray( json.v2 );
  21907. return this;
  21908. }
  21909. }
  21910. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21911. class QuadraticBezierCurve3 extends Curve {
  21912. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21913. super();
  21914. this.type = 'QuadraticBezierCurve3';
  21915. this.v0 = v0;
  21916. this.v1 = v1;
  21917. this.v2 = v2;
  21918. }
  21919. getPoint( t, optionalTarget = new Vector3() ) {
  21920. const point = optionalTarget;
  21921. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21922. point.set(
  21923. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21924. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21925. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21926. );
  21927. return point;
  21928. }
  21929. copy( source ) {
  21930. super.copy( source );
  21931. this.v0.copy( source.v0 );
  21932. this.v1.copy( source.v1 );
  21933. this.v2.copy( source.v2 );
  21934. return this;
  21935. }
  21936. toJSON() {
  21937. const data = super.toJSON();
  21938. data.v0 = this.v0.toArray();
  21939. data.v1 = this.v1.toArray();
  21940. data.v2 = this.v2.toArray();
  21941. return data;
  21942. }
  21943. fromJSON( json ) {
  21944. super.fromJSON( json );
  21945. this.v0.fromArray( json.v0 );
  21946. this.v1.fromArray( json.v1 );
  21947. this.v2.fromArray( json.v2 );
  21948. return this;
  21949. }
  21950. }
  21951. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21952. class SplineCurve extends Curve {
  21953. constructor( points = [] ) {
  21954. super();
  21955. this.type = 'SplineCurve';
  21956. this.points = points;
  21957. }
  21958. getPoint( t, optionalTarget = new Vector2() ) {
  21959. const point = optionalTarget;
  21960. const points = this.points;
  21961. const p = ( points.length - 1 ) * t;
  21962. const intPoint = Math.floor( p );
  21963. const weight = p - intPoint;
  21964. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21965. const p1 = points[ intPoint ];
  21966. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21967. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21968. point.set(
  21969. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21970. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21971. );
  21972. return point;
  21973. }
  21974. copy( source ) {
  21975. super.copy( source );
  21976. this.points = [];
  21977. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21978. const point = source.points[ i ];
  21979. this.points.push( point.clone() );
  21980. }
  21981. return this;
  21982. }
  21983. toJSON() {
  21984. const data = super.toJSON();
  21985. data.points = [];
  21986. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21987. const point = this.points[ i ];
  21988. data.points.push( point.toArray() );
  21989. }
  21990. return data;
  21991. }
  21992. fromJSON( json ) {
  21993. super.fromJSON( json );
  21994. this.points = [];
  21995. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21996. const point = json.points[ i ];
  21997. this.points.push( new Vector2().fromArray( point ) );
  21998. }
  21999. return this;
  22000. }
  22001. }
  22002. SplineCurve.prototype.isSplineCurve = true;
  22003. var Curves = /*#__PURE__*/Object.freeze({
  22004. __proto__: null,
  22005. ArcCurve: ArcCurve,
  22006. CatmullRomCurve3: CatmullRomCurve3,
  22007. CubicBezierCurve: CubicBezierCurve,
  22008. CubicBezierCurve3: CubicBezierCurve3,
  22009. EllipseCurve: EllipseCurve,
  22010. LineCurve: LineCurve,
  22011. LineCurve3: LineCurve3,
  22012. QuadraticBezierCurve: QuadraticBezierCurve,
  22013. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22014. SplineCurve: SplineCurve
  22015. });
  22016. /**************************************************************
  22017. * Curved Path - a curve path is simply a array of connected
  22018. * curves, but retains the api of a curve
  22019. **************************************************************/
  22020. class CurvePath extends Curve {
  22021. constructor() {
  22022. super();
  22023. this.type = 'CurvePath';
  22024. this.curves = [];
  22025. this.autoClose = false; // Automatically closes the path
  22026. }
  22027. add( curve ) {
  22028. this.curves.push( curve );
  22029. }
  22030. closePath() {
  22031. // Add a line curve if start and end of lines are not connected
  22032. const startPoint = this.curves[ 0 ].getPoint( 0 );
  22033. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  22034. if ( ! startPoint.equals( endPoint ) ) {
  22035. this.curves.push( new LineCurve( endPoint, startPoint ) );
  22036. }
  22037. }
  22038. // To get accurate point with reference to
  22039. // entire path distance at time t,
  22040. // following has to be done:
  22041. // 1. Length of each sub path have to be known
  22042. // 2. Locate and identify type of curve
  22043. // 3. Get t for the curve
  22044. // 4. Return curve.getPointAt(t')
  22045. getPoint( t ) {
  22046. const d = t * this.getLength();
  22047. const curveLengths = this.getCurveLengths();
  22048. let i = 0;
  22049. // To think about boundaries points.
  22050. while ( i < curveLengths.length ) {
  22051. if ( curveLengths[ i ] >= d ) {
  22052. const diff = curveLengths[ i ] - d;
  22053. const curve = this.curves[ i ];
  22054. const segmentLength = curve.getLength();
  22055. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22056. return curve.getPointAt( u );
  22057. }
  22058. i ++;
  22059. }
  22060. return null;
  22061. // loop where sum != 0, sum > d , sum+1 <d
  22062. }
  22063. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22064. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22065. // getPoint() depends on getLength
  22066. getLength() {
  22067. const lens = this.getCurveLengths();
  22068. return lens[ lens.length - 1 ];
  22069. }
  22070. // cacheLengths must be recalculated.
  22071. updateArcLengths() {
  22072. this.needsUpdate = true;
  22073. this.cacheLengths = null;
  22074. this.getCurveLengths();
  22075. }
  22076. // Compute lengths and cache them
  22077. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22078. getCurveLengths() {
  22079. // We use cache values if curves and cache array are same length
  22080. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  22081. return this.cacheLengths;
  22082. }
  22083. // Get length of sub-curve
  22084. // Push sums into cached array
  22085. const lengths = [];
  22086. let sums = 0;
  22087. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  22088. sums += this.curves[ i ].getLength();
  22089. lengths.push( sums );
  22090. }
  22091. this.cacheLengths = lengths;
  22092. return lengths;
  22093. }
  22094. getSpacedPoints( divisions = 40 ) {
  22095. const points = [];
  22096. for ( let i = 0; i <= divisions; i ++ ) {
  22097. points.push( this.getPoint( i / divisions ) );
  22098. }
  22099. if ( this.autoClose ) {
  22100. points.push( points[ 0 ] );
  22101. }
  22102. return points;
  22103. }
  22104. getPoints( divisions = 12 ) {
  22105. const points = [];
  22106. let last;
  22107. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  22108. const curve = curves[ i ];
  22109. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  22110. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  22111. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  22112. : divisions;
  22113. const pts = curve.getPoints( resolution );
  22114. for ( let j = 0; j < pts.length; j ++ ) {
  22115. const point = pts[ j ];
  22116. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  22117. points.push( point );
  22118. last = point;
  22119. }
  22120. }
  22121. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  22122. points.push( points[ 0 ] );
  22123. }
  22124. return points;
  22125. }
  22126. copy( source ) {
  22127. super.copy( source );
  22128. this.curves = [];
  22129. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  22130. const curve = source.curves[ i ];
  22131. this.curves.push( curve.clone() );
  22132. }
  22133. this.autoClose = source.autoClose;
  22134. return this;
  22135. }
  22136. toJSON() {
  22137. const data = super.toJSON();
  22138. data.autoClose = this.autoClose;
  22139. data.curves = [];
  22140. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  22141. const curve = this.curves[ i ];
  22142. data.curves.push( curve.toJSON() );
  22143. }
  22144. return data;
  22145. }
  22146. fromJSON( json ) {
  22147. super.fromJSON( json );
  22148. this.autoClose = json.autoClose;
  22149. this.curves = [];
  22150. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  22151. const curve = json.curves[ i ];
  22152. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  22153. }
  22154. return this;
  22155. }
  22156. }
  22157. class Path extends CurvePath {
  22158. constructor( points ) {
  22159. super();
  22160. this.type = 'Path';
  22161. this.currentPoint = new Vector2();
  22162. if ( points ) {
  22163. this.setFromPoints( points );
  22164. }
  22165. }
  22166. setFromPoints( points ) {
  22167. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  22168. for ( let i = 1, l = points.length; i < l; i ++ ) {
  22169. this.lineTo( points[ i ].x, points[ i ].y );
  22170. }
  22171. return this;
  22172. }
  22173. moveTo( x, y ) {
  22174. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  22175. return this;
  22176. }
  22177. lineTo( x, y ) {
  22178. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  22179. this.curves.push( curve );
  22180. this.currentPoint.set( x, y );
  22181. return this;
  22182. }
  22183. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  22184. const curve = new QuadraticBezierCurve(
  22185. this.currentPoint.clone(),
  22186. new Vector2( aCPx, aCPy ),
  22187. new Vector2( aX, aY )
  22188. );
  22189. this.curves.push( curve );
  22190. this.currentPoint.set( aX, aY );
  22191. return this;
  22192. }
  22193. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  22194. const curve = new CubicBezierCurve(
  22195. this.currentPoint.clone(),
  22196. new Vector2( aCP1x, aCP1y ),
  22197. new Vector2( aCP2x, aCP2y ),
  22198. new Vector2( aX, aY )
  22199. );
  22200. this.curves.push( curve );
  22201. this.currentPoint.set( aX, aY );
  22202. return this;
  22203. }
  22204. splineThru( pts /*Array of Vector*/ ) {
  22205. const npts = [ this.currentPoint.clone() ].concat( pts );
  22206. const curve = new SplineCurve( npts );
  22207. this.curves.push( curve );
  22208. this.currentPoint.copy( pts[ pts.length - 1 ] );
  22209. return this;
  22210. }
  22211. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22212. const x0 = this.currentPoint.x;
  22213. const y0 = this.currentPoint.y;
  22214. this.absarc( aX + x0, aY + y0, aRadius,
  22215. aStartAngle, aEndAngle, aClockwise );
  22216. return this;
  22217. }
  22218. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22219. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22220. return this;
  22221. }
  22222. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  22223. const x0 = this.currentPoint.x;
  22224. const y0 = this.currentPoint.y;
  22225. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  22226. return this;
  22227. }
  22228. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  22229. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  22230. if ( this.curves.length > 0 ) {
  22231. // if a previous curve is present, attempt to join
  22232. const firstPoint = curve.getPoint( 0 );
  22233. if ( ! firstPoint.equals( this.currentPoint ) ) {
  22234. this.lineTo( firstPoint.x, firstPoint.y );
  22235. }
  22236. }
  22237. this.curves.push( curve );
  22238. const lastPoint = curve.getPoint( 1 );
  22239. this.currentPoint.copy( lastPoint );
  22240. return this;
  22241. }
  22242. copy( source ) {
  22243. super.copy( source );
  22244. this.currentPoint.copy( source.currentPoint );
  22245. return this;
  22246. }
  22247. toJSON() {
  22248. const data = super.toJSON();
  22249. data.currentPoint = this.currentPoint.toArray();
  22250. return data;
  22251. }
  22252. fromJSON( json ) {
  22253. super.fromJSON( json );
  22254. this.currentPoint.fromArray( json.currentPoint );
  22255. return this;
  22256. }
  22257. }
  22258. class Shape extends Path {
  22259. constructor( points ) {
  22260. super( points );
  22261. this.uuid = generateUUID();
  22262. this.type = 'Shape';
  22263. this.holes = [];
  22264. }
  22265. getPointsHoles( divisions ) {
  22266. const holesPts = [];
  22267. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22268. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22269. }
  22270. return holesPts;
  22271. }
  22272. // get points of shape and holes (keypoints based on segments parameter)
  22273. extractPoints( divisions ) {
  22274. return {
  22275. shape: this.getPoints( divisions ),
  22276. holes: this.getPointsHoles( divisions )
  22277. };
  22278. }
  22279. copy( source ) {
  22280. super.copy( source );
  22281. this.holes = [];
  22282. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22283. const hole = source.holes[ i ];
  22284. this.holes.push( hole.clone() );
  22285. }
  22286. return this;
  22287. }
  22288. toJSON() {
  22289. const data = super.toJSON();
  22290. data.uuid = this.uuid;
  22291. data.holes = [];
  22292. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22293. const hole = this.holes[ i ];
  22294. data.holes.push( hole.toJSON() );
  22295. }
  22296. return data;
  22297. }
  22298. fromJSON( json ) {
  22299. super.fromJSON( json );
  22300. this.uuid = json.uuid;
  22301. this.holes = [];
  22302. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22303. const hole = json.holes[ i ];
  22304. this.holes.push( new Path().fromJSON( hole ) );
  22305. }
  22306. return this;
  22307. }
  22308. }
  22309. class Light extends Object3D {
  22310. constructor( color, intensity = 1 ) {
  22311. super();
  22312. this.type = 'Light';
  22313. this.color = new Color( color );
  22314. this.intensity = intensity;
  22315. }
  22316. dispose() {
  22317. // Empty here in base class; some subclasses override.
  22318. }
  22319. copy( source ) {
  22320. super.copy( source );
  22321. this.color.copy( source.color );
  22322. this.intensity = source.intensity;
  22323. return this;
  22324. }
  22325. toJSON( meta ) {
  22326. const data = super.toJSON( meta );
  22327. data.object.color = this.color.getHex();
  22328. data.object.intensity = this.intensity;
  22329. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  22330. if ( this.distance !== undefined ) data.object.distance = this.distance;
  22331. if ( this.angle !== undefined ) data.object.angle = this.angle;
  22332. if ( this.decay !== undefined ) data.object.decay = this.decay;
  22333. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  22334. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  22335. return data;
  22336. }
  22337. }
  22338. Light.prototype.isLight = true;
  22339. class HemisphereLight extends Light {
  22340. constructor( skyColor, groundColor, intensity ) {
  22341. super( skyColor, intensity );
  22342. this.type = 'HemisphereLight';
  22343. this.position.copy( Object3D.DefaultUp );
  22344. this.updateMatrix();
  22345. this.groundColor = new Color( groundColor );
  22346. }
  22347. copy( source ) {
  22348. Light.prototype.copy.call( this, source );
  22349. this.groundColor.copy( source.groundColor );
  22350. return this;
  22351. }
  22352. }
  22353. HemisphereLight.prototype.isHemisphereLight = true;
  22354. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  22355. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  22356. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  22357. class LightShadow {
  22358. constructor( camera ) {
  22359. this.camera = camera;
  22360. this.bias = 0;
  22361. this.normalBias = 0;
  22362. this.radius = 1;
  22363. this.mapSize = new Vector2( 512, 512 );
  22364. this.map = null;
  22365. this.mapPass = null;
  22366. this.matrix = new Matrix4();
  22367. this.autoUpdate = true;
  22368. this.needsUpdate = false;
  22369. this._frustum = new Frustum();
  22370. this._frameExtents = new Vector2( 1, 1 );
  22371. this._viewportCount = 1;
  22372. this._viewports = [
  22373. new Vector4( 0, 0, 1, 1 )
  22374. ];
  22375. }
  22376. getViewportCount() {
  22377. return this._viewportCount;
  22378. }
  22379. getFrustum() {
  22380. return this._frustum;
  22381. }
  22382. updateMatrices( light ) {
  22383. const shadowCamera = this.camera;
  22384. const shadowMatrix = this.matrix;
  22385. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  22386. shadowCamera.position.copy( _lightPositionWorld$1 );
  22387. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  22388. shadowCamera.lookAt( _lookTarget$1 );
  22389. shadowCamera.updateMatrixWorld();
  22390. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  22391. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  22392. shadowMatrix.set(
  22393. 0.5, 0.0, 0.0, 0.5,
  22394. 0.0, 0.5, 0.0, 0.5,
  22395. 0.0, 0.0, 0.5, 0.5,
  22396. 0.0, 0.0, 0.0, 1.0
  22397. );
  22398. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  22399. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  22400. }
  22401. getViewport( viewportIndex ) {
  22402. return this._viewports[ viewportIndex ];
  22403. }
  22404. getFrameExtents() {
  22405. return this._frameExtents;
  22406. }
  22407. dispose() {
  22408. if ( this.map ) {
  22409. this.map.dispose();
  22410. }
  22411. if ( this.mapPass ) {
  22412. this.mapPass.dispose();
  22413. }
  22414. }
  22415. copy( source ) {
  22416. this.camera = source.camera.clone();
  22417. this.bias = source.bias;
  22418. this.radius = source.radius;
  22419. this.mapSize.copy( source.mapSize );
  22420. return this;
  22421. }
  22422. clone() {
  22423. return new this.constructor().copy( this );
  22424. }
  22425. toJSON() {
  22426. const object = {};
  22427. if ( this.bias !== 0 ) object.bias = this.bias;
  22428. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  22429. if ( this.radius !== 1 ) object.radius = this.radius;
  22430. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  22431. object.camera = this.camera.toJSON( false ).object;
  22432. delete object.camera.matrix;
  22433. return object;
  22434. }
  22435. }
  22436. class SpotLightShadow extends LightShadow {
  22437. constructor() {
  22438. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  22439. this.focus = 1;
  22440. }
  22441. updateMatrices( light ) {
  22442. const camera = this.camera;
  22443. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22444. const aspect = this.mapSize.width / this.mapSize.height;
  22445. const far = light.distance || camera.far;
  22446. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  22447. camera.fov = fov;
  22448. camera.aspect = aspect;
  22449. camera.far = far;
  22450. camera.updateProjectionMatrix();
  22451. }
  22452. super.updateMatrices( light );
  22453. }
  22454. copy( source ) {
  22455. super.copy( source );
  22456. this.focus = source.focus;
  22457. return this;
  22458. }
  22459. }
  22460. SpotLightShadow.prototype.isSpotLightShadow = true;
  22461. class SpotLight extends Light {
  22462. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  22463. super( color, intensity );
  22464. this.type = 'SpotLight';
  22465. this.position.copy( Object3D.DefaultUp );
  22466. this.updateMatrix();
  22467. this.target = new Object3D();
  22468. this.distance = distance;
  22469. this.angle = angle;
  22470. this.penumbra = penumbra;
  22471. this.decay = decay; // for physically correct lights, should be 2.
  22472. this.shadow = new SpotLightShadow();
  22473. }
  22474. get power() {
  22475. // intensity = power per solid angle.
  22476. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22477. return this.intensity * Math.PI;
  22478. }
  22479. set power( power ) {
  22480. // intensity = power per solid angle.
  22481. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22482. this.intensity = power / Math.PI;
  22483. }
  22484. dispose() {
  22485. this.shadow.dispose();
  22486. }
  22487. copy( source ) {
  22488. super.copy( source );
  22489. this.distance = source.distance;
  22490. this.angle = source.angle;
  22491. this.penumbra = source.penumbra;
  22492. this.decay = source.decay;
  22493. this.target = source.target.clone();
  22494. this.shadow = source.shadow.clone();
  22495. return this;
  22496. }
  22497. }
  22498. SpotLight.prototype.isSpotLight = true;
  22499. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  22500. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  22501. const _lookTarget = /*@__PURE__*/ new Vector3();
  22502. class PointLightShadow extends LightShadow {
  22503. constructor() {
  22504. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  22505. this._frameExtents = new Vector2( 4, 2 );
  22506. this._viewportCount = 6;
  22507. this._viewports = [
  22508. // These viewports map a cube-map onto a 2D texture with the
  22509. // following orientation:
  22510. //
  22511. // xzXZ
  22512. // y Y
  22513. //
  22514. // X - Positive x direction
  22515. // x - Negative x direction
  22516. // Y - Positive y direction
  22517. // y - Negative y direction
  22518. // Z - Positive z direction
  22519. // z - Negative z direction
  22520. // positive X
  22521. new Vector4( 2, 1, 1, 1 ),
  22522. // negative X
  22523. new Vector4( 0, 1, 1, 1 ),
  22524. // positive Z
  22525. new Vector4( 3, 1, 1, 1 ),
  22526. // negative Z
  22527. new Vector4( 1, 1, 1, 1 ),
  22528. // positive Y
  22529. new Vector4( 3, 0, 1, 1 ),
  22530. // negative Y
  22531. new Vector4( 1, 0, 1, 1 )
  22532. ];
  22533. this._cubeDirections = [
  22534. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  22535. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  22536. ];
  22537. this._cubeUps = [
  22538. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  22539. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  22540. ];
  22541. }
  22542. updateMatrices( light, viewportIndex = 0 ) {
  22543. const camera = this.camera;
  22544. const shadowMatrix = this.matrix;
  22545. const far = light.distance || camera.far;
  22546. if ( far !== camera.far ) {
  22547. camera.far = far;
  22548. camera.updateProjectionMatrix();
  22549. }
  22550. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  22551. camera.position.copy( _lightPositionWorld );
  22552. _lookTarget.copy( camera.position );
  22553. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  22554. camera.up.copy( this._cubeUps[ viewportIndex ] );
  22555. camera.lookAt( _lookTarget );
  22556. camera.updateMatrixWorld();
  22557. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  22558. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22559. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  22560. }
  22561. }
  22562. PointLightShadow.prototype.isPointLightShadow = true;
  22563. class PointLight extends Light {
  22564. constructor( color, intensity, distance = 0, decay = 1 ) {
  22565. super( color, intensity );
  22566. this.type = 'PointLight';
  22567. this.distance = distance;
  22568. this.decay = decay; // for physically correct lights, should be 2.
  22569. this.shadow = new PointLightShadow();
  22570. }
  22571. get power() {
  22572. // intensity = power per solid angle.
  22573. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22574. return this.intensity * 4 * Math.PI;
  22575. }
  22576. set power( power ) {
  22577. // intensity = power per solid angle.
  22578. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22579. this.intensity = power / ( 4 * Math.PI );
  22580. }
  22581. dispose() {
  22582. this.shadow.dispose();
  22583. }
  22584. copy( source ) {
  22585. super.copy( source );
  22586. this.distance = source.distance;
  22587. this.decay = source.decay;
  22588. this.shadow = source.shadow.clone();
  22589. return this;
  22590. }
  22591. }
  22592. PointLight.prototype.isPointLight = true;
  22593. class OrthographicCamera extends Camera {
  22594. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  22595. super();
  22596. this.type = 'OrthographicCamera';
  22597. this.zoom = 1;
  22598. this.view = null;
  22599. this.left = left;
  22600. this.right = right;
  22601. this.top = top;
  22602. this.bottom = bottom;
  22603. this.near = near;
  22604. this.far = far;
  22605. this.updateProjectionMatrix();
  22606. }
  22607. copy( source, recursive ) {
  22608. super.copy( source, recursive );
  22609. this.left = source.left;
  22610. this.right = source.right;
  22611. this.top = source.top;
  22612. this.bottom = source.bottom;
  22613. this.near = source.near;
  22614. this.far = source.far;
  22615. this.zoom = source.zoom;
  22616. this.view = source.view === null ? null : Object.assign( {}, source.view );
  22617. return this;
  22618. }
  22619. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  22620. if ( this.view === null ) {
  22621. this.view = {
  22622. enabled: true,
  22623. fullWidth: 1,
  22624. fullHeight: 1,
  22625. offsetX: 0,
  22626. offsetY: 0,
  22627. width: 1,
  22628. height: 1
  22629. };
  22630. }
  22631. this.view.enabled = true;
  22632. this.view.fullWidth = fullWidth;
  22633. this.view.fullHeight = fullHeight;
  22634. this.view.offsetX = x;
  22635. this.view.offsetY = y;
  22636. this.view.width = width;
  22637. this.view.height = height;
  22638. this.updateProjectionMatrix();
  22639. }
  22640. clearViewOffset() {
  22641. if ( this.view !== null ) {
  22642. this.view.enabled = false;
  22643. }
  22644. this.updateProjectionMatrix();
  22645. }
  22646. updateProjectionMatrix() {
  22647. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  22648. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  22649. const cx = ( this.right + this.left ) / 2;
  22650. const cy = ( this.top + this.bottom ) / 2;
  22651. let left = cx - dx;
  22652. let right = cx + dx;
  22653. let top = cy + dy;
  22654. let bottom = cy - dy;
  22655. if ( this.view !== null && this.view.enabled ) {
  22656. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  22657. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  22658. left += scaleW * this.view.offsetX;
  22659. right = left + scaleW * this.view.width;
  22660. top -= scaleH * this.view.offsetY;
  22661. bottom = top - scaleH * this.view.height;
  22662. }
  22663. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  22664. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  22665. }
  22666. toJSON( meta ) {
  22667. const data = super.toJSON( meta );
  22668. data.object.zoom = this.zoom;
  22669. data.object.left = this.left;
  22670. data.object.right = this.right;
  22671. data.object.top = this.top;
  22672. data.object.bottom = this.bottom;
  22673. data.object.near = this.near;
  22674. data.object.far = this.far;
  22675. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  22676. return data;
  22677. }
  22678. }
  22679. OrthographicCamera.prototype.isOrthographicCamera = true;
  22680. class DirectionalLightShadow extends LightShadow {
  22681. constructor() {
  22682. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  22683. }
  22684. }
  22685. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22686. class DirectionalLight extends Light {
  22687. constructor( color, intensity ) {
  22688. super( color, intensity );
  22689. this.type = 'DirectionalLight';
  22690. this.position.copy( Object3D.DefaultUp );
  22691. this.updateMatrix();
  22692. this.target = new Object3D();
  22693. this.shadow = new DirectionalLightShadow();
  22694. }
  22695. dispose() {
  22696. this.shadow.dispose();
  22697. }
  22698. copy( source ) {
  22699. super.copy( source );
  22700. this.target = source.target.clone();
  22701. this.shadow = source.shadow.clone();
  22702. return this;
  22703. }
  22704. }
  22705. DirectionalLight.prototype.isDirectionalLight = true;
  22706. class AmbientLight extends Light {
  22707. constructor( color, intensity ) {
  22708. super( color, intensity );
  22709. this.type = 'AmbientLight';
  22710. }
  22711. }
  22712. AmbientLight.prototype.isAmbientLight = true;
  22713. class RectAreaLight extends Light {
  22714. constructor( color, intensity, width = 10, height = 10 ) {
  22715. super( color, intensity );
  22716. this.type = 'RectAreaLight';
  22717. this.width = width;
  22718. this.height = height;
  22719. }
  22720. copy( source ) {
  22721. super.copy( source );
  22722. this.width = source.width;
  22723. this.height = source.height;
  22724. return this;
  22725. }
  22726. toJSON( meta ) {
  22727. const data = super.toJSON( meta );
  22728. data.object.width = this.width;
  22729. data.object.height = this.height;
  22730. return data;
  22731. }
  22732. }
  22733. RectAreaLight.prototype.isRectAreaLight = true;
  22734. /**
  22735. * Primary reference:
  22736. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22737. *
  22738. * Secondary reference:
  22739. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22740. */
  22741. // 3-band SH defined by 9 coefficients
  22742. class SphericalHarmonics3 {
  22743. constructor() {
  22744. this.coefficients = [];
  22745. for ( let i = 0; i < 9; i ++ ) {
  22746. this.coefficients.push( new Vector3() );
  22747. }
  22748. }
  22749. set( coefficients ) {
  22750. for ( let i = 0; i < 9; i ++ ) {
  22751. this.coefficients[ i ].copy( coefficients[ i ] );
  22752. }
  22753. return this;
  22754. }
  22755. zero() {
  22756. for ( let i = 0; i < 9; i ++ ) {
  22757. this.coefficients[ i ].set( 0, 0, 0 );
  22758. }
  22759. return this;
  22760. }
  22761. // get the radiance in the direction of the normal
  22762. // target is a Vector3
  22763. getAt( normal, target ) {
  22764. // normal is assumed to be unit length
  22765. const x = normal.x, y = normal.y, z = normal.z;
  22766. const coeff = this.coefficients;
  22767. // band 0
  22768. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  22769. // band 1
  22770. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  22771. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  22772. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  22773. // band 2
  22774. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  22775. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  22776. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  22777. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  22778. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  22779. return target;
  22780. }
  22781. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22782. // target is a Vector3
  22783. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22784. getIrradianceAt( normal, target ) {
  22785. // normal is assumed to be unit length
  22786. const x = normal.x, y = normal.y, z = normal.z;
  22787. const coeff = this.coefficients;
  22788. // band 0
  22789. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  22790. // band 1
  22791. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  22792. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  22793. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  22794. // band 2
  22795. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  22796. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  22797. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  22798. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  22799. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  22800. return target;
  22801. }
  22802. add( sh ) {
  22803. for ( let i = 0; i < 9; i ++ ) {
  22804. this.coefficients[ i ].add( sh.coefficients[ i ] );
  22805. }
  22806. return this;
  22807. }
  22808. addScaledSH( sh, s ) {
  22809. for ( let i = 0; i < 9; i ++ ) {
  22810. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  22811. }
  22812. return this;
  22813. }
  22814. scale( s ) {
  22815. for ( let i = 0; i < 9; i ++ ) {
  22816. this.coefficients[ i ].multiplyScalar( s );
  22817. }
  22818. return this;
  22819. }
  22820. lerp( sh, alpha ) {
  22821. for ( let i = 0; i < 9; i ++ ) {
  22822. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  22823. }
  22824. return this;
  22825. }
  22826. equals( sh ) {
  22827. for ( let i = 0; i < 9; i ++ ) {
  22828. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  22829. return false;
  22830. }
  22831. }
  22832. return true;
  22833. }
  22834. copy( sh ) {
  22835. return this.set( sh.coefficients );
  22836. }
  22837. clone() {
  22838. return new this.constructor().copy( this );
  22839. }
  22840. fromArray( array, offset = 0 ) {
  22841. const coefficients = this.coefficients;
  22842. for ( let i = 0; i < 9; i ++ ) {
  22843. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  22844. }
  22845. return this;
  22846. }
  22847. toArray( array = [], offset = 0 ) {
  22848. const coefficients = this.coefficients;
  22849. for ( let i = 0; i < 9; i ++ ) {
  22850. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  22851. }
  22852. return array;
  22853. }
  22854. // evaluate the basis functions
  22855. // shBasis is an Array[ 9 ]
  22856. static getBasisAt( normal, shBasis ) {
  22857. // normal is assumed to be unit length
  22858. const x = normal.x, y = normal.y, z = normal.z;
  22859. // band 0
  22860. shBasis[ 0 ] = 0.282095;
  22861. // band 1
  22862. shBasis[ 1 ] = 0.488603 * y;
  22863. shBasis[ 2 ] = 0.488603 * z;
  22864. shBasis[ 3 ] = 0.488603 * x;
  22865. // band 2
  22866. shBasis[ 4 ] = 1.092548 * x * y;
  22867. shBasis[ 5 ] = 1.092548 * y * z;
  22868. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  22869. shBasis[ 7 ] = 1.092548 * x * z;
  22870. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  22871. }
  22872. }
  22873. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22874. class LightProbe extends Light {
  22875. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  22876. super( undefined, intensity );
  22877. this.sh = sh;
  22878. }
  22879. copy( source ) {
  22880. super.copy( source );
  22881. this.sh.copy( source.sh );
  22882. return this;
  22883. }
  22884. fromJSON( json ) {
  22885. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22886. this.sh.fromArray( json.sh );
  22887. return this;
  22888. }
  22889. toJSON( meta ) {
  22890. const data = super.toJSON( meta );
  22891. data.object.sh = this.sh.toArray();
  22892. return data;
  22893. }
  22894. }
  22895. LightProbe.prototype.isLightProbe = true;
  22896. class MaterialLoader extends Loader {
  22897. constructor( manager ) {
  22898. super( manager );
  22899. this.textures = {};
  22900. }
  22901. load( url, onLoad, onProgress, onError ) {
  22902. const scope = this;
  22903. const loader = new FileLoader( scope.manager );
  22904. loader.setPath( scope.path );
  22905. loader.setRequestHeader( scope.requestHeader );
  22906. loader.setWithCredentials( scope.withCredentials );
  22907. loader.load( url, function ( text ) {
  22908. try {
  22909. onLoad( scope.parse( JSON.parse( text ) ) );
  22910. } catch ( e ) {
  22911. if ( onError ) {
  22912. onError( e );
  22913. } else {
  22914. console.error( e );
  22915. }
  22916. scope.manager.itemError( url );
  22917. }
  22918. }, onProgress, onError );
  22919. }
  22920. parse( json ) {
  22921. const textures = this.textures;
  22922. function getTexture( name ) {
  22923. if ( textures[ name ] === undefined ) {
  22924. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  22925. }
  22926. return textures[ name ];
  22927. }
  22928. const material = new Materials[ json.type ]();
  22929. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  22930. if ( json.name !== undefined ) material.name = json.name;
  22931. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  22932. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  22933. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  22934. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  22935. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  22936. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  22937. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  22938. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  22939. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  22940. if ( json.fog !== undefined ) material.fog = json.fog;
  22941. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  22942. if ( json.blending !== undefined ) material.blending = json.blending;
  22943. if ( json.combine !== undefined ) material.combine = json.combine;
  22944. if ( json.side !== undefined ) material.side = json.side;
  22945. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  22946. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  22947. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  22948. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  22949. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  22950. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  22951. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  22952. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  22953. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  22954. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  22955. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  22956. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  22957. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  22958. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  22959. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  22960. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  22961. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  22962. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  22963. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  22964. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  22965. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  22966. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  22967. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  22968. if ( json.scale !== undefined ) material.scale = json.scale;
  22969. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  22970. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22971. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22972. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  22973. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  22974. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  22975. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  22976. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  22977. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  22978. if ( json.visible !== undefined ) material.visible = json.visible;
  22979. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  22980. if ( json.userData !== undefined ) material.userData = json.userData;
  22981. if ( json.vertexColors !== undefined ) {
  22982. if ( typeof json.vertexColors === 'number' ) {
  22983. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  22984. } else {
  22985. material.vertexColors = json.vertexColors;
  22986. }
  22987. }
  22988. // Shader Material
  22989. if ( json.uniforms !== undefined ) {
  22990. for ( const name in json.uniforms ) {
  22991. const uniform = json.uniforms[ name ];
  22992. material.uniforms[ name ] = {};
  22993. switch ( uniform.type ) {
  22994. case 't':
  22995. material.uniforms[ name ].value = getTexture( uniform.value );
  22996. break;
  22997. case 'c':
  22998. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  22999. break;
  23000. case 'v2':
  23001. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  23002. break;
  23003. case 'v3':
  23004. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  23005. break;
  23006. case 'v4':
  23007. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  23008. break;
  23009. case 'm3':
  23010. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  23011. break;
  23012. case 'm4':
  23013. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  23014. break;
  23015. default:
  23016. material.uniforms[ name ].value = uniform.value;
  23017. }
  23018. }
  23019. }
  23020. if ( json.defines !== undefined ) material.defines = json.defines;
  23021. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  23022. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  23023. if ( json.extensions !== undefined ) {
  23024. for ( const key in json.extensions ) {
  23025. material.extensions[ key ] = json.extensions[ key ];
  23026. }
  23027. }
  23028. // Deprecated
  23029. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  23030. // for PointsMaterial
  23031. if ( json.size !== undefined ) material.size = json.size;
  23032. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  23033. // maps
  23034. if ( json.map !== undefined ) material.map = getTexture( json.map );
  23035. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  23036. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  23037. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  23038. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  23039. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  23040. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  23041. if ( json.normalScale !== undefined ) {
  23042. let normalScale = json.normalScale;
  23043. if ( Array.isArray( normalScale ) === false ) {
  23044. // Blender exporter used to export a scalar. See #7459
  23045. normalScale = [ normalScale, normalScale ];
  23046. }
  23047. material.normalScale = new Vector2().fromArray( normalScale );
  23048. }
  23049. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  23050. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  23051. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  23052. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  23053. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  23054. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  23055. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  23056. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  23057. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  23058. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  23059. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  23060. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  23061. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  23062. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  23063. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  23064. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  23065. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  23066. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  23067. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  23068. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  23069. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  23070. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  23071. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  23072. return material;
  23073. }
  23074. setTextures( value ) {
  23075. this.textures = value;
  23076. return this;
  23077. }
  23078. }
  23079. class LoaderUtils {
  23080. static decodeText( array ) {
  23081. if ( typeof TextDecoder !== 'undefined' ) {
  23082. return new TextDecoder().decode( array );
  23083. }
  23084. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23085. // throws a "maximum call stack size exceeded" error for large arrays.
  23086. let s = '';
  23087. for ( let i = 0, il = array.length; i < il; i ++ ) {
  23088. // Implicitly assumes little-endian.
  23089. s += String.fromCharCode( array[ i ] );
  23090. }
  23091. try {
  23092. // merges multi-byte utf-8 characters.
  23093. return decodeURIComponent( escape( s ) );
  23094. } catch ( e ) { // see #16358
  23095. return s;
  23096. }
  23097. }
  23098. static extractUrlBase( url ) {
  23099. const index = url.lastIndexOf( '/' );
  23100. if ( index === - 1 ) return './';
  23101. return url.substr( 0, index + 1 );
  23102. }
  23103. }
  23104. class InstancedBufferGeometry extends BufferGeometry {
  23105. constructor() {
  23106. super();
  23107. this.type = 'InstancedBufferGeometry';
  23108. this.instanceCount = Infinity;
  23109. }
  23110. copy( source ) {
  23111. super.copy( source );
  23112. this.instanceCount = source.instanceCount;
  23113. return this;
  23114. }
  23115. clone() {
  23116. return new this.constructor().copy( this );
  23117. }
  23118. toJSON() {
  23119. const data = super.toJSON( this );
  23120. data.instanceCount = this.instanceCount;
  23121. data.isInstancedBufferGeometry = true;
  23122. return data;
  23123. }
  23124. }
  23125. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23126. class InstancedBufferAttribute extends BufferAttribute {
  23127. constructor( array, itemSize, normalized, meshPerAttribute ) {
  23128. if ( typeof ( normalized ) === 'number' ) {
  23129. meshPerAttribute = normalized;
  23130. normalized = false;
  23131. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  23132. }
  23133. super( array, itemSize, normalized );
  23134. this.meshPerAttribute = meshPerAttribute || 1;
  23135. }
  23136. copy( source ) {
  23137. super.copy( source );
  23138. this.meshPerAttribute = source.meshPerAttribute;
  23139. return this;
  23140. }
  23141. toJSON() {
  23142. const data = super.toJSON();
  23143. data.meshPerAttribute = this.meshPerAttribute;
  23144. data.isInstancedBufferAttribute = true;
  23145. return data;
  23146. }
  23147. }
  23148. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23149. class BufferGeometryLoader extends Loader {
  23150. constructor( manager ) {
  23151. super( manager );
  23152. }
  23153. load( url, onLoad, onProgress, onError ) {
  23154. const scope = this;
  23155. const loader = new FileLoader( scope.manager );
  23156. loader.setPath( scope.path );
  23157. loader.setRequestHeader( scope.requestHeader );
  23158. loader.setWithCredentials( scope.withCredentials );
  23159. loader.load( url, function ( text ) {
  23160. try {
  23161. onLoad( scope.parse( JSON.parse( text ) ) );
  23162. } catch ( e ) {
  23163. if ( onError ) {
  23164. onError( e );
  23165. } else {
  23166. console.error( e );
  23167. }
  23168. scope.manager.itemError( url );
  23169. }
  23170. }, onProgress, onError );
  23171. }
  23172. parse( json ) {
  23173. const interleavedBufferMap = {};
  23174. const arrayBufferMap = {};
  23175. function getInterleavedBuffer( json, uuid ) {
  23176. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  23177. const interleavedBuffers = json.interleavedBuffers;
  23178. const interleavedBuffer = interleavedBuffers[ uuid ];
  23179. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  23180. const array = getTypedArray( interleavedBuffer.type, buffer );
  23181. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  23182. ib.uuid = interleavedBuffer.uuid;
  23183. interleavedBufferMap[ uuid ] = ib;
  23184. return ib;
  23185. }
  23186. function getArrayBuffer( json, uuid ) {
  23187. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  23188. const arrayBuffers = json.arrayBuffers;
  23189. const arrayBuffer = arrayBuffers[ uuid ];
  23190. const ab = new Uint32Array( arrayBuffer ).buffer;
  23191. arrayBufferMap[ uuid ] = ab;
  23192. return ab;
  23193. }
  23194. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23195. const index = json.data.index;
  23196. if ( index !== undefined ) {
  23197. const typedArray = getTypedArray( index.type, index.array );
  23198. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  23199. }
  23200. const attributes = json.data.attributes;
  23201. for ( const key in attributes ) {
  23202. const attribute = attributes[ key ];
  23203. let bufferAttribute;
  23204. if ( attribute.isInterleavedBufferAttribute ) {
  23205. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  23206. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  23207. } else {
  23208. const typedArray = getTypedArray( attribute.type, attribute.array );
  23209. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23210. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  23211. }
  23212. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  23213. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  23214. if ( attribute.updateRange !== undefined ) {
  23215. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  23216. bufferAttribute.updateRange.count = attribute.updateRange.count;
  23217. }
  23218. geometry.setAttribute( key, bufferAttribute );
  23219. }
  23220. const morphAttributes = json.data.morphAttributes;
  23221. if ( morphAttributes ) {
  23222. for ( const key in morphAttributes ) {
  23223. const attributeArray = morphAttributes[ key ];
  23224. const array = [];
  23225. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  23226. const attribute = attributeArray[ i ];
  23227. let bufferAttribute;
  23228. if ( attribute.isInterleavedBufferAttribute ) {
  23229. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  23230. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  23231. } else {
  23232. const typedArray = getTypedArray( attribute.type, attribute.array );
  23233. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  23234. }
  23235. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  23236. array.push( bufferAttribute );
  23237. }
  23238. geometry.morphAttributes[ key ] = array;
  23239. }
  23240. }
  23241. const morphTargetsRelative = json.data.morphTargetsRelative;
  23242. if ( morphTargetsRelative ) {
  23243. geometry.morphTargetsRelative = true;
  23244. }
  23245. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23246. if ( groups !== undefined ) {
  23247. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  23248. const group = groups[ i ];
  23249. geometry.addGroup( group.start, group.count, group.materialIndex );
  23250. }
  23251. }
  23252. const boundingSphere = json.data.boundingSphere;
  23253. if ( boundingSphere !== undefined ) {
  23254. const center = new Vector3();
  23255. if ( boundingSphere.center !== undefined ) {
  23256. center.fromArray( boundingSphere.center );
  23257. }
  23258. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  23259. }
  23260. if ( json.name ) geometry.name = json.name;
  23261. if ( json.userData ) geometry.userData = json.userData;
  23262. return geometry;
  23263. }
  23264. }
  23265. class ObjectLoader extends Loader {
  23266. constructor( manager ) {
  23267. super( manager );
  23268. }
  23269. load( url, onLoad, onProgress, onError ) {
  23270. const scope = this;
  23271. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  23272. this.resourcePath = this.resourcePath || path;
  23273. const loader = new FileLoader( this.manager );
  23274. loader.setPath( this.path );
  23275. loader.setRequestHeader( this.requestHeader );
  23276. loader.setWithCredentials( this.withCredentials );
  23277. loader.load( url, function ( text ) {
  23278. let json = null;
  23279. try {
  23280. json = JSON.parse( text );
  23281. } catch ( error ) {
  23282. if ( onError !== undefined ) onError( error );
  23283. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  23284. return;
  23285. }
  23286. const metadata = json.metadata;
  23287. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  23288. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  23289. return;
  23290. }
  23291. scope.parse( json, onLoad );
  23292. }, onProgress, onError );
  23293. }
  23294. parse( json, onLoad ) {
  23295. const animations = this.parseAnimations( json.animations );
  23296. const shapes = this.parseShapes( json.shapes );
  23297. const geometries = this.parseGeometries( json.geometries, shapes );
  23298. const images = this.parseImages( json.images, function () {
  23299. if ( onLoad !== undefined ) onLoad( object );
  23300. } );
  23301. const textures = this.parseTextures( json.textures, images );
  23302. const materials = this.parseMaterials( json.materials, textures );
  23303. const object = this.parseObject( json.object, geometries, materials, animations );
  23304. const skeletons = this.parseSkeletons( json.skeletons, object );
  23305. this.bindSkeletons( object, skeletons );
  23306. //
  23307. if ( onLoad !== undefined ) {
  23308. let hasImages = false;
  23309. for ( const uuid in images ) {
  23310. if ( images[ uuid ] instanceof HTMLImageElement ) {
  23311. hasImages = true;
  23312. break;
  23313. }
  23314. }
  23315. if ( hasImages === false ) onLoad( object );
  23316. }
  23317. return object;
  23318. }
  23319. parseShapes( json ) {
  23320. const shapes = {};
  23321. if ( json !== undefined ) {
  23322. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23323. const shape = new Shape().fromJSON( json[ i ] );
  23324. shapes[ shape.uuid ] = shape;
  23325. }
  23326. }
  23327. return shapes;
  23328. }
  23329. parseSkeletons( json, object ) {
  23330. const skeletons = {};
  23331. const bones = {};
  23332. // generate bone lookup table
  23333. object.traverse( function ( child ) {
  23334. if ( child.isBone ) bones[ child.uuid ] = child;
  23335. } );
  23336. // create skeletons
  23337. if ( json !== undefined ) {
  23338. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23339. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  23340. skeletons[ skeleton.uuid ] = skeleton;
  23341. }
  23342. }
  23343. return skeletons;
  23344. }
  23345. parseGeometries( json, shapes ) {
  23346. const geometries = {};
  23347. let geometryShapes;
  23348. if ( json !== undefined ) {
  23349. const bufferGeometryLoader = new BufferGeometryLoader();
  23350. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23351. let geometry;
  23352. const data = json[ i ];
  23353. switch ( data.type ) {
  23354. case 'PlaneGeometry':
  23355. case 'PlaneBufferGeometry':
  23356. geometry = new Geometries[ data.type ](
  23357. data.width,
  23358. data.height,
  23359. data.widthSegments,
  23360. data.heightSegments
  23361. );
  23362. break;
  23363. case 'BoxGeometry':
  23364. case 'BoxBufferGeometry':
  23365. geometry = new Geometries[ data.type ](
  23366. data.width,
  23367. data.height,
  23368. data.depth,
  23369. data.widthSegments,
  23370. data.heightSegments,
  23371. data.depthSegments
  23372. );
  23373. break;
  23374. case 'CircleGeometry':
  23375. case 'CircleBufferGeometry':
  23376. geometry = new Geometries[ data.type ](
  23377. data.radius,
  23378. data.segments,
  23379. data.thetaStart,
  23380. data.thetaLength
  23381. );
  23382. break;
  23383. case 'CylinderGeometry':
  23384. case 'CylinderBufferGeometry':
  23385. geometry = new Geometries[ data.type ](
  23386. data.radiusTop,
  23387. data.radiusBottom,
  23388. data.height,
  23389. data.radialSegments,
  23390. data.heightSegments,
  23391. data.openEnded,
  23392. data.thetaStart,
  23393. data.thetaLength
  23394. );
  23395. break;
  23396. case 'ConeGeometry':
  23397. case 'ConeBufferGeometry':
  23398. geometry = new Geometries[ data.type ](
  23399. data.radius,
  23400. data.height,
  23401. data.radialSegments,
  23402. data.heightSegments,
  23403. data.openEnded,
  23404. data.thetaStart,
  23405. data.thetaLength
  23406. );
  23407. break;
  23408. case 'SphereGeometry':
  23409. case 'SphereBufferGeometry':
  23410. geometry = new Geometries[ data.type ](
  23411. data.radius,
  23412. data.widthSegments,
  23413. data.heightSegments,
  23414. data.phiStart,
  23415. data.phiLength,
  23416. data.thetaStart,
  23417. data.thetaLength
  23418. );
  23419. break;
  23420. case 'DodecahedronGeometry':
  23421. case 'DodecahedronBufferGeometry':
  23422. case 'IcosahedronGeometry':
  23423. case 'IcosahedronBufferGeometry':
  23424. case 'OctahedronGeometry':
  23425. case 'OctahedronBufferGeometry':
  23426. case 'TetrahedronGeometry':
  23427. case 'TetrahedronBufferGeometry':
  23428. geometry = new Geometries[ data.type ](
  23429. data.radius,
  23430. data.detail
  23431. );
  23432. break;
  23433. case 'RingGeometry':
  23434. case 'RingBufferGeometry':
  23435. geometry = new Geometries[ data.type ](
  23436. data.innerRadius,
  23437. data.outerRadius,
  23438. data.thetaSegments,
  23439. data.phiSegments,
  23440. data.thetaStart,
  23441. data.thetaLength
  23442. );
  23443. break;
  23444. case 'TorusGeometry':
  23445. case 'TorusBufferGeometry':
  23446. geometry = new Geometries[ data.type ](
  23447. data.radius,
  23448. data.tube,
  23449. data.radialSegments,
  23450. data.tubularSegments,
  23451. data.arc
  23452. );
  23453. break;
  23454. case 'TorusKnotGeometry':
  23455. case 'TorusKnotBufferGeometry':
  23456. geometry = new Geometries[ data.type ](
  23457. data.radius,
  23458. data.tube,
  23459. data.tubularSegments,
  23460. data.radialSegments,
  23461. data.p,
  23462. data.q
  23463. );
  23464. break;
  23465. case 'TubeGeometry':
  23466. case 'TubeBufferGeometry':
  23467. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23468. // User defined curves or instances of CurvePath will not be deserialized.
  23469. geometry = new Geometries[ data.type ](
  23470. new Curves[ data.path.type ]().fromJSON( data.path ),
  23471. data.tubularSegments,
  23472. data.radius,
  23473. data.radialSegments,
  23474. data.closed
  23475. );
  23476. break;
  23477. case 'LatheGeometry':
  23478. case 'LatheBufferGeometry':
  23479. geometry = new Geometries[ data.type ](
  23480. data.points,
  23481. data.segments,
  23482. data.phiStart,
  23483. data.phiLength
  23484. );
  23485. break;
  23486. case 'PolyhedronGeometry':
  23487. case 'PolyhedronBufferGeometry':
  23488. geometry = new Geometries[ data.type ](
  23489. data.vertices,
  23490. data.indices,
  23491. data.radius,
  23492. data.details
  23493. );
  23494. break;
  23495. case 'ShapeGeometry':
  23496. case 'ShapeBufferGeometry':
  23497. geometryShapes = [];
  23498. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23499. const shape = shapes[ data.shapes[ j ] ];
  23500. geometryShapes.push( shape );
  23501. }
  23502. geometry = new Geometries[ data.type ](
  23503. geometryShapes,
  23504. data.curveSegments
  23505. );
  23506. break;
  23507. case 'ExtrudeGeometry':
  23508. case 'ExtrudeBufferGeometry':
  23509. geometryShapes = [];
  23510. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23511. const shape = shapes[ data.shapes[ j ] ];
  23512. geometryShapes.push( shape );
  23513. }
  23514. const extrudePath = data.options.extrudePath;
  23515. if ( extrudePath !== undefined ) {
  23516. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23517. }
  23518. geometry = new Geometries[ data.type ](
  23519. geometryShapes,
  23520. data.options
  23521. );
  23522. break;
  23523. case 'BufferGeometry':
  23524. case 'InstancedBufferGeometry':
  23525. geometry = bufferGeometryLoader.parse( data );
  23526. break;
  23527. case 'Geometry':
  23528. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  23529. break;
  23530. default:
  23531. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  23532. continue;
  23533. }
  23534. geometry.uuid = data.uuid;
  23535. if ( data.name !== undefined ) geometry.name = data.name;
  23536. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  23537. geometries[ data.uuid ] = geometry;
  23538. }
  23539. }
  23540. return geometries;
  23541. }
  23542. parseMaterials( json, textures ) {
  23543. const cache = {}; // MultiMaterial
  23544. const materials = {};
  23545. if ( json !== undefined ) {
  23546. const loader = new MaterialLoader();
  23547. loader.setTextures( textures );
  23548. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23549. const data = json[ i ];
  23550. if ( data.type === 'MultiMaterial' ) {
  23551. // Deprecated
  23552. const array = [];
  23553. for ( let j = 0; j < data.materials.length; j ++ ) {
  23554. const material = data.materials[ j ];
  23555. if ( cache[ material.uuid ] === undefined ) {
  23556. cache[ material.uuid ] = loader.parse( material );
  23557. }
  23558. array.push( cache[ material.uuid ] );
  23559. }
  23560. materials[ data.uuid ] = array;
  23561. } else {
  23562. if ( cache[ data.uuid ] === undefined ) {
  23563. cache[ data.uuid ] = loader.parse( data );
  23564. }
  23565. materials[ data.uuid ] = cache[ data.uuid ];
  23566. }
  23567. }
  23568. }
  23569. return materials;
  23570. }
  23571. parseAnimations( json ) {
  23572. const animations = {};
  23573. if ( json !== undefined ) {
  23574. for ( let i = 0; i < json.length; i ++ ) {
  23575. const data = json[ i ];
  23576. const clip = AnimationClip.parse( data );
  23577. animations[ clip.uuid ] = clip;
  23578. }
  23579. }
  23580. return animations;
  23581. }
  23582. parseImages( json, onLoad ) {
  23583. const scope = this;
  23584. const images = {};
  23585. let loader;
  23586. function loadImage( url ) {
  23587. scope.manager.itemStart( url );
  23588. return loader.load( url, function () {
  23589. scope.manager.itemEnd( url );
  23590. }, undefined, function () {
  23591. scope.manager.itemError( url );
  23592. scope.manager.itemEnd( url );
  23593. } );
  23594. }
  23595. function deserializeImage( image ) {
  23596. if ( typeof image === 'string' ) {
  23597. const url = image;
  23598. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  23599. return loadImage( path );
  23600. } else {
  23601. if ( image.data ) {
  23602. return {
  23603. data: getTypedArray( image.type, image.data ),
  23604. width: image.width,
  23605. height: image.height
  23606. };
  23607. } else {
  23608. return null;
  23609. }
  23610. }
  23611. }
  23612. if ( json !== undefined && json.length > 0 ) {
  23613. const manager = new LoadingManager( onLoad );
  23614. loader = new ImageLoader( manager );
  23615. loader.setCrossOrigin( this.crossOrigin );
  23616. for ( let i = 0, il = json.length; i < il; i ++ ) {
  23617. const image = json[ i ];
  23618. const url = image.url;
  23619. if ( Array.isArray( url ) ) {
  23620. // load array of images e.g CubeTexture
  23621. images[ image.uuid ] = [];
  23622. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  23623. const currentUrl = url[ j ];
  23624. const deserializedImage = deserializeImage( currentUrl );
  23625. if ( deserializedImage !== null ) {
  23626. if ( deserializedImage instanceof HTMLImageElement ) {
  23627. images[ image.uuid ].push( deserializedImage );
  23628. } else {
  23629. // special case: handle array of data textures for cube textures
  23630. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  23631. }
  23632. }
  23633. }
  23634. } else {
  23635. // load single image
  23636. const deserializedImage = deserializeImage( image.url );
  23637. if ( deserializedImage !== null ) {
  23638. images[ image.uuid ] = deserializedImage;
  23639. }
  23640. }
  23641. }
  23642. }
  23643. return images;
  23644. }
  23645. parseTextures( json, images ) {
  23646. function parseConstant( value, type ) {
  23647. if ( typeof value === 'number' ) return value;
  23648. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  23649. return type[ value ];
  23650. }
  23651. const textures = {};
  23652. if ( json !== undefined ) {
  23653. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23654. const data = json[ i ];
  23655. if ( data.image === undefined ) {
  23656. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  23657. }
  23658. if ( images[ data.image ] === undefined ) {
  23659. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  23660. }
  23661. let texture;
  23662. const image = images[ data.image ];
  23663. if ( Array.isArray( image ) ) {
  23664. texture = new CubeTexture( image );
  23665. if ( image.length === 6 ) texture.needsUpdate = true;
  23666. } else {
  23667. if ( image && image.data ) {
  23668. texture = new DataTexture( image.data, image.width, image.height );
  23669. } else {
  23670. texture = new Texture( image );
  23671. }
  23672. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  23673. }
  23674. texture.uuid = data.uuid;
  23675. if ( data.name !== undefined ) texture.name = data.name;
  23676. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  23677. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  23678. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  23679. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  23680. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  23681. if ( data.wrap !== undefined ) {
  23682. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  23683. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  23684. }
  23685. if ( data.format !== undefined ) texture.format = data.format;
  23686. if ( data.type !== undefined ) texture.type = data.type;
  23687. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  23688. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  23689. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  23690. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  23691. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  23692. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  23693. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  23694. textures[ data.uuid ] = texture;
  23695. }
  23696. }
  23697. return textures;
  23698. }
  23699. parseObject( data, geometries, materials, animations ) {
  23700. let object;
  23701. function getGeometry( name ) {
  23702. if ( geometries[ name ] === undefined ) {
  23703. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  23704. }
  23705. return geometries[ name ];
  23706. }
  23707. function getMaterial( name ) {
  23708. if ( name === undefined ) return undefined;
  23709. if ( Array.isArray( name ) ) {
  23710. const array = [];
  23711. for ( let i = 0, l = name.length; i < l; i ++ ) {
  23712. const uuid = name[ i ];
  23713. if ( materials[ uuid ] === undefined ) {
  23714. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  23715. }
  23716. array.push( materials[ uuid ] );
  23717. }
  23718. return array;
  23719. }
  23720. if ( materials[ name ] === undefined ) {
  23721. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  23722. }
  23723. return materials[ name ];
  23724. }
  23725. let geometry, material;
  23726. switch ( data.type ) {
  23727. case 'Scene':
  23728. object = new Scene();
  23729. if ( data.background !== undefined ) {
  23730. if ( Number.isInteger( data.background ) ) {
  23731. object.background = new Color( data.background );
  23732. }
  23733. }
  23734. if ( data.fog !== undefined ) {
  23735. if ( data.fog.type === 'Fog' ) {
  23736. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  23737. } else if ( data.fog.type === 'FogExp2' ) {
  23738. object.fog = new FogExp2( data.fog.color, data.fog.density );
  23739. }
  23740. }
  23741. break;
  23742. case 'PerspectiveCamera':
  23743. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  23744. if ( data.focus !== undefined ) object.focus = data.focus;
  23745. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  23746. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  23747. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  23748. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  23749. break;
  23750. case 'OrthographicCamera':
  23751. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  23752. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  23753. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  23754. break;
  23755. case 'AmbientLight':
  23756. object = new AmbientLight( data.color, data.intensity );
  23757. break;
  23758. case 'DirectionalLight':
  23759. object = new DirectionalLight( data.color, data.intensity );
  23760. break;
  23761. case 'PointLight':
  23762. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  23763. break;
  23764. case 'RectAreaLight':
  23765. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  23766. break;
  23767. case 'SpotLight':
  23768. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  23769. break;
  23770. case 'HemisphereLight':
  23771. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  23772. break;
  23773. case 'LightProbe':
  23774. object = new LightProbe().fromJSON( data );
  23775. break;
  23776. case 'SkinnedMesh':
  23777. geometry = getGeometry( data.geometry );
  23778. material = getMaterial( data.material );
  23779. object = new SkinnedMesh( geometry, material );
  23780. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  23781. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  23782. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  23783. break;
  23784. case 'Mesh':
  23785. geometry = getGeometry( data.geometry );
  23786. material = getMaterial( data.material );
  23787. object = new Mesh( geometry, material );
  23788. break;
  23789. case 'InstancedMesh':
  23790. geometry = getGeometry( data.geometry );
  23791. material = getMaterial( data.material );
  23792. const count = data.count;
  23793. const instanceMatrix = data.instanceMatrix;
  23794. const instanceColor = data.instanceColor;
  23795. object = new InstancedMesh( geometry, material, count );
  23796. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  23797. if ( instanceColor !== undefined ) object.instanceColor = new BufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  23798. break;
  23799. case 'LOD':
  23800. object = new LOD();
  23801. break;
  23802. case 'Line':
  23803. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  23804. break;
  23805. case 'LineLoop':
  23806. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  23807. break;
  23808. case 'LineSegments':
  23809. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  23810. break;
  23811. case 'PointCloud':
  23812. case 'Points':
  23813. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  23814. break;
  23815. case 'Sprite':
  23816. object = new Sprite( getMaterial( data.material ) );
  23817. break;
  23818. case 'Group':
  23819. object = new Group();
  23820. break;
  23821. case 'Bone':
  23822. object = new Bone();
  23823. break;
  23824. default:
  23825. object = new Object3D();
  23826. }
  23827. object.uuid = data.uuid;
  23828. if ( data.name !== undefined ) object.name = data.name;
  23829. if ( data.matrix !== undefined ) {
  23830. object.matrix.fromArray( data.matrix );
  23831. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23832. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  23833. } else {
  23834. if ( data.position !== undefined ) object.position.fromArray( data.position );
  23835. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  23836. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  23837. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  23838. }
  23839. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  23840. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  23841. if ( data.shadow ) {
  23842. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  23843. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  23844. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  23845. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  23846. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  23847. }
  23848. if ( data.visible !== undefined ) object.visible = data.visible;
  23849. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  23850. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  23851. if ( data.userData !== undefined ) object.userData = data.userData;
  23852. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  23853. if ( data.children !== undefined ) {
  23854. const children = data.children;
  23855. for ( let i = 0; i < children.length; i ++ ) {
  23856. object.add( this.parseObject( children[ i ], geometries, materials, animations ) );
  23857. }
  23858. }
  23859. if ( data.animations !== undefined ) {
  23860. const objectAnimations = data.animations;
  23861. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  23862. const uuid = objectAnimations[ i ];
  23863. object.animations.push( animations[ uuid ] );
  23864. }
  23865. }
  23866. if ( data.type === 'LOD' ) {
  23867. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  23868. const levels = data.levels;
  23869. for ( let l = 0; l < levels.length; l ++ ) {
  23870. const level = levels[ l ];
  23871. const child = object.getObjectByProperty( 'uuid', level.object );
  23872. if ( child !== undefined ) {
  23873. object.addLevel( child, level.distance );
  23874. }
  23875. }
  23876. }
  23877. return object;
  23878. }
  23879. bindSkeletons( object, skeletons ) {
  23880. if ( Object.keys( skeletons ).length === 0 ) return;
  23881. object.traverse( function ( child ) {
  23882. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  23883. const skeleton = skeletons[ child.skeleton ];
  23884. if ( skeleton === undefined ) {
  23885. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  23886. } else {
  23887. child.bind( skeleton, child.bindMatrix );
  23888. }
  23889. }
  23890. } );
  23891. }
  23892. /* DEPRECATED */
  23893. setTexturePath( value ) {
  23894. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  23895. return this.setResourcePath( value );
  23896. }
  23897. }
  23898. const TEXTURE_MAPPING = {
  23899. UVMapping: UVMapping,
  23900. CubeReflectionMapping: CubeReflectionMapping,
  23901. CubeRefractionMapping: CubeRefractionMapping,
  23902. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23903. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23904. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23905. CubeUVRefractionMapping: CubeUVRefractionMapping
  23906. };
  23907. const TEXTURE_WRAPPING = {
  23908. RepeatWrapping: RepeatWrapping,
  23909. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23910. MirroredRepeatWrapping: MirroredRepeatWrapping
  23911. };
  23912. const TEXTURE_FILTER = {
  23913. NearestFilter: NearestFilter,
  23914. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23915. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23916. LinearFilter: LinearFilter,
  23917. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23918. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23919. };
  23920. class ImageBitmapLoader extends Loader {
  23921. constructor( manager ) {
  23922. super( manager );
  23923. if ( typeof createImageBitmap === 'undefined' ) {
  23924. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  23925. }
  23926. if ( typeof fetch === 'undefined' ) {
  23927. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  23928. }
  23929. this.options = { premultiplyAlpha: 'none' };
  23930. }
  23931. setOptions( options ) {
  23932. this.options = options;
  23933. return this;
  23934. }
  23935. load( url, onLoad, onProgress, onError ) {
  23936. if ( url === undefined ) url = '';
  23937. if ( this.path !== undefined ) url = this.path + url;
  23938. url = this.manager.resolveURL( url );
  23939. const scope = this;
  23940. const cached = Cache.get( url );
  23941. if ( cached !== undefined ) {
  23942. scope.manager.itemStart( url );
  23943. setTimeout( function () {
  23944. if ( onLoad ) onLoad( cached );
  23945. scope.manager.itemEnd( url );
  23946. }, 0 );
  23947. return cached;
  23948. }
  23949. const fetchOptions = {};
  23950. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  23951. fetchOptions.headers = this.requestHeader;
  23952. fetch( url, fetchOptions ).then( function ( res ) {
  23953. return res.blob();
  23954. } ).then( function ( blob ) {
  23955. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  23956. } ).then( function ( imageBitmap ) {
  23957. Cache.add( url, imageBitmap );
  23958. if ( onLoad ) onLoad( imageBitmap );
  23959. scope.manager.itemEnd( url );
  23960. } ).catch( function ( e ) {
  23961. if ( onError ) onError( e );
  23962. scope.manager.itemError( url );
  23963. scope.manager.itemEnd( url );
  23964. } );
  23965. scope.manager.itemStart( url );
  23966. }
  23967. }
  23968. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23969. class ShapePath {
  23970. constructor() {
  23971. this.type = 'ShapePath';
  23972. this.color = new Color();
  23973. this.subPaths = [];
  23974. this.currentPath = null;
  23975. }
  23976. moveTo( x, y ) {
  23977. this.currentPath = new Path();
  23978. this.subPaths.push( this.currentPath );
  23979. this.currentPath.moveTo( x, y );
  23980. return this;
  23981. }
  23982. lineTo( x, y ) {
  23983. this.currentPath.lineTo( x, y );
  23984. return this;
  23985. }
  23986. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23987. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  23988. return this;
  23989. }
  23990. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23991. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  23992. return this;
  23993. }
  23994. splineThru( pts ) {
  23995. this.currentPath.splineThru( pts );
  23996. return this;
  23997. }
  23998. toShapes( isCCW, noHoles ) {
  23999. function toShapesNoHoles( inSubpaths ) {
  24000. const shapes = [];
  24001. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  24002. const tmpPath = inSubpaths[ i ];
  24003. const tmpShape = new Shape();
  24004. tmpShape.curves = tmpPath.curves;
  24005. shapes.push( tmpShape );
  24006. }
  24007. return shapes;
  24008. }
  24009. function isPointInsidePolygon( inPt, inPolygon ) {
  24010. const polyLen = inPolygon.length;
  24011. // inPt on polygon contour => immediate success or
  24012. // toggling of inside/outside at every single! intersection point of an edge
  24013. // with the horizontal line through inPt, left of inPt
  24014. // not counting lowerY endpoints of edges and whole edges on that line
  24015. let inside = false;
  24016. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  24017. let edgeLowPt = inPolygon[ p ];
  24018. let edgeHighPt = inPolygon[ q ];
  24019. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24020. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24021. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  24022. // not parallel
  24023. if ( edgeDy < 0 ) {
  24024. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  24025. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  24026. }
  24027. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  24028. if ( inPt.y === edgeLowPt.y ) {
  24029. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  24030. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24031. } else {
  24032. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  24033. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  24034. if ( perpEdge < 0 ) continue;
  24035. inside = ! inside; // true intersection left of inPt
  24036. }
  24037. } else {
  24038. // parallel or collinear
  24039. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  24040. // edge lies on the same horizontal line as inPt
  24041. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  24042. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  24043. // continue;
  24044. }
  24045. }
  24046. return inside;
  24047. }
  24048. const isClockWise = ShapeUtils.isClockWise;
  24049. const subPaths = this.subPaths;
  24050. if ( subPaths.length === 0 ) return [];
  24051. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  24052. let solid, tmpPath, tmpShape;
  24053. const shapes = [];
  24054. if ( subPaths.length === 1 ) {
  24055. tmpPath = subPaths[ 0 ];
  24056. tmpShape = new Shape();
  24057. tmpShape.curves = tmpPath.curves;
  24058. shapes.push( tmpShape );
  24059. return shapes;
  24060. }
  24061. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  24062. holesFirst = isCCW ? ! holesFirst : holesFirst;
  24063. // console.log("Holes first", holesFirst);
  24064. const betterShapeHoles = [];
  24065. const newShapes = [];
  24066. let newShapeHoles = [];
  24067. let mainIdx = 0;
  24068. let tmpPoints;
  24069. newShapes[ mainIdx ] = undefined;
  24070. newShapeHoles[ mainIdx ] = [];
  24071. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  24072. tmpPath = subPaths[ i ];
  24073. tmpPoints = tmpPath.getPoints();
  24074. solid = isClockWise( tmpPoints );
  24075. solid = isCCW ? ! solid : solid;
  24076. if ( solid ) {
  24077. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  24078. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  24079. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  24080. if ( holesFirst ) mainIdx ++;
  24081. newShapeHoles[ mainIdx ] = [];
  24082. //console.log('cw', i);
  24083. } else {
  24084. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  24085. //console.log('ccw', i);
  24086. }
  24087. }
  24088. // only Holes? -> probably all Shapes with wrong orientation
  24089. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  24090. if ( newShapes.length > 1 ) {
  24091. let ambiguous = false;
  24092. const toChange = [];
  24093. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  24094. betterShapeHoles[ sIdx ] = [];
  24095. }
  24096. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  24097. const sho = newShapeHoles[ sIdx ];
  24098. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  24099. const ho = sho[ hIdx ];
  24100. let hole_unassigned = true;
  24101. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  24102. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  24103. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  24104. if ( hole_unassigned ) {
  24105. hole_unassigned = false;
  24106. betterShapeHoles[ s2Idx ].push( ho );
  24107. } else {
  24108. ambiguous = true;
  24109. }
  24110. }
  24111. }
  24112. if ( hole_unassigned ) {
  24113. betterShapeHoles[ sIdx ].push( ho );
  24114. }
  24115. }
  24116. }
  24117. // console.log("ambiguous: ", ambiguous);
  24118. if ( toChange.length > 0 ) {
  24119. // console.log("to change: ", toChange);
  24120. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  24121. }
  24122. }
  24123. let tmpHoles;
  24124. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  24125. tmpShape = newShapes[ i ].s;
  24126. shapes.push( tmpShape );
  24127. tmpHoles = newShapeHoles[ i ];
  24128. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  24129. tmpShape.holes.push( tmpHoles[ j ].h );
  24130. }
  24131. }
  24132. //console.log("shape", shapes);
  24133. return shapes;
  24134. }
  24135. }
  24136. class Font {
  24137. constructor( data ) {
  24138. this.type = 'Font';
  24139. this.data = data;
  24140. }
  24141. generateShapes( text, size = 100 ) {
  24142. const shapes = [];
  24143. const paths = createPaths( text, size, this.data );
  24144. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  24145. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  24146. }
  24147. return shapes;
  24148. }
  24149. }
  24150. function createPaths( text, size, data ) {
  24151. const chars = Array.from( text );
  24152. const scale = size / data.resolution;
  24153. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  24154. const paths = [];
  24155. let offsetX = 0, offsetY = 0;
  24156. for ( let i = 0; i < chars.length; i ++ ) {
  24157. const char = chars[ i ];
  24158. if ( char === '\n' ) {
  24159. offsetX = 0;
  24160. offsetY -= line_height;
  24161. } else {
  24162. const ret = createPath( char, scale, offsetX, offsetY, data );
  24163. offsetX += ret.offsetX;
  24164. paths.push( ret.path );
  24165. }
  24166. }
  24167. return paths;
  24168. }
  24169. function createPath( char, scale, offsetX, offsetY, data ) {
  24170. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  24171. if ( ! glyph ) {
  24172. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  24173. return;
  24174. }
  24175. const path = new ShapePath();
  24176. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24177. if ( glyph.o ) {
  24178. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  24179. for ( let i = 0, l = outline.length; i < l; ) {
  24180. const action = outline[ i ++ ];
  24181. switch ( action ) {
  24182. case 'm': // moveTo
  24183. x = outline[ i ++ ] * scale + offsetX;
  24184. y = outline[ i ++ ] * scale + offsetY;
  24185. path.moveTo( x, y );
  24186. break;
  24187. case 'l': // lineTo
  24188. x = outline[ i ++ ] * scale + offsetX;
  24189. y = outline[ i ++ ] * scale + offsetY;
  24190. path.lineTo( x, y );
  24191. break;
  24192. case 'q': // quadraticCurveTo
  24193. cpx = outline[ i ++ ] * scale + offsetX;
  24194. cpy = outline[ i ++ ] * scale + offsetY;
  24195. cpx1 = outline[ i ++ ] * scale + offsetX;
  24196. cpy1 = outline[ i ++ ] * scale + offsetY;
  24197. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  24198. break;
  24199. case 'b': // bezierCurveTo
  24200. cpx = outline[ i ++ ] * scale + offsetX;
  24201. cpy = outline[ i ++ ] * scale + offsetY;
  24202. cpx1 = outline[ i ++ ] * scale + offsetX;
  24203. cpy1 = outline[ i ++ ] * scale + offsetY;
  24204. cpx2 = outline[ i ++ ] * scale + offsetX;
  24205. cpy2 = outline[ i ++ ] * scale + offsetY;
  24206. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  24207. break;
  24208. }
  24209. }
  24210. }
  24211. return { offsetX: glyph.ha * scale, path: path };
  24212. }
  24213. Font.prototype.isFont = true;
  24214. class FontLoader extends Loader {
  24215. constructor( manager ) {
  24216. super( manager );
  24217. }
  24218. load( url, onLoad, onProgress, onError ) {
  24219. const scope = this;
  24220. const loader = new FileLoader( this.manager );
  24221. loader.setPath( this.path );
  24222. loader.setRequestHeader( this.requestHeader );
  24223. loader.setWithCredentials( scope.withCredentials );
  24224. loader.load( url, function ( text ) {
  24225. let json;
  24226. try {
  24227. json = JSON.parse( text );
  24228. } catch ( e ) {
  24229. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  24230. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  24231. }
  24232. const font = scope.parse( json );
  24233. if ( onLoad ) onLoad( font );
  24234. }, onProgress, onError );
  24235. }
  24236. parse( json ) {
  24237. return new Font( json );
  24238. }
  24239. }
  24240. let _context;
  24241. const AudioContext = {
  24242. getContext: function () {
  24243. if ( _context === undefined ) {
  24244. _context = new ( window.AudioContext || window.webkitAudioContext )();
  24245. }
  24246. return _context;
  24247. },
  24248. setContext: function ( value ) {
  24249. _context = value;
  24250. }
  24251. };
  24252. class AudioLoader extends Loader {
  24253. constructor( manager ) {
  24254. super( manager );
  24255. }
  24256. load( url, onLoad, onProgress, onError ) {
  24257. const scope = this;
  24258. const loader = new FileLoader( this.manager );
  24259. loader.setResponseType( 'arraybuffer' );
  24260. loader.setPath( this.path );
  24261. loader.setRequestHeader( this.requestHeader );
  24262. loader.setWithCredentials( this.withCredentials );
  24263. loader.load( url, function ( buffer ) {
  24264. try {
  24265. // Create a copy of the buffer. The `decodeAudioData` method
  24266. // detaches the buffer when complete, preventing reuse.
  24267. const bufferCopy = buffer.slice( 0 );
  24268. const context = AudioContext.getContext();
  24269. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  24270. onLoad( audioBuffer );
  24271. } );
  24272. } catch ( e ) {
  24273. if ( onError ) {
  24274. onError( e );
  24275. } else {
  24276. console.error( e );
  24277. }
  24278. scope.manager.itemError( url );
  24279. }
  24280. }, onProgress, onError );
  24281. }
  24282. }
  24283. class HemisphereLightProbe extends LightProbe {
  24284. constructor( skyColor, groundColor, intensity = 1 ) {
  24285. super( undefined, intensity );
  24286. const color1 = new Color().set( skyColor );
  24287. const color2 = new Color().set( groundColor );
  24288. const sky = new Vector3( color1.r, color1.g, color1.b );
  24289. const ground = new Vector3( color2.r, color2.g, color2.b );
  24290. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24291. const c0 = Math.sqrt( Math.PI );
  24292. const c1 = c0 * Math.sqrt( 0.75 );
  24293. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  24294. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  24295. }
  24296. }
  24297. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24298. class AmbientLightProbe extends LightProbe {
  24299. constructor( color, intensity = 1 ) {
  24300. super( undefined, intensity );
  24301. const color1 = new Color().set( color );
  24302. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24303. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  24304. }
  24305. }
  24306. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24307. const _eyeRight = /*@__PURE__*/ new Matrix4();
  24308. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  24309. class StereoCamera {
  24310. constructor() {
  24311. this.type = 'StereoCamera';
  24312. this.aspect = 1;
  24313. this.eyeSep = 0.064;
  24314. this.cameraL = new PerspectiveCamera();
  24315. this.cameraL.layers.enable( 1 );
  24316. this.cameraL.matrixAutoUpdate = false;
  24317. this.cameraR = new PerspectiveCamera();
  24318. this.cameraR.layers.enable( 2 );
  24319. this.cameraR.matrixAutoUpdate = false;
  24320. this._cache = {
  24321. focus: null,
  24322. fov: null,
  24323. aspect: null,
  24324. near: null,
  24325. far: null,
  24326. zoom: null,
  24327. eyeSep: null
  24328. };
  24329. }
  24330. update( camera ) {
  24331. const cache = this._cache;
  24332. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  24333. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  24334. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  24335. if ( needsUpdate ) {
  24336. cache.focus = camera.focus;
  24337. cache.fov = camera.fov;
  24338. cache.aspect = camera.aspect * this.aspect;
  24339. cache.near = camera.near;
  24340. cache.far = camera.far;
  24341. cache.zoom = camera.zoom;
  24342. cache.eyeSep = this.eyeSep;
  24343. // Off-axis stereoscopic effect based on
  24344. // http://paulbourke.net/stereographics/stereorender/
  24345. const projectionMatrix = camera.projectionMatrix.clone();
  24346. const eyeSepHalf = cache.eyeSep / 2;
  24347. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24348. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  24349. let xmin, xmax;
  24350. // translate xOffset
  24351. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  24352. _eyeRight.elements[ 12 ] = eyeSepHalf;
  24353. // for left eye
  24354. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  24355. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24356. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  24357. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  24358. this.cameraL.projectionMatrix.copy( projectionMatrix );
  24359. // for right eye
  24360. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  24361. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24362. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  24363. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  24364. this.cameraR.projectionMatrix.copy( projectionMatrix );
  24365. }
  24366. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  24367. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  24368. }
  24369. }
  24370. class Clock {
  24371. constructor( autoStart = true ) {
  24372. this.autoStart = autoStart;
  24373. this.startTime = 0;
  24374. this.oldTime = 0;
  24375. this.elapsedTime = 0;
  24376. this.running = false;
  24377. }
  24378. start() {
  24379. this.startTime = now();
  24380. this.oldTime = this.startTime;
  24381. this.elapsedTime = 0;
  24382. this.running = true;
  24383. }
  24384. stop() {
  24385. this.getElapsedTime();
  24386. this.running = false;
  24387. this.autoStart = false;
  24388. }
  24389. getElapsedTime() {
  24390. this.getDelta();
  24391. return this.elapsedTime;
  24392. }
  24393. getDelta() {
  24394. let diff = 0;
  24395. if ( this.autoStart && ! this.running ) {
  24396. this.start();
  24397. return 0;
  24398. }
  24399. if ( this.running ) {
  24400. const newTime = now();
  24401. diff = ( newTime - this.oldTime ) / 1000;
  24402. this.oldTime = newTime;
  24403. this.elapsedTime += diff;
  24404. }
  24405. return diff;
  24406. }
  24407. }
  24408. function now() {
  24409. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  24410. }
  24411. const _position$1 = /*@__PURE__*/ new Vector3();
  24412. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  24413. const _scale$1 = /*@__PURE__*/ new Vector3();
  24414. const _orientation$1 = /*@__PURE__*/ new Vector3();
  24415. class AudioListener extends Object3D {
  24416. constructor() {
  24417. super();
  24418. this.type = 'AudioListener';
  24419. this.context = AudioContext.getContext();
  24420. this.gain = this.context.createGain();
  24421. this.gain.connect( this.context.destination );
  24422. this.filter = null;
  24423. this.timeDelta = 0;
  24424. // private
  24425. this._clock = new Clock();
  24426. }
  24427. getInput() {
  24428. return this.gain;
  24429. }
  24430. removeFilter() {
  24431. if ( this.filter !== null ) {
  24432. this.gain.disconnect( this.filter );
  24433. this.filter.disconnect( this.context.destination );
  24434. this.gain.connect( this.context.destination );
  24435. this.filter = null;
  24436. }
  24437. return this;
  24438. }
  24439. getFilter() {
  24440. return this.filter;
  24441. }
  24442. setFilter( value ) {
  24443. if ( this.filter !== null ) {
  24444. this.gain.disconnect( this.filter );
  24445. this.filter.disconnect( this.context.destination );
  24446. } else {
  24447. this.gain.disconnect( this.context.destination );
  24448. }
  24449. this.filter = value;
  24450. this.gain.connect( this.filter );
  24451. this.filter.connect( this.context.destination );
  24452. return this;
  24453. }
  24454. getMasterVolume() {
  24455. return this.gain.gain.value;
  24456. }
  24457. setMasterVolume( value ) {
  24458. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  24459. return this;
  24460. }
  24461. updateMatrixWorld( force ) {
  24462. super.updateMatrixWorld( force );
  24463. const listener = this.context.listener;
  24464. const up = this.up;
  24465. this.timeDelta = this._clock.getDelta();
  24466. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  24467. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  24468. if ( listener.positionX ) {
  24469. // code path for Chrome (see #14393)
  24470. const endTime = this.context.currentTime + this.timeDelta;
  24471. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  24472. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  24473. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  24474. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  24475. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  24476. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  24477. listener.upX.linearRampToValueAtTime( up.x, endTime );
  24478. listener.upY.linearRampToValueAtTime( up.y, endTime );
  24479. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  24480. } else {
  24481. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  24482. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  24483. }
  24484. }
  24485. }
  24486. class Audio extends Object3D {
  24487. constructor( listener ) {
  24488. super();
  24489. this.type = 'Audio';
  24490. this.listener = listener;
  24491. this.context = listener.context;
  24492. this.gain = this.context.createGain();
  24493. this.gain.connect( listener.getInput() );
  24494. this.autoplay = false;
  24495. this.buffer = null;
  24496. this.detune = 0;
  24497. this.loop = false;
  24498. this.loopStart = 0;
  24499. this.loopEnd = 0;
  24500. this.offset = 0;
  24501. this.duration = undefined;
  24502. this.playbackRate = 1;
  24503. this.isPlaying = false;
  24504. this.hasPlaybackControl = true;
  24505. this.source = null;
  24506. this.sourceType = 'empty';
  24507. this._startedAt = 0;
  24508. this._progress = 0;
  24509. this._connected = false;
  24510. this.filters = [];
  24511. }
  24512. getOutput() {
  24513. return this.gain;
  24514. }
  24515. setNodeSource( audioNode ) {
  24516. this.hasPlaybackControl = false;
  24517. this.sourceType = 'audioNode';
  24518. this.source = audioNode;
  24519. this.connect();
  24520. return this;
  24521. }
  24522. setMediaElementSource( mediaElement ) {
  24523. this.hasPlaybackControl = false;
  24524. this.sourceType = 'mediaNode';
  24525. this.source = this.context.createMediaElementSource( mediaElement );
  24526. this.connect();
  24527. return this;
  24528. }
  24529. setMediaStreamSource( mediaStream ) {
  24530. this.hasPlaybackControl = false;
  24531. this.sourceType = 'mediaStreamNode';
  24532. this.source = this.context.createMediaStreamSource( mediaStream );
  24533. this.connect();
  24534. return this;
  24535. }
  24536. setBuffer( audioBuffer ) {
  24537. this.buffer = audioBuffer;
  24538. this.sourceType = 'buffer';
  24539. if ( this.autoplay ) this.play();
  24540. return this;
  24541. }
  24542. play( delay = 0 ) {
  24543. if ( this.isPlaying === true ) {
  24544. console.warn( 'THREE.Audio: Audio is already playing.' );
  24545. return;
  24546. }
  24547. if ( this.hasPlaybackControl === false ) {
  24548. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24549. return;
  24550. }
  24551. this._startedAt = this.context.currentTime + delay;
  24552. const source = this.context.createBufferSource();
  24553. source.buffer = this.buffer;
  24554. source.loop = this.loop;
  24555. source.loopStart = this.loopStart;
  24556. source.loopEnd = this.loopEnd;
  24557. source.onended = this.onEnded.bind( this );
  24558. source.start( this._startedAt, this._progress + this.offset, this.duration );
  24559. this.isPlaying = true;
  24560. this.source = source;
  24561. this.setDetune( this.detune );
  24562. this.setPlaybackRate( this.playbackRate );
  24563. return this.connect();
  24564. }
  24565. pause() {
  24566. if ( this.hasPlaybackControl === false ) {
  24567. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24568. return;
  24569. }
  24570. if ( this.isPlaying === true ) {
  24571. // update current progress
  24572. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  24573. if ( this.loop === true ) {
  24574. // ensure _progress does not exceed duration with looped audios
  24575. this._progress = this._progress % ( this.duration || this.buffer.duration );
  24576. }
  24577. this.source.stop();
  24578. this.source.onended = null;
  24579. this.isPlaying = false;
  24580. }
  24581. return this;
  24582. }
  24583. stop() {
  24584. if ( this.hasPlaybackControl === false ) {
  24585. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24586. return;
  24587. }
  24588. this._progress = 0;
  24589. this.source.stop();
  24590. this.source.onended = null;
  24591. this.isPlaying = false;
  24592. return this;
  24593. }
  24594. connect() {
  24595. if ( this.filters.length > 0 ) {
  24596. this.source.connect( this.filters[ 0 ] );
  24597. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  24598. this.filters[ i - 1 ].connect( this.filters[ i ] );
  24599. }
  24600. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  24601. } else {
  24602. this.source.connect( this.getOutput() );
  24603. }
  24604. this._connected = true;
  24605. return this;
  24606. }
  24607. disconnect() {
  24608. if ( this.filters.length > 0 ) {
  24609. this.source.disconnect( this.filters[ 0 ] );
  24610. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  24611. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  24612. }
  24613. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  24614. } else {
  24615. this.source.disconnect( this.getOutput() );
  24616. }
  24617. this._connected = false;
  24618. return this;
  24619. }
  24620. getFilters() {
  24621. return this.filters;
  24622. }
  24623. setFilters( value ) {
  24624. if ( ! value ) value = [];
  24625. if ( this._connected === true ) {
  24626. this.disconnect();
  24627. this.filters = value.slice();
  24628. this.connect();
  24629. } else {
  24630. this.filters = value.slice();
  24631. }
  24632. return this;
  24633. }
  24634. setDetune( value ) {
  24635. this.detune = value;
  24636. if ( this.source.detune === undefined ) return; // only set detune when available
  24637. if ( this.isPlaying === true ) {
  24638. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  24639. }
  24640. return this;
  24641. }
  24642. getDetune() {
  24643. return this.detune;
  24644. }
  24645. getFilter() {
  24646. return this.getFilters()[ 0 ];
  24647. }
  24648. setFilter( filter ) {
  24649. return this.setFilters( filter ? [ filter ] : [] );
  24650. }
  24651. setPlaybackRate( value ) {
  24652. if ( this.hasPlaybackControl === false ) {
  24653. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24654. return;
  24655. }
  24656. this.playbackRate = value;
  24657. if ( this.isPlaying === true ) {
  24658. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  24659. }
  24660. return this;
  24661. }
  24662. getPlaybackRate() {
  24663. return this.playbackRate;
  24664. }
  24665. onEnded() {
  24666. this.isPlaying = false;
  24667. }
  24668. getLoop() {
  24669. if ( this.hasPlaybackControl === false ) {
  24670. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24671. return false;
  24672. }
  24673. return this.loop;
  24674. }
  24675. setLoop( value ) {
  24676. if ( this.hasPlaybackControl === false ) {
  24677. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24678. return;
  24679. }
  24680. this.loop = value;
  24681. if ( this.isPlaying === true ) {
  24682. this.source.loop = this.loop;
  24683. }
  24684. return this;
  24685. }
  24686. setLoopStart( value ) {
  24687. this.loopStart = value;
  24688. return this;
  24689. }
  24690. setLoopEnd( value ) {
  24691. this.loopEnd = value;
  24692. return this;
  24693. }
  24694. getVolume() {
  24695. return this.gain.gain.value;
  24696. }
  24697. setVolume( value ) {
  24698. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  24699. return this;
  24700. }
  24701. }
  24702. const _position = /*@__PURE__*/ new Vector3();
  24703. const _quaternion = /*@__PURE__*/ new Quaternion();
  24704. const _scale = /*@__PURE__*/ new Vector3();
  24705. const _orientation = /*@__PURE__*/ new Vector3();
  24706. class PositionalAudio extends Audio {
  24707. constructor( listener ) {
  24708. super( listener );
  24709. this.panner = this.context.createPanner();
  24710. this.panner.panningModel = 'HRTF';
  24711. this.panner.connect( this.gain );
  24712. }
  24713. getOutput() {
  24714. return this.panner;
  24715. }
  24716. getRefDistance() {
  24717. return this.panner.refDistance;
  24718. }
  24719. setRefDistance( value ) {
  24720. this.panner.refDistance = value;
  24721. return this;
  24722. }
  24723. getRolloffFactor() {
  24724. return this.panner.rolloffFactor;
  24725. }
  24726. setRolloffFactor( value ) {
  24727. this.panner.rolloffFactor = value;
  24728. return this;
  24729. }
  24730. getDistanceModel() {
  24731. return this.panner.distanceModel;
  24732. }
  24733. setDistanceModel( value ) {
  24734. this.panner.distanceModel = value;
  24735. return this;
  24736. }
  24737. getMaxDistance() {
  24738. return this.panner.maxDistance;
  24739. }
  24740. setMaxDistance( value ) {
  24741. this.panner.maxDistance = value;
  24742. return this;
  24743. }
  24744. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  24745. this.panner.coneInnerAngle = coneInnerAngle;
  24746. this.panner.coneOuterAngle = coneOuterAngle;
  24747. this.panner.coneOuterGain = coneOuterGain;
  24748. return this;
  24749. }
  24750. updateMatrixWorld( force ) {
  24751. super.updateMatrixWorld( force );
  24752. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  24753. this.matrixWorld.decompose( _position, _quaternion, _scale );
  24754. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  24755. const panner = this.panner;
  24756. if ( panner.positionX ) {
  24757. // code path for Chrome and Firefox (see #14393)
  24758. const endTime = this.context.currentTime + this.listener.timeDelta;
  24759. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  24760. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  24761. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  24762. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  24763. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  24764. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  24765. } else {
  24766. panner.setPosition( _position.x, _position.y, _position.z );
  24767. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  24768. }
  24769. }
  24770. }
  24771. class AudioAnalyser {
  24772. constructor( audio, fftSize = 2048 ) {
  24773. this.analyser = audio.context.createAnalyser();
  24774. this.analyser.fftSize = fftSize;
  24775. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  24776. audio.getOutput().connect( this.analyser );
  24777. }
  24778. getFrequencyData() {
  24779. this.analyser.getByteFrequencyData( this.data );
  24780. return this.data;
  24781. }
  24782. getAverageFrequency() {
  24783. let value = 0;
  24784. const data = this.getFrequencyData();
  24785. for ( let i = 0; i < data.length; i ++ ) {
  24786. value += data[ i ];
  24787. }
  24788. return value / data.length;
  24789. }
  24790. }
  24791. class PropertyMixer {
  24792. constructor( binding, typeName, valueSize ) {
  24793. this.binding = binding;
  24794. this.valueSize = valueSize;
  24795. let mixFunction,
  24796. mixFunctionAdditive,
  24797. setIdentity;
  24798. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24799. //
  24800. // interpolators can use .buffer as their .result
  24801. // the data then goes to 'incoming'
  24802. //
  24803. // 'accu0' and 'accu1' are used frame-interleaved for
  24804. // the cumulative result and are compared to detect
  24805. // changes
  24806. //
  24807. // 'orig' stores the original state of the property
  24808. //
  24809. // 'add' is used for additive cumulative results
  24810. //
  24811. // 'work' is optional and is only present for quaternion types. It is used
  24812. // to store intermediate quaternion multiplication results
  24813. switch ( typeName ) {
  24814. case 'quaternion':
  24815. mixFunction = this._slerp;
  24816. mixFunctionAdditive = this._slerpAdditive;
  24817. setIdentity = this._setAdditiveIdentityQuaternion;
  24818. this.buffer = new Float64Array( valueSize * 6 );
  24819. this._workIndex = 5;
  24820. break;
  24821. case 'string':
  24822. case 'bool':
  24823. mixFunction = this._select;
  24824. // Use the regular mix function and for additive on these types,
  24825. // additive is not relevant for non-numeric types
  24826. mixFunctionAdditive = this._select;
  24827. setIdentity = this._setAdditiveIdentityOther;
  24828. this.buffer = new Array( valueSize * 5 );
  24829. break;
  24830. default:
  24831. mixFunction = this._lerp;
  24832. mixFunctionAdditive = this._lerpAdditive;
  24833. setIdentity = this._setAdditiveIdentityNumeric;
  24834. this.buffer = new Float64Array( valueSize * 5 );
  24835. }
  24836. this._mixBufferRegion = mixFunction;
  24837. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24838. this._setIdentity = setIdentity;
  24839. this._origIndex = 3;
  24840. this._addIndex = 4;
  24841. this.cumulativeWeight = 0;
  24842. this.cumulativeWeightAdditive = 0;
  24843. this.useCount = 0;
  24844. this.referenceCount = 0;
  24845. }
  24846. // accumulate data in the 'incoming' region into 'accu<i>'
  24847. accumulate( accuIndex, weight ) {
  24848. // note: happily accumulating nothing when weight = 0, the caller knows
  24849. // the weight and shouldn't have made the call in the first place
  24850. const buffer = this.buffer,
  24851. stride = this.valueSize,
  24852. offset = accuIndex * stride + stride;
  24853. let currentWeight = this.cumulativeWeight;
  24854. if ( currentWeight === 0 ) {
  24855. // accuN := incoming * weight
  24856. for ( let i = 0; i !== stride; ++ i ) {
  24857. buffer[ offset + i ] = buffer[ i ];
  24858. }
  24859. currentWeight = weight;
  24860. } else {
  24861. // accuN := accuN + incoming * weight
  24862. currentWeight += weight;
  24863. const mix = weight / currentWeight;
  24864. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  24865. }
  24866. this.cumulativeWeight = currentWeight;
  24867. }
  24868. // accumulate data in the 'incoming' region into 'add'
  24869. accumulateAdditive( weight ) {
  24870. const buffer = this.buffer,
  24871. stride = this.valueSize,
  24872. offset = stride * this._addIndex;
  24873. if ( this.cumulativeWeightAdditive === 0 ) {
  24874. // add = identity
  24875. this._setIdentity();
  24876. }
  24877. // add := add + incoming * weight
  24878. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  24879. this.cumulativeWeightAdditive += weight;
  24880. }
  24881. // apply the state of 'accu<i>' to the binding when accus differ
  24882. apply( accuIndex ) {
  24883. const stride = this.valueSize,
  24884. buffer = this.buffer,
  24885. offset = accuIndex * stride + stride,
  24886. weight = this.cumulativeWeight,
  24887. weightAdditive = this.cumulativeWeightAdditive,
  24888. binding = this.binding;
  24889. this.cumulativeWeight = 0;
  24890. this.cumulativeWeightAdditive = 0;
  24891. if ( weight < 1 ) {
  24892. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24893. const originalValueOffset = stride * this._origIndex;
  24894. this._mixBufferRegion(
  24895. buffer, offset, originalValueOffset, 1 - weight, stride );
  24896. }
  24897. if ( weightAdditive > 0 ) {
  24898. // accuN := accuN + additive accuN
  24899. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  24900. }
  24901. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  24902. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  24903. // value has changed -> update scene graph
  24904. binding.setValue( buffer, offset );
  24905. break;
  24906. }
  24907. }
  24908. }
  24909. // remember the state of the bound property and copy it to both accus
  24910. saveOriginalState() {
  24911. const binding = this.binding;
  24912. const buffer = this.buffer,
  24913. stride = this.valueSize,
  24914. originalValueOffset = stride * this._origIndex;
  24915. binding.getValue( buffer, originalValueOffset );
  24916. // accu[0..1] := orig -- initially detect changes against the original
  24917. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  24918. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  24919. }
  24920. // Add to identity for additive
  24921. this._setIdentity();
  24922. this.cumulativeWeight = 0;
  24923. this.cumulativeWeightAdditive = 0;
  24924. }
  24925. // apply the state previously taken via 'saveOriginalState' to the binding
  24926. restoreOriginalState() {
  24927. const originalValueOffset = this.valueSize * 3;
  24928. this.binding.setValue( this.buffer, originalValueOffset );
  24929. }
  24930. _setAdditiveIdentityNumeric() {
  24931. const startIndex = this._addIndex * this.valueSize;
  24932. const endIndex = startIndex + this.valueSize;
  24933. for ( let i = startIndex; i < endIndex; i ++ ) {
  24934. this.buffer[ i ] = 0;
  24935. }
  24936. }
  24937. _setAdditiveIdentityQuaternion() {
  24938. this._setAdditiveIdentityNumeric();
  24939. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  24940. }
  24941. _setAdditiveIdentityOther() {
  24942. const startIndex = this._origIndex * this.valueSize;
  24943. const targetIndex = this._addIndex * this.valueSize;
  24944. for ( let i = 0; i < this.valueSize; i ++ ) {
  24945. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  24946. }
  24947. }
  24948. // mix functions
  24949. _select( buffer, dstOffset, srcOffset, t, stride ) {
  24950. if ( t >= 0.5 ) {
  24951. for ( let i = 0; i !== stride; ++ i ) {
  24952. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  24953. }
  24954. }
  24955. }
  24956. _slerp( buffer, dstOffset, srcOffset, t ) {
  24957. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  24958. }
  24959. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  24960. const workOffset = this._workIndex * stride;
  24961. // Store result in intermediate buffer offset
  24962. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  24963. // Slerp to the intermediate result
  24964. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  24965. }
  24966. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  24967. const s = 1 - t;
  24968. for ( let i = 0; i !== stride; ++ i ) {
  24969. const j = dstOffset + i;
  24970. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  24971. }
  24972. }
  24973. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  24974. for ( let i = 0; i !== stride; ++ i ) {
  24975. const j = dstOffset + i;
  24976. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  24977. }
  24978. }
  24979. }
  24980. // Characters [].:/ are reserved for track binding syntax.
  24981. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24982. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  24983. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24984. // only latin characters, and the unicode \p{L} is not yet supported. So
  24985. // instead, we exclude reserved characters and match everything else.
  24986. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24987. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  24988. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24989. // be matched to parse the rest of the track name.
  24990. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  24991. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24992. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  24993. // Object on target node, and accessor. May not contain reserved
  24994. // characters. Accessor may contain any character except closing bracket.
  24995. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  24996. // Property and accessor. May not contain reserved characters. Accessor may
  24997. // contain any non-bracket characters.
  24998. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  24999. const _trackRe = new RegExp( ''
  25000. + '^'
  25001. + _directoryRe
  25002. + _nodeRe
  25003. + _objectRe
  25004. + _propertyRe
  25005. + '$'
  25006. );
  25007. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  25008. class Composite {
  25009. constructor( targetGroup, path, optionalParsedPath ) {
  25010. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  25011. this._targetGroup = targetGroup;
  25012. this._bindings = targetGroup.subscribe_( path, parsedPath );
  25013. }
  25014. getValue( array, offset ) {
  25015. this.bind(); // bind all binding
  25016. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25017. binding = this._bindings[ firstValidIndex ];
  25018. // and only call .getValue on the first
  25019. if ( binding !== undefined ) binding.getValue( array, offset );
  25020. }
  25021. setValue( array, offset ) {
  25022. const bindings = this._bindings;
  25023. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25024. bindings[ i ].setValue( array, offset );
  25025. }
  25026. }
  25027. bind() {
  25028. const bindings = this._bindings;
  25029. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25030. bindings[ i ].bind();
  25031. }
  25032. }
  25033. unbind() {
  25034. const bindings = this._bindings;
  25035. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25036. bindings[ i ].unbind();
  25037. }
  25038. }
  25039. }
  25040. // Note: This class uses a State pattern on a per-method basis:
  25041. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25042. // prototype version of these methods with one that represents
  25043. // the bound state. When the property is not found, the methods
  25044. // become no-ops.
  25045. class PropertyBinding {
  25046. constructor( rootNode, path, parsedPath ) {
  25047. this.path = path;
  25048. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  25049. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  25050. this.rootNode = rootNode;
  25051. // initial state of these methods that calls 'bind'
  25052. this.getValue = this._getValue_unbound;
  25053. this.setValue = this._setValue_unbound;
  25054. }
  25055. static create( root, path, parsedPath ) {
  25056. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  25057. return new PropertyBinding( root, path, parsedPath );
  25058. } else {
  25059. return new PropertyBinding.Composite( root, path, parsedPath );
  25060. }
  25061. }
  25062. /**
  25063. * Replaces spaces with underscores and removes unsupported characters from
  25064. * node names, to ensure compatibility with parseTrackName().
  25065. *
  25066. * @param {string} name Node name to be sanitized.
  25067. * @return {string}
  25068. */
  25069. static sanitizeNodeName( name ) {
  25070. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  25071. }
  25072. static parseTrackName( trackName ) {
  25073. const matches = _trackRe.exec( trackName );
  25074. if ( ! matches ) {
  25075. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  25076. }
  25077. const results = {
  25078. // directoryName: matches[ 1 ], // (tschw) currently unused
  25079. nodeName: matches[ 2 ],
  25080. objectName: matches[ 3 ],
  25081. objectIndex: matches[ 4 ],
  25082. propertyName: matches[ 5 ], // required
  25083. propertyIndex: matches[ 6 ]
  25084. };
  25085. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  25086. if ( lastDot !== undefined && lastDot !== - 1 ) {
  25087. const objectName = results.nodeName.substring( lastDot + 1 );
  25088. // Object names must be checked against an allowlist. Otherwise, there
  25089. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25090. // 'bar' could be the objectName, or part of a nodeName (which can
  25091. // include '.' characters).
  25092. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  25093. results.nodeName = results.nodeName.substring( 0, lastDot );
  25094. results.objectName = objectName;
  25095. }
  25096. }
  25097. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  25098. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  25099. }
  25100. return results;
  25101. }
  25102. static findNode( root, nodeName ) {
  25103. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  25104. return root;
  25105. }
  25106. // search into skeleton bones.
  25107. if ( root.skeleton ) {
  25108. const bone = root.skeleton.getBoneByName( nodeName );
  25109. if ( bone !== undefined ) {
  25110. return bone;
  25111. }
  25112. }
  25113. // search into node subtree.
  25114. if ( root.children ) {
  25115. const searchNodeSubtree = function ( children ) {
  25116. for ( let i = 0; i < children.length; i ++ ) {
  25117. const childNode = children[ i ];
  25118. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  25119. return childNode;
  25120. }
  25121. const result = searchNodeSubtree( childNode.children );
  25122. if ( result ) return result;
  25123. }
  25124. return null;
  25125. };
  25126. const subTreeNode = searchNodeSubtree( root.children );
  25127. if ( subTreeNode ) {
  25128. return subTreeNode;
  25129. }
  25130. }
  25131. return null;
  25132. }
  25133. // these are used to "bind" a nonexistent property
  25134. _getValue_unavailable() {}
  25135. _setValue_unavailable() {}
  25136. // Getters
  25137. _getValue_direct( buffer, offset ) {
  25138. buffer[ offset ] = this.node[ this.propertyName ];
  25139. }
  25140. _getValue_array( buffer, offset ) {
  25141. const source = this.resolvedProperty;
  25142. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  25143. buffer[ offset ++ ] = source[ i ];
  25144. }
  25145. }
  25146. _getValue_arrayElement( buffer, offset ) {
  25147. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  25148. }
  25149. _getValue_toArray( buffer, offset ) {
  25150. this.resolvedProperty.toArray( buffer, offset );
  25151. }
  25152. // Direct
  25153. _setValue_direct( buffer, offset ) {
  25154. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25155. }
  25156. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  25157. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25158. this.targetObject.needsUpdate = true;
  25159. }
  25160. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25161. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25162. this.targetObject.matrixWorldNeedsUpdate = true;
  25163. }
  25164. // EntireArray
  25165. _setValue_array( buffer, offset ) {
  25166. const dest = this.resolvedProperty;
  25167. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25168. dest[ i ] = buffer[ offset ++ ];
  25169. }
  25170. }
  25171. _setValue_array_setNeedsUpdate( buffer, offset ) {
  25172. const dest = this.resolvedProperty;
  25173. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25174. dest[ i ] = buffer[ offset ++ ];
  25175. }
  25176. this.targetObject.needsUpdate = true;
  25177. }
  25178. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25179. const dest = this.resolvedProperty;
  25180. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25181. dest[ i ] = buffer[ offset ++ ];
  25182. }
  25183. this.targetObject.matrixWorldNeedsUpdate = true;
  25184. }
  25185. // ArrayElement
  25186. _setValue_arrayElement( buffer, offset ) {
  25187. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25188. }
  25189. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  25190. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25191. this.targetObject.needsUpdate = true;
  25192. }
  25193. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25194. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25195. this.targetObject.matrixWorldNeedsUpdate = true;
  25196. }
  25197. // HasToFromArray
  25198. _setValue_fromArray( buffer, offset ) {
  25199. this.resolvedProperty.fromArray( buffer, offset );
  25200. }
  25201. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  25202. this.resolvedProperty.fromArray( buffer, offset );
  25203. this.targetObject.needsUpdate = true;
  25204. }
  25205. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25206. this.resolvedProperty.fromArray( buffer, offset );
  25207. this.targetObject.matrixWorldNeedsUpdate = true;
  25208. }
  25209. _getValue_unbound( targetArray, offset ) {
  25210. this.bind();
  25211. this.getValue( targetArray, offset );
  25212. }
  25213. _setValue_unbound( sourceArray, offset ) {
  25214. this.bind();
  25215. this.setValue( sourceArray, offset );
  25216. }
  25217. // create getter / setter pair for a property in the scene graph
  25218. bind() {
  25219. let targetObject = this.node;
  25220. const parsedPath = this.parsedPath;
  25221. const objectName = parsedPath.objectName;
  25222. const propertyName = parsedPath.propertyName;
  25223. let propertyIndex = parsedPath.propertyIndex;
  25224. if ( ! targetObject ) {
  25225. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  25226. this.node = targetObject;
  25227. }
  25228. // set fail state so we can just 'return' on error
  25229. this.getValue = this._getValue_unavailable;
  25230. this.setValue = this._setValue_unavailable;
  25231. // ensure there is a value node
  25232. if ( ! targetObject ) {
  25233. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  25234. return;
  25235. }
  25236. if ( objectName ) {
  25237. let objectIndex = parsedPath.objectIndex;
  25238. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25239. switch ( objectName ) {
  25240. case 'materials':
  25241. if ( ! targetObject.material ) {
  25242. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  25243. return;
  25244. }
  25245. if ( ! targetObject.material.materials ) {
  25246. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  25247. return;
  25248. }
  25249. targetObject = targetObject.material.materials;
  25250. break;
  25251. case 'bones':
  25252. if ( ! targetObject.skeleton ) {
  25253. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  25254. return;
  25255. }
  25256. // potential future optimization: skip this if propertyIndex is already an integer
  25257. // and convert the integer string to a true integer.
  25258. targetObject = targetObject.skeleton.bones;
  25259. // support resolving morphTarget names into indices.
  25260. for ( let i = 0; i < targetObject.length; i ++ ) {
  25261. if ( targetObject[ i ].name === objectIndex ) {
  25262. objectIndex = i;
  25263. break;
  25264. }
  25265. }
  25266. break;
  25267. default:
  25268. if ( targetObject[ objectName ] === undefined ) {
  25269. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  25270. return;
  25271. }
  25272. targetObject = targetObject[ objectName ];
  25273. }
  25274. if ( objectIndex !== undefined ) {
  25275. if ( targetObject[ objectIndex ] === undefined ) {
  25276. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  25277. return;
  25278. }
  25279. targetObject = targetObject[ objectIndex ];
  25280. }
  25281. }
  25282. // resolve property
  25283. const nodeProperty = targetObject[ propertyName ];
  25284. if ( nodeProperty === undefined ) {
  25285. const nodeName = parsedPath.nodeName;
  25286. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  25287. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  25288. return;
  25289. }
  25290. // determine versioning scheme
  25291. let versioning = this.Versioning.None;
  25292. this.targetObject = targetObject;
  25293. if ( targetObject.needsUpdate !== undefined ) { // material
  25294. versioning = this.Versioning.NeedsUpdate;
  25295. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  25296. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25297. }
  25298. // determine how the property gets bound
  25299. let bindingType = this.BindingType.Direct;
  25300. if ( propertyIndex !== undefined ) {
  25301. // access a sub element of the property array (only primitives are supported right now)
  25302. if ( propertyName === 'morphTargetInfluences' ) {
  25303. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25304. // support resolving morphTarget names into indices.
  25305. if ( ! targetObject.geometry ) {
  25306. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  25307. return;
  25308. }
  25309. if ( targetObject.geometry.isBufferGeometry ) {
  25310. if ( ! targetObject.geometry.morphAttributes ) {
  25311. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  25312. return;
  25313. }
  25314. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  25315. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  25316. }
  25317. } else {
  25318. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  25319. return;
  25320. }
  25321. }
  25322. bindingType = this.BindingType.ArrayElement;
  25323. this.resolvedProperty = nodeProperty;
  25324. this.propertyIndex = propertyIndex;
  25325. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  25326. // must use copy for Object3D.Euler/Quaternion
  25327. bindingType = this.BindingType.HasFromToArray;
  25328. this.resolvedProperty = nodeProperty;
  25329. } else if ( Array.isArray( nodeProperty ) ) {
  25330. bindingType = this.BindingType.EntireArray;
  25331. this.resolvedProperty = nodeProperty;
  25332. } else {
  25333. this.propertyName = propertyName;
  25334. }
  25335. // select getter / setter
  25336. this.getValue = this.GetterByBindingType[ bindingType ];
  25337. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  25338. }
  25339. unbind() {
  25340. this.node = null;
  25341. // back to the prototype version of getValue / setValue
  25342. // note: avoiding to mutate the shape of 'this' via 'delete'
  25343. this.getValue = this._getValue_unbound;
  25344. this.setValue = this._setValue_unbound;
  25345. }
  25346. }
  25347. PropertyBinding.Composite = Composite;
  25348. PropertyBinding.prototype.BindingType = {
  25349. Direct: 0,
  25350. EntireArray: 1,
  25351. ArrayElement: 2,
  25352. HasFromToArray: 3
  25353. };
  25354. PropertyBinding.prototype.Versioning = {
  25355. None: 0,
  25356. NeedsUpdate: 1,
  25357. MatrixWorldNeedsUpdate: 2
  25358. };
  25359. PropertyBinding.prototype.GetterByBindingType = [
  25360. PropertyBinding.prototype._getValue_direct,
  25361. PropertyBinding.prototype._getValue_array,
  25362. PropertyBinding.prototype._getValue_arrayElement,
  25363. PropertyBinding.prototype._getValue_toArray,
  25364. ];
  25365. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  25366. [
  25367. // Direct
  25368. PropertyBinding.prototype._setValue_direct,
  25369. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  25370. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  25371. ], [
  25372. // EntireArray
  25373. PropertyBinding.prototype._setValue_array,
  25374. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  25375. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  25376. ], [
  25377. // ArrayElement
  25378. PropertyBinding.prototype._setValue_arrayElement,
  25379. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  25380. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  25381. ], [
  25382. // HasToFromArray
  25383. PropertyBinding.prototype._setValue_fromArray,
  25384. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  25385. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  25386. ]
  25387. ];
  25388. /**
  25389. *
  25390. * A group of objects that receives a shared animation state.
  25391. *
  25392. * Usage:
  25393. *
  25394. * - Add objects you would otherwise pass as 'root' to the
  25395. * constructor or the .clipAction method of AnimationMixer.
  25396. *
  25397. * - Instead pass this object as 'root'.
  25398. *
  25399. * - You can also add and remove objects later when the mixer
  25400. * is running.
  25401. *
  25402. * Note:
  25403. *
  25404. * Objects of this class appear as one object to the mixer,
  25405. * so cache control of the individual objects must be done
  25406. * on the group.
  25407. *
  25408. * Limitation:
  25409. *
  25410. * - The animated properties must be compatible among the
  25411. * all objects in the group.
  25412. *
  25413. * - A single property can either be controlled through a
  25414. * target group or directly, but not both.
  25415. */
  25416. class AnimationObjectGroup {
  25417. constructor() {
  25418. this.uuid = generateUUID();
  25419. // cached objects followed by the active ones
  25420. this._objects = Array.prototype.slice.call( arguments );
  25421. this.nCachedObjects_ = 0; // threshold
  25422. // note: read by PropertyBinding.Composite
  25423. const indices = {};
  25424. this._indicesByUUID = indices; // for bookkeeping
  25425. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25426. indices[ arguments[ i ].uuid ] = i;
  25427. }
  25428. this._paths = []; // inside: string
  25429. this._parsedPaths = []; // inside: { we don't care, here }
  25430. this._bindings = []; // inside: Array< PropertyBinding >
  25431. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25432. const scope = this;
  25433. this.stats = {
  25434. objects: {
  25435. get total() {
  25436. return scope._objects.length;
  25437. },
  25438. get inUse() {
  25439. return this.total - scope.nCachedObjects_;
  25440. }
  25441. },
  25442. get bindingsPerObject() {
  25443. return scope._bindings.length;
  25444. }
  25445. };
  25446. }
  25447. add() {
  25448. const objects = this._objects,
  25449. indicesByUUID = this._indicesByUUID,
  25450. paths = this._paths,
  25451. parsedPaths = this._parsedPaths,
  25452. bindings = this._bindings,
  25453. nBindings = bindings.length;
  25454. let knownObject = undefined,
  25455. nObjects = objects.length,
  25456. nCachedObjects = this.nCachedObjects_;
  25457. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25458. const object = arguments[ i ],
  25459. uuid = object.uuid;
  25460. let index = indicesByUUID[ uuid ];
  25461. if ( index === undefined ) {
  25462. // unknown object -> add it to the ACTIVE region
  25463. index = nObjects ++;
  25464. indicesByUUID[ uuid ] = index;
  25465. objects.push( object );
  25466. // accounting is done, now do the same for all bindings
  25467. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25468. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  25469. }
  25470. } else if ( index < nCachedObjects ) {
  25471. knownObject = objects[ index ];
  25472. // move existing object to the ACTIVE region
  25473. const firstActiveIndex = -- nCachedObjects,
  25474. lastCachedObject = objects[ firstActiveIndex ];
  25475. indicesByUUID[ lastCachedObject.uuid ] = index;
  25476. objects[ index ] = lastCachedObject;
  25477. indicesByUUID[ uuid ] = firstActiveIndex;
  25478. objects[ firstActiveIndex ] = object;
  25479. // accounting is done, now do the same for all bindings
  25480. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25481. const bindingsForPath = bindings[ j ],
  25482. lastCached = bindingsForPath[ firstActiveIndex ];
  25483. let binding = bindingsForPath[ index ];
  25484. bindingsForPath[ index ] = lastCached;
  25485. if ( binding === undefined ) {
  25486. // since we do not bother to create new bindings
  25487. // for objects that are cached, the binding may
  25488. // or may not exist
  25489. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  25490. }
  25491. bindingsForPath[ firstActiveIndex ] = binding;
  25492. }
  25493. } else if ( objects[ index ] !== knownObject ) {
  25494. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  25495. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  25496. } // else the object is already where we want it to be
  25497. } // for arguments
  25498. this.nCachedObjects_ = nCachedObjects;
  25499. }
  25500. remove() {
  25501. const objects = this._objects,
  25502. indicesByUUID = this._indicesByUUID,
  25503. bindings = this._bindings,
  25504. nBindings = bindings.length;
  25505. let nCachedObjects = this.nCachedObjects_;
  25506. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25507. const object = arguments[ i ],
  25508. uuid = object.uuid,
  25509. index = indicesByUUID[ uuid ];
  25510. if ( index !== undefined && index >= nCachedObjects ) {
  25511. // move existing object into the CACHED region
  25512. const lastCachedIndex = nCachedObjects ++,
  25513. firstActiveObject = objects[ lastCachedIndex ];
  25514. indicesByUUID[ firstActiveObject.uuid ] = index;
  25515. objects[ index ] = firstActiveObject;
  25516. indicesByUUID[ uuid ] = lastCachedIndex;
  25517. objects[ lastCachedIndex ] = object;
  25518. // accounting is done, now do the same for all bindings
  25519. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25520. const bindingsForPath = bindings[ j ],
  25521. firstActive = bindingsForPath[ lastCachedIndex ],
  25522. binding = bindingsForPath[ index ];
  25523. bindingsForPath[ index ] = firstActive;
  25524. bindingsForPath[ lastCachedIndex ] = binding;
  25525. }
  25526. }
  25527. } // for arguments
  25528. this.nCachedObjects_ = nCachedObjects;
  25529. }
  25530. // remove & forget
  25531. uncache() {
  25532. const objects = this._objects,
  25533. indicesByUUID = this._indicesByUUID,
  25534. bindings = this._bindings,
  25535. nBindings = bindings.length;
  25536. let nCachedObjects = this.nCachedObjects_,
  25537. nObjects = objects.length;
  25538. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25539. const object = arguments[ i ],
  25540. uuid = object.uuid,
  25541. index = indicesByUUID[ uuid ];
  25542. if ( index !== undefined ) {
  25543. delete indicesByUUID[ uuid ];
  25544. if ( index < nCachedObjects ) {
  25545. // object is cached, shrink the CACHED region
  25546. const firstActiveIndex = -- nCachedObjects,
  25547. lastCachedObject = objects[ firstActiveIndex ],
  25548. lastIndex = -- nObjects,
  25549. lastObject = objects[ lastIndex ];
  25550. // last cached object takes this object's place
  25551. indicesByUUID[ lastCachedObject.uuid ] = index;
  25552. objects[ index ] = lastCachedObject;
  25553. // last object goes to the activated slot and pop
  25554. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  25555. objects[ firstActiveIndex ] = lastObject;
  25556. objects.pop();
  25557. // accounting is done, now do the same for all bindings
  25558. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25559. const bindingsForPath = bindings[ j ],
  25560. lastCached = bindingsForPath[ firstActiveIndex ],
  25561. last = bindingsForPath[ lastIndex ];
  25562. bindingsForPath[ index ] = lastCached;
  25563. bindingsForPath[ firstActiveIndex ] = last;
  25564. bindingsForPath.pop();
  25565. }
  25566. } else {
  25567. // object is active, just swap with the last and pop
  25568. const lastIndex = -- nObjects,
  25569. lastObject = objects[ lastIndex ];
  25570. if ( lastIndex > 0 ) {
  25571. indicesByUUID[ lastObject.uuid ] = index;
  25572. }
  25573. objects[ index ] = lastObject;
  25574. objects.pop();
  25575. // accounting is done, now do the same for all bindings
  25576. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25577. const bindingsForPath = bindings[ j ];
  25578. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  25579. bindingsForPath.pop();
  25580. }
  25581. } // cached or active
  25582. } // if object is known
  25583. } // for arguments
  25584. this.nCachedObjects_ = nCachedObjects;
  25585. }
  25586. // Internal interface used by befriended PropertyBinding.Composite:
  25587. subscribe_( path, parsedPath ) {
  25588. // returns an array of bindings for the given path that is changed
  25589. // according to the contained objects in the group
  25590. const indicesByPath = this._bindingsIndicesByPath;
  25591. let index = indicesByPath[ path ];
  25592. const bindings = this._bindings;
  25593. if ( index !== undefined ) return bindings[ index ];
  25594. const paths = this._paths,
  25595. parsedPaths = this._parsedPaths,
  25596. objects = this._objects,
  25597. nObjects = objects.length,
  25598. nCachedObjects = this.nCachedObjects_,
  25599. bindingsForPath = new Array( nObjects );
  25600. index = bindings.length;
  25601. indicesByPath[ path ] = index;
  25602. paths.push( path );
  25603. parsedPaths.push( parsedPath );
  25604. bindings.push( bindingsForPath );
  25605. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  25606. const object = objects[ i ];
  25607. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  25608. }
  25609. return bindingsForPath;
  25610. }
  25611. unsubscribe_( path ) {
  25612. // tells the group to forget about a property path and no longer
  25613. // update the array previously obtained with 'subscribe_'
  25614. const indicesByPath = this._bindingsIndicesByPath,
  25615. index = indicesByPath[ path ];
  25616. if ( index !== undefined ) {
  25617. const paths = this._paths,
  25618. parsedPaths = this._parsedPaths,
  25619. bindings = this._bindings,
  25620. lastBindingsIndex = bindings.length - 1,
  25621. lastBindings = bindings[ lastBindingsIndex ],
  25622. lastBindingsPath = path[ lastBindingsIndex ];
  25623. indicesByPath[ lastBindingsPath ] = index;
  25624. bindings[ index ] = lastBindings;
  25625. bindings.pop();
  25626. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  25627. parsedPaths.pop();
  25628. paths[ index ] = paths[ lastBindingsIndex ];
  25629. paths.pop();
  25630. }
  25631. }
  25632. }
  25633. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25634. class AnimationAction {
  25635. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  25636. this._mixer = mixer;
  25637. this._clip = clip;
  25638. this._localRoot = localRoot;
  25639. this.blendMode = blendMode;
  25640. const tracks = clip.tracks,
  25641. nTracks = tracks.length,
  25642. interpolants = new Array( nTracks );
  25643. const interpolantSettings = {
  25644. endingStart: ZeroCurvatureEnding,
  25645. endingEnd: ZeroCurvatureEnding
  25646. };
  25647. for ( let i = 0; i !== nTracks; ++ i ) {
  25648. const interpolant = tracks[ i ].createInterpolant( null );
  25649. interpolants[ i ] = interpolant;
  25650. interpolant.settings = interpolantSettings;
  25651. }
  25652. this._interpolantSettings = interpolantSettings;
  25653. this._interpolants = interpolants; // bound by the mixer
  25654. // inside: PropertyMixer (managed by the mixer)
  25655. this._propertyBindings = new Array( nTracks );
  25656. this._cacheIndex = null; // for the memory manager
  25657. this._byClipCacheIndex = null; // for the memory manager
  25658. this._timeScaleInterpolant = null;
  25659. this._weightInterpolant = null;
  25660. this.loop = LoopRepeat;
  25661. this._loopCount = - 1;
  25662. // global mixer time when the action is to be started
  25663. // it's set back to 'null' upon start of the action
  25664. this._startTime = null;
  25665. // scaled local time of the action
  25666. // gets clamped or wrapped to 0..clip.duration according to loop
  25667. this.time = 0;
  25668. this.timeScale = 1;
  25669. this._effectiveTimeScale = 1;
  25670. this.weight = 1;
  25671. this._effectiveWeight = 1;
  25672. this.repetitions = Infinity; // no. of repetitions when looping
  25673. this.paused = false; // true -> zero effective time scale
  25674. this.enabled = true; // false -> zero effective weight
  25675. this.clampWhenFinished = false;// keep feeding the last frame?
  25676. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  25677. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  25678. }
  25679. // State & Scheduling
  25680. play() {
  25681. this._mixer._activateAction( this );
  25682. return this;
  25683. }
  25684. stop() {
  25685. this._mixer._deactivateAction( this );
  25686. return this.reset();
  25687. }
  25688. reset() {
  25689. this.paused = false;
  25690. this.enabled = true;
  25691. this.time = 0; // restart clip
  25692. this._loopCount = - 1;// forget previous loops
  25693. this._startTime = null;// forget scheduling
  25694. return this.stopFading().stopWarping();
  25695. }
  25696. isRunning() {
  25697. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  25698. this._startTime === null && this._mixer._isActiveAction( this );
  25699. }
  25700. // return true when play has been called
  25701. isScheduled() {
  25702. return this._mixer._isActiveAction( this );
  25703. }
  25704. startAt( time ) {
  25705. this._startTime = time;
  25706. return this;
  25707. }
  25708. setLoop( mode, repetitions ) {
  25709. this.loop = mode;
  25710. this.repetitions = repetitions;
  25711. return this;
  25712. }
  25713. // Weight
  25714. // set the weight stopping any scheduled fading
  25715. // although .enabled = false yields an effective weight of zero, this
  25716. // method does *not* change .enabled, because it would be confusing
  25717. setEffectiveWeight( weight ) {
  25718. this.weight = weight;
  25719. // note: same logic as when updated at runtime
  25720. this._effectiveWeight = this.enabled ? weight : 0;
  25721. return this.stopFading();
  25722. }
  25723. // return the weight considering fading and .enabled
  25724. getEffectiveWeight() {
  25725. return this._effectiveWeight;
  25726. }
  25727. fadeIn( duration ) {
  25728. return this._scheduleFading( duration, 0, 1 );
  25729. }
  25730. fadeOut( duration ) {
  25731. return this._scheduleFading( duration, 1, 0 );
  25732. }
  25733. crossFadeFrom( fadeOutAction, duration, warp ) {
  25734. fadeOutAction.fadeOut( duration );
  25735. this.fadeIn( duration );
  25736. if ( warp ) {
  25737. const fadeInDuration = this._clip.duration,
  25738. fadeOutDuration = fadeOutAction._clip.duration,
  25739. startEndRatio = fadeOutDuration / fadeInDuration,
  25740. endStartRatio = fadeInDuration / fadeOutDuration;
  25741. fadeOutAction.warp( 1.0, startEndRatio, duration );
  25742. this.warp( endStartRatio, 1.0, duration );
  25743. }
  25744. return this;
  25745. }
  25746. crossFadeTo( fadeInAction, duration, warp ) {
  25747. return fadeInAction.crossFadeFrom( this, duration, warp );
  25748. }
  25749. stopFading() {
  25750. const weightInterpolant = this._weightInterpolant;
  25751. if ( weightInterpolant !== null ) {
  25752. this._weightInterpolant = null;
  25753. this._mixer._takeBackControlInterpolant( weightInterpolant );
  25754. }
  25755. return this;
  25756. }
  25757. // Time Scale Control
  25758. // set the time scale stopping any scheduled warping
  25759. // although .paused = true yields an effective time scale of zero, this
  25760. // method does *not* change .paused, because it would be confusing
  25761. setEffectiveTimeScale( timeScale ) {
  25762. this.timeScale = timeScale;
  25763. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25764. return this.stopWarping();
  25765. }
  25766. // return the time scale considering warping and .paused
  25767. getEffectiveTimeScale() {
  25768. return this._effectiveTimeScale;
  25769. }
  25770. setDuration( duration ) {
  25771. this.timeScale = this._clip.duration / duration;
  25772. return this.stopWarping();
  25773. }
  25774. syncWith( action ) {
  25775. this.time = action.time;
  25776. this.timeScale = action.timeScale;
  25777. return this.stopWarping();
  25778. }
  25779. halt( duration ) {
  25780. return this.warp( this._effectiveTimeScale, 0, duration );
  25781. }
  25782. warp( startTimeScale, endTimeScale, duration ) {
  25783. const mixer = this._mixer,
  25784. now = mixer.time,
  25785. timeScale = this.timeScale;
  25786. let interpolant = this._timeScaleInterpolant;
  25787. if ( interpolant === null ) {
  25788. interpolant = mixer._lendControlInterpolant();
  25789. this._timeScaleInterpolant = interpolant;
  25790. }
  25791. const times = interpolant.parameterPositions,
  25792. values = interpolant.sampleValues;
  25793. times[ 0 ] = now;
  25794. times[ 1 ] = now + duration;
  25795. values[ 0 ] = startTimeScale / timeScale;
  25796. values[ 1 ] = endTimeScale / timeScale;
  25797. return this;
  25798. }
  25799. stopWarping() {
  25800. const timeScaleInterpolant = this._timeScaleInterpolant;
  25801. if ( timeScaleInterpolant !== null ) {
  25802. this._timeScaleInterpolant = null;
  25803. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  25804. }
  25805. return this;
  25806. }
  25807. // Object Accessors
  25808. getMixer() {
  25809. return this._mixer;
  25810. }
  25811. getClip() {
  25812. return this._clip;
  25813. }
  25814. getRoot() {
  25815. return this._localRoot || this._mixer._root;
  25816. }
  25817. // Interna
  25818. _update( time, deltaTime, timeDirection, accuIndex ) {
  25819. // called by the mixer
  25820. if ( ! this.enabled ) {
  25821. // call ._updateWeight() to update ._effectiveWeight
  25822. this._updateWeight( time );
  25823. return;
  25824. }
  25825. const startTime = this._startTime;
  25826. if ( startTime !== null ) {
  25827. // check for scheduled start of action
  25828. const timeRunning = ( time - startTime ) * timeDirection;
  25829. if ( timeRunning < 0 || timeDirection === 0 ) {
  25830. return; // yet to come / don't decide when delta = 0
  25831. }
  25832. // start
  25833. this._startTime = null; // unschedule
  25834. deltaTime = timeDirection * timeRunning;
  25835. }
  25836. // apply time scale and advance time
  25837. deltaTime *= this._updateTimeScale( time );
  25838. const clipTime = this._updateTime( deltaTime );
  25839. // note: _updateTime may disable the action resulting in
  25840. // an effective weight of 0
  25841. const weight = this._updateWeight( time );
  25842. if ( weight > 0 ) {
  25843. const interpolants = this._interpolants;
  25844. const propertyMixers = this._propertyBindings;
  25845. switch ( this.blendMode ) {
  25846. case AdditiveAnimationBlendMode:
  25847. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  25848. interpolants[ j ].evaluate( clipTime );
  25849. propertyMixers[ j ].accumulateAdditive( weight );
  25850. }
  25851. break;
  25852. case NormalAnimationBlendMode:
  25853. default:
  25854. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  25855. interpolants[ j ].evaluate( clipTime );
  25856. propertyMixers[ j ].accumulate( accuIndex, weight );
  25857. }
  25858. }
  25859. }
  25860. }
  25861. _updateWeight( time ) {
  25862. let weight = 0;
  25863. if ( this.enabled ) {
  25864. weight = this.weight;
  25865. const interpolant = this._weightInterpolant;
  25866. if ( interpolant !== null ) {
  25867. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  25868. weight *= interpolantValue;
  25869. if ( time > interpolant.parameterPositions[ 1 ] ) {
  25870. this.stopFading();
  25871. if ( interpolantValue === 0 ) {
  25872. // faded out, disable
  25873. this.enabled = false;
  25874. }
  25875. }
  25876. }
  25877. }
  25878. this._effectiveWeight = weight;
  25879. return weight;
  25880. }
  25881. _updateTimeScale( time ) {
  25882. let timeScale = 0;
  25883. if ( ! this.paused ) {
  25884. timeScale = this.timeScale;
  25885. const interpolant = this._timeScaleInterpolant;
  25886. if ( interpolant !== null ) {
  25887. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  25888. timeScale *= interpolantValue;
  25889. if ( time > interpolant.parameterPositions[ 1 ] ) {
  25890. this.stopWarping();
  25891. if ( timeScale === 0 ) {
  25892. // motion has halted, pause
  25893. this.paused = true;
  25894. } else {
  25895. // warp done - apply final time scale
  25896. this.timeScale = timeScale;
  25897. }
  25898. }
  25899. }
  25900. }
  25901. this._effectiveTimeScale = timeScale;
  25902. return timeScale;
  25903. }
  25904. _updateTime( deltaTime ) {
  25905. const duration = this._clip.duration;
  25906. const loop = this.loop;
  25907. let time = this.time + deltaTime;
  25908. let loopCount = this._loopCount;
  25909. const pingPong = ( loop === LoopPingPong );
  25910. if ( deltaTime === 0 ) {
  25911. if ( loopCount === - 1 ) return time;
  25912. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  25913. }
  25914. if ( loop === LoopOnce ) {
  25915. if ( loopCount === - 1 ) {
  25916. // just started
  25917. this._loopCount = 0;
  25918. this._setEndings( true, true, false );
  25919. }
  25920. handle_stop: {
  25921. if ( time >= duration ) {
  25922. time = duration;
  25923. } else if ( time < 0 ) {
  25924. time = 0;
  25925. } else {
  25926. this.time = time;
  25927. break handle_stop;
  25928. }
  25929. if ( this.clampWhenFinished ) this.paused = true;
  25930. else this.enabled = false;
  25931. this.time = time;
  25932. this._mixer.dispatchEvent( {
  25933. type: 'finished', action: this,
  25934. direction: deltaTime < 0 ? - 1 : 1
  25935. } );
  25936. }
  25937. } else { // repetitive Repeat or PingPong
  25938. if ( loopCount === - 1 ) {
  25939. // just started
  25940. if ( deltaTime >= 0 ) {
  25941. loopCount = 0;
  25942. this._setEndings( true, this.repetitions === 0, pingPong );
  25943. } else {
  25944. // when looping in reverse direction, the initial
  25945. // transition through zero counts as a repetition,
  25946. // so leave loopCount at -1
  25947. this._setEndings( this.repetitions === 0, true, pingPong );
  25948. }
  25949. }
  25950. if ( time >= duration || time < 0 ) {
  25951. // wrap around
  25952. const loopDelta = Math.floor( time / duration ); // signed
  25953. time -= duration * loopDelta;
  25954. loopCount += Math.abs( loopDelta );
  25955. const pending = this.repetitions - loopCount;
  25956. if ( pending <= 0 ) {
  25957. // have to stop (switch state, clamp time, fire event)
  25958. if ( this.clampWhenFinished ) this.paused = true;
  25959. else this.enabled = false;
  25960. time = deltaTime > 0 ? duration : 0;
  25961. this.time = time;
  25962. this._mixer.dispatchEvent( {
  25963. type: 'finished', action: this,
  25964. direction: deltaTime > 0 ? 1 : - 1
  25965. } );
  25966. } else {
  25967. // keep running
  25968. if ( pending === 1 ) {
  25969. // entering the last round
  25970. const atStart = deltaTime < 0;
  25971. this._setEndings( atStart, ! atStart, pingPong );
  25972. } else {
  25973. this._setEndings( false, false, pingPong );
  25974. }
  25975. this._loopCount = loopCount;
  25976. this.time = time;
  25977. this._mixer.dispatchEvent( {
  25978. type: 'loop', action: this, loopDelta: loopDelta
  25979. } );
  25980. }
  25981. } else {
  25982. this.time = time;
  25983. }
  25984. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  25985. // invert time for the "pong round"
  25986. return duration - time;
  25987. }
  25988. }
  25989. return time;
  25990. }
  25991. _setEndings( atStart, atEnd, pingPong ) {
  25992. const settings = this._interpolantSettings;
  25993. if ( pingPong ) {
  25994. settings.endingStart = ZeroSlopeEnding;
  25995. settings.endingEnd = ZeroSlopeEnding;
  25996. } else {
  25997. // assuming for LoopOnce atStart == atEnd == true
  25998. if ( atStart ) {
  25999. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26000. } else {
  26001. settings.endingStart = WrapAroundEnding;
  26002. }
  26003. if ( atEnd ) {
  26004. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26005. } else {
  26006. settings.endingEnd = WrapAroundEnding;
  26007. }
  26008. }
  26009. }
  26010. _scheduleFading( duration, weightNow, weightThen ) {
  26011. const mixer = this._mixer, now = mixer.time;
  26012. let interpolant = this._weightInterpolant;
  26013. if ( interpolant === null ) {
  26014. interpolant = mixer._lendControlInterpolant();
  26015. this._weightInterpolant = interpolant;
  26016. }
  26017. const times = interpolant.parameterPositions,
  26018. values = interpolant.sampleValues;
  26019. times[ 0 ] = now;
  26020. values[ 0 ] = weightNow;
  26021. times[ 1 ] = now + duration;
  26022. values[ 1 ] = weightThen;
  26023. return this;
  26024. }
  26025. }
  26026. class AnimationMixer extends EventDispatcher {
  26027. constructor( root ) {
  26028. super();
  26029. this._root = root;
  26030. this._initMemoryManager();
  26031. this._accuIndex = 0;
  26032. this.time = 0;
  26033. this.timeScale = 1.0;
  26034. }
  26035. _bindAction( action, prototypeAction ) {
  26036. const root = action._localRoot || this._root,
  26037. tracks = action._clip.tracks,
  26038. nTracks = tracks.length,
  26039. bindings = action._propertyBindings,
  26040. interpolants = action._interpolants,
  26041. rootUuid = root.uuid,
  26042. bindingsByRoot = this._bindingsByRootAndName;
  26043. let bindingsByName = bindingsByRoot[ rootUuid ];
  26044. if ( bindingsByName === undefined ) {
  26045. bindingsByName = {};
  26046. bindingsByRoot[ rootUuid ] = bindingsByName;
  26047. }
  26048. for ( let i = 0; i !== nTracks; ++ i ) {
  26049. const track = tracks[ i ],
  26050. trackName = track.name;
  26051. let binding = bindingsByName[ trackName ];
  26052. if ( binding !== undefined ) {
  26053. bindings[ i ] = binding;
  26054. } else {
  26055. binding = bindings[ i ];
  26056. if ( binding !== undefined ) {
  26057. // existing binding, make sure the cache knows
  26058. if ( binding._cacheIndex === null ) {
  26059. ++ binding.referenceCount;
  26060. this._addInactiveBinding( binding, rootUuid, trackName );
  26061. }
  26062. continue;
  26063. }
  26064. const path = prototypeAction && prototypeAction.
  26065. _propertyBindings[ i ].binding.parsedPath;
  26066. binding = new PropertyMixer(
  26067. PropertyBinding.create( root, trackName, path ),
  26068. track.ValueTypeName, track.getValueSize() );
  26069. ++ binding.referenceCount;
  26070. this._addInactiveBinding( binding, rootUuid, trackName );
  26071. bindings[ i ] = binding;
  26072. }
  26073. interpolants[ i ].resultBuffer = binding.buffer;
  26074. }
  26075. }
  26076. _activateAction( action ) {
  26077. if ( ! this._isActiveAction( action ) ) {
  26078. if ( action._cacheIndex === null ) {
  26079. // this action has been forgotten by the cache, but the user
  26080. // appears to be still using it -> rebind
  26081. const rootUuid = ( action._localRoot || this._root ).uuid,
  26082. clipUuid = action._clip.uuid,
  26083. actionsForClip = this._actionsByClip[ clipUuid ];
  26084. this._bindAction( action,
  26085. actionsForClip && actionsForClip.knownActions[ 0 ] );
  26086. this._addInactiveAction( action, clipUuid, rootUuid );
  26087. }
  26088. const bindings = action._propertyBindings;
  26089. // increment reference counts / sort out state
  26090. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26091. const binding = bindings[ i ];
  26092. if ( binding.useCount ++ === 0 ) {
  26093. this._lendBinding( binding );
  26094. binding.saveOriginalState();
  26095. }
  26096. }
  26097. this._lendAction( action );
  26098. }
  26099. }
  26100. _deactivateAction( action ) {
  26101. if ( this._isActiveAction( action ) ) {
  26102. const bindings = action._propertyBindings;
  26103. // decrement reference counts / sort out state
  26104. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26105. const binding = bindings[ i ];
  26106. if ( -- binding.useCount === 0 ) {
  26107. binding.restoreOriginalState();
  26108. this._takeBackBinding( binding );
  26109. }
  26110. }
  26111. this._takeBackAction( action );
  26112. }
  26113. }
  26114. // Memory manager
  26115. _initMemoryManager() {
  26116. this._actions = []; // 'nActiveActions' followed by inactive ones
  26117. this._nActiveActions = 0;
  26118. this._actionsByClip = {};
  26119. // inside:
  26120. // {
  26121. // knownActions: Array< AnimationAction > - used as prototypes
  26122. // actionByRoot: AnimationAction - lookup
  26123. // }
  26124. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26125. this._nActiveBindings = 0;
  26126. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26127. this._controlInterpolants = []; // same game as above
  26128. this._nActiveControlInterpolants = 0;
  26129. const scope = this;
  26130. this.stats = {
  26131. actions: {
  26132. get total() {
  26133. return scope._actions.length;
  26134. },
  26135. get inUse() {
  26136. return scope._nActiveActions;
  26137. }
  26138. },
  26139. bindings: {
  26140. get total() {
  26141. return scope._bindings.length;
  26142. },
  26143. get inUse() {
  26144. return scope._nActiveBindings;
  26145. }
  26146. },
  26147. controlInterpolants: {
  26148. get total() {
  26149. return scope._controlInterpolants.length;
  26150. },
  26151. get inUse() {
  26152. return scope._nActiveControlInterpolants;
  26153. }
  26154. }
  26155. };
  26156. }
  26157. // Memory management for AnimationAction objects
  26158. _isActiveAction( action ) {
  26159. const index = action._cacheIndex;
  26160. return index !== null && index < this._nActiveActions;
  26161. }
  26162. _addInactiveAction( action, clipUuid, rootUuid ) {
  26163. const actions = this._actions,
  26164. actionsByClip = this._actionsByClip;
  26165. let actionsForClip = actionsByClip[ clipUuid ];
  26166. if ( actionsForClip === undefined ) {
  26167. actionsForClip = {
  26168. knownActions: [ action ],
  26169. actionByRoot: {}
  26170. };
  26171. action._byClipCacheIndex = 0;
  26172. actionsByClip[ clipUuid ] = actionsForClip;
  26173. } else {
  26174. const knownActions = actionsForClip.knownActions;
  26175. action._byClipCacheIndex = knownActions.length;
  26176. knownActions.push( action );
  26177. }
  26178. action._cacheIndex = actions.length;
  26179. actions.push( action );
  26180. actionsForClip.actionByRoot[ rootUuid ] = action;
  26181. }
  26182. _removeInactiveAction( action ) {
  26183. const actions = this._actions,
  26184. lastInactiveAction = actions[ actions.length - 1 ],
  26185. cacheIndex = action._cacheIndex;
  26186. lastInactiveAction._cacheIndex = cacheIndex;
  26187. actions[ cacheIndex ] = lastInactiveAction;
  26188. actions.pop();
  26189. action._cacheIndex = null;
  26190. const clipUuid = action._clip.uuid,
  26191. actionsByClip = this._actionsByClip,
  26192. actionsForClip = actionsByClip[ clipUuid ],
  26193. knownActionsForClip = actionsForClip.knownActions,
  26194. lastKnownAction =
  26195. knownActionsForClip[ knownActionsForClip.length - 1 ],
  26196. byClipCacheIndex = action._byClipCacheIndex;
  26197. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26198. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  26199. knownActionsForClip.pop();
  26200. action._byClipCacheIndex = null;
  26201. const actionByRoot = actionsForClip.actionByRoot,
  26202. rootUuid = ( action._localRoot || this._root ).uuid;
  26203. delete actionByRoot[ rootUuid ];
  26204. if ( knownActionsForClip.length === 0 ) {
  26205. delete actionsByClip[ clipUuid ];
  26206. }
  26207. this._removeInactiveBindingsForAction( action );
  26208. }
  26209. _removeInactiveBindingsForAction( action ) {
  26210. const bindings = action._propertyBindings;
  26211. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26212. const binding = bindings[ i ];
  26213. if ( -- binding.referenceCount === 0 ) {
  26214. this._removeInactiveBinding( binding );
  26215. }
  26216. }
  26217. }
  26218. _lendAction( action ) {
  26219. // [ active actions | inactive actions ]
  26220. // [ active actions >| inactive actions ]
  26221. // s a
  26222. // <-swap->
  26223. // a s
  26224. const actions = this._actions,
  26225. prevIndex = action._cacheIndex,
  26226. lastActiveIndex = this._nActiveActions ++,
  26227. firstInactiveAction = actions[ lastActiveIndex ];
  26228. action._cacheIndex = lastActiveIndex;
  26229. actions[ lastActiveIndex ] = action;
  26230. firstInactiveAction._cacheIndex = prevIndex;
  26231. actions[ prevIndex ] = firstInactiveAction;
  26232. }
  26233. _takeBackAction( action ) {
  26234. // [ active actions | inactive actions ]
  26235. // [ active actions |< inactive actions ]
  26236. // a s
  26237. // <-swap->
  26238. // s a
  26239. const actions = this._actions,
  26240. prevIndex = action._cacheIndex,
  26241. firstInactiveIndex = -- this._nActiveActions,
  26242. lastActiveAction = actions[ firstInactiveIndex ];
  26243. action._cacheIndex = firstInactiveIndex;
  26244. actions[ firstInactiveIndex ] = action;
  26245. lastActiveAction._cacheIndex = prevIndex;
  26246. actions[ prevIndex ] = lastActiveAction;
  26247. }
  26248. // Memory management for PropertyMixer objects
  26249. _addInactiveBinding( binding, rootUuid, trackName ) {
  26250. const bindingsByRoot = this._bindingsByRootAndName,
  26251. bindings = this._bindings;
  26252. let bindingByName = bindingsByRoot[ rootUuid ];
  26253. if ( bindingByName === undefined ) {
  26254. bindingByName = {};
  26255. bindingsByRoot[ rootUuid ] = bindingByName;
  26256. }
  26257. bindingByName[ trackName ] = binding;
  26258. binding._cacheIndex = bindings.length;
  26259. bindings.push( binding );
  26260. }
  26261. _removeInactiveBinding( binding ) {
  26262. const bindings = this._bindings,
  26263. propBinding = binding.binding,
  26264. rootUuid = propBinding.rootNode.uuid,
  26265. trackName = propBinding.path,
  26266. bindingsByRoot = this._bindingsByRootAndName,
  26267. bindingByName = bindingsByRoot[ rootUuid ],
  26268. lastInactiveBinding = bindings[ bindings.length - 1 ],
  26269. cacheIndex = binding._cacheIndex;
  26270. lastInactiveBinding._cacheIndex = cacheIndex;
  26271. bindings[ cacheIndex ] = lastInactiveBinding;
  26272. bindings.pop();
  26273. delete bindingByName[ trackName ];
  26274. if ( Object.keys( bindingByName ).length === 0 ) {
  26275. delete bindingsByRoot[ rootUuid ];
  26276. }
  26277. }
  26278. _lendBinding( binding ) {
  26279. const bindings = this._bindings,
  26280. prevIndex = binding._cacheIndex,
  26281. lastActiveIndex = this._nActiveBindings ++,
  26282. firstInactiveBinding = bindings[ lastActiveIndex ];
  26283. binding._cacheIndex = lastActiveIndex;
  26284. bindings[ lastActiveIndex ] = binding;
  26285. firstInactiveBinding._cacheIndex = prevIndex;
  26286. bindings[ prevIndex ] = firstInactiveBinding;
  26287. }
  26288. _takeBackBinding( binding ) {
  26289. const bindings = this._bindings,
  26290. prevIndex = binding._cacheIndex,
  26291. firstInactiveIndex = -- this._nActiveBindings,
  26292. lastActiveBinding = bindings[ firstInactiveIndex ];
  26293. binding._cacheIndex = firstInactiveIndex;
  26294. bindings[ firstInactiveIndex ] = binding;
  26295. lastActiveBinding._cacheIndex = prevIndex;
  26296. bindings[ prevIndex ] = lastActiveBinding;
  26297. }
  26298. // Memory management of Interpolants for weight and time scale
  26299. _lendControlInterpolant() {
  26300. const interpolants = this._controlInterpolants,
  26301. lastActiveIndex = this._nActiveControlInterpolants ++;
  26302. let interpolant = interpolants[ lastActiveIndex ];
  26303. if ( interpolant === undefined ) {
  26304. interpolant = new LinearInterpolant(
  26305. new Float32Array( 2 ), new Float32Array( 2 ),
  26306. 1, this._controlInterpolantsResultBuffer );
  26307. interpolant.__cacheIndex = lastActiveIndex;
  26308. interpolants[ lastActiveIndex ] = interpolant;
  26309. }
  26310. return interpolant;
  26311. }
  26312. _takeBackControlInterpolant( interpolant ) {
  26313. const interpolants = this._controlInterpolants,
  26314. prevIndex = interpolant.__cacheIndex,
  26315. firstInactiveIndex = -- this._nActiveControlInterpolants,
  26316. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  26317. interpolant.__cacheIndex = firstInactiveIndex;
  26318. interpolants[ firstInactiveIndex ] = interpolant;
  26319. lastActiveInterpolant.__cacheIndex = prevIndex;
  26320. interpolants[ prevIndex ] = lastActiveInterpolant;
  26321. }
  26322. // return an action for a clip optionally using a custom root target
  26323. // object (this method allocates a lot of dynamic memory in case a
  26324. // previously unknown clip/root combination is specified)
  26325. clipAction( clip, optionalRoot, blendMode ) {
  26326. const root = optionalRoot || this._root,
  26327. rootUuid = root.uuid;
  26328. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  26329. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26330. const actionsForClip = this._actionsByClip[ clipUuid ];
  26331. let prototypeAction = null;
  26332. if ( blendMode === undefined ) {
  26333. if ( clipObject !== null ) {
  26334. blendMode = clipObject.blendMode;
  26335. } else {
  26336. blendMode = NormalAnimationBlendMode;
  26337. }
  26338. }
  26339. if ( actionsForClip !== undefined ) {
  26340. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  26341. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  26342. return existingAction;
  26343. }
  26344. // we know the clip, so we don't have to parse all
  26345. // the bindings again but can just copy
  26346. prototypeAction = actionsForClip.knownActions[ 0 ];
  26347. // also, take the clip from the prototype action
  26348. if ( clipObject === null )
  26349. clipObject = prototypeAction._clip;
  26350. }
  26351. // clip must be known when specified via string
  26352. if ( clipObject === null ) return null;
  26353. // allocate all resources required to run it
  26354. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  26355. this._bindAction( newAction, prototypeAction );
  26356. // and make the action known to the memory manager
  26357. this._addInactiveAction( newAction, clipUuid, rootUuid );
  26358. return newAction;
  26359. }
  26360. // get an existing action
  26361. existingAction( clip, optionalRoot ) {
  26362. const root = optionalRoot || this._root,
  26363. rootUuid = root.uuid,
  26364. clipObject = typeof clip === 'string' ?
  26365. AnimationClip.findByName( root, clip ) : clip,
  26366. clipUuid = clipObject ? clipObject.uuid : clip,
  26367. actionsForClip = this._actionsByClip[ clipUuid ];
  26368. if ( actionsForClip !== undefined ) {
  26369. return actionsForClip.actionByRoot[ rootUuid ] || null;
  26370. }
  26371. return null;
  26372. }
  26373. // deactivates all previously scheduled actions
  26374. stopAllAction() {
  26375. const actions = this._actions,
  26376. nActions = this._nActiveActions;
  26377. for ( let i = nActions - 1; i >= 0; -- i ) {
  26378. actions[ i ].stop();
  26379. }
  26380. return this;
  26381. }
  26382. // advance the time and update apply the animation
  26383. update( deltaTime ) {
  26384. deltaTime *= this.timeScale;
  26385. const actions = this._actions,
  26386. nActions = this._nActiveActions,
  26387. time = this.time += deltaTime,
  26388. timeDirection = Math.sign( deltaTime ),
  26389. accuIndex = this._accuIndex ^= 1;
  26390. // run active actions
  26391. for ( let i = 0; i !== nActions; ++ i ) {
  26392. const action = actions[ i ];
  26393. action._update( time, deltaTime, timeDirection, accuIndex );
  26394. }
  26395. // update scene graph
  26396. const bindings = this._bindings,
  26397. nBindings = this._nActiveBindings;
  26398. for ( let i = 0; i !== nBindings; ++ i ) {
  26399. bindings[ i ].apply( accuIndex );
  26400. }
  26401. return this;
  26402. }
  26403. // Allows you to seek to a specific time in an animation.
  26404. setTime( timeInSeconds ) {
  26405. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26406. for ( let i = 0; i < this._actions.length; i ++ ) {
  26407. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26408. }
  26409. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  26410. }
  26411. // return this mixer's root target object
  26412. getRoot() {
  26413. return this._root;
  26414. }
  26415. // free all resources specific to a particular clip
  26416. uncacheClip( clip ) {
  26417. const actions = this._actions,
  26418. clipUuid = clip.uuid,
  26419. actionsByClip = this._actionsByClip,
  26420. actionsForClip = actionsByClip[ clipUuid ];
  26421. if ( actionsForClip !== undefined ) {
  26422. // note: just calling _removeInactiveAction would mess up the
  26423. // iteration state and also require updating the state we can
  26424. // just throw away
  26425. const actionsToRemove = actionsForClip.knownActions;
  26426. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  26427. const action = actionsToRemove[ i ];
  26428. this._deactivateAction( action );
  26429. const cacheIndex = action._cacheIndex,
  26430. lastInactiveAction = actions[ actions.length - 1 ];
  26431. action._cacheIndex = null;
  26432. action._byClipCacheIndex = null;
  26433. lastInactiveAction._cacheIndex = cacheIndex;
  26434. actions[ cacheIndex ] = lastInactiveAction;
  26435. actions.pop();
  26436. this._removeInactiveBindingsForAction( action );
  26437. }
  26438. delete actionsByClip[ clipUuid ];
  26439. }
  26440. }
  26441. // free all resources specific to a particular root target object
  26442. uncacheRoot( root ) {
  26443. const rootUuid = root.uuid,
  26444. actionsByClip = this._actionsByClip;
  26445. for ( const clipUuid in actionsByClip ) {
  26446. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  26447. action = actionByRoot[ rootUuid ];
  26448. if ( action !== undefined ) {
  26449. this._deactivateAction( action );
  26450. this._removeInactiveAction( action );
  26451. }
  26452. }
  26453. const bindingsByRoot = this._bindingsByRootAndName,
  26454. bindingByName = bindingsByRoot[ rootUuid ];
  26455. if ( bindingByName !== undefined ) {
  26456. for ( const trackName in bindingByName ) {
  26457. const binding = bindingByName[ trackName ];
  26458. binding.restoreOriginalState();
  26459. this._removeInactiveBinding( binding );
  26460. }
  26461. }
  26462. }
  26463. // remove a targeted clip from the cache
  26464. uncacheAction( clip, optionalRoot ) {
  26465. const action = this.existingAction( clip, optionalRoot );
  26466. if ( action !== null ) {
  26467. this._deactivateAction( action );
  26468. this._removeInactiveAction( action );
  26469. }
  26470. }
  26471. }
  26472. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  26473. class Uniform {
  26474. constructor( value ) {
  26475. if ( typeof value === 'string' ) {
  26476. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  26477. value = arguments[ 1 ];
  26478. }
  26479. this.value = value;
  26480. }
  26481. clone() {
  26482. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  26483. }
  26484. }
  26485. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26486. constructor( array, stride, meshPerAttribute = 1 ) {
  26487. super( array, stride );
  26488. this.meshPerAttribute = meshPerAttribute || 1;
  26489. }
  26490. copy( source ) {
  26491. super.copy( source );
  26492. this.meshPerAttribute = source.meshPerAttribute;
  26493. return this;
  26494. }
  26495. clone( data ) {
  26496. const ib = super.clone( data );
  26497. ib.meshPerAttribute = this.meshPerAttribute;
  26498. return ib;
  26499. }
  26500. toJSON( data ) {
  26501. const json = super.toJSON( data );
  26502. json.isInstancedInterleavedBuffer = true;
  26503. json.meshPerAttribute = this.meshPerAttribute;
  26504. return json;
  26505. }
  26506. }
  26507. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26508. class GLBufferAttribute {
  26509. constructor( buffer, type, itemSize, elementSize, count ) {
  26510. this.buffer = buffer;
  26511. this.type = type;
  26512. this.itemSize = itemSize;
  26513. this.elementSize = elementSize;
  26514. this.count = count;
  26515. this.version = 0;
  26516. }
  26517. set needsUpdate( value ) {
  26518. if ( value === true ) this.version ++;
  26519. }
  26520. setBuffer( buffer ) {
  26521. this.buffer = buffer;
  26522. return this;
  26523. }
  26524. setType( type, elementSize ) {
  26525. this.type = type;
  26526. this.elementSize = elementSize;
  26527. return this;
  26528. }
  26529. setItemSize( itemSize ) {
  26530. this.itemSize = itemSize;
  26531. return this;
  26532. }
  26533. setCount( count ) {
  26534. this.count = count;
  26535. return this;
  26536. }
  26537. }
  26538. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26539. class Raycaster {
  26540. constructor( origin, direction, near = 0, far = Infinity ) {
  26541. this.ray = new Ray( origin, direction );
  26542. // direction is assumed to be normalized (for accurate distance calculations)
  26543. this.near = near;
  26544. this.far = far;
  26545. this.camera = null;
  26546. this.layers = new Layers();
  26547. this.params = {
  26548. Mesh: {},
  26549. Line: { threshold: 1 },
  26550. LOD: {},
  26551. Points: { threshold: 1 },
  26552. Sprite: {}
  26553. };
  26554. }
  26555. set( origin, direction ) {
  26556. // direction is assumed to be normalized (for accurate distance calculations)
  26557. this.ray.set( origin, direction );
  26558. }
  26559. setFromCamera( coords, camera ) {
  26560. if ( camera && camera.isPerspectiveCamera ) {
  26561. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  26562. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  26563. this.camera = camera;
  26564. } else if ( camera && camera.isOrthographicCamera ) {
  26565. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  26566. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  26567. this.camera = camera;
  26568. } else {
  26569. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  26570. }
  26571. }
  26572. intersectObject( object, recursive = false, intersects = [] ) {
  26573. intersectObject( object, this, intersects, recursive );
  26574. intersects.sort( ascSort );
  26575. return intersects;
  26576. }
  26577. intersectObjects( objects, recursive = false, intersects = [] ) {
  26578. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  26579. intersectObject( objects[ i ], this, intersects, recursive );
  26580. }
  26581. intersects.sort( ascSort );
  26582. return intersects;
  26583. }
  26584. }
  26585. function ascSort( a, b ) {
  26586. return a.distance - b.distance;
  26587. }
  26588. function intersectObject( object, raycaster, intersects, recursive ) {
  26589. if ( object.layers.test( raycaster.layers ) ) {
  26590. object.raycast( raycaster, intersects );
  26591. }
  26592. if ( recursive === true ) {
  26593. const children = object.children;
  26594. for ( let i = 0, l = children.length; i < l; i ++ ) {
  26595. intersectObject( children[ i ], raycaster, intersects, true );
  26596. }
  26597. }
  26598. }
  26599. /**
  26600. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26601. *
  26602. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26603. * The azimuthal angle (theta) is measured from the positive z-axis.
  26604. */
  26605. class Spherical {
  26606. constructor( radius = 1, phi = 0, theta = 0 ) {
  26607. this.radius = radius;
  26608. this.phi = phi; // polar angle
  26609. this.theta = theta; // azimuthal angle
  26610. return this;
  26611. }
  26612. set( radius, phi, theta ) {
  26613. this.radius = radius;
  26614. this.phi = phi;
  26615. this.theta = theta;
  26616. return this;
  26617. }
  26618. copy( other ) {
  26619. this.radius = other.radius;
  26620. this.phi = other.phi;
  26621. this.theta = other.theta;
  26622. return this;
  26623. }
  26624. // restrict phi to be betwee EPS and PI-EPS
  26625. makeSafe() {
  26626. const EPS = 0.000001;
  26627. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  26628. return this;
  26629. }
  26630. setFromVector3( v ) {
  26631. return this.setFromCartesianCoords( v.x, v.y, v.z );
  26632. }
  26633. setFromCartesianCoords( x, y, z ) {
  26634. this.radius = Math.sqrt( x * x + y * y + z * z );
  26635. if ( this.radius === 0 ) {
  26636. this.theta = 0;
  26637. this.phi = 0;
  26638. } else {
  26639. this.theta = Math.atan2( x, z );
  26640. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  26641. }
  26642. return this;
  26643. }
  26644. clone() {
  26645. return new this.constructor().copy( this );
  26646. }
  26647. }
  26648. /**
  26649. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26650. */
  26651. class Cylindrical {
  26652. constructor( radius = 1, theta = 0, y = 0 ) {
  26653. this.radius = radius; // distance from the origin to a point in the x-z plane
  26654. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26655. this.y = y; // height above the x-z plane
  26656. return this;
  26657. }
  26658. set( radius, theta, y ) {
  26659. this.radius = radius;
  26660. this.theta = theta;
  26661. this.y = y;
  26662. return this;
  26663. }
  26664. copy( other ) {
  26665. this.radius = other.radius;
  26666. this.theta = other.theta;
  26667. this.y = other.y;
  26668. return this;
  26669. }
  26670. setFromVector3( v ) {
  26671. return this.setFromCartesianCoords( v.x, v.y, v.z );
  26672. }
  26673. setFromCartesianCoords( x, y, z ) {
  26674. this.radius = Math.sqrt( x * x + z * z );
  26675. this.theta = Math.atan2( x, z );
  26676. this.y = y;
  26677. return this;
  26678. }
  26679. clone() {
  26680. return new this.constructor().copy( this );
  26681. }
  26682. }
  26683. const _vector$4 = /*@__PURE__*/ new Vector2();
  26684. class Box2 {
  26685. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  26686. this.min = min;
  26687. this.max = max;
  26688. }
  26689. set( min, max ) {
  26690. this.min.copy( min );
  26691. this.max.copy( max );
  26692. return this;
  26693. }
  26694. setFromPoints( points ) {
  26695. this.makeEmpty();
  26696. for ( let i = 0, il = points.length; i < il; i ++ ) {
  26697. this.expandByPoint( points[ i ] );
  26698. }
  26699. return this;
  26700. }
  26701. setFromCenterAndSize( center, size ) {
  26702. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  26703. this.min.copy( center ).sub( halfSize );
  26704. this.max.copy( center ).add( halfSize );
  26705. return this;
  26706. }
  26707. clone() {
  26708. return new this.constructor().copy( this );
  26709. }
  26710. copy( box ) {
  26711. this.min.copy( box.min );
  26712. this.max.copy( box.max );
  26713. return this;
  26714. }
  26715. makeEmpty() {
  26716. this.min.x = this.min.y = + Infinity;
  26717. this.max.x = this.max.y = - Infinity;
  26718. return this;
  26719. }
  26720. isEmpty() {
  26721. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26722. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  26723. }
  26724. getCenter( target ) {
  26725. if ( target === undefined ) {
  26726. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  26727. target = new Vector2();
  26728. }
  26729. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  26730. }
  26731. getSize( target ) {
  26732. if ( target === undefined ) {
  26733. console.warn( 'THREE.Box2: .getSize() target is now required' );
  26734. target = new Vector2();
  26735. }
  26736. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  26737. }
  26738. expandByPoint( point ) {
  26739. this.min.min( point );
  26740. this.max.max( point );
  26741. return this;
  26742. }
  26743. expandByVector( vector ) {
  26744. this.min.sub( vector );
  26745. this.max.add( vector );
  26746. return this;
  26747. }
  26748. expandByScalar( scalar ) {
  26749. this.min.addScalar( - scalar );
  26750. this.max.addScalar( scalar );
  26751. return this;
  26752. }
  26753. containsPoint( point ) {
  26754. return point.x < this.min.x || point.x > this.max.x ||
  26755. point.y < this.min.y || point.y > this.max.y ? false : true;
  26756. }
  26757. containsBox( box ) {
  26758. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  26759. this.min.y <= box.min.y && box.max.y <= this.max.y;
  26760. }
  26761. getParameter( point, target ) {
  26762. // This can potentially have a divide by zero if the box
  26763. // has a size dimension of 0.
  26764. if ( target === undefined ) {
  26765. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  26766. target = new Vector2();
  26767. }
  26768. return target.set(
  26769. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  26770. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  26771. );
  26772. }
  26773. intersectsBox( box ) {
  26774. // using 4 splitting planes to rule out intersections
  26775. return box.max.x < this.min.x || box.min.x > this.max.x ||
  26776. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  26777. }
  26778. clampPoint( point, target ) {
  26779. if ( target === undefined ) {
  26780. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  26781. target = new Vector2();
  26782. }
  26783. return target.copy( point ).clamp( this.min, this.max );
  26784. }
  26785. distanceToPoint( point ) {
  26786. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  26787. return clampedPoint.sub( point ).length();
  26788. }
  26789. intersect( box ) {
  26790. this.min.max( box.min );
  26791. this.max.min( box.max );
  26792. return this;
  26793. }
  26794. union( box ) {
  26795. this.min.min( box.min );
  26796. this.max.max( box.max );
  26797. return this;
  26798. }
  26799. translate( offset ) {
  26800. this.min.add( offset );
  26801. this.max.add( offset );
  26802. return this;
  26803. }
  26804. equals( box ) {
  26805. return box.min.equals( this.min ) && box.max.equals( this.max );
  26806. }
  26807. }
  26808. Box2.prototype.isBox2 = true;
  26809. const _startP = /*@__PURE__*/ new Vector3();
  26810. const _startEnd = /*@__PURE__*/ new Vector3();
  26811. class Line3 {
  26812. constructor( start = new Vector3(), end = new Vector3() ) {
  26813. this.start = start;
  26814. this.end = end;
  26815. }
  26816. set( start, end ) {
  26817. this.start.copy( start );
  26818. this.end.copy( end );
  26819. return this;
  26820. }
  26821. copy( line ) {
  26822. this.start.copy( line.start );
  26823. this.end.copy( line.end );
  26824. return this;
  26825. }
  26826. getCenter( target ) {
  26827. if ( target === undefined ) {
  26828. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  26829. target = new Vector3();
  26830. }
  26831. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  26832. }
  26833. delta( target ) {
  26834. if ( target === undefined ) {
  26835. console.warn( 'THREE.Line3: .delta() target is now required' );
  26836. target = new Vector3();
  26837. }
  26838. return target.subVectors( this.end, this.start );
  26839. }
  26840. distanceSq() {
  26841. return this.start.distanceToSquared( this.end );
  26842. }
  26843. distance() {
  26844. return this.start.distanceTo( this.end );
  26845. }
  26846. at( t, target ) {
  26847. if ( target === undefined ) {
  26848. console.warn( 'THREE.Line3: .at() target is now required' );
  26849. target = new Vector3();
  26850. }
  26851. return this.delta( target ).multiplyScalar( t ).add( this.start );
  26852. }
  26853. closestPointToPointParameter( point, clampToLine ) {
  26854. _startP.subVectors( point, this.start );
  26855. _startEnd.subVectors( this.end, this.start );
  26856. const startEnd2 = _startEnd.dot( _startEnd );
  26857. const startEnd_startP = _startEnd.dot( _startP );
  26858. let t = startEnd_startP / startEnd2;
  26859. if ( clampToLine ) {
  26860. t = clamp( t, 0, 1 );
  26861. }
  26862. return t;
  26863. }
  26864. closestPointToPoint( point, clampToLine, target ) {
  26865. const t = this.closestPointToPointParameter( point, clampToLine );
  26866. if ( target === undefined ) {
  26867. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  26868. target = new Vector3();
  26869. }
  26870. return this.delta( target ).multiplyScalar( t ).add( this.start );
  26871. }
  26872. applyMatrix4( matrix ) {
  26873. this.start.applyMatrix4( matrix );
  26874. this.end.applyMatrix4( matrix );
  26875. return this;
  26876. }
  26877. equals( line ) {
  26878. return line.start.equals( this.start ) && line.end.equals( this.end );
  26879. }
  26880. clone() {
  26881. return new this.constructor().copy( this );
  26882. }
  26883. }
  26884. class ImmediateRenderObject extends Object3D {
  26885. constructor( material ) {
  26886. super();
  26887. this.material = material;
  26888. this.render = function ( /* renderCallback */ ) {};
  26889. this.hasPositions = false;
  26890. this.hasNormals = false;
  26891. this.hasColors = false;
  26892. this.hasUvs = false;
  26893. this.positionArray = null;
  26894. this.normalArray = null;
  26895. this.colorArray = null;
  26896. this.uvArray = null;
  26897. this.count = 0;
  26898. }
  26899. }
  26900. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26901. const _vector$3 = /*@__PURE__*/ new Vector3();
  26902. class SpotLightHelper extends Object3D {
  26903. constructor( light, color ) {
  26904. super();
  26905. this.light = light;
  26906. this.light.updateMatrixWorld();
  26907. this.matrix = light.matrixWorld;
  26908. this.matrixAutoUpdate = false;
  26909. this.color = color;
  26910. const geometry = new BufferGeometry();
  26911. const positions = [
  26912. 0, 0, 0, 0, 0, 1,
  26913. 0, 0, 0, 1, 0, 1,
  26914. 0, 0, 0, - 1, 0, 1,
  26915. 0, 0, 0, 0, 1, 1,
  26916. 0, 0, 0, 0, - 1, 1
  26917. ];
  26918. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  26919. const p1 = ( i / l ) * Math.PI * 2;
  26920. const p2 = ( j / l ) * Math.PI * 2;
  26921. positions.push(
  26922. Math.cos( p1 ), Math.sin( p1 ), 1,
  26923. Math.cos( p2 ), Math.sin( p2 ), 1
  26924. );
  26925. }
  26926. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  26927. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  26928. this.cone = new LineSegments( geometry, material );
  26929. this.add( this.cone );
  26930. this.update();
  26931. }
  26932. dispose() {
  26933. this.cone.geometry.dispose();
  26934. this.cone.material.dispose();
  26935. }
  26936. update() {
  26937. this.light.updateMatrixWorld();
  26938. const coneLength = this.light.distance ? this.light.distance : 1000;
  26939. const coneWidth = coneLength * Math.tan( this.light.angle );
  26940. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  26941. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  26942. this.cone.lookAt( _vector$3 );
  26943. if ( this.color !== undefined ) {
  26944. this.cone.material.color.set( this.color );
  26945. } else {
  26946. this.cone.material.color.copy( this.light.color );
  26947. }
  26948. }
  26949. }
  26950. const _vector$2 = /*@__PURE__*/ new Vector3();
  26951. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  26952. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  26953. class SkeletonHelper extends LineSegments {
  26954. constructor( object ) {
  26955. const bones = getBoneList( object );
  26956. const geometry = new BufferGeometry();
  26957. const vertices = [];
  26958. const colors = [];
  26959. const color1 = new Color( 0, 0, 1 );
  26960. const color2 = new Color( 0, 1, 0 );
  26961. for ( let i = 0; i < bones.length; i ++ ) {
  26962. const bone = bones[ i ];
  26963. if ( bone.parent && bone.parent.isBone ) {
  26964. vertices.push( 0, 0, 0 );
  26965. vertices.push( 0, 0, 0 );
  26966. colors.push( color1.r, color1.g, color1.b );
  26967. colors.push( color2.r, color2.g, color2.b );
  26968. }
  26969. }
  26970. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26971. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  26972. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  26973. super( geometry, material );
  26974. this.type = 'SkeletonHelper';
  26975. this.isSkeletonHelper = true;
  26976. this.root = object;
  26977. this.bones = bones;
  26978. this.matrix = object.matrixWorld;
  26979. this.matrixAutoUpdate = false;
  26980. }
  26981. updateMatrixWorld( force ) {
  26982. const bones = this.bones;
  26983. const geometry = this.geometry;
  26984. const position = geometry.getAttribute( 'position' );
  26985. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  26986. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  26987. const bone = bones[ i ];
  26988. if ( bone.parent && bone.parent.isBone ) {
  26989. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  26990. _vector$2.setFromMatrixPosition( _boneMatrix );
  26991. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  26992. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  26993. _vector$2.setFromMatrixPosition( _boneMatrix );
  26994. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  26995. j += 2;
  26996. }
  26997. }
  26998. geometry.getAttribute( 'position' ).needsUpdate = true;
  26999. super.updateMatrixWorld( force );
  27000. }
  27001. }
  27002. function getBoneList( object ) {
  27003. const boneList = [];
  27004. if ( object && object.isBone ) {
  27005. boneList.push( object );
  27006. }
  27007. for ( let i = 0; i < object.children.length; i ++ ) {
  27008. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  27009. }
  27010. return boneList;
  27011. }
  27012. class PointLightHelper extends Mesh {
  27013. constructor( light, sphereSize, color ) {
  27014. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  27015. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27016. super( geometry, material );
  27017. this.light = light;
  27018. this.light.updateMatrixWorld();
  27019. this.color = color;
  27020. this.type = 'PointLightHelper';
  27021. this.matrix = this.light.matrixWorld;
  27022. this.matrixAutoUpdate = false;
  27023. this.update();
  27024. /*
  27025. // TODO: delete this comment?
  27026. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27027. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27028. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27029. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27030. const d = light.distance;
  27031. if ( d === 0.0 ) {
  27032. this.lightDistance.visible = false;
  27033. } else {
  27034. this.lightDistance.scale.set( d, d, d );
  27035. }
  27036. this.add( this.lightDistance );
  27037. */
  27038. }
  27039. dispose() {
  27040. this.geometry.dispose();
  27041. this.material.dispose();
  27042. }
  27043. update() {
  27044. if ( this.color !== undefined ) {
  27045. this.material.color.set( this.color );
  27046. } else {
  27047. this.material.color.copy( this.light.color );
  27048. }
  27049. /*
  27050. const d = this.light.distance;
  27051. if ( d === 0.0 ) {
  27052. this.lightDistance.visible = false;
  27053. } else {
  27054. this.lightDistance.visible = true;
  27055. this.lightDistance.scale.set( d, d, d );
  27056. }
  27057. */
  27058. }
  27059. }
  27060. const _vector$1 = /*@__PURE__*/ new Vector3();
  27061. const _color1 = /*@__PURE__*/ new Color();
  27062. const _color2 = /*@__PURE__*/ new Color();
  27063. class HemisphereLightHelper extends Object3D {
  27064. constructor( light, size, color ) {
  27065. super();
  27066. this.light = light;
  27067. this.light.updateMatrixWorld();
  27068. this.matrix = light.matrixWorld;
  27069. this.matrixAutoUpdate = false;
  27070. this.color = color;
  27071. const geometry = new OctahedronGeometry( size );
  27072. geometry.rotateY( Math.PI * 0.5 );
  27073. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27074. if ( this.color === undefined ) this.material.vertexColors = true;
  27075. const position = geometry.getAttribute( 'position' );
  27076. const colors = new Float32Array( position.count * 3 );
  27077. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  27078. this.add( new Mesh( geometry, this.material ) );
  27079. this.update();
  27080. }
  27081. dispose() {
  27082. this.children[ 0 ].geometry.dispose();
  27083. this.children[ 0 ].material.dispose();
  27084. }
  27085. update() {
  27086. const mesh = this.children[ 0 ];
  27087. if ( this.color !== undefined ) {
  27088. this.material.color.set( this.color );
  27089. } else {
  27090. const colors = mesh.geometry.getAttribute( 'color' );
  27091. _color1.copy( this.light.color );
  27092. _color2.copy( this.light.groundColor );
  27093. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  27094. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  27095. colors.setXYZ( i, color.r, color.g, color.b );
  27096. }
  27097. colors.needsUpdate = true;
  27098. }
  27099. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  27100. }
  27101. }
  27102. class GridHelper extends LineSegments {
  27103. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  27104. color1 = new Color( color1 );
  27105. color2 = new Color( color2 );
  27106. const center = divisions / 2;
  27107. const step = size / divisions;
  27108. const halfSize = size / 2;
  27109. const vertices = [], colors = [];
  27110. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  27111. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  27112. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  27113. const color = i === center ? color1 : color2;
  27114. color.toArray( colors, j ); j += 3;
  27115. color.toArray( colors, j ); j += 3;
  27116. color.toArray( colors, j ); j += 3;
  27117. color.toArray( colors, j ); j += 3;
  27118. }
  27119. const geometry = new BufferGeometry();
  27120. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27121. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27122. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27123. super( geometry, material );
  27124. this.type = 'GridHelper';
  27125. }
  27126. }
  27127. class PolarGridHelper extends LineSegments {
  27128. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  27129. color1 = new Color( color1 );
  27130. color2 = new Color( color2 );
  27131. const vertices = [];
  27132. const colors = [];
  27133. // create the radials
  27134. for ( let i = 0; i <= radials; i ++ ) {
  27135. const v = ( i / radials ) * ( Math.PI * 2 );
  27136. const x = Math.sin( v ) * radius;
  27137. const z = Math.cos( v ) * radius;
  27138. vertices.push( 0, 0, 0 );
  27139. vertices.push( x, 0, z );
  27140. const color = ( i & 1 ) ? color1 : color2;
  27141. colors.push( color.r, color.g, color.b );
  27142. colors.push( color.r, color.g, color.b );
  27143. }
  27144. // create the circles
  27145. for ( let i = 0; i <= circles; i ++ ) {
  27146. const color = ( i & 1 ) ? color1 : color2;
  27147. const r = radius - ( radius / circles * i );
  27148. for ( let j = 0; j < divisions; j ++ ) {
  27149. // first vertex
  27150. let v = ( j / divisions ) * ( Math.PI * 2 );
  27151. let x = Math.sin( v ) * r;
  27152. let z = Math.cos( v ) * r;
  27153. vertices.push( x, 0, z );
  27154. colors.push( color.r, color.g, color.b );
  27155. // second vertex
  27156. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  27157. x = Math.sin( v ) * r;
  27158. z = Math.cos( v ) * r;
  27159. vertices.push( x, 0, z );
  27160. colors.push( color.r, color.g, color.b );
  27161. }
  27162. }
  27163. const geometry = new BufferGeometry();
  27164. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27165. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27166. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27167. super( geometry, material );
  27168. this.type = 'PolarGridHelper';
  27169. }
  27170. }
  27171. const _v1 = /*@__PURE__*/ new Vector3();
  27172. const _v2 = /*@__PURE__*/ new Vector3();
  27173. const _v3 = /*@__PURE__*/ new Vector3();
  27174. class DirectionalLightHelper extends Object3D {
  27175. constructor( light, size, color ) {
  27176. super();
  27177. this.light = light;
  27178. this.light.updateMatrixWorld();
  27179. this.matrix = light.matrixWorld;
  27180. this.matrixAutoUpdate = false;
  27181. this.color = color;
  27182. if ( size === undefined ) size = 1;
  27183. let geometry = new BufferGeometry();
  27184. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  27185. - size, size, 0,
  27186. size, size, 0,
  27187. size, - size, 0,
  27188. - size, - size, 0,
  27189. - size, size, 0
  27190. ], 3 ) );
  27191. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27192. this.lightPlane = new Line( geometry, material );
  27193. this.add( this.lightPlane );
  27194. geometry = new BufferGeometry();
  27195. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  27196. this.targetLine = new Line( geometry, material );
  27197. this.add( this.targetLine );
  27198. this.update();
  27199. }
  27200. dispose() {
  27201. this.lightPlane.geometry.dispose();
  27202. this.lightPlane.material.dispose();
  27203. this.targetLine.geometry.dispose();
  27204. this.targetLine.material.dispose();
  27205. }
  27206. update() {
  27207. _v1.setFromMatrixPosition( this.light.matrixWorld );
  27208. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  27209. _v3.subVectors( _v2, _v1 );
  27210. this.lightPlane.lookAt( _v2 );
  27211. if ( this.color !== undefined ) {
  27212. this.lightPlane.material.color.set( this.color );
  27213. this.targetLine.material.color.set( this.color );
  27214. } else {
  27215. this.lightPlane.material.color.copy( this.light.color );
  27216. this.targetLine.material.color.copy( this.light.color );
  27217. }
  27218. this.targetLine.lookAt( _v2 );
  27219. this.targetLine.scale.z = _v3.length();
  27220. }
  27221. }
  27222. const _vector = /*@__PURE__*/ new Vector3();
  27223. const _camera = /*@__PURE__*/ new Camera();
  27224. /**
  27225. * - shows frustum, line of sight and up of the camera
  27226. * - suitable for fast updates
  27227. * - based on frustum visualization in lightgl.js shadowmap example
  27228. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27229. */
  27230. class CameraHelper extends LineSegments {
  27231. constructor( camera ) {
  27232. const geometry = new BufferGeometry();
  27233. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  27234. const vertices = [];
  27235. const colors = [];
  27236. const pointMap = {};
  27237. // colors
  27238. const colorFrustum = new Color( 0xffaa00 );
  27239. const colorCone = new Color( 0xff0000 );
  27240. const colorUp = new Color( 0x00aaff );
  27241. const colorTarget = new Color( 0xffffff );
  27242. const colorCross = new Color( 0x333333 );
  27243. // near
  27244. addLine( 'n1', 'n2', colorFrustum );
  27245. addLine( 'n2', 'n4', colorFrustum );
  27246. addLine( 'n4', 'n3', colorFrustum );
  27247. addLine( 'n3', 'n1', colorFrustum );
  27248. // far
  27249. addLine( 'f1', 'f2', colorFrustum );
  27250. addLine( 'f2', 'f4', colorFrustum );
  27251. addLine( 'f4', 'f3', colorFrustum );
  27252. addLine( 'f3', 'f1', colorFrustum );
  27253. // sides
  27254. addLine( 'n1', 'f1', colorFrustum );
  27255. addLine( 'n2', 'f2', colorFrustum );
  27256. addLine( 'n3', 'f3', colorFrustum );
  27257. addLine( 'n4', 'f4', colorFrustum );
  27258. // cone
  27259. addLine( 'p', 'n1', colorCone );
  27260. addLine( 'p', 'n2', colorCone );
  27261. addLine( 'p', 'n3', colorCone );
  27262. addLine( 'p', 'n4', colorCone );
  27263. // up
  27264. addLine( 'u1', 'u2', colorUp );
  27265. addLine( 'u2', 'u3', colorUp );
  27266. addLine( 'u3', 'u1', colorUp );
  27267. // target
  27268. addLine( 'c', 't', colorTarget );
  27269. addLine( 'p', 'c', colorCross );
  27270. // cross
  27271. addLine( 'cn1', 'cn2', colorCross );
  27272. addLine( 'cn3', 'cn4', colorCross );
  27273. addLine( 'cf1', 'cf2', colorCross );
  27274. addLine( 'cf3', 'cf4', colorCross );
  27275. function addLine( a, b, color ) {
  27276. addPoint( a, color );
  27277. addPoint( b, color );
  27278. }
  27279. function addPoint( id, color ) {
  27280. vertices.push( 0, 0, 0 );
  27281. colors.push( color.r, color.g, color.b );
  27282. if ( pointMap[ id ] === undefined ) {
  27283. pointMap[ id ] = [];
  27284. }
  27285. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  27286. }
  27287. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27288. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27289. super( geometry, material );
  27290. this.type = 'CameraHelper';
  27291. this.camera = camera;
  27292. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  27293. this.matrix = camera.matrixWorld;
  27294. this.matrixAutoUpdate = false;
  27295. this.pointMap = pointMap;
  27296. this.update();
  27297. }
  27298. update() {
  27299. const geometry = this.geometry;
  27300. const pointMap = this.pointMap;
  27301. const w = 1, h = 1;
  27302. // we need just camera projection matrix inverse
  27303. // world matrix must be identity
  27304. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  27305. // center / target
  27306. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  27307. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  27308. // near
  27309. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  27310. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  27311. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  27312. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  27313. // far
  27314. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  27315. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  27316. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  27317. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  27318. // up
  27319. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  27320. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  27321. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  27322. // cross
  27323. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  27324. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  27325. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  27326. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  27327. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  27328. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  27329. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  27330. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  27331. geometry.getAttribute( 'position' ).needsUpdate = true;
  27332. }
  27333. dispose() {
  27334. this.geometry.dispose();
  27335. this.material.dispose();
  27336. }
  27337. }
  27338. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  27339. _vector.set( x, y, z ).unproject( camera );
  27340. const points = pointMap[ point ];
  27341. if ( points !== undefined ) {
  27342. const position = geometry.getAttribute( 'position' );
  27343. for ( let i = 0, l = points.length; i < l; i ++ ) {
  27344. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  27345. }
  27346. }
  27347. }
  27348. const _box = /*@__PURE__*/ new Box3();
  27349. class BoxHelper extends LineSegments {
  27350. constructor( object, color = 0xffff00 ) {
  27351. 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 ] );
  27352. const positions = new Float32Array( 8 * 3 );
  27353. const geometry = new BufferGeometry();
  27354. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  27355. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  27356. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27357. this.object = object;
  27358. this.type = 'BoxHelper';
  27359. this.matrixAutoUpdate = false;
  27360. this.update();
  27361. }
  27362. update( object ) {
  27363. if ( object !== undefined ) {
  27364. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  27365. }
  27366. if ( this.object !== undefined ) {
  27367. _box.setFromObject( this.object );
  27368. }
  27369. if ( _box.isEmpty() ) return;
  27370. const min = _box.min;
  27371. const max = _box.max;
  27372. /*
  27373. 5____4
  27374. 1/___0/|
  27375. | 6__|_7
  27376. 2/___3/
  27377. 0: max.x, max.y, max.z
  27378. 1: min.x, max.y, max.z
  27379. 2: min.x, min.y, max.z
  27380. 3: max.x, min.y, max.z
  27381. 4: max.x, max.y, min.z
  27382. 5: min.x, max.y, min.z
  27383. 6: min.x, min.y, min.z
  27384. 7: max.x, min.y, min.z
  27385. */
  27386. const position = this.geometry.attributes.position;
  27387. const array = position.array;
  27388. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  27389. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  27390. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  27391. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  27392. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  27393. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  27394. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  27395. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  27396. position.needsUpdate = true;
  27397. this.geometry.computeBoundingSphere();
  27398. }
  27399. setFromObject( object ) {
  27400. this.object = object;
  27401. this.update();
  27402. return this;
  27403. }
  27404. copy( source ) {
  27405. LineSegments.prototype.copy.call( this, source );
  27406. this.object = source.object;
  27407. return this;
  27408. }
  27409. }
  27410. class Box3Helper extends LineSegments {
  27411. constructor( box, color = 0xffff00 ) {
  27412. 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 ] );
  27413. 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 ];
  27414. const geometry = new BufferGeometry();
  27415. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  27416. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27417. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27418. this.box = box;
  27419. this.type = 'Box3Helper';
  27420. this.geometry.computeBoundingSphere();
  27421. }
  27422. updateMatrixWorld( force ) {
  27423. const box = this.box;
  27424. if ( box.isEmpty() ) return;
  27425. box.getCenter( this.position );
  27426. box.getSize( this.scale );
  27427. this.scale.multiplyScalar( 0.5 );
  27428. super.updateMatrixWorld( force );
  27429. }
  27430. }
  27431. class PlaneHelper extends Line {
  27432. constructor( plane, size = 1, hex = 0xffff00 ) {
  27433. const color = hex;
  27434. 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 ];
  27435. const geometry = new BufferGeometry();
  27436. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27437. geometry.computeBoundingSphere();
  27438. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27439. this.type = 'PlaneHelper';
  27440. this.plane = plane;
  27441. this.size = size;
  27442. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  27443. const geometry2 = new BufferGeometry();
  27444. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  27445. geometry2.computeBoundingSphere();
  27446. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  27447. }
  27448. updateMatrixWorld( force ) {
  27449. let scale = - this.plane.constant;
  27450. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  27451. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  27452. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27453. this.lookAt( this.plane.normal );
  27454. super.updateMatrixWorld( force );
  27455. }
  27456. }
  27457. const _axis = /*@__PURE__*/ new Vector3();
  27458. let _lineGeometry, _coneGeometry;
  27459. class ArrowHelper extends Object3D {
  27460. // dir is assumed to be normalized
  27461. 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 ) {
  27462. super();
  27463. this.type = 'ArrowHelper';
  27464. if ( _lineGeometry === undefined ) {
  27465. _lineGeometry = new BufferGeometry();
  27466. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  27467. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  27468. _coneGeometry.translate( 0, - 0.5, 0 );
  27469. }
  27470. this.position.copy( origin );
  27471. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27472. this.line.matrixAutoUpdate = false;
  27473. this.add( this.line );
  27474. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  27475. this.cone.matrixAutoUpdate = false;
  27476. this.add( this.cone );
  27477. this.setDirection( dir );
  27478. this.setLength( length, headLength, headWidth );
  27479. }
  27480. setDirection( dir ) {
  27481. // dir is assumed to be normalized
  27482. if ( dir.y > 0.99999 ) {
  27483. this.quaternion.set( 0, 0, 0, 1 );
  27484. } else if ( dir.y < - 0.99999 ) {
  27485. this.quaternion.set( 1, 0, 0, 0 );
  27486. } else {
  27487. _axis.set( dir.z, 0, - dir.x ).normalize();
  27488. const radians = Math.acos( dir.y );
  27489. this.quaternion.setFromAxisAngle( _axis, radians );
  27490. }
  27491. }
  27492. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  27493. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  27494. this.line.updateMatrix();
  27495. this.cone.scale.set( headWidth, headLength, headWidth );
  27496. this.cone.position.y = length;
  27497. this.cone.updateMatrix();
  27498. }
  27499. setColor( color ) {
  27500. this.line.material.color.set( color );
  27501. this.cone.material.color.set( color );
  27502. }
  27503. copy( source ) {
  27504. super.copy( source, false );
  27505. this.line.copy( source.line );
  27506. this.cone.copy( source.cone );
  27507. return this;
  27508. }
  27509. }
  27510. class AxesHelper extends LineSegments {
  27511. constructor( size = 1 ) {
  27512. const vertices = [
  27513. 0, 0, 0, size, 0, 0,
  27514. 0, 0, 0, 0, size, 0,
  27515. 0, 0, 0, 0, 0, size
  27516. ];
  27517. const colors = [
  27518. 1, 0, 0, 1, 0.6, 0,
  27519. 0, 1, 0, 0.6, 1, 0,
  27520. 0, 0, 1, 0, 0.6, 1
  27521. ];
  27522. const geometry = new BufferGeometry();
  27523. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27524. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27525. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27526. super( geometry, material );
  27527. this.type = 'AxesHelper';
  27528. }
  27529. dispose() {
  27530. this.geometry.dispose();
  27531. this.material.dispose();
  27532. }
  27533. }
  27534. const _floatView = new Float32Array( 1 );
  27535. const _int32View = new Int32Array( _floatView.buffer );
  27536. class DataUtils {
  27537. // Converts float32 to float16 (stored as uint16 value).
  27538. static toHalfFloat( val ) {
  27539. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27540. /* This method is faster than the OpenEXR implementation (very often
  27541. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27542. * by James Tursa?s half-precision code. */
  27543. _floatView[ 0 ] = val;
  27544. const x = _int32View[ 0 ];
  27545. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  27546. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  27547. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  27548. /* If zero, or denormal, or exponent underflows too much for a denormal
  27549. * half, return signed zero. */
  27550. if ( e < 103 ) return bits;
  27551. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27552. if ( e > 142 ) {
  27553. bits |= 0x7c00;
  27554. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27555. * not Inf, so make sure we set one mantissa bit too. */
  27556. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  27557. return bits;
  27558. }
  27559. /* If exponent underflows but not too much, return a denormal */
  27560. if ( e < 113 ) {
  27561. m |= 0x0800;
  27562. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27563. * to 1, which is OK. */
  27564. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  27565. return bits;
  27566. }
  27567. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  27568. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27569. * the exponent, which is OK. */
  27570. bits += m & 1;
  27571. return bits;
  27572. }
  27573. }
  27574. const LOD_MIN = 4;
  27575. const LOD_MAX = 8;
  27576. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  27577. // The standard deviations (radians) associated with the extra mips. These are
  27578. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27579. // geometric shadowing function. These sigma values squared must match the
  27580. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27581. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27582. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27583. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27584. // samples and exit early, but not recompile the shader.
  27585. const MAX_SAMPLES = 20;
  27586. const ENCODINGS = {
  27587. [ LinearEncoding ]: 0,
  27588. [ sRGBEncoding ]: 1,
  27589. [ RGBEEncoding ]: 2,
  27590. [ RGBM7Encoding ]: 3,
  27591. [ RGBM16Encoding ]: 4,
  27592. [ RGBDEncoding ]: 5,
  27593. [ GammaEncoding ]: 6
  27594. };
  27595. const backgroundMaterial = new MeshBasicMaterial( {
  27596. side: BackSide,
  27597. depthWrite: false,
  27598. depthTest: false,
  27599. } );
  27600. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27601. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  27602. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  27603. const _clearColor = /*@__PURE__*/ new Color();
  27604. let _oldTarget = null;
  27605. // Golden Ratio
  27606. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27607. const INV_PHI = 1 / PHI;
  27608. // Vertices of a dodecahedron (except the opposites, which represent the
  27609. // same axis), used as axis directions evenly spread on a sphere.
  27610. const _axisDirections = [
  27611. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  27612. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27613. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27614. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27615. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27616. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27617. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27618. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27619. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27620. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  27621. /**
  27622. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27623. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27624. * blur to be quickly accessed based on material roughness. It is packed into a
  27625. * special CubeUV format that allows us to perform custom interpolation so that
  27626. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27627. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27628. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27629. * higher roughness levels. In this way we maintain resolution to smoothly
  27630. * interpolate diffuse lighting while limiting sampling computation.
  27631. *
  27632. * Paper: Fast, Accurate Image-Based Lighting
  27633. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27634. */
  27635. function convertLinearToRGBE( color ) {
  27636. const maxComponent = Math.max( color.r, color.g, color.b );
  27637. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  27638. color.multiplyScalar( Math.pow( 2.0, - fExp ) );
  27639. const alpha = ( fExp + 128.0 ) / 255.0;
  27640. return alpha;
  27641. }
  27642. class PMREMGenerator {
  27643. constructor( renderer ) {
  27644. this._renderer = renderer;
  27645. this._pingPongRenderTarget = null;
  27646. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  27647. this._equirectShader = null;
  27648. this._cubemapShader = null;
  27649. this._compileMaterial( this._blurMaterial );
  27650. }
  27651. /**
  27652. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27653. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27654. * in radians to be applied to the scene before PMREM generation. Optional near
  27655. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27656. * is placed at the origin).
  27657. */
  27658. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27659. _oldTarget = this._renderer.getRenderTarget();
  27660. const cubeUVRenderTarget = this._allocateTargets();
  27661. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27662. if ( sigma > 0 ) {
  27663. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27664. }
  27665. this._applyPMREM( cubeUVRenderTarget );
  27666. this._cleanup( cubeUVRenderTarget );
  27667. return cubeUVRenderTarget;
  27668. }
  27669. /**
  27670. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27671. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27672. * as this matches best with the 256 x 256 cubemap output.
  27673. */
  27674. fromEquirectangular( equirectangular ) {
  27675. return this._fromTexture( equirectangular );
  27676. }
  27677. /**
  27678. * Generates a PMREM from an cubemap texture, which can be either LDR
  27679. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27680. * as this matches best with the 256 x 256 cubemap output.
  27681. */
  27682. fromCubemap( cubemap ) {
  27683. return this._fromTexture( cubemap );
  27684. }
  27685. /**
  27686. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27687. * your texture's network fetch for increased concurrency.
  27688. */
  27689. compileCubemapShader() {
  27690. if ( this._cubemapShader === null ) {
  27691. this._cubemapShader = _getCubemapShader();
  27692. this._compileMaterial( this._cubemapShader );
  27693. }
  27694. }
  27695. /**
  27696. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27697. * your texture's network fetch for increased concurrency.
  27698. */
  27699. compileEquirectangularShader() {
  27700. if ( this._equirectShader === null ) {
  27701. this._equirectShader = _getEquirectShader();
  27702. this._compileMaterial( this._equirectShader );
  27703. }
  27704. }
  27705. /**
  27706. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27707. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27708. * one of them will cause any others to also become unusable.
  27709. */
  27710. dispose() {
  27711. this._blurMaterial.dispose();
  27712. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  27713. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  27714. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  27715. _lodPlanes[ i ].dispose();
  27716. }
  27717. }
  27718. // private interface
  27719. _cleanup( outputTarget ) {
  27720. this._pingPongRenderTarget.dispose();
  27721. this._renderer.setRenderTarget( _oldTarget );
  27722. outputTarget.scissorTest = false;
  27723. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27724. }
  27725. _fromTexture( texture ) {
  27726. _oldTarget = this._renderer.getRenderTarget();
  27727. const cubeUVRenderTarget = this._allocateTargets( texture );
  27728. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27729. this._applyPMREM( cubeUVRenderTarget );
  27730. this._cleanup( cubeUVRenderTarget );
  27731. return cubeUVRenderTarget;
  27732. }
  27733. _allocateTargets( texture ) { // warning: null texture is valid
  27734. const params = {
  27735. magFilter: NearestFilter,
  27736. minFilter: NearestFilter,
  27737. generateMipmaps: false,
  27738. type: UnsignedByteType,
  27739. format: RGBEFormat,
  27740. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  27741. depthBuffer: false
  27742. };
  27743. const cubeUVRenderTarget = _createRenderTarget( params );
  27744. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27745. this._pingPongRenderTarget = _createRenderTarget( params );
  27746. return cubeUVRenderTarget;
  27747. }
  27748. _compileMaterial( material ) {
  27749. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  27750. this._renderer.compile( tmpMesh, _flatCamera );
  27751. }
  27752. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27753. const fov = 90;
  27754. const aspect = 1;
  27755. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  27756. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  27757. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27758. const renderer = this._renderer;
  27759. const originalAutoClear = renderer.autoClear;
  27760. const outputEncoding = renderer.outputEncoding;
  27761. const toneMapping = renderer.toneMapping;
  27762. renderer.getClearColor( _clearColor );
  27763. renderer.toneMapping = NoToneMapping;
  27764. renderer.outputEncoding = LinearEncoding;
  27765. renderer.autoClear = false;
  27766. let useSolidColor = false;
  27767. const background = scene.background;
  27768. if ( background ) {
  27769. if ( background.isColor ) {
  27770. backgroundMaterial.color.copy( background ).convertSRGBToLinear();
  27771. scene.background = null;
  27772. const alpha = convertLinearToRGBE( backgroundMaterial.color );
  27773. backgroundMaterial.opacity = alpha;
  27774. useSolidColor = true;
  27775. }
  27776. } else {
  27777. backgroundMaterial.color.copy( _clearColor ).convertSRGBToLinear();
  27778. const alpha = convertLinearToRGBE( backgroundMaterial.color );
  27779. backgroundMaterial.opacity = alpha;
  27780. useSolidColor = true;
  27781. }
  27782. for ( let i = 0; i < 6; i ++ ) {
  27783. const col = i % 3;
  27784. if ( col == 0 ) {
  27785. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27786. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27787. } else if ( col == 1 ) {
  27788. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27789. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27790. } else {
  27791. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27792. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27793. }
  27794. _setViewport( cubeUVRenderTarget,
  27795. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  27796. renderer.setRenderTarget( cubeUVRenderTarget );
  27797. if ( useSolidColor ) {
  27798. renderer.render( backgroundBox, cubeCamera );
  27799. }
  27800. renderer.render( scene, cubeCamera );
  27801. }
  27802. renderer.toneMapping = toneMapping;
  27803. renderer.outputEncoding = outputEncoding;
  27804. renderer.autoClear = originalAutoClear;
  27805. }
  27806. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27807. const renderer = this._renderer;
  27808. if ( texture.isCubeTexture ) {
  27809. if ( this._cubemapShader == null ) {
  27810. this._cubemapShader = _getCubemapShader();
  27811. }
  27812. } else {
  27813. if ( this._equirectShader == null ) {
  27814. this._equirectShader = _getEquirectShader();
  27815. }
  27816. }
  27817. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27818. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  27819. const uniforms = material.uniforms;
  27820. uniforms[ 'envMap' ].value = texture;
  27821. if ( ! texture.isCubeTexture ) {
  27822. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  27823. }
  27824. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  27825. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  27826. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  27827. renderer.setRenderTarget( cubeUVRenderTarget );
  27828. renderer.render( mesh, _flatCamera );
  27829. }
  27830. _applyPMREM( cubeUVRenderTarget ) {
  27831. const renderer = this._renderer;
  27832. const autoClear = renderer.autoClear;
  27833. renderer.autoClear = false;
  27834. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  27835. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  27836. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  27837. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27838. }
  27839. renderer.autoClear = autoClear;
  27840. }
  27841. /**
  27842. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27843. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27844. * the blur latitudinally (around the poles), and then longitudinally (towards
  27845. * the poles) to approximate the orthogonally-separable blur. It is least
  27846. * accurate at the poles, but still does a decent job.
  27847. */
  27848. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27849. const pingPongRenderTarget = this._pingPongRenderTarget;
  27850. this._halfBlur(
  27851. cubeUVRenderTarget,
  27852. pingPongRenderTarget,
  27853. lodIn,
  27854. lodOut,
  27855. sigma,
  27856. 'latitudinal',
  27857. poleAxis );
  27858. this._halfBlur(
  27859. pingPongRenderTarget,
  27860. cubeUVRenderTarget,
  27861. lodOut,
  27862. lodOut,
  27863. sigma,
  27864. 'longitudinal',
  27865. poleAxis );
  27866. }
  27867. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27868. const renderer = this._renderer;
  27869. const blurMaterial = this._blurMaterial;
  27870. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27871. console.error(
  27872. 'blur direction must be either latitudinal or longitudinal!' );
  27873. }
  27874. // Number of standard deviations at which to cut off the discrete approximation.
  27875. const STANDARD_DEVIATIONS = 3;
  27876. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  27877. const blurUniforms = blurMaterial.uniforms;
  27878. const pixels = _sizeLods[ lodIn ] - 1;
  27879. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27880. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27881. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27882. if ( samples > MAX_SAMPLES ) {
  27883. console.warn( `sigmaRadians, ${
  27884. sigmaRadians}, is too large and will clip, as it requested ${
  27885. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27886. }
  27887. const weights = [];
  27888. let sum = 0;
  27889. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27890. const x = i / sigmaPixels;
  27891. const weight = Math.exp( - x * x / 2 );
  27892. weights.push( weight );
  27893. if ( i == 0 ) {
  27894. sum += weight;
  27895. } else if ( i < samples ) {
  27896. sum += 2 * weight;
  27897. }
  27898. }
  27899. for ( let i = 0; i < weights.length; i ++ ) {
  27900. weights[ i ] = weights[ i ] / sum;
  27901. }
  27902. blurUniforms[ 'envMap' ].value = targetIn.texture;
  27903. blurUniforms[ 'samples' ].value = samples;
  27904. blurUniforms[ 'weights' ].value = weights;
  27905. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  27906. if ( poleAxis ) {
  27907. blurUniforms[ 'poleAxis' ].value = poleAxis;
  27908. }
  27909. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  27910. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  27911. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  27912. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  27913. const outputSize = _sizeLods[ lodOut ];
  27914. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  27915. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  27916. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27917. renderer.setRenderTarget( targetOut );
  27918. renderer.render( blurMesh, _flatCamera );
  27919. }
  27920. }
  27921. function _isLDR( texture ) {
  27922. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  27923. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27924. }
  27925. function _createPlanes() {
  27926. const _lodPlanes = [];
  27927. const _sizeLods = [];
  27928. const _sigmas = [];
  27929. let lod = LOD_MAX;
  27930. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  27931. const sizeLod = Math.pow( 2, lod );
  27932. _sizeLods.push( sizeLod );
  27933. let sigma = 1.0 / sizeLod;
  27934. if ( i > LOD_MAX - LOD_MIN ) {
  27935. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  27936. } else if ( i == 0 ) {
  27937. sigma = 0;
  27938. }
  27939. _sigmas.push( sigma );
  27940. const texelSize = 1.0 / ( sizeLod - 1 );
  27941. const min = - texelSize / 2;
  27942. const max = 1 + texelSize / 2;
  27943. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27944. const cubeFaces = 6;
  27945. const vertices = 6;
  27946. const positionSize = 3;
  27947. const uvSize = 2;
  27948. const faceIndexSize = 1;
  27949. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27950. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27951. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27952. for ( let face = 0; face < cubeFaces; face ++ ) {
  27953. const x = ( face % 3 ) * 2 / 3 - 1;
  27954. const y = face > 2 ? 0 : - 1;
  27955. const coordinates = [
  27956. x, y, 0,
  27957. x + 2 / 3, y, 0,
  27958. x + 2 / 3, y + 1, 0,
  27959. x, y, 0,
  27960. x + 2 / 3, y + 1, 0,
  27961. x, y + 1, 0
  27962. ];
  27963. position.set( coordinates, positionSize * vertices * face );
  27964. uv.set( uv1, uvSize * vertices * face );
  27965. const fill = [ face, face, face, face, face, face ];
  27966. faceIndex.set( fill, faceIndexSize * vertices * face );
  27967. }
  27968. const planes = new BufferGeometry();
  27969. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27970. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27971. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27972. _lodPlanes.push( planes );
  27973. if ( lod > LOD_MIN ) {
  27974. lod --;
  27975. }
  27976. }
  27977. return { _lodPlanes, _sizeLods, _sigmas };
  27978. }
  27979. function _createRenderTarget( params ) {
  27980. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  27981. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27982. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27983. cubeUVRenderTarget.scissorTest = true;
  27984. return cubeUVRenderTarget;
  27985. }
  27986. function _setViewport( target, x, y, width, height ) {
  27987. target.viewport.set( x, y, width, height );
  27988. target.scissor.set( x, y, width, height );
  27989. }
  27990. function _getBlurShader( maxSamples ) {
  27991. const weights = new Float32Array( maxSamples );
  27992. const poleAxis = new Vector3( 0, 1, 0 );
  27993. const shaderMaterial = new RawShaderMaterial( {
  27994. name: 'SphericalGaussianBlur',
  27995. defines: { 'n': maxSamples },
  27996. uniforms: {
  27997. 'envMap': { value: null },
  27998. 'samples': { value: 1 },
  27999. 'weights': { value: weights },
  28000. 'latitudinal': { value: false },
  28001. 'dTheta': { value: 0 },
  28002. 'mipInt': { value: 0 },
  28003. 'poleAxis': { value: poleAxis },
  28004. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  28005. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  28006. },
  28007. vertexShader: _getCommonVertexShader(),
  28008. fragmentShader: /* glsl */`
  28009. precision mediump float;
  28010. precision mediump int;
  28011. varying vec3 vOutputDirection;
  28012. uniform sampler2D envMap;
  28013. uniform int samples;
  28014. uniform float weights[ n ];
  28015. uniform bool latitudinal;
  28016. uniform float dTheta;
  28017. uniform float mipInt;
  28018. uniform vec3 poleAxis;
  28019. ${ _getEncodings() }
  28020. #define ENVMAP_TYPE_CUBE_UV
  28021. #include <cube_uv_reflection_fragment>
  28022. vec3 getSample( float theta, vec3 axis ) {
  28023. float cosTheta = cos( theta );
  28024. // Rodrigues' axis-angle rotation
  28025. vec3 sampleDirection = vOutputDirection * cosTheta
  28026. + cross( axis, vOutputDirection ) * sin( theta )
  28027. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  28028. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  28029. }
  28030. void main() {
  28031. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  28032. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  28033. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  28034. }
  28035. axis = normalize( axis );
  28036. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  28037. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  28038. for ( int i = 1; i < n; i++ ) {
  28039. if ( i >= samples ) {
  28040. break;
  28041. }
  28042. float theta = dTheta * float( i );
  28043. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  28044. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  28045. }
  28046. gl_FragColor = linearToOutputTexel( gl_FragColor );
  28047. }
  28048. `,
  28049. blending: NoBlending,
  28050. depthTest: false,
  28051. depthWrite: false
  28052. } );
  28053. return shaderMaterial;
  28054. }
  28055. function _getEquirectShader() {
  28056. const texelSize = new Vector2( 1, 1 );
  28057. const shaderMaterial = new RawShaderMaterial( {
  28058. name: 'EquirectangularToCubeUV',
  28059. uniforms: {
  28060. 'envMap': { value: null },
  28061. 'texelSize': { value: texelSize },
  28062. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  28063. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  28064. },
  28065. vertexShader: _getCommonVertexShader(),
  28066. fragmentShader: /* glsl */`
  28067. precision mediump float;
  28068. precision mediump int;
  28069. varying vec3 vOutputDirection;
  28070. uniform sampler2D envMap;
  28071. uniform vec2 texelSize;
  28072. ${ _getEncodings() }
  28073. #include <common>
  28074. void main() {
  28075. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  28076. vec3 outputDirection = normalize( vOutputDirection );
  28077. vec2 uv = equirectUv( outputDirection );
  28078. vec2 f = fract( uv / texelSize - 0.5 );
  28079. uv -= f * texelSize;
  28080. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28081. uv.x += texelSize.x;
  28082. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28083. uv.y += texelSize.y;
  28084. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28085. uv.x -= texelSize.x;
  28086. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28087. vec3 tm = mix( tl, tr, f.x );
  28088. vec3 bm = mix( bl, br, f.x );
  28089. gl_FragColor.rgb = mix( tm, bm, f.y );
  28090. gl_FragColor = linearToOutputTexel( gl_FragColor );
  28091. }
  28092. `,
  28093. blending: NoBlending,
  28094. depthTest: false,
  28095. depthWrite: false
  28096. } );
  28097. return shaderMaterial;
  28098. }
  28099. function _getCubemapShader() {
  28100. const shaderMaterial = new RawShaderMaterial( {
  28101. name: 'CubemapToCubeUV',
  28102. uniforms: {
  28103. 'envMap': { value: null },
  28104. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  28105. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  28106. },
  28107. vertexShader: _getCommonVertexShader(),
  28108. fragmentShader: /* glsl */`
  28109. precision mediump float;
  28110. precision mediump int;
  28111. varying vec3 vOutputDirection;
  28112. uniform samplerCube envMap;
  28113. ${ _getEncodings() }
  28114. void main() {
  28115. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  28116. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  28117. gl_FragColor = linearToOutputTexel( gl_FragColor );
  28118. }
  28119. `,
  28120. blending: NoBlending,
  28121. depthTest: false,
  28122. depthWrite: false
  28123. } );
  28124. return shaderMaterial;
  28125. }
  28126. function _getCommonVertexShader() {
  28127. return /* glsl */`
  28128. precision mediump float;
  28129. precision mediump int;
  28130. attribute vec3 position;
  28131. attribute vec2 uv;
  28132. attribute float faceIndex;
  28133. varying vec3 vOutputDirection;
  28134. // RH coordinate system; PMREM face-indexing convention
  28135. vec3 getDirection( vec2 uv, float face ) {
  28136. uv = 2.0 * uv - 1.0;
  28137. vec3 direction = vec3( uv, 1.0 );
  28138. if ( face == 0.0 ) {
  28139. direction = direction.zyx; // ( 1, v, u ) pos x
  28140. } else if ( face == 1.0 ) {
  28141. direction = direction.xzy;
  28142. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  28143. } else if ( face == 2.0 ) {
  28144. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  28145. } else if ( face == 3.0 ) {
  28146. direction = direction.zyx;
  28147. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  28148. } else if ( face == 4.0 ) {
  28149. direction = direction.xzy;
  28150. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  28151. } else if ( face == 5.0 ) {
  28152. direction.z *= -1.0; // ( u, v, -1 ) neg z
  28153. }
  28154. return direction;
  28155. }
  28156. void main() {
  28157. vOutputDirection = getDirection( uv, faceIndex );
  28158. gl_Position = vec4( position, 1.0 );
  28159. }
  28160. `;
  28161. }
  28162. function _getEncodings() {
  28163. return /* glsl */`
  28164. uniform int inputEncoding;
  28165. uniform int outputEncoding;
  28166. #include <encodings_pars_fragment>
  28167. vec4 inputTexelToLinear( vec4 value ) {
  28168. if ( inputEncoding == 0 ) {
  28169. return value;
  28170. } else if ( inputEncoding == 1 ) {
  28171. return sRGBToLinear( value );
  28172. } else if ( inputEncoding == 2 ) {
  28173. return RGBEToLinear( value );
  28174. } else if ( inputEncoding == 3 ) {
  28175. return RGBMToLinear( value, 7.0 );
  28176. } else if ( inputEncoding == 4 ) {
  28177. return RGBMToLinear( value, 16.0 );
  28178. } else if ( inputEncoding == 5 ) {
  28179. return RGBDToLinear( value, 256.0 );
  28180. } else {
  28181. return GammaToLinear( value, 2.2 );
  28182. }
  28183. }
  28184. vec4 linearToOutputTexel( vec4 value ) {
  28185. if ( outputEncoding == 0 ) {
  28186. return value;
  28187. } else if ( outputEncoding == 1 ) {
  28188. return LinearTosRGB( value );
  28189. } else if ( outputEncoding == 2 ) {
  28190. return LinearToRGBE( value );
  28191. } else if ( outputEncoding == 3 ) {
  28192. return LinearToRGBM( value, 7.0 );
  28193. } else if ( outputEncoding == 4 ) {
  28194. return LinearToRGBM( value, 16.0 );
  28195. } else if ( outputEncoding == 5 ) {
  28196. return LinearToRGBD( value, 256.0 );
  28197. } else {
  28198. return LinearToGamma( value, 2.2 );
  28199. }
  28200. }
  28201. vec4 envMapTexelToLinear( vec4 color ) {
  28202. return inputTexelToLinear( color );
  28203. }
  28204. `;
  28205. }
  28206. const LineStrip = 0;
  28207. const LinePieces = 1;
  28208. const NoColors = 0;
  28209. const FaceColors = 1;
  28210. const VertexColors = 2;
  28211. function MeshFaceMaterial( materials ) {
  28212. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  28213. return materials;
  28214. }
  28215. function MultiMaterial( materials = [] ) {
  28216. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  28217. materials.isMultiMaterial = true;
  28218. materials.materials = materials;
  28219. materials.clone = function () {
  28220. return materials.slice();
  28221. };
  28222. return materials;
  28223. }
  28224. function PointCloud( geometry, material ) {
  28225. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28226. return new Points( geometry, material );
  28227. }
  28228. function Particle( material ) {
  28229. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28230. return new Sprite( material );
  28231. }
  28232. function ParticleSystem( geometry, material ) {
  28233. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28234. return new Points( geometry, material );
  28235. }
  28236. function PointCloudMaterial( parameters ) {
  28237. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28238. return new PointsMaterial( parameters );
  28239. }
  28240. function ParticleBasicMaterial( parameters ) {
  28241. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28242. return new PointsMaterial( parameters );
  28243. }
  28244. function ParticleSystemMaterial( parameters ) {
  28245. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28246. return new PointsMaterial( parameters );
  28247. }
  28248. function Vertex( x, y, z ) {
  28249. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28250. return new Vector3( x, y, z );
  28251. }
  28252. //
  28253. function DynamicBufferAttribute( array, itemSize ) {
  28254. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  28255. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  28256. }
  28257. function Int8Attribute( array, itemSize ) {
  28258. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28259. return new Int8BufferAttribute( array, itemSize );
  28260. }
  28261. function Uint8Attribute( array, itemSize ) {
  28262. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28263. return new Uint8BufferAttribute( array, itemSize );
  28264. }
  28265. function Uint8ClampedAttribute( array, itemSize ) {
  28266. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28267. return new Uint8ClampedBufferAttribute( array, itemSize );
  28268. }
  28269. function Int16Attribute( array, itemSize ) {
  28270. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28271. return new Int16BufferAttribute( array, itemSize );
  28272. }
  28273. function Uint16Attribute( array, itemSize ) {
  28274. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28275. return new Uint16BufferAttribute( array, itemSize );
  28276. }
  28277. function Int32Attribute( array, itemSize ) {
  28278. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28279. return new Int32BufferAttribute( array, itemSize );
  28280. }
  28281. function Uint32Attribute( array, itemSize ) {
  28282. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28283. return new Uint32BufferAttribute( array, itemSize );
  28284. }
  28285. function Float32Attribute( array, itemSize ) {
  28286. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28287. return new Float32BufferAttribute( array, itemSize );
  28288. }
  28289. function Float64Attribute( array, itemSize ) {
  28290. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  28291. return new Float64BufferAttribute( array, itemSize );
  28292. }
  28293. //
  28294. Curve.create = function ( construct, getPoint ) {
  28295. console.log( 'THREE.Curve.create() has been deprecated' );
  28296. construct.prototype = Object.create( Curve.prototype );
  28297. construct.prototype.constructor = construct;
  28298. construct.prototype.getPoint = getPoint;
  28299. return construct;
  28300. };
  28301. //
  28302. Path.prototype.fromPoints = function ( points ) {
  28303. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28304. return this.setFromPoints( points );
  28305. };
  28306. //
  28307. function AxisHelper( size ) {
  28308. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28309. return new AxesHelper( size );
  28310. }
  28311. function BoundingBoxHelper( object, color ) {
  28312. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28313. return new BoxHelper( object, color );
  28314. }
  28315. function EdgesHelper( object, hex ) {
  28316. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28317. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28318. }
  28319. GridHelper.prototype.setColors = function () {
  28320. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28321. };
  28322. SkeletonHelper.prototype.update = function () {
  28323. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28324. };
  28325. function WireframeHelper( object, hex ) {
  28326. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28327. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28328. }
  28329. //
  28330. Loader.prototype.extractUrlBase = function ( url ) {
  28331. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28332. return LoaderUtils.extractUrlBase( url );
  28333. };
  28334. Loader.Handlers = {
  28335. add: function ( /* regex, loader */ ) {
  28336. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28337. },
  28338. get: function ( /* file */ ) {
  28339. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28340. }
  28341. };
  28342. function XHRLoader( manager ) {
  28343. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28344. return new FileLoader( manager );
  28345. }
  28346. function BinaryTextureLoader( manager ) {
  28347. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28348. return new DataTextureLoader( manager );
  28349. }
  28350. //
  28351. Box2.prototype.center = function ( optionalTarget ) {
  28352. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28353. return this.getCenter( optionalTarget );
  28354. };
  28355. Box2.prototype.empty = function () {
  28356. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28357. return this.isEmpty();
  28358. };
  28359. Box2.prototype.isIntersectionBox = function ( box ) {
  28360. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28361. return this.intersectsBox( box );
  28362. };
  28363. Box2.prototype.size = function ( optionalTarget ) {
  28364. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28365. return this.getSize( optionalTarget );
  28366. };
  28367. //
  28368. Box3.prototype.center = function ( optionalTarget ) {
  28369. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28370. return this.getCenter( optionalTarget );
  28371. };
  28372. Box3.prototype.empty = function () {
  28373. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28374. return this.isEmpty();
  28375. };
  28376. Box3.prototype.isIntersectionBox = function ( box ) {
  28377. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28378. return this.intersectsBox( box );
  28379. };
  28380. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28381. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28382. return this.intersectsSphere( sphere );
  28383. };
  28384. Box3.prototype.size = function ( optionalTarget ) {
  28385. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  28386. return this.getSize( optionalTarget );
  28387. };
  28388. //
  28389. Sphere.prototype.empty = function () {
  28390. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  28391. return this.isEmpty();
  28392. };
  28393. //
  28394. Frustum.prototype.setFromMatrix = function ( m ) {
  28395. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  28396. return this.setFromProjectionMatrix( m );
  28397. };
  28398. //
  28399. Line3.prototype.center = function ( optionalTarget ) {
  28400. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  28401. return this.getCenter( optionalTarget );
  28402. };
  28403. //
  28404. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  28405. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28406. return this.toArray( array, offset );
  28407. };
  28408. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  28409. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  28410. return vector.applyMatrix3( this );
  28411. };
  28412. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  28413. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  28414. };
  28415. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  28416. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  28417. return attribute.applyMatrix3( this );
  28418. };
  28419. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28420. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  28421. };
  28422. Matrix3.prototype.getInverse = function ( matrix ) {
  28423. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28424. return this.copy( matrix ).invert();
  28425. };
  28426. //
  28427. Matrix4.prototype.extractPosition = function ( m ) {
  28428. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  28429. return this.copyPosition( m );
  28430. };
  28431. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  28432. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28433. return this.toArray( array, offset );
  28434. };
  28435. Matrix4.prototype.getPosition = function () {
  28436. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  28437. return new Vector3().setFromMatrixColumn( this, 3 );
  28438. };
  28439. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  28440. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  28441. return this.makeRotationFromQuaternion( q );
  28442. };
  28443. Matrix4.prototype.multiplyToArray = function () {
  28444. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  28445. };
  28446. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  28447. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28448. return vector.applyMatrix4( this );
  28449. };
  28450. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  28451. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28452. return vector.applyMatrix4( this );
  28453. };
  28454. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  28455. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  28456. };
  28457. Matrix4.prototype.rotateAxis = function ( v ) {
  28458. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  28459. v.transformDirection( this );
  28460. };
  28461. Matrix4.prototype.crossVector = function ( vector ) {
  28462. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28463. return vector.applyMatrix4( this );
  28464. };
  28465. Matrix4.prototype.translate = function () {
  28466. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  28467. };
  28468. Matrix4.prototype.rotateX = function () {
  28469. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  28470. };
  28471. Matrix4.prototype.rotateY = function () {
  28472. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  28473. };
  28474. Matrix4.prototype.rotateZ = function () {
  28475. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  28476. };
  28477. Matrix4.prototype.rotateByAxis = function () {
  28478. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  28479. };
  28480. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  28481. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  28482. return attribute.applyMatrix4( this );
  28483. };
  28484. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28485. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  28486. };
  28487. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  28488. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  28489. return this.makePerspective( left, right, top, bottom, near, far );
  28490. };
  28491. Matrix4.prototype.getInverse = function ( matrix ) {
  28492. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28493. return this.copy( matrix ).invert();
  28494. };
  28495. //
  28496. Plane.prototype.isIntersectionLine = function ( line ) {
  28497. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  28498. return this.intersectsLine( line );
  28499. };
  28500. //
  28501. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  28502. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  28503. return vector.applyQuaternion( this );
  28504. };
  28505. Quaternion.prototype.inverse = function ( ) {
  28506. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  28507. return this.invert();
  28508. };
  28509. //
  28510. Ray.prototype.isIntersectionBox = function ( box ) {
  28511. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28512. return this.intersectsBox( box );
  28513. };
  28514. Ray.prototype.isIntersectionPlane = function ( plane ) {
  28515. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  28516. return this.intersectsPlane( plane );
  28517. };
  28518. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  28519. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28520. return this.intersectsSphere( sphere );
  28521. };
  28522. //
  28523. Triangle.prototype.area = function () {
  28524. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  28525. return this.getArea();
  28526. };
  28527. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  28528. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28529. return this.getBarycoord( point, target );
  28530. };
  28531. Triangle.prototype.midpoint = function ( target ) {
  28532. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  28533. return this.getMidpoint( target );
  28534. };
  28535. Triangle.prototypenormal = function ( target ) {
  28536. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28537. return this.getNormal( target );
  28538. };
  28539. Triangle.prototype.plane = function ( target ) {
  28540. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  28541. return this.getPlane( target );
  28542. };
  28543. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  28544. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28545. return Triangle.getBarycoord( point, a, b, c, target );
  28546. };
  28547. Triangle.normal = function ( a, b, c, target ) {
  28548. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28549. return Triangle.getNormal( a, b, c, target );
  28550. };
  28551. //
  28552. Shape.prototype.extractAllPoints = function ( divisions ) {
  28553. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  28554. return this.extractPoints( divisions );
  28555. };
  28556. Shape.prototype.extrude = function ( options ) {
  28557. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  28558. return new ExtrudeGeometry( this, options );
  28559. };
  28560. Shape.prototype.makeGeometry = function ( options ) {
  28561. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  28562. return new ShapeGeometry( this, options );
  28563. };
  28564. //
  28565. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  28566. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28567. return this.fromBufferAttribute( attribute, index, offset );
  28568. };
  28569. Vector2.prototype.distanceToManhattan = function ( v ) {
  28570. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28571. return this.manhattanDistanceTo( v );
  28572. };
  28573. Vector2.prototype.lengthManhattan = function () {
  28574. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  28575. return this.manhattanLength();
  28576. };
  28577. //
  28578. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28579. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  28580. };
  28581. Vector3.prototype.setEulerFromQuaternion = function () {
  28582. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  28583. };
  28584. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  28585. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  28586. return this.setFromMatrixPosition( m );
  28587. };
  28588. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  28589. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  28590. return this.setFromMatrixScale( m );
  28591. };
  28592. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  28593. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  28594. return this.setFromMatrixColumn( matrix, index );
  28595. };
  28596. Vector3.prototype.applyProjection = function ( m ) {
  28597. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  28598. return this.applyMatrix4( m );
  28599. };
  28600. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  28601. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28602. return this.fromBufferAttribute( attribute, index, offset );
  28603. };
  28604. Vector3.prototype.distanceToManhattan = function ( v ) {
  28605. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28606. return this.manhattanDistanceTo( v );
  28607. };
  28608. Vector3.prototype.lengthManhattan = function () {
  28609. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  28610. return this.manhattanLength();
  28611. };
  28612. //
  28613. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  28614. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28615. return this.fromBufferAttribute( attribute, index, offset );
  28616. };
  28617. Vector4.prototype.lengthManhattan = function () {
  28618. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  28619. return this.manhattanLength();
  28620. };
  28621. //
  28622. Object3D.prototype.getChildByName = function ( name ) {
  28623. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  28624. return this.getObjectByName( name );
  28625. };
  28626. Object3D.prototype.renderDepth = function () {
  28627. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  28628. };
  28629. Object3D.prototype.translate = function ( distance, axis ) {
  28630. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  28631. return this.translateOnAxis( axis, distance );
  28632. };
  28633. Object3D.prototype.getWorldRotation = function () {
  28634. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  28635. };
  28636. Object3D.prototype.applyMatrix = function ( matrix ) {
  28637. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  28638. return this.applyMatrix4( matrix );
  28639. };
  28640. Object.defineProperties( Object3D.prototype, {
  28641. eulerOrder: {
  28642. get: function () {
  28643. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28644. return this.rotation.order;
  28645. },
  28646. set: function ( value ) {
  28647. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28648. this.rotation.order = value;
  28649. }
  28650. },
  28651. useQuaternion: {
  28652. get: function () {
  28653. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28654. },
  28655. set: function () {
  28656. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28657. }
  28658. }
  28659. } );
  28660. Mesh.prototype.setDrawMode = function () {
  28661. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28662. };
  28663. Object.defineProperties( Mesh.prototype, {
  28664. drawMode: {
  28665. get: function () {
  28666. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  28667. return TrianglesDrawMode;
  28668. },
  28669. set: function () {
  28670. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28671. }
  28672. }
  28673. } );
  28674. SkinnedMesh.prototype.initBones = function () {
  28675. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  28676. };
  28677. //
  28678. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  28679. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  28680. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  28681. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  28682. this.setFocalLength( focalLength );
  28683. };
  28684. //
  28685. Object.defineProperties( Light.prototype, {
  28686. onlyShadow: {
  28687. set: function () {
  28688. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  28689. }
  28690. },
  28691. shadowCameraFov: {
  28692. set: function ( value ) {
  28693. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  28694. this.shadow.camera.fov = value;
  28695. }
  28696. },
  28697. shadowCameraLeft: {
  28698. set: function ( value ) {
  28699. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  28700. this.shadow.camera.left = value;
  28701. }
  28702. },
  28703. shadowCameraRight: {
  28704. set: function ( value ) {
  28705. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  28706. this.shadow.camera.right = value;
  28707. }
  28708. },
  28709. shadowCameraTop: {
  28710. set: function ( value ) {
  28711. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  28712. this.shadow.camera.top = value;
  28713. }
  28714. },
  28715. shadowCameraBottom: {
  28716. set: function ( value ) {
  28717. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  28718. this.shadow.camera.bottom = value;
  28719. }
  28720. },
  28721. shadowCameraNear: {
  28722. set: function ( value ) {
  28723. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  28724. this.shadow.camera.near = value;
  28725. }
  28726. },
  28727. shadowCameraFar: {
  28728. set: function ( value ) {
  28729. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  28730. this.shadow.camera.far = value;
  28731. }
  28732. },
  28733. shadowCameraVisible: {
  28734. set: function () {
  28735. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  28736. }
  28737. },
  28738. shadowBias: {
  28739. set: function ( value ) {
  28740. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  28741. this.shadow.bias = value;
  28742. }
  28743. },
  28744. shadowDarkness: {
  28745. set: function () {
  28746. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  28747. }
  28748. },
  28749. shadowMapWidth: {
  28750. set: function ( value ) {
  28751. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  28752. this.shadow.mapSize.width = value;
  28753. }
  28754. },
  28755. shadowMapHeight: {
  28756. set: function ( value ) {
  28757. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  28758. this.shadow.mapSize.height = value;
  28759. }
  28760. }
  28761. } );
  28762. //
  28763. Object.defineProperties( BufferAttribute.prototype, {
  28764. length: {
  28765. get: function () {
  28766. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  28767. return this.array.length;
  28768. }
  28769. },
  28770. dynamic: {
  28771. get: function () {
  28772. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  28773. return this.usage === DynamicDrawUsage;
  28774. },
  28775. set: function ( /* value */ ) {
  28776. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  28777. this.setUsage( DynamicDrawUsage );
  28778. }
  28779. }
  28780. } );
  28781. BufferAttribute.prototype.setDynamic = function ( value ) {
  28782. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  28783. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  28784. return this;
  28785. };
  28786. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  28787. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  28788. },
  28789. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  28790. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  28791. };
  28792. //
  28793. BufferGeometry.prototype.addIndex = function ( index ) {
  28794. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  28795. this.setIndex( index );
  28796. };
  28797. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  28798. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  28799. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  28800. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  28801. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  28802. }
  28803. if ( name === 'index' ) {
  28804. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  28805. this.setIndex( attribute );
  28806. return this;
  28807. }
  28808. return this.setAttribute( name, attribute );
  28809. };
  28810. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  28811. if ( indexOffset !== undefined ) {
  28812. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  28813. }
  28814. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  28815. this.addGroup( start, count );
  28816. };
  28817. BufferGeometry.prototype.clearDrawCalls = function () {
  28818. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  28819. this.clearGroups();
  28820. };
  28821. BufferGeometry.prototype.computeOffsets = function () {
  28822. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  28823. };
  28824. BufferGeometry.prototype.removeAttribute = function ( name ) {
  28825. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  28826. return this.deleteAttribute( name );
  28827. };
  28828. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  28829. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  28830. return this.applyMatrix4( matrix );
  28831. };
  28832. Object.defineProperties( BufferGeometry.prototype, {
  28833. drawcalls: {
  28834. get: function () {
  28835. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  28836. return this.groups;
  28837. }
  28838. },
  28839. offsets: {
  28840. get: function () {
  28841. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  28842. return this.groups;
  28843. }
  28844. }
  28845. } );
  28846. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  28847. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  28848. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  28849. return this;
  28850. };
  28851. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  28852. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  28853. };
  28854. //
  28855. ExtrudeGeometry.prototype.getArrays = function () {
  28856. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  28857. };
  28858. ExtrudeGeometry.prototype.addShapeList = function () {
  28859. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  28860. };
  28861. ExtrudeGeometry.prototype.addShape = function () {
  28862. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  28863. };
  28864. //
  28865. Scene.prototype.dispose = function () {
  28866. console.error( 'THREE.Scene: .dispose() has been removed.' );
  28867. };
  28868. //
  28869. Uniform.prototype.onUpdate = function () {
  28870. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  28871. return this;
  28872. };
  28873. //
  28874. Object.defineProperties( Material.prototype, {
  28875. wrapAround: {
  28876. get: function () {
  28877. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  28878. },
  28879. set: function () {
  28880. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  28881. }
  28882. },
  28883. overdraw: {
  28884. get: function () {
  28885. console.warn( 'THREE.Material: .overdraw has been removed.' );
  28886. },
  28887. set: function () {
  28888. console.warn( 'THREE.Material: .overdraw has been removed.' );
  28889. }
  28890. },
  28891. wrapRGB: {
  28892. get: function () {
  28893. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  28894. return new Color();
  28895. }
  28896. },
  28897. shading: {
  28898. get: function () {
  28899. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  28900. },
  28901. set: function ( value ) {
  28902. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  28903. this.flatShading = ( value === FlatShading );
  28904. }
  28905. },
  28906. stencilMask: {
  28907. get: function () {
  28908. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  28909. return this.stencilFuncMask;
  28910. },
  28911. set: function ( value ) {
  28912. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  28913. this.stencilFuncMask = value;
  28914. }
  28915. }
  28916. } );
  28917. Object.defineProperties( ShaderMaterial.prototype, {
  28918. derivatives: {
  28919. get: function () {
  28920. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  28921. return this.extensions.derivatives;
  28922. },
  28923. set: function ( value ) {
  28924. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  28925. this.extensions.derivatives = value;
  28926. }
  28927. }
  28928. } );
  28929. //
  28930. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  28931. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  28932. this.setRenderTarget( renderTarget );
  28933. this.clear( color, depth, stencil );
  28934. };
  28935. WebGLRenderer.prototype.animate = function ( callback ) {
  28936. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  28937. this.setAnimationLoop( callback );
  28938. };
  28939. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28940. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  28941. return this.getRenderTarget();
  28942. };
  28943. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28944. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  28945. return this.capabilities.getMaxAnisotropy();
  28946. };
  28947. WebGLRenderer.prototype.getPrecision = function () {
  28948. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  28949. return this.capabilities.precision;
  28950. };
  28951. WebGLRenderer.prototype.resetGLState = function () {
  28952. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  28953. return this.state.reset();
  28954. };
  28955. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28956. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  28957. return this.extensions.get( 'OES_texture_float' );
  28958. };
  28959. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28960. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  28961. return this.extensions.get( 'OES_texture_half_float' );
  28962. };
  28963. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28964. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  28965. return this.extensions.get( 'OES_standard_derivatives' );
  28966. };
  28967. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28968. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  28969. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  28970. };
  28971. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28972. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  28973. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  28974. };
  28975. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28976. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  28977. return this.extensions.get( 'EXT_blend_minmax' );
  28978. };
  28979. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28980. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  28981. return this.capabilities.vertexTextures;
  28982. };
  28983. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28984. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  28985. return this.extensions.get( 'ANGLE_instanced_arrays' );
  28986. };
  28987. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  28988. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  28989. this.setScissorTest( boolean );
  28990. };
  28991. WebGLRenderer.prototype.initMaterial = function () {
  28992. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  28993. };
  28994. WebGLRenderer.prototype.addPrePlugin = function () {
  28995. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  28996. };
  28997. WebGLRenderer.prototype.addPostPlugin = function () {
  28998. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  28999. };
  29000. WebGLRenderer.prototype.updateShadowMap = function () {
  29001. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29002. };
  29003. WebGLRenderer.prototype.setFaceCulling = function () {
  29004. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  29005. };
  29006. WebGLRenderer.prototype.allocTextureUnit = function () {
  29007. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  29008. };
  29009. WebGLRenderer.prototype.setTexture = function () {
  29010. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  29011. };
  29012. WebGLRenderer.prototype.setTexture2D = function () {
  29013. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  29014. };
  29015. WebGLRenderer.prototype.setTextureCube = function () {
  29016. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  29017. };
  29018. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29019. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  29020. return this.getActiveMipmapLevel();
  29021. };
  29022. Object.defineProperties( WebGLRenderer.prototype, {
  29023. shadowMapEnabled: {
  29024. get: function () {
  29025. return this.shadowMap.enabled;
  29026. },
  29027. set: function ( value ) {
  29028. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29029. this.shadowMap.enabled = value;
  29030. }
  29031. },
  29032. shadowMapType: {
  29033. get: function () {
  29034. return this.shadowMap.type;
  29035. },
  29036. set: function ( value ) {
  29037. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29038. this.shadowMap.type = value;
  29039. }
  29040. },
  29041. shadowMapCullFace: {
  29042. get: function () {
  29043. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29044. return undefined;
  29045. },
  29046. set: function ( /* value */ ) {
  29047. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29048. }
  29049. },
  29050. context: {
  29051. get: function () {
  29052. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  29053. return this.getContext();
  29054. }
  29055. },
  29056. vr: {
  29057. get: function () {
  29058. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  29059. return this.xr;
  29060. }
  29061. },
  29062. gammaInput: {
  29063. get: function () {
  29064. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29065. return false;
  29066. },
  29067. set: function () {
  29068. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29069. }
  29070. },
  29071. gammaOutput: {
  29072. get: function () {
  29073. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29074. return false;
  29075. },
  29076. set: function ( value ) {
  29077. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29078. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  29079. }
  29080. },
  29081. toneMappingWhitePoint: {
  29082. get: function () {
  29083. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29084. return 1.0;
  29085. },
  29086. set: function () {
  29087. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29088. }
  29089. },
  29090. } );
  29091. Object.defineProperties( WebGLShadowMap.prototype, {
  29092. cullFace: {
  29093. get: function () {
  29094. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29095. return undefined;
  29096. },
  29097. set: function ( /* cullFace */ ) {
  29098. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29099. }
  29100. },
  29101. renderReverseSided: {
  29102. get: function () {
  29103. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29104. return undefined;
  29105. },
  29106. set: function () {
  29107. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29108. }
  29109. },
  29110. renderSingleSided: {
  29111. get: function () {
  29112. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29113. return undefined;
  29114. },
  29115. set: function () {
  29116. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29117. }
  29118. }
  29119. } );
  29120. function WebGLRenderTargetCube( width, height, options ) {
  29121. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  29122. return new WebGLCubeRenderTarget( width, options );
  29123. }
  29124. //
  29125. Object.defineProperties( WebGLRenderTarget.prototype, {
  29126. wrapS: {
  29127. get: function () {
  29128. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29129. return this.texture.wrapS;
  29130. },
  29131. set: function ( value ) {
  29132. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29133. this.texture.wrapS = value;
  29134. }
  29135. },
  29136. wrapT: {
  29137. get: function () {
  29138. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29139. return this.texture.wrapT;
  29140. },
  29141. set: function ( value ) {
  29142. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29143. this.texture.wrapT = value;
  29144. }
  29145. },
  29146. magFilter: {
  29147. get: function () {
  29148. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29149. return this.texture.magFilter;
  29150. },
  29151. set: function ( value ) {
  29152. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29153. this.texture.magFilter = value;
  29154. }
  29155. },
  29156. minFilter: {
  29157. get: function () {
  29158. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29159. return this.texture.minFilter;
  29160. },
  29161. set: function ( value ) {
  29162. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29163. this.texture.minFilter = value;
  29164. }
  29165. },
  29166. anisotropy: {
  29167. get: function () {
  29168. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29169. return this.texture.anisotropy;
  29170. },
  29171. set: function ( value ) {
  29172. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29173. this.texture.anisotropy = value;
  29174. }
  29175. },
  29176. offset: {
  29177. get: function () {
  29178. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29179. return this.texture.offset;
  29180. },
  29181. set: function ( value ) {
  29182. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29183. this.texture.offset = value;
  29184. }
  29185. },
  29186. repeat: {
  29187. get: function () {
  29188. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29189. return this.texture.repeat;
  29190. },
  29191. set: function ( value ) {
  29192. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29193. this.texture.repeat = value;
  29194. }
  29195. },
  29196. format: {
  29197. get: function () {
  29198. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29199. return this.texture.format;
  29200. },
  29201. set: function ( value ) {
  29202. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29203. this.texture.format = value;
  29204. }
  29205. },
  29206. type: {
  29207. get: function () {
  29208. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29209. return this.texture.type;
  29210. },
  29211. set: function ( value ) {
  29212. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29213. this.texture.type = value;
  29214. }
  29215. },
  29216. generateMipmaps: {
  29217. get: function () {
  29218. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29219. return this.texture.generateMipmaps;
  29220. },
  29221. set: function ( value ) {
  29222. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29223. this.texture.generateMipmaps = value;
  29224. }
  29225. }
  29226. } );
  29227. //
  29228. Audio.prototype.load = function ( file ) {
  29229. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29230. const scope = this;
  29231. const audioLoader = new AudioLoader();
  29232. audioLoader.load( file, function ( buffer ) {
  29233. scope.setBuffer( buffer );
  29234. } );
  29235. return this;
  29236. };
  29237. AudioAnalyser.prototype.getData = function () {
  29238. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29239. return this.getFrequencyData();
  29240. };
  29241. //
  29242. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29243. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29244. return this.update( renderer, scene );
  29245. };
  29246. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29247. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29248. return this.renderTarget.clear( renderer, color, depth, stencil );
  29249. };
  29250. ImageUtils.crossOrigin = undefined;
  29251. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29252. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29253. const loader = new TextureLoader();
  29254. loader.setCrossOrigin( this.crossOrigin );
  29255. const texture = loader.load( url, onLoad, undefined, onError );
  29256. if ( mapping ) texture.mapping = mapping;
  29257. return texture;
  29258. };
  29259. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29260. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29261. const loader = new CubeTextureLoader();
  29262. loader.setCrossOrigin( this.crossOrigin );
  29263. const texture = loader.load( urls, onLoad, undefined, onError );
  29264. if ( mapping ) texture.mapping = mapping;
  29265. return texture;
  29266. };
  29267. ImageUtils.loadCompressedTexture = function () {
  29268. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29269. };
  29270. ImageUtils.loadCompressedTextureCube = function () {
  29271. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29272. };
  29273. //
  29274. function CanvasRenderer() {
  29275. console.error( 'THREE.CanvasRenderer has been removed' );
  29276. }
  29277. //
  29278. function JSONLoader() {
  29279. console.error( 'THREE.JSONLoader has been removed.' );
  29280. }
  29281. //
  29282. const SceneUtils = {
  29283. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29284. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29285. },
  29286. detach: function ( /* child, parent, scene */ ) {
  29287. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29288. },
  29289. attach: function ( /* child, scene, parent */ ) {
  29290. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29291. }
  29292. };
  29293. //
  29294. function LensFlare() {
  29295. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29296. }
  29297. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29298. /* eslint-disable no-undef */
  29299. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29300. revision: REVISION,
  29301. } } ) );
  29302. /* eslint-enable no-undef */
  29303. }
  29304. if ( typeof window !== 'undefined' ) {
  29305. if ( window.__THREE__ ) {
  29306. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29307. } else {
  29308. window.__THREE__ = REVISION;
  29309. }
  29310. }
  29311. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxGeometry as BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry as DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry as ExtrudeBufferGeometry, ExtrudeGeometry, FaceColors, FileLoader, FlatShading, Float16BufferAttribute, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GammaEncoding, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, 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 as ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneGeometry as PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry as PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry as RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry as ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereGeometry as SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry as TetrahedronBufferGeometry, TetrahedronGeometry, TextGeometry as TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusGeometry as TorusBufferGeometry, TorusGeometry, TorusKnotGeometry as TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry as TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGL1Renderer, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };