three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035
  1. // threejs.org/license
  2. // Polyfills
  3. if ( Number.EPSILON === undefined ) {
  4. Number.EPSILON = Math.pow( 2, - 52 );
  5. }
  6. if ( Number.isInteger === undefined ) {
  7. // Missing in IE
  8. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  9. Number.isInteger = function ( value ) {
  10. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  11. };
  12. }
  13. //
  14. if ( Math.sign === undefined ) {
  15. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  16. Math.sign = function ( x ) {
  17. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  18. };
  19. }
  20. if ( 'name' in Function.prototype === false ) {
  21. // Missing in IE
  22. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  23. Object.defineProperty( Function.prototype, 'name', {
  24. get: function () {
  25. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  26. }
  27. } );
  28. }
  29. if ( Object.assign === undefined ) {
  30. // Missing in IE
  31. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  32. Object.assign = function ( target ) {
  33. if ( target === undefined || target === null ) {
  34. throw new TypeError( 'Cannot convert undefined or null to object' );
  35. }
  36. const output = Object( target );
  37. for ( let index = 1; index < arguments.length; index ++ ) {
  38. const source = arguments[ index ];
  39. if ( source !== undefined && source !== null ) {
  40. for ( const nextKey in source ) {
  41. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  42. output[ nextKey ] = source[ nextKey ];
  43. }
  44. }
  45. }
  46. }
  47. return output;
  48. };
  49. }
  50. const REVISION = '121dev';
  51. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  52. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  53. const CullFaceNone = 0;
  54. const CullFaceBack = 1;
  55. const CullFaceFront = 2;
  56. const CullFaceFrontBack = 3;
  57. const BasicShadowMap = 0;
  58. const PCFShadowMap = 1;
  59. const PCFSoftShadowMap = 2;
  60. const VSMShadowMap = 3;
  61. const FrontSide = 0;
  62. const BackSide = 1;
  63. const DoubleSide = 2;
  64. const FlatShading = 1;
  65. const SmoothShading = 2;
  66. const NoBlending = 0;
  67. const NormalBlending = 1;
  68. const AdditiveBlending = 2;
  69. const SubtractiveBlending = 3;
  70. const MultiplyBlending = 4;
  71. const CustomBlending = 5;
  72. const AddEquation = 100;
  73. const SubtractEquation = 101;
  74. const ReverseSubtractEquation = 102;
  75. const MinEquation = 103;
  76. const MaxEquation = 104;
  77. const ZeroFactor = 200;
  78. const OneFactor = 201;
  79. const SrcColorFactor = 202;
  80. const OneMinusSrcColorFactor = 203;
  81. const SrcAlphaFactor = 204;
  82. const OneMinusSrcAlphaFactor = 205;
  83. const DstAlphaFactor = 206;
  84. const OneMinusDstAlphaFactor = 207;
  85. const DstColorFactor = 208;
  86. const OneMinusDstColorFactor = 209;
  87. const SrcAlphaSaturateFactor = 210;
  88. const NeverDepth = 0;
  89. const AlwaysDepth = 1;
  90. const LessDepth = 2;
  91. const LessEqualDepth = 3;
  92. const EqualDepth = 4;
  93. const GreaterEqualDepth = 5;
  94. const GreaterDepth = 6;
  95. const NotEqualDepth = 7;
  96. const MultiplyOperation = 0;
  97. const MixOperation = 1;
  98. const AddOperation = 2;
  99. const NoToneMapping = 0;
  100. const LinearToneMapping = 1;
  101. const ReinhardToneMapping = 2;
  102. const CineonToneMapping = 3;
  103. const ACESFilmicToneMapping = 4;
  104. const CustomToneMapping = 5;
  105. const UVMapping = 300;
  106. const CubeReflectionMapping = 301;
  107. const CubeRefractionMapping = 302;
  108. const EquirectangularReflectionMapping = 303;
  109. const EquirectangularRefractionMapping = 304;
  110. const CubeUVReflectionMapping = 306;
  111. const CubeUVRefractionMapping = 307;
  112. const RepeatWrapping = 1000;
  113. const ClampToEdgeWrapping = 1001;
  114. const MirroredRepeatWrapping = 1002;
  115. const NearestFilter = 1003;
  116. const NearestMipmapNearestFilter = 1004;
  117. const NearestMipMapNearestFilter = 1004;
  118. const NearestMipmapLinearFilter = 1005;
  119. const NearestMipMapLinearFilter = 1005;
  120. const LinearFilter = 1006;
  121. const LinearMipmapNearestFilter = 1007;
  122. const LinearMipMapNearestFilter = 1007;
  123. const LinearMipmapLinearFilter = 1008;
  124. const LinearMipMapLinearFilter = 1008;
  125. const UnsignedByteType = 1009;
  126. const ByteType = 1010;
  127. const ShortType = 1011;
  128. const UnsignedShortType = 1012;
  129. const IntType = 1013;
  130. const UnsignedIntType = 1014;
  131. const FloatType = 1015;
  132. const HalfFloatType = 1016;
  133. const UnsignedShort4444Type = 1017;
  134. const UnsignedShort5551Type = 1018;
  135. const UnsignedShort565Type = 1019;
  136. const UnsignedInt248Type = 1020;
  137. const AlphaFormat = 1021;
  138. const RGBFormat = 1022;
  139. const RGBAFormat = 1023;
  140. const LuminanceFormat = 1024;
  141. const LuminanceAlphaFormat = 1025;
  142. const RGBEFormat = RGBAFormat;
  143. const DepthFormat = 1026;
  144. const DepthStencilFormat = 1027;
  145. const RedFormat = 1028;
  146. const RedIntegerFormat = 1029;
  147. const RGFormat = 1030;
  148. const RGIntegerFormat = 1031;
  149. const RGBIntegerFormat = 1032;
  150. const RGBAIntegerFormat = 1033;
  151. const RGB_S3TC_DXT1_Format = 33776;
  152. const RGBA_S3TC_DXT1_Format = 33777;
  153. const RGBA_S3TC_DXT3_Format = 33778;
  154. const RGBA_S3TC_DXT5_Format = 33779;
  155. const RGB_PVRTC_4BPPV1_Format = 35840;
  156. const RGB_PVRTC_2BPPV1_Format = 35841;
  157. const RGBA_PVRTC_4BPPV1_Format = 35842;
  158. const RGBA_PVRTC_2BPPV1_Format = 35843;
  159. const RGB_ETC1_Format = 36196;
  160. const RGB_ETC2_Format = 37492;
  161. const RGBA_ETC2_EAC_Format = 37496;
  162. const RGBA_ASTC_4x4_Format = 37808;
  163. const RGBA_ASTC_5x4_Format = 37809;
  164. const RGBA_ASTC_5x5_Format = 37810;
  165. const RGBA_ASTC_6x5_Format = 37811;
  166. const RGBA_ASTC_6x6_Format = 37812;
  167. const RGBA_ASTC_8x5_Format = 37813;
  168. const RGBA_ASTC_8x6_Format = 37814;
  169. const RGBA_ASTC_8x8_Format = 37815;
  170. const RGBA_ASTC_10x5_Format = 37816;
  171. const RGBA_ASTC_10x6_Format = 37817;
  172. const RGBA_ASTC_10x8_Format = 37818;
  173. const RGBA_ASTC_10x10_Format = 37819;
  174. const RGBA_ASTC_12x10_Format = 37820;
  175. const RGBA_ASTC_12x12_Format = 37821;
  176. const RGBA_BPTC_Format = 36492;
  177. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  178. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  179. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  180. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  181. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  182. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  183. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  184. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  185. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  186. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  187. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  188. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  189. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  190. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  191. const LoopOnce = 2200;
  192. const LoopRepeat = 2201;
  193. const LoopPingPong = 2202;
  194. const InterpolateDiscrete = 2300;
  195. const InterpolateLinear = 2301;
  196. const InterpolateSmooth = 2302;
  197. const ZeroCurvatureEnding = 2400;
  198. const ZeroSlopeEnding = 2401;
  199. const WrapAroundEnding = 2402;
  200. const NormalAnimationBlendMode = 2500;
  201. const AdditiveAnimationBlendMode = 2501;
  202. const TrianglesDrawMode = 0;
  203. const TriangleStripDrawMode = 1;
  204. const TriangleFanDrawMode = 2;
  205. const LinearEncoding = 3000;
  206. const sRGBEncoding = 3001;
  207. const GammaEncoding = 3007;
  208. const RGBEEncoding = 3002;
  209. const LogLuvEncoding = 3003;
  210. const RGBM7Encoding = 3004;
  211. const RGBM16Encoding = 3005;
  212. const RGBDEncoding = 3006;
  213. const BasicDepthPacking = 3200;
  214. const RGBADepthPacking = 3201;
  215. const TangentSpaceNormalMap = 0;
  216. const ObjectSpaceNormalMap = 1;
  217. const ZeroStencilOp = 0;
  218. const KeepStencilOp = 7680;
  219. const ReplaceStencilOp = 7681;
  220. const IncrementStencilOp = 7682;
  221. const DecrementStencilOp = 7683;
  222. const IncrementWrapStencilOp = 34055;
  223. const DecrementWrapStencilOp = 34056;
  224. const InvertStencilOp = 5386;
  225. const NeverStencilFunc = 512;
  226. const LessStencilFunc = 513;
  227. const EqualStencilFunc = 514;
  228. const LessEqualStencilFunc = 515;
  229. const GreaterStencilFunc = 516;
  230. const NotEqualStencilFunc = 517;
  231. const GreaterEqualStencilFunc = 518;
  232. const AlwaysStencilFunc = 519;
  233. const StaticDrawUsage = 35044;
  234. const DynamicDrawUsage = 35048;
  235. const StreamDrawUsage = 35040;
  236. const StaticReadUsage = 35045;
  237. const DynamicReadUsage = 35049;
  238. const StreamReadUsage = 35041;
  239. const StaticCopyUsage = 35046;
  240. const DynamicCopyUsage = 35050;
  241. const StreamCopyUsage = 35042;
  242. const GLSL1 = "100";
  243. const GLSL3 = "300 es";
  244. /**
  245. * https://github.com/mrdoob/eventdispatcher.js/
  246. */
  247. function EventDispatcher() {}
  248. Object.assign( EventDispatcher.prototype, {
  249. addEventListener: function ( type, listener ) {
  250. if ( this._listeners === undefined ) this._listeners = {};
  251. const listeners = this._listeners;
  252. if ( listeners[ type ] === undefined ) {
  253. listeners[ type ] = [];
  254. }
  255. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  256. listeners[ type ].push( listener );
  257. }
  258. },
  259. hasEventListener: function ( type, listener ) {
  260. if ( this._listeners === undefined ) return false;
  261. const listeners = this._listeners;
  262. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  263. },
  264. removeEventListener: function ( type, listener ) {
  265. if ( this._listeners === undefined ) return;
  266. const listeners = this._listeners;
  267. const listenerArray = listeners[ type ];
  268. if ( listenerArray !== undefined ) {
  269. const index = listenerArray.indexOf( listener );
  270. if ( index !== - 1 ) {
  271. listenerArray.splice( index, 1 );
  272. }
  273. }
  274. },
  275. dispatchEvent: function ( event ) {
  276. if ( this._listeners === undefined ) return;
  277. const listeners = this._listeners;
  278. const listenerArray = listeners[ event.type ];
  279. if ( listenerArray !== undefined ) {
  280. event.target = this;
  281. // Make a copy, in case listeners are removed while iterating.
  282. const array = listenerArray.slice( 0 );
  283. for ( let i = 0, l = array.length; i < l; i ++ ) {
  284. array[ i ].call( this, event );
  285. }
  286. }
  287. }
  288. } );
  289. const _lut = [];
  290. for ( let i = 0; i < 256; i ++ ) {
  291. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  292. }
  293. let _seed = 1234567;
  294. const MathUtils = {
  295. DEG2RAD: Math.PI / 180,
  296. RAD2DEG: 180 / Math.PI,
  297. generateUUID: function () {
  298. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  299. const d0 = Math.random() * 0xffffffff | 0;
  300. const d1 = Math.random() * 0xffffffff | 0;
  301. const d2 = Math.random() * 0xffffffff | 0;
  302. const d3 = Math.random() * 0xffffffff | 0;
  303. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  304. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  305. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  306. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  307. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  308. return uuid.toUpperCase();
  309. },
  310. clamp: function ( value, min, max ) {
  311. return Math.max( min, Math.min( max, value ) );
  312. },
  313. // compute euclidian modulo of m % n
  314. // https://en.wikipedia.org/wiki/Modulo_operation
  315. euclideanModulo: function ( n, m ) {
  316. return ( ( n % m ) + m ) % m;
  317. },
  318. // Linear mapping from range <a1, a2> to range <b1, b2>
  319. mapLinear: function ( x, a1, a2, b1, b2 ) {
  320. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  321. },
  322. // https://en.wikipedia.org/wiki/Linear_interpolation
  323. lerp: function ( x, y, t ) {
  324. return ( 1 - t ) * x + t * y;
  325. },
  326. // http://en.wikipedia.org/wiki/Smoothstep
  327. smoothstep: function ( x, min, max ) {
  328. if ( x <= min ) return 0;
  329. if ( x >= max ) return 1;
  330. x = ( x - min ) / ( max - min );
  331. return x * x * ( 3 - 2 * x );
  332. },
  333. smootherstep: function ( x, min, max ) {
  334. if ( x <= min ) return 0;
  335. if ( x >= max ) return 1;
  336. x = ( x - min ) / ( max - min );
  337. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  338. },
  339. // Random integer from <low, high> interval
  340. randInt: function ( low, high ) {
  341. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  342. },
  343. // Random float from <low, high> interval
  344. randFloat: function ( low, high ) {
  345. return low + Math.random() * ( high - low );
  346. },
  347. // Random float from <-range/2, range/2> interval
  348. randFloatSpread: function ( range ) {
  349. return range * ( 0.5 - Math.random() );
  350. },
  351. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  352. seededRandom: function ( s ) {
  353. if ( s !== undefined ) _seed = s % 2147483647;
  354. // Park-Miller algorithm
  355. _seed = _seed * 16807 % 2147483647;
  356. return ( _seed - 1 ) / 2147483646;
  357. },
  358. degToRad: function ( degrees ) {
  359. return degrees * MathUtils.DEG2RAD;
  360. },
  361. radToDeg: function ( radians ) {
  362. return radians * MathUtils.RAD2DEG;
  363. },
  364. isPowerOfTwo: function ( value ) {
  365. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  366. },
  367. ceilPowerOfTwo: function ( value ) {
  368. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  369. },
  370. floorPowerOfTwo: function ( value ) {
  371. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  372. },
  373. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  374. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  375. // rotations are applied to the axes in the order specified by 'order'
  376. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  377. // angles are in radians
  378. const cos = Math.cos;
  379. const sin = Math.sin;
  380. const c2 = cos( b / 2 );
  381. const s2 = sin( b / 2 );
  382. const c13 = cos( ( a + c ) / 2 );
  383. const s13 = sin( ( a + c ) / 2 );
  384. const c1_3 = cos( ( a - c ) / 2 );
  385. const s1_3 = sin( ( a - c ) / 2 );
  386. const c3_1 = cos( ( c - a ) / 2 );
  387. const s3_1 = sin( ( c - a ) / 2 );
  388. switch ( order ) {
  389. case 'XYX':
  390. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  391. break;
  392. case 'YZY':
  393. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  394. break;
  395. case 'ZXZ':
  396. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  397. break;
  398. case 'XZX':
  399. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  400. break;
  401. case 'YXY':
  402. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  403. break;
  404. case 'ZYZ':
  405. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  406. break;
  407. default:
  408. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  409. }
  410. }
  411. };
  412. class Vector2 {
  413. constructor( x = 0, y = 0 ) {
  414. Object.defineProperty( this, 'isVector2', { value: true } );
  415. this.x = x;
  416. this.y = y;
  417. }
  418. get width() {
  419. return this.x;
  420. }
  421. set width( value ) {
  422. this.x = value;
  423. }
  424. get height() {
  425. return this.y;
  426. }
  427. set height( value ) {
  428. this.y = value;
  429. }
  430. set( x, y ) {
  431. this.x = x;
  432. this.y = y;
  433. return this;
  434. }
  435. setScalar( scalar ) {
  436. this.x = scalar;
  437. this.y = scalar;
  438. return this;
  439. }
  440. setX( x ) {
  441. this.x = x;
  442. return this;
  443. }
  444. setY( y ) {
  445. this.y = y;
  446. return this;
  447. }
  448. setComponent( index, value ) {
  449. switch ( index ) {
  450. case 0: this.x = value; break;
  451. case 1: this.y = value; break;
  452. default: throw new Error( 'index is out of range: ' + index );
  453. }
  454. return this;
  455. }
  456. getComponent( index ) {
  457. switch ( index ) {
  458. case 0: return this.x;
  459. case 1: return this.y;
  460. default: throw new Error( 'index is out of range: ' + index );
  461. }
  462. }
  463. clone() {
  464. return new this.constructor( this.x, this.y );
  465. }
  466. copy( v ) {
  467. this.x = v.x;
  468. this.y = v.y;
  469. return this;
  470. }
  471. add( v, w ) {
  472. if ( w !== undefined ) {
  473. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  474. return this.addVectors( v, w );
  475. }
  476. this.x += v.x;
  477. this.y += v.y;
  478. return this;
  479. }
  480. addScalar( s ) {
  481. this.x += s;
  482. this.y += s;
  483. return this;
  484. }
  485. addVectors( a, b ) {
  486. this.x = a.x + b.x;
  487. this.y = a.y + b.y;
  488. return this;
  489. }
  490. addScaledVector( v, s ) {
  491. this.x += v.x * s;
  492. this.y += v.y * s;
  493. return this;
  494. }
  495. sub( v, w ) {
  496. if ( w !== undefined ) {
  497. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  498. return this.subVectors( v, w );
  499. }
  500. this.x -= v.x;
  501. this.y -= v.y;
  502. return this;
  503. }
  504. subScalar( s ) {
  505. this.x -= s;
  506. this.y -= s;
  507. return this;
  508. }
  509. subVectors( a, b ) {
  510. this.x = a.x - b.x;
  511. this.y = a.y - b.y;
  512. return this;
  513. }
  514. multiply( v ) {
  515. this.x *= v.x;
  516. this.y *= v.y;
  517. return this;
  518. }
  519. multiplyScalar( scalar ) {
  520. this.x *= scalar;
  521. this.y *= scalar;
  522. return this;
  523. }
  524. divide( v ) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. return this;
  528. }
  529. divideScalar( scalar ) {
  530. return this.multiplyScalar( 1 / scalar );
  531. }
  532. applyMatrix3( m ) {
  533. const x = this.x, y = this.y;
  534. const e = m.elements;
  535. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  536. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  537. return this;
  538. }
  539. min( v ) {
  540. this.x = Math.min( this.x, v.x );
  541. this.y = Math.min( this.y, v.y );
  542. return this;
  543. }
  544. max( v ) {
  545. this.x = Math.max( this.x, v.x );
  546. this.y = Math.max( this.y, v.y );
  547. return this;
  548. }
  549. clamp( min, max ) {
  550. // assumes min < max, componentwise
  551. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  552. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  553. return this;
  554. }
  555. clampScalar( minVal, maxVal ) {
  556. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  557. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  558. return this;
  559. }
  560. clampLength( min, max ) {
  561. const length = this.length();
  562. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  563. }
  564. floor() {
  565. this.x = Math.floor( this.x );
  566. this.y = Math.floor( this.y );
  567. return this;
  568. }
  569. ceil() {
  570. this.x = Math.ceil( this.x );
  571. this.y = Math.ceil( this.y );
  572. return this;
  573. }
  574. round() {
  575. this.x = Math.round( this.x );
  576. this.y = Math.round( this.y );
  577. return this;
  578. }
  579. roundToZero() {
  580. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  581. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  582. return this;
  583. }
  584. negate() {
  585. this.x = - this.x;
  586. this.y = - this.y;
  587. return this;
  588. }
  589. dot( v ) {
  590. return this.x * v.x + this.y * v.y;
  591. }
  592. cross( v ) {
  593. return this.x * v.y - this.y * v.x;
  594. }
  595. lengthSq() {
  596. return this.x * this.x + this.y * this.y;
  597. }
  598. length() {
  599. return Math.sqrt( this.x * this.x + this.y * this.y );
  600. }
  601. manhattanLength() {
  602. return Math.abs( this.x ) + Math.abs( this.y );
  603. }
  604. normalize() {
  605. return this.divideScalar( this.length() || 1 );
  606. }
  607. angle() {
  608. // computes the angle in radians with respect to the positive x-axis
  609. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  610. return angle;
  611. }
  612. distanceTo( v ) {
  613. return Math.sqrt( this.distanceToSquared( v ) );
  614. }
  615. distanceToSquared( v ) {
  616. const dx = this.x - v.x, dy = this.y - v.y;
  617. return dx * dx + dy * dy;
  618. }
  619. manhattanDistanceTo( v ) {
  620. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  621. }
  622. setLength( length ) {
  623. return this.normalize().multiplyScalar( length );
  624. }
  625. lerp( v, alpha ) {
  626. this.x += ( v.x - this.x ) * alpha;
  627. this.y += ( v.y - this.y ) * alpha;
  628. return this;
  629. }
  630. lerpVectors( v1, v2, alpha ) {
  631. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  632. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  633. return this;
  634. }
  635. equals( v ) {
  636. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  637. }
  638. fromArray( array, offset ) {
  639. if ( offset === undefined ) offset = 0;
  640. this.x = array[ offset ];
  641. this.y = array[ offset + 1 ];
  642. return this;
  643. }
  644. toArray( array, offset ) {
  645. if ( array === undefined ) array = [];
  646. if ( offset === undefined ) offset = 0;
  647. array[ offset ] = this.x;
  648. array[ offset + 1 ] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute( attribute, index, offset ) {
  652. if ( offset !== undefined ) {
  653. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  654. }
  655. this.x = attribute.getX( index );
  656. this.y = attribute.getY( index );
  657. return this;
  658. }
  659. rotateAround( center, angle ) {
  660. const c = Math.cos( angle ), s = Math.sin( angle );
  661. const x = this.x - center.x;
  662. const y = this.y - center.y;
  663. this.x = x * c - y * s + center.x;
  664. this.y = x * s + y * c + center.y;
  665. return this;
  666. }
  667. random() {
  668. this.x = Math.random();
  669. this.y = Math.random();
  670. return this;
  671. }
  672. }
  673. class Matrix3 {
  674. constructor() {
  675. Object.defineProperty( this, 'isMatrix3', { value: true } );
  676. this.elements = [
  677. 1, 0, 0,
  678. 0, 1, 0,
  679. 0, 0, 1
  680. ];
  681. if ( arguments.length > 0 ) {
  682. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  683. }
  684. }
  685. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  686. const te = this.elements;
  687. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  688. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  689. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  690. return this;
  691. }
  692. identity() {
  693. this.set(
  694. 1, 0, 0,
  695. 0, 1, 0,
  696. 0, 0, 1
  697. );
  698. return this;
  699. }
  700. clone() {
  701. return new this.constructor().fromArray( this.elements );
  702. }
  703. copy( m ) {
  704. const te = this.elements;
  705. const me = m.elements;
  706. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  707. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  708. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  709. return this;
  710. }
  711. extractBasis( xAxis, yAxis, zAxis ) {
  712. xAxis.setFromMatrix3Column( this, 0 );
  713. yAxis.setFromMatrix3Column( this, 1 );
  714. zAxis.setFromMatrix3Column( this, 2 );
  715. return this;
  716. }
  717. setFromMatrix4( m ) {
  718. const me = m.elements;
  719. this.set(
  720. me[ 0 ], me[ 4 ], me[ 8 ],
  721. me[ 1 ], me[ 5 ], me[ 9 ],
  722. me[ 2 ], me[ 6 ], me[ 10 ]
  723. );
  724. return this;
  725. }
  726. multiply( m ) {
  727. return this.multiplyMatrices( this, m );
  728. }
  729. premultiply( m ) {
  730. return this.multiplyMatrices( m, this );
  731. }
  732. multiplyMatrices( a, b ) {
  733. const ae = a.elements;
  734. const be = b.elements;
  735. const te = this.elements;
  736. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  737. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  738. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  739. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  740. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  741. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  742. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  743. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  744. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  745. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  746. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  747. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  748. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  749. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  750. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  751. return this;
  752. }
  753. multiplyScalar( s ) {
  754. const te = this.elements;
  755. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  756. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  757. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  758. return this;
  759. }
  760. determinant() {
  761. const te = this.elements;
  762. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  763. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  764. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  765. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  766. }
  767. getInverse( matrix, throwOnDegenerate ) {
  768. if ( throwOnDegenerate !== undefined ) {
  769. console.warn( "THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate." );
  770. }
  771. const me = matrix.elements,
  772. te = this.elements,
  773. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  774. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  775. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  776. t11 = n33 * n22 - n32 * n23,
  777. t12 = n32 * n13 - n33 * n12,
  778. t13 = n23 * n12 - n22 * n13,
  779. det = n11 * t11 + n21 * t12 + n31 * t13;
  780. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  781. const detInv = 1 / det;
  782. te[ 0 ] = t11 * detInv;
  783. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  784. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  785. te[ 3 ] = t12 * detInv;
  786. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  787. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  788. te[ 6 ] = t13 * detInv;
  789. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  790. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  791. return this;
  792. }
  793. transpose() {
  794. let tmp;
  795. const m = this.elements;
  796. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  797. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  798. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  799. return this;
  800. }
  801. getNormalMatrix( matrix4 ) {
  802. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  803. }
  804. transposeIntoArray( r ) {
  805. const m = this.elements;
  806. r[ 0 ] = m[ 0 ];
  807. r[ 1 ] = m[ 3 ];
  808. r[ 2 ] = m[ 6 ];
  809. r[ 3 ] = m[ 1 ];
  810. r[ 4 ] = m[ 4 ];
  811. r[ 5 ] = m[ 7 ];
  812. r[ 6 ] = m[ 2 ];
  813. r[ 7 ] = m[ 5 ];
  814. r[ 8 ] = m[ 8 ];
  815. return this;
  816. }
  817. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  818. const c = Math.cos( rotation );
  819. const s = Math.sin( rotation );
  820. this.set(
  821. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  822. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  823. 0, 0, 1
  824. );
  825. }
  826. scale( sx, sy ) {
  827. const te = this.elements;
  828. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  829. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  830. return this;
  831. }
  832. rotate( theta ) {
  833. const c = Math.cos( theta );
  834. const s = Math.sin( theta );
  835. const te = this.elements;
  836. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  837. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  838. te[ 0 ] = c * a11 + s * a21;
  839. te[ 3 ] = c * a12 + s * a22;
  840. te[ 6 ] = c * a13 + s * a23;
  841. te[ 1 ] = - s * a11 + c * a21;
  842. te[ 4 ] = - s * a12 + c * a22;
  843. te[ 7 ] = - s * a13 + c * a23;
  844. return this;
  845. }
  846. translate( tx, ty ) {
  847. const te = this.elements;
  848. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  849. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  850. return this;
  851. }
  852. equals( matrix ) {
  853. const te = this.elements;
  854. const me = matrix.elements;
  855. for ( let i = 0; i < 9; i ++ ) {
  856. if ( te[ i ] !== me[ i ] ) return false;
  857. }
  858. return true;
  859. }
  860. fromArray( array, offset ) {
  861. if ( offset === undefined ) offset = 0;
  862. for ( let i = 0; i < 9; i ++ ) {
  863. this.elements[ i ] = array[ i + offset ];
  864. }
  865. return this;
  866. }
  867. toArray( array, offset ) {
  868. if ( array === undefined ) array = [];
  869. if ( offset === undefined ) offset = 0;
  870. const te = this.elements;
  871. array[ offset ] = te[ 0 ];
  872. array[ offset + 1 ] = te[ 1 ];
  873. array[ offset + 2 ] = te[ 2 ];
  874. array[ offset + 3 ] = te[ 3 ];
  875. array[ offset + 4 ] = te[ 4 ];
  876. array[ offset + 5 ] = te[ 5 ];
  877. array[ offset + 6 ] = te[ 6 ];
  878. array[ offset + 7 ] = te[ 7 ];
  879. array[ offset + 8 ] = te[ 8 ];
  880. return array;
  881. }
  882. }
  883. let _canvas;
  884. const ImageUtils = {
  885. getDataURL: function ( image ) {
  886. if ( /^data:/i.test( image.src ) ) {
  887. return image.src;
  888. }
  889. if ( typeof HTMLCanvasElement == 'undefined' ) {
  890. return image.src;
  891. }
  892. let canvas;
  893. if ( image instanceof HTMLCanvasElement ) {
  894. canvas = image;
  895. } else {
  896. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  897. _canvas.width = image.width;
  898. _canvas.height = image.height;
  899. const context = _canvas.getContext( '2d' );
  900. if ( image instanceof ImageData ) {
  901. context.putImageData( image, 0, 0 );
  902. } else {
  903. context.drawImage( image, 0, 0, image.width, image.height );
  904. }
  905. canvas = _canvas;
  906. }
  907. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  908. return canvas.toDataURL( 'image/jpeg', 0.6 );
  909. } else {
  910. return canvas.toDataURL( 'image/png' );
  911. }
  912. }
  913. };
  914. let textureId = 0;
  915. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  916. Object.defineProperty( this, 'id', { value: textureId ++ } );
  917. this.uuid = MathUtils.generateUUID();
  918. this.name = '';
  919. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  920. this.mipmaps = [];
  921. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  922. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  923. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  924. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  925. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  926. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  927. this.format = format !== undefined ? format : RGBAFormat;
  928. this.internalFormat = null;
  929. this.type = type !== undefined ? type : UnsignedByteType;
  930. this.offset = new Vector2( 0, 0 );
  931. this.repeat = new Vector2( 1, 1 );
  932. this.center = new Vector2( 0, 0 );
  933. this.rotation = 0;
  934. this.matrixAutoUpdate = true;
  935. this.matrix = new Matrix3();
  936. this.generateMipmaps = true;
  937. this.premultiplyAlpha = false;
  938. this.flipY = true;
  939. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  940. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  941. //
  942. // Also changing the encoding after already used by a Material will not automatically make the Material
  943. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  944. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  945. this.version = 0;
  946. this.onUpdate = null;
  947. }
  948. Texture.DEFAULT_IMAGE = undefined;
  949. Texture.DEFAULT_MAPPING = UVMapping;
  950. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  951. constructor: Texture,
  952. isTexture: true,
  953. updateMatrix: function () {
  954. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  955. },
  956. clone: function () {
  957. return new this.constructor().copy( this );
  958. },
  959. copy: function ( source ) {
  960. this.name = source.name;
  961. this.image = source.image;
  962. this.mipmaps = source.mipmaps.slice( 0 );
  963. this.mapping = source.mapping;
  964. this.wrapS = source.wrapS;
  965. this.wrapT = source.wrapT;
  966. this.magFilter = source.magFilter;
  967. this.minFilter = source.minFilter;
  968. this.anisotropy = source.anisotropy;
  969. this.format = source.format;
  970. this.internalFormat = source.internalFormat;
  971. this.type = source.type;
  972. this.offset.copy( source.offset );
  973. this.repeat.copy( source.repeat );
  974. this.center.copy( source.center );
  975. this.rotation = source.rotation;
  976. this.matrixAutoUpdate = source.matrixAutoUpdate;
  977. this.matrix.copy( source.matrix );
  978. this.generateMipmaps = source.generateMipmaps;
  979. this.premultiplyAlpha = source.premultiplyAlpha;
  980. this.flipY = source.flipY;
  981. this.unpackAlignment = source.unpackAlignment;
  982. this.encoding = source.encoding;
  983. return this;
  984. },
  985. toJSON: function ( meta ) {
  986. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  987. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  988. return meta.textures[ this.uuid ];
  989. }
  990. const output = {
  991. metadata: {
  992. version: 4.5,
  993. type: 'Texture',
  994. generator: 'Texture.toJSON'
  995. },
  996. uuid: this.uuid,
  997. name: this.name,
  998. mapping: this.mapping,
  999. repeat: [ this.repeat.x, this.repeat.y ],
  1000. offset: [ this.offset.x, this.offset.y ],
  1001. center: [ this.center.x, this.center.y ],
  1002. rotation: this.rotation,
  1003. wrap: [ this.wrapS, this.wrapT ],
  1004. format: this.format,
  1005. type: this.type,
  1006. encoding: this.encoding,
  1007. minFilter: this.minFilter,
  1008. magFilter: this.magFilter,
  1009. anisotropy: this.anisotropy,
  1010. flipY: this.flipY,
  1011. premultiplyAlpha: this.premultiplyAlpha,
  1012. unpackAlignment: this.unpackAlignment
  1013. };
  1014. if ( this.image !== undefined ) {
  1015. // TODO: Move to THREE.Image
  1016. const image = this.image;
  1017. if ( image.uuid === undefined ) {
  1018. image.uuid = MathUtils.generateUUID(); // UGH
  1019. }
  1020. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1021. let url;
  1022. if ( Array.isArray( image ) ) {
  1023. // process array of images e.g. CubeTexture
  1024. url = [];
  1025. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1026. url.push( ImageUtils.getDataURL( image[ i ] ) );
  1027. }
  1028. } else {
  1029. // process single image
  1030. url = ImageUtils.getDataURL( image );
  1031. }
  1032. meta.images[ image.uuid ] = {
  1033. uuid: image.uuid,
  1034. url: url
  1035. };
  1036. }
  1037. output.image = image.uuid;
  1038. }
  1039. if ( ! isRootObject ) {
  1040. meta.textures[ this.uuid ] = output;
  1041. }
  1042. return output;
  1043. },
  1044. dispose: function () {
  1045. this.dispatchEvent( { type: 'dispose' } );
  1046. },
  1047. transformUv: function ( uv ) {
  1048. if ( this.mapping !== UVMapping ) return uv;
  1049. uv.applyMatrix3( this.matrix );
  1050. if ( uv.x < 0 || uv.x > 1 ) {
  1051. switch ( this.wrapS ) {
  1052. case RepeatWrapping:
  1053. uv.x = uv.x - Math.floor( uv.x );
  1054. break;
  1055. case ClampToEdgeWrapping:
  1056. uv.x = uv.x < 0 ? 0 : 1;
  1057. break;
  1058. case MirroredRepeatWrapping:
  1059. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1060. uv.x = Math.ceil( uv.x ) - uv.x;
  1061. } else {
  1062. uv.x = uv.x - Math.floor( uv.x );
  1063. }
  1064. break;
  1065. }
  1066. }
  1067. if ( uv.y < 0 || uv.y > 1 ) {
  1068. switch ( this.wrapT ) {
  1069. case RepeatWrapping:
  1070. uv.y = uv.y - Math.floor( uv.y );
  1071. break;
  1072. case ClampToEdgeWrapping:
  1073. uv.y = uv.y < 0 ? 0 : 1;
  1074. break;
  1075. case MirroredRepeatWrapping:
  1076. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1077. uv.y = Math.ceil( uv.y ) - uv.y;
  1078. } else {
  1079. uv.y = uv.y - Math.floor( uv.y );
  1080. }
  1081. break;
  1082. }
  1083. }
  1084. if ( this.flipY ) {
  1085. uv.y = 1 - uv.y;
  1086. }
  1087. return uv;
  1088. }
  1089. } );
  1090. Object.defineProperty( Texture.prototype, "needsUpdate", {
  1091. set: function ( value ) {
  1092. if ( value === true ) this.version ++;
  1093. }
  1094. } );
  1095. class Vector4 {
  1096. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1097. Object.defineProperty( this, 'isVector4', { value: true } );
  1098. this.x = x;
  1099. this.y = y;
  1100. this.z = z;
  1101. this.w = w;
  1102. }
  1103. get width() {
  1104. return this.z;
  1105. }
  1106. set width( value ) {
  1107. this.z = value;
  1108. }
  1109. get height() {
  1110. return this.w;
  1111. }
  1112. set height( value ) {
  1113. this.w = value;
  1114. }
  1115. set( x, y, z, w ) {
  1116. this.x = x;
  1117. this.y = y;
  1118. this.z = z;
  1119. this.w = w;
  1120. return this;
  1121. }
  1122. setScalar( scalar ) {
  1123. this.x = scalar;
  1124. this.y = scalar;
  1125. this.z = scalar;
  1126. this.w = scalar;
  1127. return this;
  1128. }
  1129. setX( x ) {
  1130. this.x = x;
  1131. return this;
  1132. }
  1133. setY( y ) {
  1134. this.y = y;
  1135. return this;
  1136. }
  1137. setZ( z ) {
  1138. this.z = z;
  1139. return this;
  1140. }
  1141. setW( w ) {
  1142. this.w = w;
  1143. return this;
  1144. }
  1145. setComponent( index, value ) {
  1146. switch ( index ) {
  1147. case 0: this.x = value; break;
  1148. case 1: this.y = value; break;
  1149. case 2: this.z = value; break;
  1150. case 3: this.w = value; break;
  1151. default: throw new Error( 'index is out of range: ' + index );
  1152. }
  1153. return this;
  1154. }
  1155. getComponent( index ) {
  1156. switch ( index ) {
  1157. case 0: return this.x;
  1158. case 1: return this.y;
  1159. case 2: return this.z;
  1160. case 3: return this.w;
  1161. default: throw new Error( 'index is out of range: ' + index );
  1162. }
  1163. }
  1164. clone() {
  1165. return new this.constructor( this.x, this.y, this.z, this.w );
  1166. }
  1167. copy( v ) {
  1168. this.x = v.x;
  1169. this.y = v.y;
  1170. this.z = v.z;
  1171. this.w = ( v.w !== undefined ) ? v.w : 1;
  1172. return this;
  1173. }
  1174. add( v, w ) {
  1175. if ( w !== undefined ) {
  1176. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1177. return this.addVectors( v, w );
  1178. }
  1179. this.x += v.x;
  1180. this.y += v.y;
  1181. this.z += v.z;
  1182. this.w += v.w;
  1183. return this;
  1184. }
  1185. addScalar( s ) {
  1186. this.x += s;
  1187. this.y += s;
  1188. this.z += s;
  1189. this.w += s;
  1190. return this;
  1191. }
  1192. addVectors( a, b ) {
  1193. this.x = a.x + b.x;
  1194. this.y = a.y + b.y;
  1195. this.z = a.z + b.z;
  1196. this.w = a.w + b.w;
  1197. return this;
  1198. }
  1199. addScaledVector( v, s ) {
  1200. this.x += v.x * s;
  1201. this.y += v.y * s;
  1202. this.z += v.z * s;
  1203. this.w += v.w * s;
  1204. return this;
  1205. }
  1206. sub( v, w ) {
  1207. if ( w !== undefined ) {
  1208. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1209. return this.subVectors( v, w );
  1210. }
  1211. this.x -= v.x;
  1212. this.y -= v.y;
  1213. this.z -= v.z;
  1214. this.w -= v.w;
  1215. return this;
  1216. }
  1217. subScalar( s ) {
  1218. this.x -= s;
  1219. this.y -= s;
  1220. this.z -= s;
  1221. this.w -= s;
  1222. return this;
  1223. }
  1224. subVectors( a, b ) {
  1225. this.x = a.x - b.x;
  1226. this.y = a.y - b.y;
  1227. this.z = a.z - b.z;
  1228. this.w = a.w - b.w;
  1229. return this;
  1230. }
  1231. multiplyScalar( scalar ) {
  1232. this.x *= scalar;
  1233. this.y *= scalar;
  1234. this.z *= scalar;
  1235. this.w *= scalar;
  1236. return this;
  1237. }
  1238. applyMatrix4( m ) {
  1239. const x = this.x, y = this.y, z = this.z, w = this.w;
  1240. const e = m.elements;
  1241. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1242. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1243. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1244. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1245. return this;
  1246. }
  1247. divideScalar( scalar ) {
  1248. return this.multiplyScalar( 1 / scalar );
  1249. }
  1250. setAxisAngleFromQuaternion( q ) {
  1251. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1252. // q is assumed to be normalized
  1253. this.w = 2 * Math.acos( q.w );
  1254. const s = Math.sqrt( 1 - q.w * q.w );
  1255. if ( s < 0.0001 ) {
  1256. this.x = 1;
  1257. this.y = 0;
  1258. this.z = 0;
  1259. } else {
  1260. this.x = q.x / s;
  1261. this.y = q.y / s;
  1262. this.z = q.z / s;
  1263. }
  1264. return this;
  1265. }
  1266. setAxisAngleFromRotationMatrix( m ) {
  1267. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1268. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1269. let angle, x, y, z; // variables for result
  1270. const epsilon = 0.01, // margin to allow for rounding errors
  1271. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1272. te = m.elements,
  1273. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1274. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1275. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1276. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1277. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1278. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1279. // singularity found
  1280. // first check for identity matrix which must have +1 for all terms
  1281. // in leading diagonal and zero in other terms
  1282. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1283. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1284. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1285. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1286. // this singularity is identity matrix so angle = 0
  1287. this.set( 1, 0, 0, 0 );
  1288. return this; // zero angle, arbitrary axis
  1289. }
  1290. // otherwise this singularity is angle = 180
  1291. angle = Math.PI;
  1292. const xx = ( m11 + 1 ) / 2;
  1293. const yy = ( m22 + 1 ) / 2;
  1294. const zz = ( m33 + 1 ) / 2;
  1295. const xy = ( m12 + m21 ) / 4;
  1296. const xz = ( m13 + m31 ) / 4;
  1297. const yz = ( m23 + m32 ) / 4;
  1298. if ( ( xx > yy ) && ( xx > zz ) ) {
  1299. // m11 is the largest diagonal term
  1300. if ( xx < epsilon ) {
  1301. x = 0;
  1302. y = 0.707106781;
  1303. z = 0.707106781;
  1304. } else {
  1305. x = Math.sqrt( xx );
  1306. y = xy / x;
  1307. z = xz / x;
  1308. }
  1309. } else if ( yy > zz ) {
  1310. // m22 is the largest diagonal term
  1311. if ( yy < epsilon ) {
  1312. x = 0.707106781;
  1313. y = 0;
  1314. z = 0.707106781;
  1315. } else {
  1316. y = Math.sqrt( yy );
  1317. x = xy / y;
  1318. z = yz / y;
  1319. }
  1320. } else {
  1321. // m33 is the largest diagonal term so base result on this
  1322. if ( zz < epsilon ) {
  1323. x = 0.707106781;
  1324. y = 0.707106781;
  1325. z = 0;
  1326. } else {
  1327. z = Math.sqrt( zz );
  1328. x = xz / z;
  1329. y = yz / z;
  1330. }
  1331. }
  1332. this.set( x, y, z, angle );
  1333. return this; // return 180 deg rotation
  1334. }
  1335. // as we have reached here there are no singularities so we can handle normally
  1336. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1337. ( m13 - m31 ) * ( m13 - m31 ) +
  1338. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1339. if ( Math.abs( s ) < 0.001 ) s = 1;
  1340. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1341. // caught by singularity test above, but I've left it in just in case
  1342. this.x = ( m32 - m23 ) / s;
  1343. this.y = ( m13 - m31 ) / s;
  1344. this.z = ( m21 - m12 ) / s;
  1345. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1346. return this;
  1347. }
  1348. min( v ) {
  1349. this.x = Math.min( this.x, v.x );
  1350. this.y = Math.min( this.y, v.y );
  1351. this.z = Math.min( this.z, v.z );
  1352. this.w = Math.min( this.w, v.w );
  1353. return this;
  1354. }
  1355. max( v ) {
  1356. this.x = Math.max( this.x, v.x );
  1357. this.y = Math.max( this.y, v.y );
  1358. this.z = Math.max( this.z, v.z );
  1359. this.w = Math.max( this.w, v.w );
  1360. return this;
  1361. }
  1362. clamp( min, max ) {
  1363. // assumes min < max, componentwise
  1364. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1365. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1366. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1367. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1368. return this;
  1369. }
  1370. clampScalar( minVal, maxVal ) {
  1371. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1372. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1373. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1374. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1375. return this;
  1376. }
  1377. clampLength( min, max ) {
  1378. const length = this.length();
  1379. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1380. }
  1381. floor() {
  1382. this.x = Math.floor( this.x );
  1383. this.y = Math.floor( this.y );
  1384. this.z = Math.floor( this.z );
  1385. this.w = Math.floor( this.w );
  1386. return this;
  1387. }
  1388. ceil() {
  1389. this.x = Math.ceil( this.x );
  1390. this.y = Math.ceil( this.y );
  1391. this.z = Math.ceil( this.z );
  1392. this.w = Math.ceil( this.w );
  1393. return this;
  1394. }
  1395. round() {
  1396. this.x = Math.round( this.x );
  1397. this.y = Math.round( this.y );
  1398. this.z = Math.round( this.z );
  1399. this.w = Math.round( this.w );
  1400. return this;
  1401. }
  1402. roundToZero() {
  1403. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1404. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1405. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1406. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1407. return this;
  1408. }
  1409. negate() {
  1410. this.x = - this.x;
  1411. this.y = - this.y;
  1412. this.z = - this.z;
  1413. this.w = - this.w;
  1414. return this;
  1415. }
  1416. dot( v ) {
  1417. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1418. }
  1419. lengthSq() {
  1420. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1421. }
  1422. length() {
  1423. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1424. }
  1425. manhattanLength() {
  1426. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1427. }
  1428. normalize() {
  1429. return this.divideScalar( this.length() || 1 );
  1430. }
  1431. setLength( length ) {
  1432. return this.normalize().multiplyScalar( length );
  1433. }
  1434. lerp( v, alpha ) {
  1435. this.x += ( v.x - this.x ) * alpha;
  1436. this.y += ( v.y - this.y ) * alpha;
  1437. this.z += ( v.z - this.z ) * alpha;
  1438. this.w += ( v.w - this.w ) * alpha;
  1439. return this;
  1440. }
  1441. lerpVectors( v1, v2, alpha ) {
  1442. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1443. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1444. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1445. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1446. return this;
  1447. }
  1448. equals( v ) {
  1449. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1450. }
  1451. fromArray( array, offset ) {
  1452. if ( offset === undefined ) offset = 0;
  1453. this.x = array[ offset ];
  1454. this.y = array[ offset + 1 ];
  1455. this.z = array[ offset + 2 ];
  1456. this.w = array[ offset + 3 ];
  1457. return this;
  1458. }
  1459. toArray( array, offset ) {
  1460. if ( array === undefined ) array = [];
  1461. if ( offset === undefined ) offset = 0;
  1462. array[ offset ] = this.x;
  1463. array[ offset + 1 ] = this.y;
  1464. array[ offset + 2 ] = this.z;
  1465. array[ offset + 3 ] = this.w;
  1466. return array;
  1467. }
  1468. fromBufferAttribute( attribute, index, offset ) {
  1469. if ( offset !== undefined ) {
  1470. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1471. }
  1472. this.x = attribute.getX( index );
  1473. this.y = attribute.getY( index );
  1474. this.z = attribute.getZ( index );
  1475. this.w = attribute.getW( index );
  1476. return this;
  1477. }
  1478. random() {
  1479. this.x = Math.random();
  1480. this.y = Math.random();
  1481. this.z = Math.random();
  1482. this.w = Math.random();
  1483. return this;
  1484. }
  1485. }
  1486. /*
  1487. In options, we can specify:
  1488. * Texture parameters for an auto-generated target texture
  1489. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1490. */
  1491. function WebGLRenderTarget( width, height, options ) {
  1492. this.width = width;
  1493. this.height = height;
  1494. this.scissor = new Vector4( 0, 0, width, height );
  1495. this.scissorTest = false;
  1496. this.viewport = new Vector4( 0, 0, width, height );
  1497. options = options || {};
  1498. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1499. this.texture.image = {};
  1500. this.texture.image.width = width;
  1501. this.texture.image.height = height;
  1502. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1503. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1504. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1505. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1506. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1507. }
  1508. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  1509. constructor: WebGLRenderTarget,
  1510. isWebGLRenderTarget: true,
  1511. setSize: function ( width, height ) {
  1512. if ( this.width !== width || this.height !== height ) {
  1513. this.width = width;
  1514. this.height = height;
  1515. this.texture.image.width = width;
  1516. this.texture.image.height = height;
  1517. this.dispose();
  1518. }
  1519. this.viewport.set( 0, 0, width, height );
  1520. this.scissor.set( 0, 0, width, height );
  1521. },
  1522. clone: function () {
  1523. return new this.constructor().copy( this );
  1524. },
  1525. copy: function ( source ) {
  1526. this.width = source.width;
  1527. this.height = source.height;
  1528. this.viewport.copy( source.viewport );
  1529. this.texture = source.texture.clone();
  1530. this.depthBuffer = source.depthBuffer;
  1531. this.stencilBuffer = source.stencilBuffer;
  1532. this.depthTexture = source.depthTexture;
  1533. return this;
  1534. },
  1535. dispose: function () {
  1536. this.dispatchEvent( { type: 'dispose' } );
  1537. }
  1538. } );
  1539. function WebGLMultisampleRenderTarget( width, height, options ) {
  1540. WebGLRenderTarget.call( this, width, height, options );
  1541. this.samples = 4;
  1542. }
  1543. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  1544. constructor: WebGLMultisampleRenderTarget,
  1545. isWebGLMultisampleRenderTarget: true,
  1546. copy: function ( source ) {
  1547. WebGLRenderTarget.prototype.copy.call( this, source );
  1548. this.samples = source.samples;
  1549. return this;
  1550. }
  1551. } );
  1552. class Quaternion {
  1553. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1554. Object.defineProperty( this, 'isQuaternion', { value: true } );
  1555. this._x = x;
  1556. this._y = y;
  1557. this._z = z;
  1558. this._w = w;
  1559. }
  1560. static slerp( qa, qb, qm, t ) {
  1561. return qm.copy( qa ).slerp( qb, t );
  1562. }
  1563. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1564. // fuzz-free, array-based Quaternion SLERP operation
  1565. let x0 = src0[ srcOffset0 + 0 ],
  1566. y0 = src0[ srcOffset0 + 1 ],
  1567. z0 = src0[ srcOffset0 + 2 ],
  1568. w0 = src0[ srcOffset0 + 3 ];
  1569. const x1 = src1[ srcOffset1 + 0 ],
  1570. y1 = src1[ srcOffset1 + 1 ],
  1571. z1 = src1[ srcOffset1 + 2 ],
  1572. w1 = src1[ srcOffset1 + 3 ];
  1573. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1574. let s = 1 - t;
  1575. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1576. dir = ( cos >= 0 ? 1 : - 1 ),
  1577. sqrSin = 1 - cos * cos;
  1578. // Skip the Slerp for tiny steps to avoid numeric problems:
  1579. if ( sqrSin > Number.EPSILON ) {
  1580. const sin = Math.sqrt( sqrSin ),
  1581. len = Math.atan2( sin, cos * dir );
  1582. s = Math.sin( s * len ) / sin;
  1583. t = Math.sin( t * len ) / sin;
  1584. }
  1585. const tDir = t * dir;
  1586. x0 = x0 * s + x1 * tDir;
  1587. y0 = y0 * s + y1 * tDir;
  1588. z0 = z0 * s + z1 * tDir;
  1589. w0 = w0 * s + w1 * tDir;
  1590. // Normalize in case we just did a lerp:
  1591. if ( s === 1 - t ) {
  1592. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1593. x0 *= f;
  1594. y0 *= f;
  1595. z0 *= f;
  1596. w0 *= f;
  1597. }
  1598. }
  1599. dst[ dstOffset ] = x0;
  1600. dst[ dstOffset + 1 ] = y0;
  1601. dst[ dstOffset + 2 ] = z0;
  1602. dst[ dstOffset + 3 ] = w0;
  1603. }
  1604. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1605. const x0 = src0[ srcOffset0 ];
  1606. const y0 = src0[ srcOffset0 + 1 ];
  1607. const z0 = src0[ srcOffset0 + 2 ];
  1608. const w0 = src0[ srcOffset0 + 3 ];
  1609. const x1 = src1[ srcOffset1 ];
  1610. const y1 = src1[ srcOffset1 + 1 ];
  1611. const z1 = src1[ srcOffset1 + 2 ];
  1612. const w1 = src1[ srcOffset1 + 3 ];
  1613. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1614. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1615. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1616. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1617. return dst;
  1618. }
  1619. get x() {
  1620. return this._x;
  1621. }
  1622. set x( value ) {
  1623. this._x = value;
  1624. this._onChangeCallback();
  1625. }
  1626. get y() {
  1627. return this._y;
  1628. }
  1629. set y( value ) {
  1630. this._y = value;
  1631. this._onChangeCallback();
  1632. }
  1633. get z() {
  1634. return this._z;
  1635. }
  1636. set z( value ) {
  1637. this._z = value;
  1638. this._onChangeCallback();
  1639. }
  1640. get w() {
  1641. return this._w;
  1642. }
  1643. set w( value ) {
  1644. this._w = value;
  1645. this._onChangeCallback();
  1646. }
  1647. set( x, y, z, w ) {
  1648. this._x = x;
  1649. this._y = y;
  1650. this._z = z;
  1651. this._w = w;
  1652. this._onChangeCallback();
  1653. return this;
  1654. }
  1655. clone() {
  1656. return new this.constructor( this._x, this._y, this._z, this._w );
  1657. }
  1658. copy( quaternion ) {
  1659. this._x = quaternion.x;
  1660. this._y = quaternion.y;
  1661. this._z = quaternion.z;
  1662. this._w = quaternion.w;
  1663. this._onChangeCallback();
  1664. return this;
  1665. }
  1666. setFromEuler( euler, update ) {
  1667. if ( ! ( euler && euler.isEuler ) ) {
  1668. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1669. }
  1670. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1671. // http://www.mathworks.com/matlabcentral/fileexchange/
  1672. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1673. // content/SpinCalc.m
  1674. const cos = Math.cos;
  1675. const sin = Math.sin;
  1676. const c1 = cos( x / 2 );
  1677. const c2 = cos( y / 2 );
  1678. const c3 = cos( z / 2 );
  1679. const s1 = sin( x / 2 );
  1680. const s2 = sin( y / 2 );
  1681. const s3 = sin( z / 2 );
  1682. switch ( order ) {
  1683. case 'XYZ':
  1684. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1685. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1686. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1687. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1688. break;
  1689. case 'YXZ':
  1690. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1691. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1692. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1693. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1694. break;
  1695. case 'ZXY':
  1696. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1697. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1698. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1699. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1700. break;
  1701. case 'ZYX':
  1702. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1703. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1704. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1705. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1706. break;
  1707. case 'YZX':
  1708. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1709. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1710. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1711. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1712. break;
  1713. case 'XZY':
  1714. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1715. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1716. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1717. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1718. break;
  1719. default:
  1720. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1721. }
  1722. if ( update !== false ) this._onChangeCallback();
  1723. return this;
  1724. }
  1725. setFromAxisAngle( axis, angle ) {
  1726. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1727. // assumes axis is normalized
  1728. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1729. this._x = axis.x * s;
  1730. this._y = axis.y * s;
  1731. this._z = axis.z * s;
  1732. this._w = Math.cos( halfAngle );
  1733. this._onChangeCallback();
  1734. return this;
  1735. }
  1736. setFromRotationMatrix( m ) {
  1737. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1738. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1739. const te = m.elements,
  1740. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1741. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1742. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1743. trace = m11 + m22 + m33;
  1744. if ( trace > 0 ) {
  1745. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1746. this._w = 0.25 / s;
  1747. this._x = ( m32 - m23 ) * s;
  1748. this._y = ( m13 - m31 ) * s;
  1749. this._z = ( m21 - m12 ) * s;
  1750. } else if ( m11 > m22 && m11 > m33 ) {
  1751. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1752. this._w = ( m32 - m23 ) / s;
  1753. this._x = 0.25 * s;
  1754. this._y = ( m12 + m21 ) / s;
  1755. this._z = ( m13 + m31 ) / s;
  1756. } else if ( m22 > m33 ) {
  1757. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1758. this._w = ( m13 - m31 ) / s;
  1759. this._x = ( m12 + m21 ) / s;
  1760. this._y = 0.25 * s;
  1761. this._z = ( m23 + m32 ) / s;
  1762. } else {
  1763. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1764. this._w = ( m21 - m12 ) / s;
  1765. this._x = ( m13 + m31 ) / s;
  1766. this._y = ( m23 + m32 ) / s;
  1767. this._z = 0.25 * s;
  1768. }
  1769. this._onChangeCallback();
  1770. return this;
  1771. }
  1772. setFromUnitVectors( vFrom, vTo ) {
  1773. // assumes direction vectors vFrom and vTo are normalized
  1774. const EPS = 0.000001;
  1775. let r = vFrom.dot( vTo ) + 1;
  1776. if ( r < EPS ) {
  1777. r = 0;
  1778. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1779. this._x = - vFrom.y;
  1780. this._y = vFrom.x;
  1781. this._z = 0;
  1782. this._w = r;
  1783. } else {
  1784. this._x = 0;
  1785. this._y = - vFrom.z;
  1786. this._z = vFrom.y;
  1787. this._w = r;
  1788. }
  1789. } else {
  1790. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1791. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1792. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1793. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1794. this._w = r;
  1795. }
  1796. return this.normalize();
  1797. }
  1798. angleTo( q ) {
  1799. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  1800. }
  1801. rotateTowards( q, step ) {
  1802. const angle = this.angleTo( q );
  1803. if ( angle === 0 ) return this;
  1804. const t = Math.min( 1, step / angle );
  1805. this.slerp( q, t );
  1806. return this;
  1807. }
  1808. identity() {
  1809. return this.set( 0, 0, 0, 1 );
  1810. }
  1811. inverse() {
  1812. // quaternion is assumed to have unit length
  1813. return this.conjugate();
  1814. }
  1815. conjugate() {
  1816. this._x *= - 1;
  1817. this._y *= - 1;
  1818. this._z *= - 1;
  1819. this._onChangeCallback();
  1820. return this;
  1821. }
  1822. dot( v ) {
  1823. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1824. }
  1825. lengthSq() {
  1826. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1827. }
  1828. length() {
  1829. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1830. }
  1831. normalize() {
  1832. let l = this.length();
  1833. if ( l === 0 ) {
  1834. this._x = 0;
  1835. this._y = 0;
  1836. this._z = 0;
  1837. this._w = 1;
  1838. } else {
  1839. l = 1 / l;
  1840. this._x = this._x * l;
  1841. this._y = this._y * l;
  1842. this._z = this._z * l;
  1843. this._w = this._w * l;
  1844. }
  1845. this._onChangeCallback();
  1846. return this;
  1847. }
  1848. multiply( q, p ) {
  1849. if ( p !== undefined ) {
  1850. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1851. return this.multiplyQuaternions( q, p );
  1852. }
  1853. return this.multiplyQuaternions( this, q );
  1854. }
  1855. premultiply( q ) {
  1856. return this.multiplyQuaternions( q, this );
  1857. }
  1858. multiplyQuaternions( a, b ) {
  1859. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1860. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1861. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1862. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1863. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1864. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1865. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1866. this._onChangeCallback();
  1867. return this;
  1868. }
  1869. slerp( qb, t ) {
  1870. if ( t === 0 ) return this;
  1871. if ( t === 1 ) return this.copy( qb );
  1872. const x = this._x, y = this._y, z = this._z, w = this._w;
  1873. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1874. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1875. if ( cosHalfTheta < 0 ) {
  1876. this._w = - qb._w;
  1877. this._x = - qb._x;
  1878. this._y = - qb._y;
  1879. this._z = - qb._z;
  1880. cosHalfTheta = - cosHalfTheta;
  1881. } else {
  1882. this.copy( qb );
  1883. }
  1884. if ( cosHalfTheta >= 1.0 ) {
  1885. this._w = w;
  1886. this._x = x;
  1887. this._y = y;
  1888. this._z = z;
  1889. return this;
  1890. }
  1891. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1892. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1893. const s = 1 - t;
  1894. this._w = s * w + t * this._w;
  1895. this._x = s * x + t * this._x;
  1896. this._y = s * y + t * this._y;
  1897. this._z = s * z + t * this._z;
  1898. this.normalize();
  1899. this._onChangeCallback();
  1900. return this;
  1901. }
  1902. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1903. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1904. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1905. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1906. this._w = ( w * ratioA + this._w * ratioB );
  1907. this._x = ( x * ratioA + this._x * ratioB );
  1908. this._y = ( y * ratioA + this._y * ratioB );
  1909. this._z = ( z * ratioA + this._z * ratioB );
  1910. this._onChangeCallback();
  1911. return this;
  1912. }
  1913. equals( quaternion ) {
  1914. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1915. }
  1916. fromArray( array, offset ) {
  1917. if ( offset === undefined ) offset = 0;
  1918. this._x = array[ offset ];
  1919. this._y = array[ offset + 1 ];
  1920. this._z = array[ offset + 2 ];
  1921. this._w = array[ offset + 3 ];
  1922. this._onChangeCallback();
  1923. return this;
  1924. }
  1925. toArray( array, offset ) {
  1926. if ( array === undefined ) array = [];
  1927. if ( offset === undefined ) offset = 0;
  1928. array[ offset ] = this._x;
  1929. array[ offset + 1 ] = this._y;
  1930. array[ offset + 2 ] = this._z;
  1931. array[ offset + 3 ] = this._w;
  1932. return array;
  1933. }
  1934. fromBufferAttribute( attribute, index ) {
  1935. this._x = attribute.getX( index );
  1936. this._y = attribute.getY( index );
  1937. this._z = attribute.getZ( index );
  1938. this._w = attribute.getW( index );
  1939. return this;
  1940. }
  1941. _onChange( callback ) {
  1942. this._onChangeCallback = callback;
  1943. return this;
  1944. }
  1945. _onChangeCallback() {}
  1946. }
  1947. class Vector3 {
  1948. constructor( x = 0, y = 0, z = 0 ) {
  1949. Object.defineProperty( this, 'isVector3', { value: true } );
  1950. this.x = x;
  1951. this.y = y;
  1952. this.z = z;
  1953. }
  1954. set( x, y, z ) {
  1955. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1956. this.x = x;
  1957. this.y = y;
  1958. this.z = z;
  1959. return this;
  1960. }
  1961. setScalar( scalar ) {
  1962. this.x = scalar;
  1963. this.y = scalar;
  1964. this.z = scalar;
  1965. return this;
  1966. }
  1967. setX( x ) {
  1968. this.x = x;
  1969. return this;
  1970. }
  1971. setY( y ) {
  1972. this.y = y;
  1973. return this;
  1974. }
  1975. setZ( z ) {
  1976. this.z = z;
  1977. return this;
  1978. }
  1979. setComponent( index, value ) {
  1980. switch ( index ) {
  1981. case 0: this.x = value; break;
  1982. case 1: this.y = value; break;
  1983. case 2: this.z = value; break;
  1984. default: throw new Error( 'index is out of range: ' + index );
  1985. }
  1986. return this;
  1987. }
  1988. getComponent( index ) {
  1989. switch ( index ) {
  1990. case 0: return this.x;
  1991. case 1: return this.y;
  1992. case 2: return this.z;
  1993. default: throw new Error( 'index is out of range: ' + index );
  1994. }
  1995. }
  1996. clone() {
  1997. return new this.constructor( this.x, this.y, this.z );
  1998. }
  1999. copy( v ) {
  2000. this.x = v.x;
  2001. this.y = v.y;
  2002. this.z = v.z;
  2003. return this;
  2004. }
  2005. add( v, w ) {
  2006. if ( w !== undefined ) {
  2007. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2008. return this.addVectors( v, w );
  2009. }
  2010. this.x += v.x;
  2011. this.y += v.y;
  2012. this.z += v.z;
  2013. return this;
  2014. }
  2015. addScalar( s ) {
  2016. this.x += s;
  2017. this.y += s;
  2018. this.z += s;
  2019. return this;
  2020. }
  2021. addVectors( a, b ) {
  2022. this.x = a.x + b.x;
  2023. this.y = a.y + b.y;
  2024. this.z = a.z + b.z;
  2025. return this;
  2026. }
  2027. addScaledVector( v, s ) {
  2028. this.x += v.x * s;
  2029. this.y += v.y * s;
  2030. this.z += v.z * s;
  2031. return this;
  2032. }
  2033. sub( v, w ) {
  2034. if ( w !== undefined ) {
  2035. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2036. return this.subVectors( v, w );
  2037. }
  2038. this.x -= v.x;
  2039. this.y -= v.y;
  2040. this.z -= v.z;
  2041. return this;
  2042. }
  2043. subScalar( s ) {
  2044. this.x -= s;
  2045. this.y -= s;
  2046. this.z -= s;
  2047. return this;
  2048. }
  2049. subVectors( a, b ) {
  2050. this.x = a.x - b.x;
  2051. this.y = a.y - b.y;
  2052. this.z = a.z - b.z;
  2053. return this;
  2054. }
  2055. multiply( v, w ) {
  2056. if ( w !== undefined ) {
  2057. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2058. return this.multiplyVectors( v, w );
  2059. }
  2060. this.x *= v.x;
  2061. this.y *= v.y;
  2062. this.z *= v.z;
  2063. return this;
  2064. }
  2065. multiplyScalar( scalar ) {
  2066. this.x *= scalar;
  2067. this.y *= scalar;
  2068. this.z *= scalar;
  2069. return this;
  2070. }
  2071. multiplyVectors( a, b ) {
  2072. this.x = a.x * b.x;
  2073. this.y = a.y * b.y;
  2074. this.z = a.z * b.z;
  2075. return this;
  2076. }
  2077. applyEuler( euler ) {
  2078. if ( ! ( euler && euler.isEuler ) ) {
  2079. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2080. }
  2081. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  2082. }
  2083. applyAxisAngle( axis, angle ) {
  2084. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  2085. }
  2086. applyMatrix3( m ) {
  2087. const x = this.x, y = this.y, z = this.z;
  2088. const e = m.elements;
  2089. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2090. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2091. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2092. return this;
  2093. }
  2094. applyNormalMatrix( m ) {
  2095. return this.applyMatrix3( m ).normalize();
  2096. }
  2097. applyMatrix4( m ) {
  2098. const x = this.x, y = this.y, z = this.z;
  2099. const e = m.elements;
  2100. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2101. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2102. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2103. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2104. return this;
  2105. }
  2106. applyQuaternion( q ) {
  2107. const x = this.x, y = this.y, z = this.z;
  2108. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2109. // calculate quat * vector
  2110. const ix = qw * x + qy * z - qz * y;
  2111. const iy = qw * y + qz * x - qx * z;
  2112. const iz = qw * z + qx * y - qy * x;
  2113. const iw = - qx * x - qy * y - qz * z;
  2114. // calculate result * inverse quat
  2115. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2116. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2117. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2118. return this;
  2119. }
  2120. project( camera ) {
  2121. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2122. }
  2123. unproject( camera ) {
  2124. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2125. }
  2126. transformDirection( m ) {
  2127. // input: THREE.Matrix4 affine matrix
  2128. // vector interpreted as a direction
  2129. const x = this.x, y = this.y, z = this.z;
  2130. const e = m.elements;
  2131. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2132. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2133. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2134. return this.normalize();
  2135. }
  2136. divide( v ) {
  2137. this.x /= v.x;
  2138. this.y /= v.y;
  2139. this.z /= v.z;
  2140. return this;
  2141. }
  2142. divideScalar( scalar ) {
  2143. return this.multiplyScalar( 1 / scalar );
  2144. }
  2145. min( v ) {
  2146. this.x = Math.min( this.x, v.x );
  2147. this.y = Math.min( this.y, v.y );
  2148. this.z = Math.min( this.z, v.z );
  2149. return this;
  2150. }
  2151. max( v ) {
  2152. this.x = Math.max( this.x, v.x );
  2153. this.y = Math.max( this.y, v.y );
  2154. this.z = Math.max( this.z, v.z );
  2155. return this;
  2156. }
  2157. clamp( min, max ) {
  2158. // assumes min < max, componentwise
  2159. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2160. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2161. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2162. return this;
  2163. }
  2164. clampScalar( minVal, maxVal ) {
  2165. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2166. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2167. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2168. return this;
  2169. }
  2170. clampLength( min, max ) {
  2171. const length = this.length();
  2172. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2173. }
  2174. floor() {
  2175. this.x = Math.floor( this.x );
  2176. this.y = Math.floor( this.y );
  2177. this.z = Math.floor( this.z );
  2178. return this;
  2179. }
  2180. ceil() {
  2181. this.x = Math.ceil( this.x );
  2182. this.y = Math.ceil( this.y );
  2183. this.z = Math.ceil( this.z );
  2184. return this;
  2185. }
  2186. round() {
  2187. this.x = Math.round( this.x );
  2188. this.y = Math.round( this.y );
  2189. this.z = Math.round( this.z );
  2190. return this;
  2191. }
  2192. roundToZero() {
  2193. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2194. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2195. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2196. return this;
  2197. }
  2198. negate() {
  2199. this.x = - this.x;
  2200. this.y = - this.y;
  2201. this.z = - this.z;
  2202. return this;
  2203. }
  2204. dot( v ) {
  2205. return this.x * v.x + this.y * v.y + this.z * v.z;
  2206. }
  2207. // TODO lengthSquared?
  2208. lengthSq() {
  2209. return this.x * this.x + this.y * this.y + this.z * this.z;
  2210. }
  2211. length() {
  2212. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2213. }
  2214. manhattanLength() {
  2215. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2216. }
  2217. normalize() {
  2218. return this.divideScalar( this.length() || 1 );
  2219. }
  2220. setLength( length ) {
  2221. return this.normalize().multiplyScalar( length );
  2222. }
  2223. lerp( v, alpha ) {
  2224. this.x += ( v.x - this.x ) * alpha;
  2225. this.y += ( v.y - this.y ) * alpha;
  2226. this.z += ( v.z - this.z ) * alpha;
  2227. return this;
  2228. }
  2229. lerpVectors( v1, v2, alpha ) {
  2230. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2231. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2232. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2233. return this;
  2234. }
  2235. cross( v, w ) {
  2236. if ( w !== undefined ) {
  2237. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2238. return this.crossVectors( v, w );
  2239. }
  2240. return this.crossVectors( this, v );
  2241. }
  2242. crossVectors( a, b ) {
  2243. const ax = a.x, ay = a.y, az = a.z;
  2244. const bx = b.x, by = b.y, bz = b.z;
  2245. this.x = ay * bz - az * by;
  2246. this.y = az * bx - ax * bz;
  2247. this.z = ax * by - ay * bx;
  2248. return this;
  2249. }
  2250. projectOnVector( v ) {
  2251. const denominator = v.lengthSq();
  2252. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2253. const scalar = v.dot( this ) / denominator;
  2254. return this.copy( v ).multiplyScalar( scalar );
  2255. }
  2256. projectOnPlane( planeNormal ) {
  2257. _vector.copy( this ).projectOnVector( planeNormal );
  2258. return this.sub( _vector );
  2259. }
  2260. reflect( normal ) {
  2261. // reflect incident vector off plane orthogonal to normal
  2262. // normal is assumed to have unit length
  2263. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2264. }
  2265. angleTo( v ) {
  2266. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2267. if ( denominator === 0 ) return Math.PI / 2;
  2268. const theta = this.dot( v ) / denominator;
  2269. // clamp, to handle numerical problems
  2270. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  2271. }
  2272. distanceTo( v ) {
  2273. return Math.sqrt( this.distanceToSquared( v ) );
  2274. }
  2275. distanceToSquared( v ) {
  2276. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2277. return dx * dx + dy * dy + dz * dz;
  2278. }
  2279. manhattanDistanceTo( v ) {
  2280. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2281. }
  2282. setFromSpherical( s ) {
  2283. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2284. }
  2285. setFromSphericalCoords( radius, phi, theta ) {
  2286. const sinPhiRadius = Math.sin( phi ) * radius;
  2287. this.x = sinPhiRadius * Math.sin( theta );
  2288. this.y = Math.cos( phi ) * radius;
  2289. this.z = sinPhiRadius * Math.cos( theta );
  2290. return this;
  2291. }
  2292. setFromCylindrical( c ) {
  2293. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2294. }
  2295. setFromCylindricalCoords( radius, theta, y ) {
  2296. this.x = radius * Math.sin( theta );
  2297. this.y = y;
  2298. this.z = radius * Math.cos( theta );
  2299. return this;
  2300. }
  2301. setFromMatrixPosition( m ) {
  2302. const e = m.elements;
  2303. this.x = e[ 12 ];
  2304. this.y = e[ 13 ];
  2305. this.z = e[ 14 ];
  2306. return this;
  2307. }
  2308. setFromMatrixScale( m ) {
  2309. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2310. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2311. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2312. this.x = sx;
  2313. this.y = sy;
  2314. this.z = sz;
  2315. return this;
  2316. }
  2317. setFromMatrixColumn( m, index ) {
  2318. return this.fromArray( m.elements, index * 4 );
  2319. }
  2320. setFromMatrix3Column( m, index ) {
  2321. return this.fromArray( m.elements, index * 3 );
  2322. }
  2323. equals( v ) {
  2324. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2325. }
  2326. fromArray( array, offset ) {
  2327. if ( offset === undefined ) offset = 0;
  2328. this.x = array[ offset ];
  2329. this.y = array[ offset + 1 ];
  2330. this.z = array[ offset + 2 ];
  2331. return this;
  2332. }
  2333. toArray( array, offset ) {
  2334. if ( array === undefined ) array = [];
  2335. if ( offset === undefined ) offset = 0;
  2336. array[ offset ] = this.x;
  2337. array[ offset + 1 ] = this.y;
  2338. array[ offset + 2 ] = this.z;
  2339. return array;
  2340. }
  2341. fromBufferAttribute( attribute, index, offset ) {
  2342. if ( offset !== undefined ) {
  2343. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2344. }
  2345. this.x = attribute.getX( index );
  2346. this.y = attribute.getY( index );
  2347. this.z = attribute.getZ( index );
  2348. return this;
  2349. }
  2350. random() {
  2351. this.x = Math.random();
  2352. this.y = Math.random();
  2353. this.z = Math.random();
  2354. return this;
  2355. }
  2356. }
  2357. const _vector = /*@__PURE__*/ new Vector3();
  2358. const _quaternion = /*@__PURE__*/ new Quaternion();
  2359. class Box3 {
  2360. constructor( min, max ) {
  2361. Object.defineProperty( this, 'isBox3', { value: true } );
  2362. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  2363. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  2364. }
  2365. set( min, max ) {
  2366. this.min.copy( min );
  2367. this.max.copy( max );
  2368. return this;
  2369. }
  2370. setFromArray( array ) {
  2371. let minX = + Infinity;
  2372. let minY = + Infinity;
  2373. let minZ = + Infinity;
  2374. let maxX = - Infinity;
  2375. let maxY = - Infinity;
  2376. let maxZ = - Infinity;
  2377. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2378. const x = array[ i ];
  2379. const y = array[ i + 1 ];
  2380. const z = array[ i + 2 ];
  2381. if ( x < minX ) minX = x;
  2382. if ( y < minY ) minY = y;
  2383. if ( z < minZ ) minZ = z;
  2384. if ( x > maxX ) maxX = x;
  2385. if ( y > maxY ) maxY = y;
  2386. if ( z > maxZ ) maxZ = z;
  2387. }
  2388. this.min.set( minX, minY, minZ );
  2389. this.max.set( maxX, maxY, maxZ );
  2390. return this;
  2391. }
  2392. setFromBufferAttribute( attribute ) {
  2393. let minX = + Infinity;
  2394. let minY = + Infinity;
  2395. let minZ = + Infinity;
  2396. let maxX = - Infinity;
  2397. let maxY = - Infinity;
  2398. let maxZ = - Infinity;
  2399. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2400. const x = attribute.getX( i );
  2401. const y = attribute.getY( i );
  2402. const z = attribute.getZ( i );
  2403. if ( x < minX ) minX = x;
  2404. if ( y < minY ) minY = y;
  2405. if ( z < minZ ) minZ = z;
  2406. if ( x > maxX ) maxX = x;
  2407. if ( y > maxY ) maxY = y;
  2408. if ( z > maxZ ) maxZ = z;
  2409. }
  2410. this.min.set( minX, minY, minZ );
  2411. this.max.set( maxX, maxY, maxZ );
  2412. return this;
  2413. }
  2414. setFromPoints( points ) {
  2415. this.makeEmpty();
  2416. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2417. this.expandByPoint( points[ i ] );
  2418. }
  2419. return this;
  2420. }
  2421. setFromCenterAndSize( center, size ) {
  2422. const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  2423. this.min.copy( center ).sub( halfSize );
  2424. this.max.copy( center ).add( halfSize );
  2425. return this;
  2426. }
  2427. setFromObject( object ) {
  2428. this.makeEmpty();
  2429. return this.expandByObject( object );
  2430. }
  2431. clone() {
  2432. return new this.constructor().copy( this );
  2433. }
  2434. copy( box ) {
  2435. this.min.copy( box.min );
  2436. this.max.copy( box.max );
  2437. return this;
  2438. }
  2439. makeEmpty() {
  2440. this.min.x = this.min.y = this.min.z = + Infinity;
  2441. this.max.x = this.max.y = this.max.z = - Infinity;
  2442. return this;
  2443. }
  2444. isEmpty() {
  2445. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2446. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2447. }
  2448. getCenter( target ) {
  2449. if ( target === undefined ) {
  2450. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  2451. target = new Vector3();
  2452. }
  2453. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2454. }
  2455. getSize( target ) {
  2456. if ( target === undefined ) {
  2457. console.warn( 'THREE.Box3: .getSize() target is now required' );
  2458. target = new Vector3();
  2459. }
  2460. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2461. }
  2462. expandByPoint( point ) {
  2463. this.min.min( point );
  2464. this.max.max( point );
  2465. return this;
  2466. }
  2467. expandByVector( vector ) {
  2468. this.min.sub( vector );
  2469. this.max.add( vector );
  2470. return this;
  2471. }
  2472. expandByScalar( scalar ) {
  2473. this.min.addScalar( - scalar );
  2474. this.max.addScalar( scalar );
  2475. return this;
  2476. }
  2477. expandByObject( object ) {
  2478. // Computes the world-axis-aligned bounding box of an object (including its children),
  2479. // accounting for both the object's, and children's, world transforms
  2480. object.updateWorldMatrix( false, false );
  2481. const geometry = object.geometry;
  2482. if ( geometry !== undefined ) {
  2483. if ( geometry.boundingBox === null ) {
  2484. geometry.computeBoundingBox();
  2485. }
  2486. _box.copy( geometry.boundingBox );
  2487. _box.applyMatrix4( object.matrixWorld );
  2488. this.union( _box );
  2489. }
  2490. const children = object.children;
  2491. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2492. this.expandByObject( children[ i ] );
  2493. }
  2494. return this;
  2495. }
  2496. containsPoint( point ) {
  2497. return point.x < this.min.x || point.x > this.max.x ||
  2498. point.y < this.min.y || point.y > this.max.y ||
  2499. point.z < this.min.z || point.z > this.max.z ? false : true;
  2500. }
  2501. containsBox( box ) {
  2502. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2503. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2504. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2505. }
  2506. getParameter( point, target ) {
  2507. // This can potentially have a divide by zero if the box
  2508. // has a size dimension of 0.
  2509. if ( target === undefined ) {
  2510. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  2511. target = new Vector3();
  2512. }
  2513. return target.set(
  2514. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2515. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2516. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2517. );
  2518. }
  2519. intersectsBox( box ) {
  2520. // using 6 splitting planes to rule out intersections.
  2521. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2522. box.max.y < this.min.y || box.min.y > this.max.y ||
  2523. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2524. }
  2525. intersectsSphere( sphere ) {
  2526. // Find the point on the AABB closest to the sphere center.
  2527. this.clampPoint( sphere.center, _vector$1 );
  2528. // If that point is inside the sphere, the AABB and sphere intersect.
  2529. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2530. }
  2531. intersectsPlane( plane ) {
  2532. // We compute the minimum and maximum dot product values. If those values
  2533. // are on the same side (back or front) of the plane, then there is no intersection.
  2534. let min, max;
  2535. if ( plane.normal.x > 0 ) {
  2536. min = plane.normal.x * this.min.x;
  2537. max = plane.normal.x * this.max.x;
  2538. } else {
  2539. min = plane.normal.x * this.max.x;
  2540. max = plane.normal.x * this.min.x;
  2541. }
  2542. if ( plane.normal.y > 0 ) {
  2543. min += plane.normal.y * this.min.y;
  2544. max += plane.normal.y * this.max.y;
  2545. } else {
  2546. min += plane.normal.y * this.max.y;
  2547. max += plane.normal.y * this.min.y;
  2548. }
  2549. if ( plane.normal.z > 0 ) {
  2550. min += plane.normal.z * this.min.z;
  2551. max += plane.normal.z * this.max.z;
  2552. } else {
  2553. min += plane.normal.z * this.max.z;
  2554. max += plane.normal.z * this.min.z;
  2555. }
  2556. return ( min <= - plane.constant && max >= - plane.constant );
  2557. }
  2558. intersectsTriangle( triangle ) {
  2559. if ( this.isEmpty() ) {
  2560. return false;
  2561. }
  2562. // compute box center and extents
  2563. this.getCenter( _center );
  2564. _extents.subVectors( this.max, _center );
  2565. // translate triangle to aabb origin
  2566. _v0.subVectors( triangle.a, _center );
  2567. _v1.subVectors( triangle.b, _center );
  2568. _v2.subVectors( triangle.c, _center );
  2569. // compute edge vectors for triangle
  2570. _f0.subVectors( _v1, _v0 );
  2571. _f1.subVectors( _v2, _v1 );
  2572. _f2.subVectors( _v0, _v2 );
  2573. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2574. // 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
  2575. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2576. let axes = [
  2577. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2578. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2579. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2580. ];
  2581. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  2582. return false;
  2583. }
  2584. // test 3 face normals from the aabb
  2585. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2586. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  2587. return false;
  2588. }
  2589. // finally testing the face normal of the triangle
  2590. // use already existing triangle edge vectors here
  2591. _triangleNormal.crossVectors( _f0, _f1 );
  2592. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2593. return satForAxes( axes, _v0, _v1, _v2, _extents );
  2594. }
  2595. clampPoint( point, target ) {
  2596. if ( target === undefined ) {
  2597. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  2598. target = new Vector3();
  2599. }
  2600. return target.copy( point ).clamp( this.min, this.max );
  2601. }
  2602. distanceToPoint( point ) {
  2603. const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  2604. return clampedPoint.sub( point ).length();
  2605. }
  2606. getBoundingSphere( target ) {
  2607. if ( target === undefined ) {
  2608. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  2609. //target = new Sphere(); // removed to avoid cyclic dependency
  2610. }
  2611. this.getCenter( target.center );
  2612. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  2613. return target;
  2614. }
  2615. intersect( box ) {
  2616. this.min.max( box.min );
  2617. this.max.min( box.max );
  2618. // 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.
  2619. if ( this.isEmpty() ) this.makeEmpty();
  2620. return this;
  2621. }
  2622. union( box ) {
  2623. this.min.min( box.min );
  2624. this.max.max( box.max );
  2625. return this;
  2626. }
  2627. applyMatrix4( matrix ) {
  2628. // transform of empty box is an empty box.
  2629. if ( this.isEmpty() ) return this;
  2630. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2631. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2632. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2633. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2634. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2635. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2636. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2637. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2638. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2639. this.setFromPoints( _points );
  2640. return this;
  2641. }
  2642. translate( offset ) {
  2643. this.min.add( offset );
  2644. this.max.add( offset );
  2645. return this;
  2646. }
  2647. equals( box ) {
  2648. return box.min.equals( this.min ) && box.max.equals( this.max );
  2649. }
  2650. }
  2651. function satForAxes( axes, v0, v1, v2, extents ) {
  2652. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2653. _testAxis.fromArray( axes, i );
  2654. // project the aabb onto the seperating axis
  2655. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2656. // project all 3 vertices of the triangle onto the seperating axis
  2657. const p0 = v0.dot( _testAxis );
  2658. const p1 = v1.dot( _testAxis );
  2659. const p2 = v2.dot( _testAxis );
  2660. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2661. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2662. // points of the projected triangle are outside the projected half-length of the aabb
  2663. // the axis is seperating and we can exit
  2664. return false;
  2665. }
  2666. }
  2667. return true;
  2668. }
  2669. const _points = [
  2670. /*@__PURE__*/ new Vector3(),
  2671. /*@__PURE__*/ new Vector3(),
  2672. /*@__PURE__*/ new Vector3(),
  2673. /*@__PURE__*/ new Vector3(),
  2674. /*@__PURE__*/ new Vector3(),
  2675. /*@__PURE__*/ new Vector3(),
  2676. /*@__PURE__*/ new Vector3(),
  2677. /*@__PURE__*/ new Vector3()
  2678. ];
  2679. const _vector$1 = /*@__PURE__*/ new Vector3();
  2680. const _box = /*@__PURE__*/ new Box3();
  2681. // triangle centered vertices
  2682. const _v0 = /*@__PURE__*/ new Vector3();
  2683. const _v1 = /*@__PURE__*/ new Vector3();
  2684. const _v2 = /*@__PURE__*/ new Vector3();
  2685. // triangle edge vectors
  2686. const _f0 = /*@__PURE__*/ new Vector3();
  2687. const _f1 = /*@__PURE__*/ new Vector3();
  2688. const _f2 = /*@__PURE__*/ new Vector3();
  2689. const _center = /*@__PURE__*/ new Vector3();
  2690. const _extents = /*@__PURE__*/ new Vector3();
  2691. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2692. const _testAxis = /*@__PURE__*/ new Vector3();
  2693. const _box$1 = /*@__PURE__*/ new Box3();
  2694. class Sphere {
  2695. constructor( center, radius ) {
  2696. this.center = ( center !== undefined ) ? center : new Vector3();
  2697. this.radius = ( radius !== undefined ) ? radius : - 1;
  2698. }
  2699. set( center, radius ) {
  2700. this.center.copy( center );
  2701. this.radius = radius;
  2702. return this;
  2703. }
  2704. setFromPoints( points, optionalCenter ) {
  2705. const center = this.center;
  2706. if ( optionalCenter !== undefined ) {
  2707. center.copy( optionalCenter );
  2708. } else {
  2709. _box$1.setFromPoints( points ).getCenter( center );
  2710. }
  2711. let maxRadiusSq = 0;
  2712. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2713. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2714. }
  2715. this.radius = Math.sqrt( maxRadiusSq );
  2716. return this;
  2717. }
  2718. clone() {
  2719. return new this.constructor().copy( this );
  2720. }
  2721. copy( sphere ) {
  2722. this.center.copy( sphere.center );
  2723. this.radius = sphere.radius;
  2724. return this;
  2725. }
  2726. isEmpty() {
  2727. return ( this.radius < 0 );
  2728. }
  2729. makeEmpty() {
  2730. this.center.set( 0, 0, 0 );
  2731. this.radius = - 1;
  2732. return this;
  2733. }
  2734. containsPoint( point ) {
  2735. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2736. }
  2737. distanceToPoint( point ) {
  2738. return ( point.distanceTo( this.center ) - this.radius );
  2739. }
  2740. intersectsSphere( sphere ) {
  2741. const radiusSum = this.radius + sphere.radius;
  2742. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2743. }
  2744. intersectsBox( box ) {
  2745. return box.intersectsSphere( this );
  2746. }
  2747. intersectsPlane( plane ) {
  2748. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2749. }
  2750. clampPoint( point, target ) {
  2751. const deltaLengthSq = this.center.distanceToSquared( point );
  2752. if ( target === undefined ) {
  2753. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  2754. target = new Vector3();
  2755. }
  2756. target.copy( point );
  2757. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2758. target.sub( this.center ).normalize();
  2759. target.multiplyScalar( this.radius ).add( this.center );
  2760. }
  2761. return target;
  2762. }
  2763. getBoundingBox( target ) {
  2764. if ( target === undefined ) {
  2765. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  2766. target = new Box3();
  2767. }
  2768. if ( this.isEmpty() ) {
  2769. // Empty sphere produces empty bounding box
  2770. target.makeEmpty();
  2771. return target;
  2772. }
  2773. target.set( this.center, this.center );
  2774. target.expandByScalar( this.radius );
  2775. return target;
  2776. }
  2777. applyMatrix4( matrix ) {
  2778. this.center.applyMatrix4( matrix );
  2779. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2780. return this;
  2781. }
  2782. translate( offset ) {
  2783. this.center.add( offset );
  2784. return this;
  2785. }
  2786. equals( sphere ) {
  2787. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2788. }
  2789. }
  2790. const _vector$2 = /*@__PURE__*/ new Vector3();
  2791. const _segCenter = /*@__PURE__*/ new Vector3();
  2792. const _segDir = /*@__PURE__*/ new Vector3();
  2793. const _diff = /*@__PURE__*/ new Vector3();
  2794. const _edge1 = /*@__PURE__*/ new Vector3();
  2795. const _edge2 = /*@__PURE__*/ new Vector3();
  2796. const _normal = /*@__PURE__*/ new Vector3();
  2797. class Ray {
  2798. constructor( origin, direction ) {
  2799. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  2800. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  2801. }
  2802. set( origin, direction ) {
  2803. this.origin.copy( origin );
  2804. this.direction.copy( direction );
  2805. return this;
  2806. }
  2807. clone() {
  2808. return new this.constructor().copy( this );
  2809. }
  2810. copy( ray ) {
  2811. this.origin.copy( ray.origin );
  2812. this.direction.copy( ray.direction );
  2813. return this;
  2814. }
  2815. at( t, target ) {
  2816. if ( target === undefined ) {
  2817. console.warn( 'THREE.Ray: .at() target is now required' );
  2818. target = new Vector3();
  2819. }
  2820. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2821. }
  2822. lookAt( v ) {
  2823. this.direction.copy( v ).sub( this.origin ).normalize();
  2824. return this;
  2825. }
  2826. recast( t ) {
  2827. this.origin.copy( this.at( t, _vector$2 ) );
  2828. return this;
  2829. }
  2830. closestPointToPoint( point, target ) {
  2831. if ( target === undefined ) {
  2832. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  2833. target = new Vector3();
  2834. }
  2835. target.subVectors( point, this.origin );
  2836. const directionDistance = target.dot( this.direction );
  2837. if ( directionDistance < 0 ) {
  2838. return target.copy( this.origin );
  2839. }
  2840. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2841. }
  2842. distanceToPoint( point ) {
  2843. return Math.sqrt( this.distanceSqToPoint( point ) );
  2844. }
  2845. distanceSqToPoint( point ) {
  2846. const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  2847. // point behind the ray
  2848. if ( directionDistance < 0 ) {
  2849. return this.origin.distanceToSquared( point );
  2850. }
  2851. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2852. return _vector$2.distanceToSquared( point );
  2853. }
  2854. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  2855. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2856. // It returns the min distance between the ray and the segment
  2857. // defined by v0 and v1
  2858. // It can also set two optional targets :
  2859. // - The closest point on the ray
  2860. // - The closest point on the segment
  2861. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  2862. _segDir.copy( v1 ).sub( v0 ).normalize();
  2863. _diff.copy( this.origin ).sub( _segCenter );
  2864. const segExtent = v0.distanceTo( v1 ) * 0.5;
  2865. const a01 = - this.direction.dot( _segDir );
  2866. const b0 = _diff.dot( this.direction );
  2867. const b1 = - _diff.dot( _segDir );
  2868. const c = _diff.lengthSq();
  2869. const det = Math.abs( 1 - a01 * a01 );
  2870. let s0, s1, sqrDist, extDet;
  2871. if ( det > 0 ) {
  2872. // The ray and segment are not parallel.
  2873. s0 = a01 * b1 - b0;
  2874. s1 = a01 * b0 - b1;
  2875. extDet = segExtent * det;
  2876. if ( s0 >= 0 ) {
  2877. if ( s1 >= - extDet ) {
  2878. if ( s1 <= extDet ) {
  2879. // region 0
  2880. // Minimum at interior points of ray and segment.
  2881. const invDet = 1 / det;
  2882. s0 *= invDet;
  2883. s1 *= invDet;
  2884. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  2885. } else {
  2886. // region 1
  2887. s1 = segExtent;
  2888. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2889. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2890. }
  2891. } else {
  2892. // region 5
  2893. s1 = - segExtent;
  2894. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2895. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2896. }
  2897. } else {
  2898. if ( s1 <= - extDet ) {
  2899. // region 4
  2900. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  2901. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2902. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2903. } else if ( s1 <= extDet ) {
  2904. // region 3
  2905. s0 = 0;
  2906. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2907. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  2908. } else {
  2909. // region 2
  2910. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  2911. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2912. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2913. }
  2914. }
  2915. } else {
  2916. // Ray and segment are parallel.
  2917. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  2918. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2919. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2920. }
  2921. if ( optionalPointOnRay ) {
  2922. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  2923. }
  2924. if ( optionalPointOnSegment ) {
  2925. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  2926. }
  2927. return sqrDist;
  2928. }
  2929. intersectSphere( sphere, target ) {
  2930. _vector$2.subVectors( sphere.center, this.origin );
  2931. const tca = _vector$2.dot( this.direction );
  2932. const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  2933. const radius2 = sphere.radius * sphere.radius;
  2934. if ( d2 > radius2 ) return null;
  2935. const thc = Math.sqrt( radius2 - d2 );
  2936. // t0 = first intersect point - entrance on front of sphere
  2937. const t0 = tca - thc;
  2938. // t1 = second intersect point - exit point on back of sphere
  2939. const t1 = tca + thc;
  2940. // test to see if both t0 and t1 are behind the ray - if so, return null
  2941. if ( t0 < 0 && t1 < 0 ) return null;
  2942. // test to see if t0 is behind the ray:
  2943. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  2944. // in order to always return an intersect point that is in front of the ray.
  2945. if ( t0 < 0 ) return this.at( t1, target );
  2946. // else t0 is in front of the ray, so return the first collision point scaled by t0
  2947. return this.at( t0, target );
  2948. }
  2949. intersectsSphere( sphere ) {
  2950. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  2951. }
  2952. distanceToPlane( plane ) {
  2953. const denominator = plane.normal.dot( this.direction );
  2954. if ( denominator === 0 ) {
  2955. // line is coplanar, return origin
  2956. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  2957. return 0;
  2958. }
  2959. // Null is preferable to undefined since undefined means.... it is undefined
  2960. return null;
  2961. }
  2962. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2963. // Return if the ray never intersects the plane
  2964. return t >= 0 ? t : null;
  2965. }
  2966. intersectPlane( plane, target ) {
  2967. const t = this.distanceToPlane( plane );
  2968. if ( t === null ) {
  2969. return null;
  2970. }
  2971. return this.at( t, target );
  2972. }
  2973. intersectsPlane( plane ) {
  2974. // check if the ray lies on the plane first
  2975. const distToPoint = plane.distanceToPoint( this.origin );
  2976. if ( distToPoint === 0 ) {
  2977. return true;
  2978. }
  2979. const denominator = plane.normal.dot( this.direction );
  2980. if ( denominator * distToPoint < 0 ) {
  2981. return true;
  2982. }
  2983. // ray origin is behind the plane (and is pointing behind it)
  2984. return false;
  2985. }
  2986. intersectBox( box, target ) {
  2987. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  2988. const invdirx = 1 / this.direction.x,
  2989. invdiry = 1 / this.direction.y,
  2990. invdirz = 1 / this.direction.z;
  2991. const origin = this.origin;
  2992. if ( invdirx >= 0 ) {
  2993. tmin = ( box.min.x - origin.x ) * invdirx;
  2994. tmax = ( box.max.x - origin.x ) * invdirx;
  2995. } else {
  2996. tmin = ( box.max.x - origin.x ) * invdirx;
  2997. tmax = ( box.min.x - origin.x ) * invdirx;
  2998. }
  2999. if ( invdiry >= 0 ) {
  3000. tymin = ( box.min.y - origin.y ) * invdiry;
  3001. tymax = ( box.max.y - origin.y ) * invdiry;
  3002. } else {
  3003. tymin = ( box.max.y - origin.y ) * invdiry;
  3004. tymax = ( box.min.y - origin.y ) * invdiry;
  3005. }
  3006. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3007. // These lines also handle the case where tmin or tmax is NaN
  3008. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3009. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3010. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3011. if ( invdirz >= 0 ) {
  3012. tzmin = ( box.min.z - origin.z ) * invdirz;
  3013. tzmax = ( box.max.z - origin.z ) * invdirz;
  3014. } else {
  3015. tzmin = ( box.max.z - origin.z ) * invdirz;
  3016. tzmax = ( box.min.z - origin.z ) * invdirz;
  3017. }
  3018. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3019. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3020. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3021. //return point closest to the ray (positive side)
  3022. if ( tmax < 0 ) return null;
  3023. return this.at( tmin >= 0 ? tmin : tmax, target );
  3024. }
  3025. intersectsBox( box ) {
  3026. return this.intersectBox( box, _vector$2 ) !== null;
  3027. }
  3028. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3029. // Compute the offset origin, edges, and normal.
  3030. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3031. _edge1.subVectors( b, a );
  3032. _edge2.subVectors( c, a );
  3033. _normal.crossVectors( _edge1, _edge2 );
  3034. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3035. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3036. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3037. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3038. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3039. let DdN = this.direction.dot( _normal );
  3040. let sign;
  3041. if ( DdN > 0 ) {
  3042. if ( backfaceCulling ) return null;
  3043. sign = 1;
  3044. } else if ( DdN < 0 ) {
  3045. sign = - 1;
  3046. DdN = - DdN;
  3047. } else {
  3048. return null;
  3049. }
  3050. _diff.subVectors( this.origin, a );
  3051. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3052. // b1 < 0, no intersection
  3053. if ( DdQxE2 < 0 ) {
  3054. return null;
  3055. }
  3056. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3057. // b2 < 0, no intersection
  3058. if ( DdE1xQ < 0 ) {
  3059. return null;
  3060. }
  3061. // b1+b2 > 1, no intersection
  3062. if ( DdQxE2 + DdE1xQ > DdN ) {
  3063. return null;
  3064. }
  3065. // Line intersects triangle, check if ray does.
  3066. const QdN = - sign * _diff.dot( _normal );
  3067. // t < 0, no intersection
  3068. if ( QdN < 0 ) {
  3069. return null;
  3070. }
  3071. // Ray intersects triangle.
  3072. return this.at( QdN / DdN, target );
  3073. }
  3074. applyMatrix4( matrix4 ) {
  3075. this.origin.applyMatrix4( matrix4 );
  3076. this.direction.transformDirection( matrix4 );
  3077. return this;
  3078. }
  3079. equals( ray ) {
  3080. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3081. }
  3082. }
  3083. class Matrix4 {
  3084. constructor() {
  3085. Object.defineProperty( this, 'isMatrix4', { value: true } );
  3086. this.elements = [
  3087. 1, 0, 0, 0,
  3088. 0, 1, 0, 0,
  3089. 0, 0, 1, 0,
  3090. 0, 0, 0, 1
  3091. ];
  3092. if ( arguments.length > 0 ) {
  3093. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3094. }
  3095. }
  3096. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3097. const te = this.elements;
  3098. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3099. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3100. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3101. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3102. return this;
  3103. }
  3104. identity() {
  3105. this.set(
  3106. 1, 0, 0, 0,
  3107. 0, 1, 0, 0,
  3108. 0, 0, 1, 0,
  3109. 0, 0, 0, 1
  3110. );
  3111. return this;
  3112. }
  3113. clone() {
  3114. return new Matrix4().fromArray( this.elements );
  3115. }
  3116. copy( m ) {
  3117. const te = this.elements;
  3118. const me = m.elements;
  3119. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3120. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3121. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3122. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3123. return this;
  3124. }
  3125. copyPosition( m ) {
  3126. const te = this.elements, me = m.elements;
  3127. te[ 12 ] = me[ 12 ];
  3128. te[ 13 ] = me[ 13 ];
  3129. te[ 14 ] = me[ 14 ];
  3130. return this;
  3131. }
  3132. extractBasis( xAxis, yAxis, zAxis ) {
  3133. xAxis.setFromMatrixColumn( this, 0 );
  3134. yAxis.setFromMatrixColumn( this, 1 );
  3135. zAxis.setFromMatrixColumn( this, 2 );
  3136. return this;
  3137. }
  3138. makeBasis( xAxis, yAxis, zAxis ) {
  3139. this.set(
  3140. xAxis.x, yAxis.x, zAxis.x, 0,
  3141. xAxis.y, yAxis.y, zAxis.y, 0,
  3142. xAxis.z, yAxis.z, zAxis.z, 0,
  3143. 0, 0, 0, 1
  3144. );
  3145. return this;
  3146. }
  3147. extractRotation( m ) {
  3148. // this method does not support reflection matrices
  3149. const te = this.elements;
  3150. const me = m.elements;
  3151. const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length();
  3152. const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length();
  3153. const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length();
  3154. te[ 0 ] = me[ 0 ] * scaleX;
  3155. te[ 1 ] = me[ 1 ] * scaleX;
  3156. te[ 2 ] = me[ 2 ] * scaleX;
  3157. te[ 3 ] = 0;
  3158. te[ 4 ] = me[ 4 ] * scaleY;
  3159. te[ 5 ] = me[ 5 ] * scaleY;
  3160. te[ 6 ] = me[ 6 ] * scaleY;
  3161. te[ 7 ] = 0;
  3162. te[ 8 ] = me[ 8 ] * scaleZ;
  3163. te[ 9 ] = me[ 9 ] * scaleZ;
  3164. te[ 10 ] = me[ 10 ] * scaleZ;
  3165. te[ 11 ] = 0;
  3166. te[ 12 ] = 0;
  3167. te[ 13 ] = 0;
  3168. te[ 14 ] = 0;
  3169. te[ 15 ] = 1;
  3170. return this;
  3171. }
  3172. makeRotationFromEuler( euler ) {
  3173. if ( ! ( euler && euler.isEuler ) ) {
  3174. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3175. }
  3176. const te = this.elements;
  3177. const x = euler.x, y = euler.y, z = euler.z;
  3178. const a = Math.cos( x ), b = Math.sin( x );
  3179. const c = Math.cos( y ), d = Math.sin( y );
  3180. const e = Math.cos( z ), f = Math.sin( z );
  3181. if ( euler.order === 'XYZ' ) {
  3182. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3183. te[ 0 ] = c * e;
  3184. te[ 4 ] = - c * f;
  3185. te[ 8 ] = d;
  3186. te[ 1 ] = af + be * d;
  3187. te[ 5 ] = ae - bf * d;
  3188. te[ 9 ] = - b * c;
  3189. te[ 2 ] = bf - ae * d;
  3190. te[ 6 ] = be + af * d;
  3191. te[ 10 ] = a * c;
  3192. } else if ( euler.order === 'YXZ' ) {
  3193. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3194. te[ 0 ] = ce + df * b;
  3195. te[ 4 ] = de * b - cf;
  3196. te[ 8 ] = a * d;
  3197. te[ 1 ] = a * f;
  3198. te[ 5 ] = a * e;
  3199. te[ 9 ] = - b;
  3200. te[ 2 ] = cf * b - de;
  3201. te[ 6 ] = df + ce * b;
  3202. te[ 10 ] = a * c;
  3203. } else if ( euler.order === 'ZXY' ) {
  3204. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3205. te[ 0 ] = ce - df * b;
  3206. te[ 4 ] = - a * f;
  3207. te[ 8 ] = de + cf * b;
  3208. te[ 1 ] = cf + de * b;
  3209. te[ 5 ] = a * e;
  3210. te[ 9 ] = df - ce * b;
  3211. te[ 2 ] = - a * d;
  3212. te[ 6 ] = b;
  3213. te[ 10 ] = a * c;
  3214. } else if ( euler.order === 'ZYX' ) {
  3215. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3216. te[ 0 ] = c * e;
  3217. te[ 4 ] = be * d - af;
  3218. te[ 8 ] = ae * d + bf;
  3219. te[ 1 ] = c * f;
  3220. te[ 5 ] = bf * d + ae;
  3221. te[ 9 ] = af * d - be;
  3222. te[ 2 ] = - d;
  3223. te[ 6 ] = b * c;
  3224. te[ 10 ] = a * c;
  3225. } else if ( euler.order === 'YZX' ) {
  3226. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3227. te[ 0 ] = c * e;
  3228. te[ 4 ] = bd - ac * f;
  3229. te[ 8 ] = bc * f + ad;
  3230. te[ 1 ] = f;
  3231. te[ 5 ] = a * e;
  3232. te[ 9 ] = - b * e;
  3233. te[ 2 ] = - d * e;
  3234. te[ 6 ] = ad * f + bc;
  3235. te[ 10 ] = ac - bd * f;
  3236. } else if ( euler.order === 'XZY' ) {
  3237. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3238. te[ 0 ] = c * e;
  3239. te[ 4 ] = - f;
  3240. te[ 8 ] = d * e;
  3241. te[ 1 ] = ac * f + bd;
  3242. te[ 5 ] = a * e;
  3243. te[ 9 ] = ad * f - bc;
  3244. te[ 2 ] = bc * f - ad;
  3245. te[ 6 ] = b * e;
  3246. te[ 10 ] = bd * f + ac;
  3247. }
  3248. // bottom row
  3249. te[ 3 ] = 0;
  3250. te[ 7 ] = 0;
  3251. te[ 11 ] = 0;
  3252. // last column
  3253. te[ 12 ] = 0;
  3254. te[ 13 ] = 0;
  3255. te[ 14 ] = 0;
  3256. te[ 15 ] = 1;
  3257. return this;
  3258. }
  3259. makeRotationFromQuaternion( q ) {
  3260. return this.compose( _zero, q, _one );
  3261. }
  3262. lookAt( eye, target, up ) {
  3263. const te = this.elements;
  3264. _z.subVectors( eye, target );
  3265. if ( _z.lengthSq() === 0 ) {
  3266. // eye and target are in the same position
  3267. _z.z = 1;
  3268. }
  3269. _z.normalize();
  3270. _x.crossVectors( up, _z );
  3271. if ( _x.lengthSq() === 0 ) {
  3272. // up and z are parallel
  3273. if ( Math.abs( up.z ) === 1 ) {
  3274. _z.x += 0.0001;
  3275. } else {
  3276. _z.z += 0.0001;
  3277. }
  3278. _z.normalize();
  3279. _x.crossVectors( up, _z );
  3280. }
  3281. _x.normalize();
  3282. _y.crossVectors( _z, _x );
  3283. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3284. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3285. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3286. return this;
  3287. }
  3288. multiply( m, n ) {
  3289. if ( n !== undefined ) {
  3290. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3291. return this.multiplyMatrices( m, n );
  3292. }
  3293. return this.multiplyMatrices( this, m );
  3294. }
  3295. premultiply( m ) {
  3296. return this.multiplyMatrices( m, this );
  3297. }
  3298. multiplyMatrices( a, b ) {
  3299. const ae = a.elements;
  3300. const be = b.elements;
  3301. const te = this.elements;
  3302. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3303. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3304. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3305. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3306. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3307. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3308. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3309. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3310. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3311. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3312. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3313. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3314. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3315. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3316. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3317. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3318. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3319. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3320. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3321. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3322. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3323. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3324. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3325. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3326. return this;
  3327. }
  3328. multiplyScalar( s ) {
  3329. const te = this.elements;
  3330. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3331. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3332. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3333. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3334. return this;
  3335. }
  3336. determinant() {
  3337. const te = this.elements;
  3338. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3339. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3340. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3341. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3342. //TODO: make this more efficient
  3343. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3344. return (
  3345. n41 * (
  3346. + n14 * n23 * n32
  3347. - n13 * n24 * n32
  3348. - n14 * n22 * n33
  3349. + n12 * n24 * n33
  3350. + n13 * n22 * n34
  3351. - n12 * n23 * n34
  3352. ) +
  3353. n42 * (
  3354. + n11 * n23 * n34
  3355. - n11 * n24 * n33
  3356. + n14 * n21 * n33
  3357. - n13 * n21 * n34
  3358. + n13 * n24 * n31
  3359. - n14 * n23 * n31
  3360. ) +
  3361. n43 * (
  3362. + n11 * n24 * n32
  3363. - n11 * n22 * n34
  3364. - n14 * n21 * n32
  3365. + n12 * n21 * n34
  3366. + n14 * n22 * n31
  3367. - n12 * n24 * n31
  3368. ) +
  3369. n44 * (
  3370. - n13 * n22 * n31
  3371. - n11 * n23 * n32
  3372. + n11 * n22 * n33
  3373. + n13 * n21 * n32
  3374. - n12 * n21 * n33
  3375. + n12 * n23 * n31
  3376. )
  3377. );
  3378. }
  3379. transpose() {
  3380. const te = this.elements;
  3381. let tmp;
  3382. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3383. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3384. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3385. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3386. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3387. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3388. return this;
  3389. }
  3390. setPosition( x, y, z ) {
  3391. const te = this.elements;
  3392. if ( x.isVector3 ) {
  3393. te[ 12 ] = x.x;
  3394. te[ 13 ] = x.y;
  3395. te[ 14 ] = x.z;
  3396. } else {
  3397. te[ 12 ] = x;
  3398. te[ 13 ] = y;
  3399. te[ 14 ] = z;
  3400. }
  3401. return this;
  3402. }
  3403. getInverse( m, throwOnDegenerate ) {
  3404. if ( throwOnDegenerate !== undefined ) {
  3405. console.warn( "THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate." );
  3406. }
  3407. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3408. const te = this.elements,
  3409. me = m.elements,
  3410. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  3411. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  3412. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  3413. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  3414. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3415. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3416. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3417. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3418. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3419. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3420. const detInv = 1 / det;
  3421. te[ 0 ] = t11 * detInv;
  3422. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3423. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3424. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3425. te[ 4 ] = t12 * detInv;
  3426. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3427. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3428. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3429. te[ 8 ] = t13 * detInv;
  3430. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3431. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3432. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3433. te[ 12 ] = t14 * detInv;
  3434. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3435. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3436. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3437. return this;
  3438. }
  3439. scale( v ) {
  3440. const te = this.elements;
  3441. const x = v.x, y = v.y, z = v.z;
  3442. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3443. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3444. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3445. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3446. return this;
  3447. }
  3448. getMaxScaleOnAxis() {
  3449. const te = this.elements;
  3450. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3451. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3452. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3453. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3454. }
  3455. makeTranslation( x, y, z ) {
  3456. this.set(
  3457. 1, 0, 0, x,
  3458. 0, 1, 0, y,
  3459. 0, 0, 1, z,
  3460. 0, 0, 0, 1
  3461. );
  3462. return this;
  3463. }
  3464. makeRotationX( theta ) {
  3465. const c = Math.cos( theta ), s = Math.sin( theta );
  3466. this.set(
  3467. 1, 0, 0, 0,
  3468. 0, c, - s, 0,
  3469. 0, s, c, 0,
  3470. 0, 0, 0, 1
  3471. );
  3472. return this;
  3473. }
  3474. makeRotationY( theta ) {
  3475. const c = Math.cos( theta ), s = Math.sin( theta );
  3476. this.set(
  3477. c, 0, s, 0,
  3478. 0, 1, 0, 0,
  3479. - s, 0, c, 0,
  3480. 0, 0, 0, 1
  3481. );
  3482. return this;
  3483. }
  3484. makeRotationZ( theta ) {
  3485. const c = Math.cos( theta ), s = Math.sin( theta );
  3486. this.set(
  3487. c, - s, 0, 0,
  3488. s, c, 0, 0,
  3489. 0, 0, 1, 0,
  3490. 0, 0, 0, 1
  3491. );
  3492. return this;
  3493. }
  3494. makeRotationAxis( axis, angle ) {
  3495. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3496. const c = Math.cos( angle );
  3497. const s = Math.sin( angle );
  3498. const t = 1 - c;
  3499. const x = axis.x, y = axis.y, z = axis.z;
  3500. const tx = t * x, ty = t * y;
  3501. this.set(
  3502. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3503. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3504. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3505. 0, 0, 0, 1
  3506. );
  3507. return this;
  3508. }
  3509. makeScale( x, y, z ) {
  3510. this.set(
  3511. x, 0, 0, 0,
  3512. 0, y, 0, 0,
  3513. 0, 0, z, 0,
  3514. 0, 0, 0, 1
  3515. );
  3516. return this;
  3517. }
  3518. makeShear( x, y, z ) {
  3519. this.set(
  3520. 1, y, z, 0,
  3521. x, 1, z, 0,
  3522. x, y, 1, 0,
  3523. 0, 0, 0, 1
  3524. );
  3525. return this;
  3526. }
  3527. compose( position, quaternion, scale ) {
  3528. const te = this.elements;
  3529. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3530. const x2 = x + x, y2 = y + y, z2 = z + z;
  3531. const xx = x * x2, xy = x * y2, xz = x * z2;
  3532. const yy = y * y2, yz = y * z2, zz = z * z2;
  3533. const wx = w * x2, wy = w * y2, wz = w * z2;
  3534. const sx = scale.x, sy = scale.y, sz = scale.z;
  3535. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3536. te[ 1 ] = ( xy + wz ) * sx;
  3537. te[ 2 ] = ( xz - wy ) * sx;
  3538. te[ 3 ] = 0;
  3539. te[ 4 ] = ( xy - wz ) * sy;
  3540. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3541. te[ 6 ] = ( yz + wx ) * sy;
  3542. te[ 7 ] = 0;
  3543. te[ 8 ] = ( xz + wy ) * sz;
  3544. te[ 9 ] = ( yz - wx ) * sz;
  3545. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3546. te[ 11 ] = 0;
  3547. te[ 12 ] = position.x;
  3548. te[ 13 ] = position.y;
  3549. te[ 14 ] = position.z;
  3550. te[ 15 ] = 1;
  3551. return this;
  3552. }
  3553. decompose( position, quaternion, scale ) {
  3554. const te = this.elements;
  3555. let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3556. const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3557. const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3558. // if determine is negative, we need to invert one scale
  3559. const det = this.determinant();
  3560. if ( det < 0 ) sx = - sx;
  3561. position.x = te[ 12 ];
  3562. position.y = te[ 13 ];
  3563. position.z = te[ 14 ];
  3564. // scale the rotation part
  3565. _m1.copy( this );
  3566. const invSX = 1 / sx;
  3567. const invSY = 1 / sy;
  3568. const invSZ = 1 / sz;
  3569. _m1.elements[ 0 ] *= invSX;
  3570. _m1.elements[ 1 ] *= invSX;
  3571. _m1.elements[ 2 ] *= invSX;
  3572. _m1.elements[ 4 ] *= invSY;
  3573. _m1.elements[ 5 ] *= invSY;
  3574. _m1.elements[ 6 ] *= invSY;
  3575. _m1.elements[ 8 ] *= invSZ;
  3576. _m1.elements[ 9 ] *= invSZ;
  3577. _m1.elements[ 10 ] *= invSZ;
  3578. quaternion.setFromRotationMatrix( _m1 );
  3579. scale.x = sx;
  3580. scale.y = sy;
  3581. scale.z = sz;
  3582. return this;
  3583. }
  3584. makePerspective( left, right, top, bottom, near, far ) {
  3585. if ( far === undefined ) {
  3586. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3587. }
  3588. const te = this.elements;
  3589. const x = 2 * near / ( right - left );
  3590. const y = 2 * near / ( top - bottom );
  3591. const a = ( right + left ) / ( right - left );
  3592. const b = ( top + bottom ) / ( top - bottom );
  3593. const c = - ( far + near ) / ( far - near );
  3594. const d = - 2 * far * near / ( far - near );
  3595. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3596. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3597. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3598. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3599. return this;
  3600. }
  3601. makeOrthographic( left, right, top, bottom, near, far ) {
  3602. const te = this.elements;
  3603. const w = 1.0 / ( right - left );
  3604. const h = 1.0 / ( top - bottom );
  3605. const p = 1.0 / ( far - near );
  3606. const x = ( right + left ) * w;
  3607. const y = ( top + bottom ) * h;
  3608. const z = ( far + near ) * p;
  3609. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3610. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3611. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3612. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3613. return this;
  3614. }
  3615. equals( matrix ) {
  3616. const te = this.elements;
  3617. const me = matrix.elements;
  3618. for ( let i = 0; i < 16; i ++ ) {
  3619. if ( te[ i ] !== me[ i ] ) return false;
  3620. }
  3621. return true;
  3622. }
  3623. fromArray( array, offset ) {
  3624. if ( offset === undefined ) offset = 0;
  3625. for ( let i = 0; i < 16; i ++ ) {
  3626. this.elements[ i ] = array[ i + offset ];
  3627. }
  3628. return this;
  3629. }
  3630. toArray( array, offset ) {
  3631. if ( array === undefined ) array = [];
  3632. if ( offset === undefined ) offset = 0;
  3633. const te = this.elements;
  3634. array[ offset ] = te[ 0 ];
  3635. array[ offset + 1 ] = te[ 1 ];
  3636. array[ offset + 2 ] = te[ 2 ];
  3637. array[ offset + 3 ] = te[ 3 ];
  3638. array[ offset + 4 ] = te[ 4 ];
  3639. array[ offset + 5 ] = te[ 5 ];
  3640. array[ offset + 6 ] = te[ 6 ];
  3641. array[ offset + 7 ] = te[ 7 ];
  3642. array[ offset + 8 ] = te[ 8 ];
  3643. array[ offset + 9 ] = te[ 9 ];
  3644. array[ offset + 10 ] = te[ 10 ];
  3645. array[ offset + 11 ] = te[ 11 ];
  3646. array[ offset + 12 ] = te[ 12 ];
  3647. array[ offset + 13 ] = te[ 13 ];
  3648. array[ offset + 14 ] = te[ 14 ];
  3649. array[ offset + 15 ] = te[ 15 ];
  3650. return array;
  3651. }
  3652. }
  3653. const _v1$1 = /*@__PURE__*/ new Vector3();
  3654. const _m1 = /*@__PURE__*/ new Matrix4();
  3655. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3656. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3657. const _x = /*@__PURE__*/ new Vector3();
  3658. const _y = /*@__PURE__*/ new Vector3();
  3659. const _z = /*@__PURE__*/ new Vector3();
  3660. class Euler {
  3661. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3662. Object.defineProperty( this, 'isEuler', { value: true } );
  3663. this._x = x;
  3664. this._y = y;
  3665. this._z = z;
  3666. this._order = order;
  3667. }
  3668. get x() {
  3669. return this._x;
  3670. }
  3671. set x( value ) {
  3672. this._x = value;
  3673. this._onChangeCallback();
  3674. }
  3675. get y() {
  3676. return this._y;
  3677. }
  3678. set y( value ) {
  3679. this._y = value;
  3680. this._onChangeCallback();
  3681. }
  3682. get z() {
  3683. return this._z;
  3684. }
  3685. set z( value ) {
  3686. this._z = value;
  3687. this._onChangeCallback();
  3688. }
  3689. get order() {
  3690. return this._order;
  3691. }
  3692. set order( value ) {
  3693. this._order = value;
  3694. this._onChangeCallback();
  3695. }
  3696. set( x, y, z, order ) {
  3697. this._x = x;
  3698. this._y = y;
  3699. this._z = z;
  3700. this._order = order || this._order;
  3701. this._onChangeCallback();
  3702. return this;
  3703. }
  3704. clone() {
  3705. return new this.constructor( this._x, this._y, this._z, this._order );
  3706. }
  3707. copy( euler ) {
  3708. this._x = euler._x;
  3709. this._y = euler._y;
  3710. this._z = euler._z;
  3711. this._order = euler._order;
  3712. this._onChangeCallback();
  3713. return this;
  3714. }
  3715. setFromRotationMatrix( m, order, update ) {
  3716. const clamp = MathUtils.clamp;
  3717. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3718. const te = m.elements;
  3719. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3720. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3721. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3722. order = order || this._order;
  3723. switch ( order ) {
  3724. case 'XYZ':
  3725. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3726. if ( Math.abs( m13 ) < 0.9999999 ) {
  3727. this._x = Math.atan2( - m23, m33 );
  3728. this._z = Math.atan2( - m12, m11 );
  3729. } else {
  3730. this._x = Math.atan2( m32, m22 );
  3731. this._z = 0;
  3732. }
  3733. break;
  3734. case 'YXZ':
  3735. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3736. if ( Math.abs( m23 ) < 0.9999999 ) {
  3737. this._y = Math.atan2( m13, m33 );
  3738. this._z = Math.atan2( m21, m22 );
  3739. } else {
  3740. this._y = Math.atan2( - m31, m11 );
  3741. this._z = 0;
  3742. }
  3743. break;
  3744. case 'ZXY':
  3745. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3746. if ( Math.abs( m32 ) < 0.9999999 ) {
  3747. this._y = Math.atan2( - m31, m33 );
  3748. this._z = Math.atan2( - m12, m22 );
  3749. } else {
  3750. this._y = 0;
  3751. this._z = Math.atan2( m21, m11 );
  3752. }
  3753. break;
  3754. case 'ZYX':
  3755. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3756. if ( Math.abs( m31 ) < 0.9999999 ) {
  3757. this._x = Math.atan2( m32, m33 );
  3758. this._z = Math.atan2( m21, m11 );
  3759. } else {
  3760. this._x = 0;
  3761. this._z = Math.atan2( - m12, m22 );
  3762. }
  3763. break;
  3764. case 'YZX':
  3765. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3766. if ( Math.abs( m21 ) < 0.9999999 ) {
  3767. this._x = Math.atan2( - m23, m22 );
  3768. this._y = Math.atan2( - m31, m11 );
  3769. } else {
  3770. this._x = 0;
  3771. this._y = Math.atan2( m13, m33 );
  3772. }
  3773. break;
  3774. case 'XZY':
  3775. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3776. if ( Math.abs( m12 ) < 0.9999999 ) {
  3777. this._x = Math.atan2( m32, m22 );
  3778. this._y = Math.atan2( m13, m11 );
  3779. } else {
  3780. this._x = Math.atan2( - m23, m33 );
  3781. this._y = 0;
  3782. }
  3783. break;
  3784. default:
  3785. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3786. }
  3787. this._order = order;
  3788. if ( update !== false ) this._onChangeCallback();
  3789. return this;
  3790. }
  3791. setFromQuaternion( q, order, update ) {
  3792. _matrix.makeRotationFromQuaternion( q );
  3793. return this.setFromRotationMatrix( _matrix, order, update );
  3794. }
  3795. setFromVector3( v, order ) {
  3796. return this.set( v.x, v.y, v.z, order || this._order );
  3797. }
  3798. reorder( newOrder ) {
  3799. // WARNING: this discards revolution information -bhouston
  3800. _quaternion$1.setFromEuler( this );
  3801. return this.setFromQuaternion( _quaternion$1, newOrder );
  3802. }
  3803. equals( euler ) {
  3804. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3805. }
  3806. fromArray( array ) {
  3807. this._x = array[ 0 ];
  3808. this._y = array[ 1 ];
  3809. this._z = array[ 2 ];
  3810. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3811. this._onChangeCallback();
  3812. return this;
  3813. }
  3814. toArray( array, offset ) {
  3815. if ( array === undefined ) array = [];
  3816. if ( offset === undefined ) offset = 0;
  3817. array[ offset ] = this._x;
  3818. array[ offset + 1 ] = this._y;
  3819. array[ offset + 2 ] = this._z;
  3820. array[ offset + 3 ] = this._order;
  3821. return array;
  3822. }
  3823. toVector3( optionalResult ) {
  3824. if ( optionalResult ) {
  3825. return optionalResult.set( this._x, this._y, this._z );
  3826. } else {
  3827. return new Vector3( this._x, this._y, this._z );
  3828. }
  3829. }
  3830. _onChange( callback ) {
  3831. this._onChangeCallback = callback;
  3832. return this;
  3833. }
  3834. _onChangeCallback() {}
  3835. }
  3836. Euler.DefaultOrder = 'XYZ';
  3837. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  3838. const _matrix = /*@__PURE__*/ new Matrix4();
  3839. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  3840. class Layers {
  3841. constructor() {
  3842. this.mask = 1 | 0;
  3843. }
  3844. set( channel ) {
  3845. this.mask = 1 << channel | 0;
  3846. }
  3847. enable( channel ) {
  3848. this.mask |= 1 << channel | 0;
  3849. }
  3850. enableAll() {
  3851. this.mask = 0xffffffff | 0;
  3852. }
  3853. toggle( channel ) {
  3854. this.mask ^= 1 << channel | 0;
  3855. }
  3856. disable( channel ) {
  3857. this.mask &= ~ ( 1 << channel | 0 );
  3858. }
  3859. disableAll() {
  3860. this.mask = 0;
  3861. }
  3862. test( layers ) {
  3863. return ( this.mask & layers.mask ) !== 0;
  3864. }
  3865. }
  3866. let _object3DId = 0;
  3867. const _v1$2 = new Vector3();
  3868. const _q1 = new Quaternion();
  3869. const _m1$1 = new Matrix4();
  3870. const _target = new Vector3();
  3871. const _position = new Vector3();
  3872. const _scale = new Vector3();
  3873. const _quaternion$2 = new Quaternion();
  3874. const _xAxis = new Vector3( 1, 0, 0 );
  3875. const _yAxis = new Vector3( 0, 1, 0 );
  3876. const _zAxis = new Vector3( 0, 0, 1 );
  3877. const _addedEvent = { type: 'added' };
  3878. const _removedEvent = { type: 'removed' };
  3879. function Object3D() {
  3880. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  3881. this.uuid = MathUtils.generateUUID();
  3882. this.name = '';
  3883. this.type = 'Object3D';
  3884. this.parent = null;
  3885. this.children = [];
  3886. this.up = Object3D.DefaultUp.clone();
  3887. const position = new Vector3();
  3888. const rotation = new Euler();
  3889. const quaternion = new Quaternion();
  3890. const scale = new Vector3( 1, 1, 1 );
  3891. function onRotationChange() {
  3892. quaternion.setFromEuler( rotation, false );
  3893. }
  3894. function onQuaternionChange() {
  3895. rotation.setFromQuaternion( quaternion, undefined, false );
  3896. }
  3897. rotation._onChange( onRotationChange );
  3898. quaternion._onChange( onQuaternionChange );
  3899. Object.defineProperties( this, {
  3900. position: {
  3901. configurable: true,
  3902. enumerable: true,
  3903. value: position
  3904. },
  3905. rotation: {
  3906. configurable: true,
  3907. enumerable: true,
  3908. value: rotation
  3909. },
  3910. quaternion: {
  3911. configurable: true,
  3912. enumerable: true,
  3913. value: quaternion
  3914. },
  3915. scale: {
  3916. configurable: true,
  3917. enumerable: true,
  3918. value: scale
  3919. },
  3920. modelViewMatrix: {
  3921. value: new Matrix4()
  3922. },
  3923. normalMatrix: {
  3924. value: new Matrix3()
  3925. }
  3926. } );
  3927. this.matrix = new Matrix4();
  3928. this.matrixWorld = new Matrix4();
  3929. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  3930. this.matrixWorldNeedsUpdate = false;
  3931. this.layers = new Layers();
  3932. this.visible = true;
  3933. this.castShadow = false;
  3934. this.receiveShadow = false;
  3935. this.frustumCulled = true;
  3936. this.renderOrder = 0;
  3937. this.userData = {};
  3938. }
  3939. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  3940. Object3D.DefaultMatrixAutoUpdate = true;
  3941. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  3942. constructor: Object3D,
  3943. isObject3D: true,
  3944. onBeforeRender: function () {},
  3945. onAfterRender: function () {},
  3946. applyMatrix4: function ( matrix ) {
  3947. if ( this.matrixAutoUpdate ) this.updateMatrix();
  3948. this.matrix.premultiply( matrix );
  3949. this.matrix.decompose( this.position, this.quaternion, this.scale );
  3950. },
  3951. applyQuaternion: function ( q ) {
  3952. this.quaternion.premultiply( q );
  3953. return this;
  3954. },
  3955. setRotationFromAxisAngle: function ( axis, angle ) {
  3956. // assumes axis is normalized
  3957. this.quaternion.setFromAxisAngle( axis, angle );
  3958. },
  3959. setRotationFromEuler: function ( euler ) {
  3960. this.quaternion.setFromEuler( euler, true );
  3961. },
  3962. setRotationFromMatrix: function ( m ) {
  3963. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3964. this.quaternion.setFromRotationMatrix( m );
  3965. },
  3966. setRotationFromQuaternion: function ( q ) {
  3967. // assumes q is normalized
  3968. this.quaternion.copy( q );
  3969. },
  3970. rotateOnAxis: function ( axis, angle ) {
  3971. // rotate object on axis in object space
  3972. // axis is assumed to be normalized
  3973. _q1.setFromAxisAngle( axis, angle );
  3974. this.quaternion.multiply( _q1 );
  3975. return this;
  3976. },
  3977. rotateOnWorldAxis: function ( axis, angle ) {
  3978. // rotate object on axis in world space
  3979. // axis is assumed to be normalized
  3980. // method assumes no rotated parent
  3981. _q1.setFromAxisAngle( axis, angle );
  3982. this.quaternion.premultiply( _q1 );
  3983. return this;
  3984. },
  3985. rotateX: function ( angle ) {
  3986. return this.rotateOnAxis( _xAxis, angle );
  3987. },
  3988. rotateY: function ( angle ) {
  3989. return this.rotateOnAxis( _yAxis, angle );
  3990. },
  3991. rotateZ: function ( angle ) {
  3992. return this.rotateOnAxis( _zAxis, angle );
  3993. },
  3994. translateOnAxis: function ( axis, distance ) {
  3995. // translate object by distance along axis in object space
  3996. // axis is assumed to be normalized
  3997. _v1$2.copy( axis ).applyQuaternion( this.quaternion );
  3998. this.position.add( _v1$2.multiplyScalar( distance ) );
  3999. return this;
  4000. },
  4001. translateX: function ( distance ) {
  4002. return this.translateOnAxis( _xAxis, distance );
  4003. },
  4004. translateY: function ( distance ) {
  4005. return this.translateOnAxis( _yAxis, distance );
  4006. },
  4007. translateZ: function ( distance ) {
  4008. return this.translateOnAxis( _zAxis, distance );
  4009. },
  4010. localToWorld: function ( vector ) {
  4011. return vector.applyMatrix4( this.matrixWorld );
  4012. },
  4013. worldToLocal: function ( vector ) {
  4014. return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );
  4015. },
  4016. lookAt: function ( x, y, z ) {
  4017. // This method does not support objects having non-uniformly-scaled parent(s)
  4018. if ( x.isVector3 ) {
  4019. _target.copy( x );
  4020. } else {
  4021. _target.set( x, y, z );
  4022. }
  4023. const parent = this.parent;
  4024. this.updateWorldMatrix( true, false );
  4025. _position.setFromMatrixPosition( this.matrixWorld );
  4026. if ( this.isCamera || this.isLight ) {
  4027. _m1$1.lookAt( _position, _target, this.up );
  4028. } else {
  4029. _m1$1.lookAt( _target, _position, this.up );
  4030. }
  4031. this.quaternion.setFromRotationMatrix( _m1$1 );
  4032. if ( parent ) {
  4033. _m1$1.extractRotation( parent.matrixWorld );
  4034. _q1.setFromRotationMatrix( _m1$1 );
  4035. this.quaternion.premultiply( _q1.inverse() );
  4036. }
  4037. },
  4038. add: function ( object ) {
  4039. if ( arguments.length > 1 ) {
  4040. for ( let i = 0; i < arguments.length; i ++ ) {
  4041. this.add( arguments[ i ] );
  4042. }
  4043. return this;
  4044. }
  4045. if ( object === this ) {
  4046. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4047. return this;
  4048. }
  4049. if ( ( object && object.isObject3D ) ) {
  4050. if ( object.parent !== null ) {
  4051. object.parent.remove( object );
  4052. }
  4053. object.parent = this;
  4054. this.children.push( object );
  4055. object.dispatchEvent( _addedEvent );
  4056. } else {
  4057. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4058. }
  4059. return this;
  4060. },
  4061. remove: function ( object ) {
  4062. if ( arguments.length > 1 ) {
  4063. for ( let i = 0; i < arguments.length; i ++ ) {
  4064. this.remove( arguments[ i ] );
  4065. }
  4066. return this;
  4067. }
  4068. const index = this.children.indexOf( object );
  4069. if ( index !== - 1 ) {
  4070. object.parent = null;
  4071. this.children.splice( index, 1 );
  4072. object.dispatchEvent( _removedEvent );
  4073. }
  4074. return this;
  4075. },
  4076. attach: function ( object ) {
  4077. // adds object as a child of this, while maintaining the object's world transform
  4078. this.updateWorldMatrix( true, false );
  4079. _m1$1.getInverse( this.matrixWorld );
  4080. if ( object.parent !== null ) {
  4081. object.parent.updateWorldMatrix( true, false );
  4082. _m1$1.multiply( object.parent.matrixWorld );
  4083. }
  4084. object.applyMatrix4( _m1$1 );
  4085. object.updateWorldMatrix( false, false );
  4086. this.add( object );
  4087. return this;
  4088. },
  4089. getObjectById: function ( id ) {
  4090. return this.getObjectByProperty( 'id', id );
  4091. },
  4092. getObjectByName: function ( name ) {
  4093. return this.getObjectByProperty( 'name', name );
  4094. },
  4095. getObjectByProperty: function ( name, value ) {
  4096. if ( this[ name ] === value ) return this;
  4097. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4098. const child = this.children[ i ];
  4099. const object = child.getObjectByProperty( name, value );
  4100. if ( object !== undefined ) {
  4101. return object;
  4102. }
  4103. }
  4104. return undefined;
  4105. },
  4106. getWorldPosition: function ( target ) {
  4107. if ( target === undefined ) {
  4108. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4109. target = new Vector3();
  4110. }
  4111. this.updateWorldMatrix( true, false );
  4112. return target.setFromMatrixPosition( this.matrixWorld );
  4113. },
  4114. getWorldQuaternion: function ( target ) {
  4115. if ( target === undefined ) {
  4116. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4117. target = new Quaternion();
  4118. }
  4119. this.updateWorldMatrix( true, false );
  4120. this.matrixWorld.decompose( _position, target, _scale );
  4121. return target;
  4122. },
  4123. getWorldScale: function ( target ) {
  4124. if ( target === undefined ) {
  4125. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4126. target = new Vector3();
  4127. }
  4128. this.updateWorldMatrix( true, false );
  4129. this.matrixWorld.decompose( _position, _quaternion$2, target );
  4130. return target;
  4131. },
  4132. getWorldDirection: function ( target ) {
  4133. if ( target === undefined ) {
  4134. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4135. target = new Vector3();
  4136. }
  4137. this.updateWorldMatrix( true, false );
  4138. const e = this.matrixWorld.elements;
  4139. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4140. },
  4141. raycast: function () {},
  4142. traverse: function ( callback ) {
  4143. callback( this );
  4144. const children = this.children;
  4145. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4146. children[ i ].traverse( callback );
  4147. }
  4148. },
  4149. traverseVisible: function ( callback ) {
  4150. if ( this.visible === false ) return;
  4151. callback( this );
  4152. const children = this.children;
  4153. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4154. children[ i ].traverseVisible( callback );
  4155. }
  4156. },
  4157. traverseAncestors: function ( callback ) {
  4158. const parent = this.parent;
  4159. if ( parent !== null ) {
  4160. callback( parent );
  4161. parent.traverseAncestors( callback );
  4162. }
  4163. },
  4164. updateMatrix: function () {
  4165. this.matrix.compose( this.position, this.quaternion, this.scale );
  4166. this.matrixWorldNeedsUpdate = true;
  4167. },
  4168. updateMatrixWorld: function ( force ) {
  4169. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4170. if ( this.matrixWorldNeedsUpdate || force ) {
  4171. if ( this.parent === null ) {
  4172. this.matrixWorld.copy( this.matrix );
  4173. } else {
  4174. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4175. }
  4176. this.matrixWorldNeedsUpdate = false;
  4177. force = true;
  4178. }
  4179. // update children
  4180. const children = this.children;
  4181. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4182. children[ i ].updateMatrixWorld( force );
  4183. }
  4184. },
  4185. updateWorldMatrix: function ( updateParents, updateChildren ) {
  4186. const parent = this.parent;
  4187. if ( updateParents === true && parent !== null ) {
  4188. parent.updateWorldMatrix( true, false );
  4189. }
  4190. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4191. if ( this.parent === null ) {
  4192. this.matrixWorld.copy( this.matrix );
  4193. } else {
  4194. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4195. }
  4196. // update children
  4197. if ( updateChildren === true ) {
  4198. const children = this.children;
  4199. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4200. children[ i ].updateWorldMatrix( false, true );
  4201. }
  4202. }
  4203. },
  4204. toJSON: function ( meta ) {
  4205. // meta is a string when called from JSON.stringify
  4206. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4207. const output = {};
  4208. // meta is a hash used to collect geometries, materials.
  4209. // not providing it implies that this is the root object
  4210. // being serialized.
  4211. if ( isRootObject ) {
  4212. // initialize meta obj
  4213. meta = {
  4214. geometries: {},
  4215. materials: {},
  4216. textures: {},
  4217. images: {},
  4218. shapes: {}
  4219. };
  4220. output.metadata = {
  4221. version: 4.5,
  4222. type: 'Object',
  4223. generator: 'Object3D.toJSON'
  4224. };
  4225. }
  4226. // standard Object3D serialization
  4227. const object = {};
  4228. object.uuid = this.uuid;
  4229. object.type = this.type;
  4230. if ( this.name !== '' ) object.name = this.name;
  4231. if ( this.castShadow === true ) object.castShadow = true;
  4232. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4233. if ( this.visible === false ) object.visible = false;
  4234. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4235. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4236. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4237. object.layers = this.layers.mask;
  4238. object.matrix = this.matrix.toArray();
  4239. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4240. // object specific properties
  4241. if ( this.isInstancedMesh ) {
  4242. object.type = 'InstancedMesh';
  4243. object.count = this.count;
  4244. object.instanceMatrix = this.instanceMatrix.toJSON();
  4245. }
  4246. //
  4247. function serialize( library, element ) {
  4248. if ( library[ element.uuid ] === undefined ) {
  4249. library[ element.uuid ] = element.toJSON( meta );
  4250. }
  4251. return element.uuid;
  4252. }
  4253. if ( this.isMesh || this.isLine || this.isPoints ) {
  4254. object.geometry = serialize( meta.geometries, this.geometry );
  4255. const parameters = this.geometry.parameters;
  4256. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4257. const shapes = parameters.shapes;
  4258. if ( Array.isArray( shapes ) ) {
  4259. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4260. const shape = shapes[ i ];
  4261. serialize( meta.shapes, shape );
  4262. }
  4263. } else {
  4264. serialize( meta.shapes, shapes );
  4265. }
  4266. }
  4267. }
  4268. if ( this.material !== undefined ) {
  4269. if ( Array.isArray( this.material ) ) {
  4270. const uuids = [];
  4271. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4272. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4273. }
  4274. object.material = uuids;
  4275. } else {
  4276. object.material = serialize( meta.materials, this.material );
  4277. }
  4278. }
  4279. //
  4280. if ( this.children.length > 0 ) {
  4281. object.children = [];
  4282. for ( let i = 0; i < this.children.length; i ++ ) {
  4283. object.children.push( this.children[ i ].toJSON( meta ).object );
  4284. }
  4285. }
  4286. if ( isRootObject ) {
  4287. const geometries = extractFromCache( meta.geometries );
  4288. const materials = extractFromCache( meta.materials );
  4289. const textures = extractFromCache( meta.textures );
  4290. const images = extractFromCache( meta.images );
  4291. const shapes = extractFromCache( meta.shapes );
  4292. if ( geometries.length > 0 ) output.geometries = geometries;
  4293. if ( materials.length > 0 ) output.materials = materials;
  4294. if ( textures.length > 0 ) output.textures = textures;
  4295. if ( images.length > 0 ) output.images = images;
  4296. if ( shapes.length > 0 ) output.shapes = shapes;
  4297. }
  4298. output.object = object;
  4299. return output;
  4300. // extract data from the cache hash
  4301. // remove metadata on each item
  4302. // and return as array
  4303. function extractFromCache( cache ) {
  4304. const values = [];
  4305. for ( const key in cache ) {
  4306. const data = cache[ key ];
  4307. delete data.metadata;
  4308. values.push( data );
  4309. }
  4310. return values;
  4311. }
  4312. },
  4313. clone: function ( recursive ) {
  4314. return new this.constructor().copy( this, recursive );
  4315. },
  4316. copy: function ( source, recursive ) {
  4317. if ( recursive === undefined ) recursive = true;
  4318. this.name = source.name;
  4319. this.up.copy( source.up );
  4320. this.position.copy( source.position );
  4321. this.rotation.order = source.rotation.order;
  4322. this.quaternion.copy( source.quaternion );
  4323. this.scale.copy( source.scale );
  4324. this.matrix.copy( source.matrix );
  4325. this.matrixWorld.copy( source.matrixWorld );
  4326. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4327. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4328. this.layers.mask = source.layers.mask;
  4329. this.visible = source.visible;
  4330. this.castShadow = source.castShadow;
  4331. this.receiveShadow = source.receiveShadow;
  4332. this.frustumCulled = source.frustumCulled;
  4333. this.renderOrder = source.renderOrder;
  4334. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4335. if ( recursive === true ) {
  4336. for ( let i = 0; i < source.children.length; i ++ ) {
  4337. const child = source.children[ i ];
  4338. this.add( child.clone() );
  4339. }
  4340. }
  4341. return this;
  4342. }
  4343. } );
  4344. const _vector1 = /*@__PURE__*/ new Vector3();
  4345. const _vector2 = /*@__PURE__*/ new Vector3();
  4346. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  4347. class Plane {
  4348. constructor( normal, constant ) {
  4349. Object.defineProperty( this, 'isPlane', { value: true } );
  4350. // normal is assumed to be normalized
  4351. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  4352. this.constant = ( constant !== undefined ) ? constant : 0;
  4353. }
  4354. set( normal, constant ) {
  4355. this.normal.copy( normal );
  4356. this.constant = constant;
  4357. return this;
  4358. }
  4359. setComponents( x, y, z, w ) {
  4360. this.normal.set( x, y, z );
  4361. this.constant = w;
  4362. return this;
  4363. }
  4364. setFromNormalAndCoplanarPoint( normal, point ) {
  4365. this.normal.copy( normal );
  4366. this.constant = - point.dot( this.normal );
  4367. return this;
  4368. }
  4369. setFromCoplanarPoints( a, b, c ) {
  4370. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  4371. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4372. this.setFromNormalAndCoplanarPoint( normal, a );
  4373. return this;
  4374. }
  4375. clone() {
  4376. return new this.constructor().copy( this );
  4377. }
  4378. copy( plane ) {
  4379. this.normal.copy( plane.normal );
  4380. this.constant = plane.constant;
  4381. return this;
  4382. }
  4383. normalize() {
  4384. // Note: will lead to a divide by zero if the plane is invalid.
  4385. const inverseNormalLength = 1.0 / this.normal.length();
  4386. this.normal.multiplyScalar( inverseNormalLength );
  4387. this.constant *= inverseNormalLength;
  4388. return this;
  4389. }
  4390. negate() {
  4391. this.constant *= - 1;
  4392. this.normal.negate();
  4393. return this;
  4394. }
  4395. distanceToPoint( point ) {
  4396. return this.normal.dot( point ) + this.constant;
  4397. }
  4398. distanceToSphere( sphere ) {
  4399. return this.distanceToPoint( sphere.center ) - sphere.radius;
  4400. }
  4401. projectPoint( point, target ) {
  4402. if ( target === undefined ) {
  4403. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  4404. target = new Vector3();
  4405. }
  4406. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  4407. }
  4408. intersectLine( line, target ) {
  4409. if ( target === undefined ) {
  4410. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  4411. target = new Vector3();
  4412. }
  4413. const direction = line.delta( _vector1 );
  4414. const denominator = this.normal.dot( direction );
  4415. if ( denominator === 0 ) {
  4416. // line is coplanar, return origin
  4417. if ( this.distanceToPoint( line.start ) === 0 ) {
  4418. return target.copy( line.start );
  4419. }
  4420. // Unsure if this is the correct method to handle this case.
  4421. return undefined;
  4422. }
  4423. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  4424. if ( t < 0 || t > 1 ) {
  4425. return undefined;
  4426. }
  4427. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  4428. }
  4429. intersectsLine( line ) {
  4430. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4431. const startSign = this.distanceToPoint( line.start );
  4432. const endSign = this.distanceToPoint( line.end );
  4433. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  4434. }
  4435. intersectsBox( box ) {
  4436. return box.intersectsPlane( this );
  4437. }
  4438. intersectsSphere( sphere ) {
  4439. return sphere.intersectsPlane( this );
  4440. }
  4441. coplanarPoint( target ) {
  4442. if ( target === undefined ) {
  4443. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  4444. target = new Vector3();
  4445. }
  4446. return target.copy( this.normal ).multiplyScalar( - this.constant );
  4447. }
  4448. applyMatrix4( matrix, optionalNormalMatrix ) {
  4449. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  4450. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  4451. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  4452. this.constant = - referencePoint.dot( normal );
  4453. return this;
  4454. }
  4455. translate( offset ) {
  4456. this.constant -= offset.dot( this.normal );
  4457. return this;
  4458. }
  4459. equals( plane ) {
  4460. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4461. }
  4462. }
  4463. const _v0$1 = /*@__PURE__*/ new Vector3();
  4464. const _v1$3 = /*@__PURE__*/ new Vector3();
  4465. const _v2$1 = /*@__PURE__*/ new Vector3();
  4466. const _v3 = /*@__PURE__*/ new Vector3();
  4467. const _vab = /*@__PURE__*/ new Vector3();
  4468. const _vac = /*@__PURE__*/ new Vector3();
  4469. const _vbc = /*@__PURE__*/ new Vector3();
  4470. const _vap = /*@__PURE__*/ new Vector3();
  4471. const _vbp = /*@__PURE__*/ new Vector3();
  4472. const _vcp = /*@__PURE__*/ new Vector3();
  4473. class Triangle {
  4474. constructor( a, b, c ) {
  4475. this.a = ( a !== undefined ) ? a : new Vector3();
  4476. this.b = ( b !== undefined ) ? b : new Vector3();
  4477. this.c = ( c !== undefined ) ? c : new Vector3();
  4478. }
  4479. static getNormal( a, b, c, target ) {
  4480. if ( target === undefined ) {
  4481. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  4482. target = new Vector3();
  4483. }
  4484. target.subVectors( c, b );
  4485. _v0$1.subVectors( a, b );
  4486. target.cross( _v0$1 );
  4487. const targetLengthSq = target.lengthSq();
  4488. if ( targetLengthSq > 0 ) {
  4489. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4490. }
  4491. return target.set( 0, 0, 0 );
  4492. }
  4493. // static/instance method to calculate barycentric coordinates
  4494. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4495. static getBarycoord( point, a, b, c, target ) {
  4496. _v0$1.subVectors( c, a );
  4497. _v1$3.subVectors( b, a );
  4498. _v2$1.subVectors( point, a );
  4499. const dot00 = _v0$1.dot( _v0$1 );
  4500. const dot01 = _v0$1.dot( _v1$3 );
  4501. const dot02 = _v0$1.dot( _v2$1 );
  4502. const dot11 = _v1$3.dot( _v1$3 );
  4503. const dot12 = _v1$3.dot( _v2$1 );
  4504. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4505. if ( target === undefined ) {
  4506. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  4507. target = new Vector3();
  4508. }
  4509. // collinear or singular triangle
  4510. if ( denom === 0 ) {
  4511. // arbitrary location outside of triangle?
  4512. // not sure if this is the best idea, maybe should be returning undefined
  4513. return target.set( - 2, - 1, - 1 );
  4514. }
  4515. const invDenom = 1 / denom;
  4516. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4517. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4518. // barycentric coordinates must always sum to 1
  4519. return target.set( 1 - u - v, v, u );
  4520. }
  4521. static containsPoint( point, a, b, c ) {
  4522. this.getBarycoord( point, a, b, c, _v3 );
  4523. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  4524. }
  4525. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4526. this.getBarycoord( point, p1, p2, p3, _v3 );
  4527. target.set( 0, 0 );
  4528. target.addScaledVector( uv1, _v3.x );
  4529. target.addScaledVector( uv2, _v3.y );
  4530. target.addScaledVector( uv3, _v3.z );
  4531. return target;
  4532. }
  4533. static isFrontFacing( a, b, c, direction ) {
  4534. _v0$1.subVectors( c, b );
  4535. _v1$3.subVectors( a, b );
  4536. // strictly front facing
  4537. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4538. }
  4539. set( a, b, c ) {
  4540. this.a.copy( a );
  4541. this.b.copy( b );
  4542. this.c.copy( c );
  4543. return this;
  4544. }
  4545. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4546. this.a.copy( points[ i0 ] );
  4547. this.b.copy( points[ i1 ] );
  4548. this.c.copy( points[ i2 ] );
  4549. return this;
  4550. }
  4551. clone() {
  4552. return new this.constructor().copy( this );
  4553. }
  4554. copy( triangle ) {
  4555. this.a.copy( triangle.a );
  4556. this.b.copy( triangle.b );
  4557. this.c.copy( triangle.c );
  4558. return this;
  4559. }
  4560. getArea() {
  4561. _v0$1.subVectors( this.c, this.b );
  4562. _v1$3.subVectors( this.a, this.b );
  4563. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4564. }
  4565. getMidpoint( target ) {
  4566. if ( target === undefined ) {
  4567. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  4568. target = new Vector3();
  4569. }
  4570. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4571. }
  4572. getNormal( target ) {
  4573. return Triangle.getNormal( this.a, this.b, this.c, target );
  4574. }
  4575. getPlane( target ) {
  4576. if ( target === undefined ) {
  4577. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  4578. target = new Plane();
  4579. }
  4580. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4581. }
  4582. getBarycoord( point, target ) {
  4583. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4584. }
  4585. getUV( point, uv1, uv2, uv3, target ) {
  4586. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4587. }
  4588. containsPoint( point ) {
  4589. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4590. }
  4591. isFrontFacing( direction ) {
  4592. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4593. }
  4594. intersectsBox( box ) {
  4595. return box.intersectsTriangle( this );
  4596. }
  4597. closestPointToPoint( p, target ) {
  4598. if ( target === undefined ) {
  4599. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  4600. target = new Vector3();
  4601. }
  4602. const a = this.a, b = this.b, c = this.c;
  4603. let v, w;
  4604. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4605. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4606. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4607. // basically, we're distinguishing which of the voronoi regions of the triangle
  4608. // the point lies in with the minimum amount of redundant computation.
  4609. _vab.subVectors( b, a );
  4610. _vac.subVectors( c, a );
  4611. _vap.subVectors( p, a );
  4612. const d1 = _vab.dot( _vap );
  4613. const d2 = _vac.dot( _vap );
  4614. if ( d1 <= 0 && d2 <= 0 ) {
  4615. // vertex region of A; barycentric coords (1, 0, 0)
  4616. return target.copy( a );
  4617. }
  4618. _vbp.subVectors( p, b );
  4619. const d3 = _vab.dot( _vbp );
  4620. const d4 = _vac.dot( _vbp );
  4621. if ( d3 >= 0 && d4 <= d3 ) {
  4622. // vertex region of B; barycentric coords (0, 1, 0)
  4623. return target.copy( b );
  4624. }
  4625. const vc = d1 * d4 - d3 * d2;
  4626. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4627. v = d1 / ( d1 - d3 );
  4628. // edge region of AB; barycentric coords (1-v, v, 0)
  4629. return target.copy( a ).addScaledVector( _vab, v );
  4630. }
  4631. _vcp.subVectors( p, c );
  4632. const d5 = _vab.dot( _vcp );
  4633. const d6 = _vac.dot( _vcp );
  4634. if ( d6 >= 0 && d5 <= d6 ) {
  4635. // vertex region of C; barycentric coords (0, 0, 1)
  4636. return target.copy( c );
  4637. }
  4638. const vb = d5 * d2 - d1 * d6;
  4639. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4640. w = d2 / ( d2 - d6 );
  4641. // edge region of AC; barycentric coords (1-w, 0, w)
  4642. return target.copy( a ).addScaledVector( _vac, w );
  4643. }
  4644. const va = d3 * d6 - d5 * d4;
  4645. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4646. _vbc.subVectors( c, b );
  4647. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4648. // edge region of BC; barycentric coords (0, 1-w, w)
  4649. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4650. }
  4651. // face region
  4652. const denom = 1 / ( va + vb + vc );
  4653. // u = va * denom
  4654. v = vb * denom;
  4655. w = vc * denom;
  4656. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4657. }
  4658. equals( triangle ) {
  4659. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4660. }
  4661. }
  4662. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  4663. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  4664. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  4665. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  4666. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  4667. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  4668. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  4669. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  4670. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  4671. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  4672. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  4673. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  4674. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  4675. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  4676. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  4677. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  4678. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  4679. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  4680. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  4681. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  4682. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  4683. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  4684. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  4685. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  4686. const _hslA = { h: 0, s: 0, l: 0 };
  4687. const _hslB = { h: 0, s: 0, l: 0 };
  4688. function hue2rgb( p, q, t ) {
  4689. if ( t < 0 ) t += 1;
  4690. if ( t > 1 ) t -= 1;
  4691. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  4692. if ( t < 1 / 2 ) return q;
  4693. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  4694. return p;
  4695. }
  4696. function SRGBToLinear( c ) {
  4697. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  4698. }
  4699. function LinearToSRGB( c ) {
  4700. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  4701. }
  4702. class Color {
  4703. constructor( r, g, b ) {
  4704. Object.defineProperty( this, 'isColor', { value: true } );
  4705. if ( g === undefined && b === undefined ) {
  4706. // r is THREE.Color, hex or string
  4707. return this.set( r );
  4708. }
  4709. return this.setRGB( r, g, b );
  4710. }
  4711. set( value ) {
  4712. if ( value && value.isColor ) {
  4713. this.copy( value );
  4714. } else if ( typeof value === 'number' ) {
  4715. this.setHex( value );
  4716. } else if ( typeof value === 'string' ) {
  4717. this.setStyle( value );
  4718. }
  4719. return this;
  4720. }
  4721. setScalar( scalar ) {
  4722. this.r = scalar;
  4723. this.g = scalar;
  4724. this.b = scalar;
  4725. return this;
  4726. }
  4727. setHex( hex ) {
  4728. hex = Math.floor( hex );
  4729. this.r = ( hex >> 16 & 255 ) / 255;
  4730. this.g = ( hex >> 8 & 255 ) / 255;
  4731. this.b = ( hex & 255 ) / 255;
  4732. return this;
  4733. }
  4734. setRGB( r, g, b ) {
  4735. this.r = r;
  4736. this.g = g;
  4737. this.b = b;
  4738. return this;
  4739. }
  4740. setHSL( h, s, l ) {
  4741. // h,s,l ranges are in 0.0 - 1.0
  4742. h = MathUtils.euclideanModulo( h, 1 );
  4743. s = MathUtils.clamp( s, 0, 1 );
  4744. l = MathUtils.clamp( l, 0, 1 );
  4745. if ( s === 0 ) {
  4746. this.r = this.g = this.b = l;
  4747. } else {
  4748. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  4749. const q = ( 2 * l ) - p;
  4750. this.r = hue2rgb( q, p, h + 1 / 3 );
  4751. this.g = hue2rgb( q, p, h );
  4752. this.b = hue2rgb( q, p, h - 1 / 3 );
  4753. }
  4754. return this;
  4755. }
  4756. setStyle( style ) {
  4757. function handleAlpha( string ) {
  4758. if ( string === undefined ) return;
  4759. if ( parseFloat( string ) < 1 ) {
  4760. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  4761. }
  4762. }
  4763. let m;
  4764. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  4765. // rgb / hsl
  4766. let color;
  4767. const name = m[ 1 ];
  4768. const components = m[ 2 ];
  4769. switch ( name ) {
  4770. case 'rgb':
  4771. case 'rgba':
  4772. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  4773. // rgb(255,0,0) rgba(255,0,0,0.5)
  4774. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  4775. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  4776. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  4777. handleAlpha( color[ 5 ] );
  4778. return this;
  4779. }
  4780. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  4781. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  4782. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  4783. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  4784. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  4785. handleAlpha( color[ 5 ] );
  4786. return this;
  4787. }
  4788. break;
  4789. case 'hsl':
  4790. case 'hsla':
  4791. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  4792. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  4793. const h = parseFloat( color[ 1 ] ) / 360;
  4794. const s = parseInt( color[ 2 ], 10 ) / 100;
  4795. const l = parseInt( color[ 3 ], 10 ) / 100;
  4796. handleAlpha( color[ 5 ] );
  4797. return this.setHSL( h, s, l );
  4798. }
  4799. break;
  4800. }
  4801. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  4802. // hex color
  4803. const hex = m[ 1 ];
  4804. const size = hex.length;
  4805. if ( size === 3 ) {
  4806. // #ff0
  4807. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  4808. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  4809. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  4810. return this;
  4811. } else if ( size === 6 ) {
  4812. // #ff0000
  4813. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  4814. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  4815. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  4816. return this;
  4817. }
  4818. }
  4819. if ( style && style.length > 0 ) {
  4820. return this.setColorName( style );
  4821. }
  4822. return this;
  4823. }
  4824. setColorName( style ) {
  4825. // color keywords
  4826. const hex = _colorKeywords[ style ];
  4827. if ( hex !== undefined ) {
  4828. // red
  4829. this.setHex( hex );
  4830. } else {
  4831. // unknown color
  4832. console.warn( 'THREE.Color: Unknown color ' + style );
  4833. }
  4834. return this;
  4835. }
  4836. clone() {
  4837. return new this.constructor( this.r, this.g, this.b );
  4838. }
  4839. copy( color ) {
  4840. this.r = color.r;
  4841. this.g = color.g;
  4842. this.b = color.b;
  4843. return this;
  4844. }
  4845. copyGammaToLinear( color, gammaFactor ) {
  4846. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  4847. this.r = Math.pow( color.r, gammaFactor );
  4848. this.g = Math.pow( color.g, gammaFactor );
  4849. this.b = Math.pow( color.b, gammaFactor );
  4850. return this;
  4851. }
  4852. copyLinearToGamma( color, gammaFactor ) {
  4853. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  4854. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  4855. this.r = Math.pow( color.r, safeInverse );
  4856. this.g = Math.pow( color.g, safeInverse );
  4857. this.b = Math.pow( color.b, safeInverse );
  4858. return this;
  4859. }
  4860. convertGammaToLinear( gammaFactor ) {
  4861. this.copyGammaToLinear( this, gammaFactor );
  4862. return this;
  4863. }
  4864. convertLinearToGamma( gammaFactor ) {
  4865. this.copyLinearToGamma( this, gammaFactor );
  4866. return this;
  4867. }
  4868. copySRGBToLinear( color ) {
  4869. this.r = SRGBToLinear( color.r );
  4870. this.g = SRGBToLinear( color.g );
  4871. this.b = SRGBToLinear( color.b );
  4872. return this;
  4873. }
  4874. copyLinearToSRGB( color ) {
  4875. this.r = LinearToSRGB( color.r );
  4876. this.g = LinearToSRGB( color.g );
  4877. this.b = LinearToSRGB( color.b );
  4878. return this;
  4879. }
  4880. convertSRGBToLinear() {
  4881. this.copySRGBToLinear( this );
  4882. return this;
  4883. }
  4884. convertLinearToSRGB() {
  4885. this.copyLinearToSRGB( this );
  4886. return this;
  4887. }
  4888. getHex() {
  4889. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  4890. }
  4891. getHexString() {
  4892. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  4893. }
  4894. getHSL( target ) {
  4895. // h,s,l ranges are in 0.0 - 1.0
  4896. if ( target === undefined ) {
  4897. console.warn( 'THREE.Color: .getHSL() target is now required' );
  4898. target = { h: 0, s: 0, l: 0 };
  4899. }
  4900. const r = this.r, g = this.g, b = this.b;
  4901. const max = Math.max( r, g, b );
  4902. const min = Math.min( r, g, b );
  4903. let hue, saturation;
  4904. const lightness = ( min + max ) / 2.0;
  4905. if ( min === max ) {
  4906. hue = 0;
  4907. saturation = 0;
  4908. } else {
  4909. const delta = max - min;
  4910. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  4911. switch ( max ) {
  4912. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  4913. case g: hue = ( b - r ) / delta + 2; break;
  4914. case b: hue = ( r - g ) / delta + 4; break;
  4915. }
  4916. hue /= 6;
  4917. }
  4918. target.h = hue;
  4919. target.s = saturation;
  4920. target.l = lightness;
  4921. return target;
  4922. }
  4923. getStyle() {
  4924. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  4925. }
  4926. offsetHSL( h, s, l ) {
  4927. this.getHSL( _hslA );
  4928. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  4929. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  4930. return this;
  4931. }
  4932. add( color ) {
  4933. this.r += color.r;
  4934. this.g += color.g;
  4935. this.b += color.b;
  4936. return this;
  4937. }
  4938. addColors( color1, color2 ) {
  4939. this.r = color1.r + color2.r;
  4940. this.g = color1.g + color2.g;
  4941. this.b = color1.b + color2.b;
  4942. return this;
  4943. }
  4944. addScalar( s ) {
  4945. this.r += s;
  4946. this.g += s;
  4947. this.b += s;
  4948. return this;
  4949. }
  4950. sub( color ) {
  4951. this.r = Math.max( 0, this.r - color.r );
  4952. this.g = Math.max( 0, this.g - color.g );
  4953. this.b = Math.max( 0, this.b - color.b );
  4954. return this;
  4955. }
  4956. multiply( color ) {
  4957. this.r *= color.r;
  4958. this.g *= color.g;
  4959. this.b *= color.b;
  4960. return this;
  4961. }
  4962. multiplyScalar( s ) {
  4963. this.r *= s;
  4964. this.g *= s;
  4965. this.b *= s;
  4966. return this;
  4967. }
  4968. lerp( color, alpha ) {
  4969. this.r += ( color.r - this.r ) * alpha;
  4970. this.g += ( color.g - this.g ) * alpha;
  4971. this.b += ( color.b - this.b ) * alpha;
  4972. return this;
  4973. }
  4974. lerpHSL( color, alpha ) {
  4975. this.getHSL( _hslA );
  4976. color.getHSL( _hslB );
  4977. const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  4978. const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  4979. const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  4980. this.setHSL( h, s, l );
  4981. return this;
  4982. }
  4983. equals( c ) {
  4984. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  4985. }
  4986. fromArray( array, offset ) {
  4987. if ( offset === undefined ) offset = 0;
  4988. this.r = array[ offset ];
  4989. this.g = array[ offset + 1 ];
  4990. this.b = array[ offset + 2 ];
  4991. return this;
  4992. }
  4993. toArray( array, offset ) {
  4994. if ( array === undefined ) array = [];
  4995. if ( offset === undefined ) offset = 0;
  4996. array[ offset ] = this.r;
  4997. array[ offset + 1 ] = this.g;
  4998. array[ offset + 2 ] = this.b;
  4999. return array;
  5000. }
  5001. fromBufferAttribute( attribute, index ) {
  5002. this.r = attribute.getX( index );
  5003. this.g = attribute.getY( index );
  5004. this.b = attribute.getZ( index );
  5005. if ( attribute.normalized === true ) {
  5006. // assuming Uint8Array
  5007. this.r /= 255;
  5008. this.g /= 255;
  5009. this.b /= 255;
  5010. }
  5011. return this;
  5012. }
  5013. toJSON() {
  5014. return this.getHex();
  5015. }
  5016. }
  5017. Color.NAMES = _colorKeywords;
  5018. Color.prototype.r = 1;
  5019. Color.prototype.g = 1;
  5020. Color.prototype.b = 1;
  5021. class Face3 {
  5022. constructor( a, b, c, normal, color, materialIndex ) {
  5023. this.a = a;
  5024. this.b = b;
  5025. this.c = c;
  5026. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  5027. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5028. this.color = ( color && color.isColor ) ? color : new Color();
  5029. this.vertexColors = Array.isArray( color ) ? color : [];
  5030. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5031. }
  5032. clone() {
  5033. return new this.constructor().copy( this );
  5034. }
  5035. copy( source ) {
  5036. this.a = source.a;
  5037. this.b = source.b;
  5038. this.c = source.c;
  5039. this.normal.copy( source.normal );
  5040. this.color.copy( source.color );
  5041. this.materialIndex = source.materialIndex;
  5042. for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5043. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5044. }
  5045. for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5046. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5047. }
  5048. return this;
  5049. }
  5050. }
  5051. let materialId = 0;
  5052. function Material() {
  5053. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5054. this.uuid = MathUtils.generateUUID();
  5055. this.name = '';
  5056. this.type = 'Material';
  5057. this.fog = true;
  5058. this.blending = NormalBlending;
  5059. this.side = FrontSide;
  5060. this.flatShading = false;
  5061. this.vertexColors = false;
  5062. this.opacity = 1;
  5063. this.transparent = false;
  5064. this.blendSrc = SrcAlphaFactor;
  5065. this.blendDst = OneMinusSrcAlphaFactor;
  5066. this.blendEquation = AddEquation;
  5067. this.blendSrcAlpha = null;
  5068. this.blendDstAlpha = null;
  5069. this.blendEquationAlpha = null;
  5070. this.depthFunc = LessEqualDepth;
  5071. this.depthTest = true;
  5072. this.depthWrite = true;
  5073. this.stencilWriteMask = 0xff;
  5074. this.stencilFunc = AlwaysStencilFunc;
  5075. this.stencilRef = 0;
  5076. this.stencilFuncMask = 0xff;
  5077. this.stencilFail = KeepStencilOp;
  5078. this.stencilZFail = KeepStencilOp;
  5079. this.stencilZPass = KeepStencilOp;
  5080. this.stencilWrite = false;
  5081. this.clippingPlanes = null;
  5082. this.clipIntersection = false;
  5083. this.clipShadows = false;
  5084. this.shadowSide = null;
  5085. this.colorWrite = true;
  5086. this.precision = null; // override the renderer's default precision for this material
  5087. this.polygonOffset = false;
  5088. this.polygonOffsetFactor = 0;
  5089. this.polygonOffsetUnits = 0;
  5090. this.dithering = false;
  5091. this.alphaTest = 0;
  5092. this.premultipliedAlpha = false;
  5093. this.visible = true;
  5094. this.toneMapped = true;
  5095. this.userData = {};
  5096. this.version = 0;
  5097. }
  5098. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5099. constructor: Material,
  5100. isMaterial: true,
  5101. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  5102. customProgramCacheKey: function () {
  5103. return this.onBeforeCompile.toString();
  5104. },
  5105. setValues: function ( values ) {
  5106. if ( values === undefined ) return;
  5107. for ( const key in values ) {
  5108. const newValue = values[ key ];
  5109. if ( newValue === undefined ) {
  5110. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  5111. continue;
  5112. }
  5113. // for backward compatability if shading is set in the constructor
  5114. if ( key === 'shading' ) {
  5115. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5116. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5117. continue;
  5118. }
  5119. const currentValue = this[ key ];
  5120. if ( currentValue === undefined ) {
  5121. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  5122. continue;
  5123. }
  5124. if ( currentValue && currentValue.isColor ) {
  5125. currentValue.set( newValue );
  5126. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5127. currentValue.copy( newValue );
  5128. } else {
  5129. this[ key ] = newValue;
  5130. }
  5131. }
  5132. },
  5133. toJSON: function ( meta ) {
  5134. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5135. if ( isRoot ) {
  5136. meta = {
  5137. textures: {},
  5138. images: {}
  5139. };
  5140. }
  5141. const data = {
  5142. metadata: {
  5143. version: 4.5,
  5144. type: 'Material',
  5145. generator: 'Material.toJSON'
  5146. }
  5147. };
  5148. // standard Material serialization
  5149. data.uuid = this.uuid;
  5150. data.type = this.type;
  5151. if ( this.name !== '' ) data.name = this.name;
  5152. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5153. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5154. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5155. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  5156. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5157. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5158. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5159. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5160. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5161. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5162. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5163. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5164. }
  5165. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5166. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5167. }
  5168. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5169. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5170. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5171. }
  5172. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5173. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5174. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5175. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5176. if ( this.aoMap && this.aoMap.isTexture ) {
  5177. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5178. data.aoMapIntensity = this.aoMapIntensity;
  5179. }
  5180. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5181. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5182. data.bumpScale = this.bumpScale;
  5183. }
  5184. if ( this.normalMap && this.normalMap.isTexture ) {
  5185. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5186. data.normalMapType = this.normalMapType;
  5187. data.normalScale = this.normalScale.toArray();
  5188. }
  5189. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5190. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5191. data.displacementScale = this.displacementScale;
  5192. data.displacementBias = this.displacementBias;
  5193. }
  5194. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5195. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5196. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5197. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5198. if ( this.envMap && this.envMap.isTexture ) {
  5199. data.envMap = this.envMap.toJSON( meta ).uuid;
  5200. data.reflectivity = this.reflectivity; // Scale behind envMap
  5201. data.refractionRatio = this.refractionRatio;
  5202. if ( this.combine !== undefined ) data.combine = this.combine;
  5203. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5204. }
  5205. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5206. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5207. }
  5208. if ( this.size !== undefined ) data.size = this.size;
  5209. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5210. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5211. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5212. if ( this.side !== FrontSide ) data.side = this.side;
  5213. if ( this.vertexColors ) data.vertexColors = true;
  5214. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5215. if ( this.transparent === true ) data.transparent = this.transparent;
  5216. data.depthFunc = this.depthFunc;
  5217. data.depthTest = this.depthTest;
  5218. data.depthWrite = this.depthWrite;
  5219. data.stencilWrite = this.stencilWrite;
  5220. data.stencilWriteMask = this.stencilWriteMask;
  5221. data.stencilFunc = this.stencilFunc;
  5222. data.stencilRef = this.stencilRef;
  5223. data.stencilFuncMask = this.stencilFuncMask;
  5224. data.stencilFail = this.stencilFail;
  5225. data.stencilZFail = this.stencilZFail;
  5226. data.stencilZPass = this.stencilZPass;
  5227. // rotation (SpriteMaterial)
  5228. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5229. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5230. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5231. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5232. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5233. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5234. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5235. if ( this.scale !== undefined ) data.scale = this.scale;
  5236. if ( this.dithering === true ) data.dithering = true;
  5237. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5238. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5239. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5240. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5241. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5242. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5243. if ( this.morphTargets === true ) data.morphTargets = true;
  5244. if ( this.morphNormals === true ) data.morphNormals = true;
  5245. if ( this.skinning === true ) data.skinning = true;
  5246. if ( this.visible === false ) data.visible = false;
  5247. if ( this.toneMapped === false ) data.toneMapped = false;
  5248. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5249. // TODO: Copied from Object3D.toJSON
  5250. function extractFromCache( cache ) {
  5251. const values = [];
  5252. for ( const key in cache ) {
  5253. const data = cache[ key ];
  5254. delete data.metadata;
  5255. values.push( data );
  5256. }
  5257. return values;
  5258. }
  5259. if ( isRoot ) {
  5260. const textures = extractFromCache( meta.textures );
  5261. const images = extractFromCache( meta.images );
  5262. if ( textures.length > 0 ) data.textures = textures;
  5263. if ( images.length > 0 ) data.images = images;
  5264. }
  5265. return data;
  5266. },
  5267. clone: function () {
  5268. return new this.constructor().copy( this );
  5269. },
  5270. copy: function ( source ) {
  5271. this.name = source.name;
  5272. this.fog = source.fog;
  5273. this.blending = source.blending;
  5274. this.side = source.side;
  5275. this.flatShading = source.flatShading;
  5276. this.vertexColors = source.vertexColors;
  5277. this.opacity = source.opacity;
  5278. this.transparent = source.transparent;
  5279. this.blendSrc = source.blendSrc;
  5280. this.blendDst = source.blendDst;
  5281. this.blendEquation = source.blendEquation;
  5282. this.blendSrcAlpha = source.blendSrcAlpha;
  5283. this.blendDstAlpha = source.blendDstAlpha;
  5284. this.blendEquationAlpha = source.blendEquationAlpha;
  5285. this.depthFunc = source.depthFunc;
  5286. this.depthTest = source.depthTest;
  5287. this.depthWrite = source.depthWrite;
  5288. this.stencilWriteMask = source.stencilWriteMask;
  5289. this.stencilFunc = source.stencilFunc;
  5290. this.stencilRef = source.stencilRef;
  5291. this.stencilFuncMask = source.stencilFuncMask;
  5292. this.stencilFail = source.stencilFail;
  5293. this.stencilZFail = source.stencilZFail;
  5294. this.stencilZPass = source.stencilZPass;
  5295. this.stencilWrite = source.stencilWrite;
  5296. const srcPlanes = source.clippingPlanes;
  5297. let dstPlanes = null;
  5298. if ( srcPlanes !== null ) {
  5299. const n = srcPlanes.length;
  5300. dstPlanes = new Array( n );
  5301. for ( let i = 0; i !== n; ++ i ) {
  5302. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5303. }
  5304. }
  5305. this.clippingPlanes = dstPlanes;
  5306. this.clipIntersection = source.clipIntersection;
  5307. this.clipShadows = source.clipShadows;
  5308. this.shadowSide = source.shadowSide;
  5309. this.colorWrite = source.colorWrite;
  5310. this.precision = source.precision;
  5311. this.polygonOffset = source.polygonOffset;
  5312. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5313. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5314. this.dithering = source.dithering;
  5315. this.alphaTest = source.alphaTest;
  5316. this.premultipliedAlpha = source.premultipliedAlpha;
  5317. this.visible = source.visible;
  5318. this.toneMapped = source.toneMapped;
  5319. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5320. return this;
  5321. },
  5322. dispose: function () {
  5323. this.dispatchEvent( { type: 'dispose' } );
  5324. }
  5325. } );
  5326. Object.defineProperty( Material.prototype, 'needsUpdate', {
  5327. set: function ( value ) {
  5328. if ( value === true ) this.version ++;
  5329. }
  5330. } );
  5331. /**
  5332. * parameters = {
  5333. * color: <hex>,
  5334. * opacity: <float>,
  5335. * map: new THREE.Texture( <Image> ),
  5336. *
  5337. * lightMap: new THREE.Texture( <Image> ),
  5338. * lightMapIntensity: <float>
  5339. *
  5340. * aoMap: new THREE.Texture( <Image> ),
  5341. * aoMapIntensity: <float>
  5342. *
  5343. * specularMap: new THREE.Texture( <Image> ),
  5344. *
  5345. * alphaMap: new THREE.Texture( <Image> ),
  5346. *
  5347. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5348. * combine: THREE.Multiply,
  5349. * reflectivity: <float>,
  5350. * refractionRatio: <float>,
  5351. *
  5352. * depthTest: <bool>,
  5353. * depthWrite: <bool>,
  5354. *
  5355. * wireframe: <boolean>,
  5356. * wireframeLinewidth: <float>,
  5357. *
  5358. * skinning: <bool>,
  5359. * morphTargets: <bool>
  5360. * }
  5361. */
  5362. function MeshBasicMaterial( parameters ) {
  5363. Material.call( this );
  5364. this.type = 'MeshBasicMaterial';
  5365. this.color = new Color( 0xffffff ); // emissive
  5366. this.map = null;
  5367. this.lightMap = null;
  5368. this.lightMapIntensity = 1.0;
  5369. this.aoMap = null;
  5370. this.aoMapIntensity = 1.0;
  5371. this.specularMap = null;
  5372. this.alphaMap = null;
  5373. this.envMap = null;
  5374. this.combine = MultiplyOperation;
  5375. this.reflectivity = 1;
  5376. this.refractionRatio = 0.98;
  5377. this.wireframe = false;
  5378. this.wireframeLinewidth = 1;
  5379. this.wireframeLinecap = 'round';
  5380. this.wireframeLinejoin = 'round';
  5381. this.skinning = false;
  5382. this.morphTargets = false;
  5383. this.setValues( parameters );
  5384. }
  5385. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  5386. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  5387. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5388. MeshBasicMaterial.prototype.copy = function ( source ) {
  5389. Material.prototype.copy.call( this, source );
  5390. this.color.copy( source.color );
  5391. this.map = source.map;
  5392. this.lightMap = source.lightMap;
  5393. this.lightMapIntensity = source.lightMapIntensity;
  5394. this.aoMap = source.aoMap;
  5395. this.aoMapIntensity = source.aoMapIntensity;
  5396. this.specularMap = source.specularMap;
  5397. this.alphaMap = source.alphaMap;
  5398. this.envMap = source.envMap;
  5399. this.combine = source.combine;
  5400. this.reflectivity = source.reflectivity;
  5401. this.refractionRatio = source.refractionRatio;
  5402. this.wireframe = source.wireframe;
  5403. this.wireframeLinewidth = source.wireframeLinewidth;
  5404. this.wireframeLinecap = source.wireframeLinecap;
  5405. this.wireframeLinejoin = source.wireframeLinejoin;
  5406. this.skinning = source.skinning;
  5407. this.morphTargets = source.morphTargets;
  5408. return this;
  5409. };
  5410. const _vector$3 = new Vector3();
  5411. const _vector2$1 = new Vector2();
  5412. function BufferAttribute( array, itemSize, normalized ) {
  5413. if ( Array.isArray( array ) ) {
  5414. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5415. }
  5416. this.name = '';
  5417. this.array = array;
  5418. this.itemSize = itemSize;
  5419. this.count = array !== undefined ? array.length / itemSize : 0;
  5420. this.normalized = normalized === true;
  5421. this.usage = StaticDrawUsage;
  5422. this.updateRange = { offset: 0, count: - 1 };
  5423. this.version = 0;
  5424. }
  5425. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  5426. set: function ( value ) {
  5427. if ( value === true ) this.version ++;
  5428. }
  5429. } );
  5430. Object.assign( BufferAttribute.prototype, {
  5431. isBufferAttribute: true,
  5432. onUploadCallback: function () {},
  5433. setUsage: function ( value ) {
  5434. this.usage = value;
  5435. return this;
  5436. },
  5437. copy: function ( source ) {
  5438. this.name = source.name;
  5439. this.array = new source.array.constructor( source.array );
  5440. this.itemSize = source.itemSize;
  5441. this.count = source.count;
  5442. this.normalized = source.normalized;
  5443. this.usage = source.usage;
  5444. return this;
  5445. },
  5446. copyAt: function ( index1, attribute, index2 ) {
  5447. index1 *= this.itemSize;
  5448. index2 *= attribute.itemSize;
  5449. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5450. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5451. }
  5452. return this;
  5453. },
  5454. copyArray: function ( array ) {
  5455. this.array.set( array );
  5456. return this;
  5457. },
  5458. copyColorsArray: function ( colors ) {
  5459. const array = this.array;
  5460. let offset = 0;
  5461. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5462. let color = colors[ i ];
  5463. if ( color === undefined ) {
  5464. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5465. color = new Color();
  5466. }
  5467. array[ offset ++ ] = color.r;
  5468. array[ offset ++ ] = color.g;
  5469. array[ offset ++ ] = color.b;
  5470. }
  5471. return this;
  5472. },
  5473. copyVector2sArray: function ( vectors ) {
  5474. const array = this.array;
  5475. let offset = 0;
  5476. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5477. let vector = vectors[ i ];
  5478. if ( vector === undefined ) {
  5479. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5480. vector = new Vector2();
  5481. }
  5482. array[ offset ++ ] = vector.x;
  5483. array[ offset ++ ] = vector.y;
  5484. }
  5485. return this;
  5486. },
  5487. copyVector3sArray: function ( vectors ) {
  5488. const array = this.array;
  5489. let offset = 0;
  5490. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5491. let vector = vectors[ i ];
  5492. if ( vector === undefined ) {
  5493. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5494. vector = new Vector3();
  5495. }
  5496. array[ offset ++ ] = vector.x;
  5497. array[ offset ++ ] = vector.y;
  5498. array[ offset ++ ] = vector.z;
  5499. }
  5500. return this;
  5501. },
  5502. copyVector4sArray: function ( vectors ) {
  5503. const array = this.array;
  5504. let offset = 0;
  5505. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5506. let vector = vectors[ i ];
  5507. if ( vector === undefined ) {
  5508. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5509. vector = new Vector4();
  5510. }
  5511. array[ offset ++ ] = vector.x;
  5512. array[ offset ++ ] = vector.y;
  5513. array[ offset ++ ] = vector.z;
  5514. array[ offset ++ ] = vector.w;
  5515. }
  5516. return this;
  5517. },
  5518. applyMatrix3: function ( m ) {
  5519. if ( this.itemSize === 2 ) {
  5520. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5521. _vector2$1.fromBufferAttribute( this, i );
  5522. _vector2$1.applyMatrix3( m );
  5523. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5524. }
  5525. } else if ( this.itemSize === 3 ) {
  5526. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5527. _vector$3.fromBufferAttribute( this, i );
  5528. _vector$3.applyMatrix3( m );
  5529. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5530. }
  5531. }
  5532. return this;
  5533. },
  5534. applyMatrix4: function ( m ) {
  5535. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5536. _vector$3.x = this.getX( i );
  5537. _vector$3.y = this.getY( i );
  5538. _vector$3.z = this.getZ( i );
  5539. _vector$3.applyMatrix4( m );
  5540. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5541. }
  5542. return this;
  5543. },
  5544. applyNormalMatrix: function ( m ) {
  5545. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5546. _vector$3.x = this.getX( i );
  5547. _vector$3.y = this.getY( i );
  5548. _vector$3.z = this.getZ( i );
  5549. _vector$3.applyNormalMatrix( m );
  5550. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5551. }
  5552. return this;
  5553. },
  5554. transformDirection: function ( m ) {
  5555. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5556. _vector$3.x = this.getX( i );
  5557. _vector$3.y = this.getY( i );
  5558. _vector$3.z = this.getZ( i );
  5559. _vector$3.transformDirection( m );
  5560. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5561. }
  5562. return this;
  5563. },
  5564. set: function ( value, offset ) {
  5565. if ( offset === undefined ) offset = 0;
  5566. this.array.set( value, offset );
  5567. return this;
  5568. },
  5569. getX: function ( index ) {
  5570. return this.array[ index * this.itemSize ];
  5571. },
  5572. setX: function ( index, x ) {
  5573. this.array[ index * this.itemSize ] = x;
  5574. return this;
  5575. },
  5576. getY: function ( index ) {
  5577. return this.array[ index * this.itemSize + 1 ];
  5578. },
  5579. setY: function ( index, y ) {
  5580. this.array[ index * this.itemSize + 1 ] = y;
  5581. return this;
  5582. },
  5583. getZ: function ( index ) {
  5584. return this.array[ index * this.itemSize + 2 ];
  5585. },
  5586. setZ: function ( index, z ) {
  5587. this.array[ index * this.itemSize + 2 ] = z;
  5588. return this;
  5589. },
  5590. getW: function ( index ) {
  5591. return this.array[ index * this.itemSize + 3 ];
  5592. },
  5593. setW: function ( index, w ) {
  5594. this.array[ index * this.itemSize + 3 ] = w;
  5595. return this;
  5596. },
  5597. setXY: function ( index, x, y ) {
  5598. index *= this.itemSize;
  5599. this.array[ index + 0 ] = x;
  5600. this.array[ index + 1 ] = y;
  5601. return this;
  5602. },
  5603. setXYZ: function ( index, x, y, z ) {
  5604. index *= this.itemSize;
  5605. this.array[ index + 0 ] = x;
  5606. this.array[ index + 1 ] = y;
  5607. this.array[ index + 2 ] = z;
  5608. return this;
  5609. },
  5610. setXYZW: function ( index, x, y, z, w ) {
  5611. index *= this.itemSize;
  5612. this.array[ index + 0 ] = x;
  5613. this.array[ index + 1 ] = y;
  5614. this.array[ index + 2 ] = z;
  5615. this.array[ index + 3 ] = w;
  5616. return this;
  5617. },
  5618. onUpload: function ( callback ) {
  5619. this.onUploadCallback = callback;
  5620. return this;
  5621. },
  5622. clone: function () {
  5623. return new this.constructor( this.array, this.itemSize ).copy( this );
  5624. },
  5625. toJSON: function () {
  5626. return {
  5627. itemSize: this.itemSize,
  5628. type: this.array.constructor.name,
  5629. array: Array.prototype.slice.call( this.array ),
  5630. normalized: this.normalized
  5631. };
  5632. }
  5633. } );
  5634. //
  5635. function Int8BufferAttribute( array, itemSize, normalized ) {
  5636. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  5637. }
  5638. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5639. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  5640. function Uint8BufferAttribute( array, itemSize, normalized ) {
  5641. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  5642. }
  5643. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5644. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  5645. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  5646. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  5647. }
  5648. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5649. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  5650. function Int16BufferAttribute( array, itemSize, normalized ) {
  5651. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  5652. }
  5653. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5654. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  5655. function Uint16BufferAttribute( array, itemSize, normalized ) {
  5656. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  5657. }
  5658. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5659. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  5660. function Int32BufferAttribute( array, itemSize, normalized ) {
  5661. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  5662. }
  5663. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5664. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  5665. function Uint32BufferAttribute( array, itemSize, normalized ) {
  5666. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  5667. }
  5668. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5669. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  5670. function Float32BufferAttribute( array, itemSize, normalized ) {
  5671. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  5672. }
  5673. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5674. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  5675. function Float64BufferAttribute( array, itemSize, normalized ) {
  5676. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  5677. }
  5678. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5679. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  5680. class DirectGeometry {
  5681. constructor() {
  5682. this.vertices = [];
  5683. this.normals = [];
  5684. this.colors = [];
  5685. this.uvs = [];
  5686. this.uvs2 = [];
  5687. this.groups = [];
  5688. this.morphTargets = {};
  5689. this.skinWeights = [];
  5690. this.skinIndices = [];
  5691. // this.lineDistances = [];
  5692. this.boundingBox = null;
  5693. this.boundingSphere = null;
  5694. // update flags
  5695. this.verticesNeedUpdate = false;
  5696. this.normalsNeedUpdate = false;
  5697. this.colorsNeedUpdate = false;
  5698. this.uvsNeedUpdate = false;
  5699. this.groupsNeedUpdate = false;
  5700. }
  5701. computeGroups( geometry ) {
  5702. const groups = [];
  5703. let group, i;
  5704. let materialIndex = undefined;
  5705. const faces = geometry.faces;
  5706. for ( i = 0; i < faces.length; i ++ ) {
  5707. const face = faces[ i ];
  5708. // materials
  5709. if ( face.materialIndex !== materialIndex ) {
  5710. materialIndex = face.materialIndex;
  5711. if ( group !== undefined ) {
  5712. group.count = ( i * 3 ) - group.start;
  5713. groups.push( group );
  5714. }
  5715. group = {
  5716. start: i * 3,
  5717. materialIndex: materialIndex
  5718. };
  5719. }
  5720. }
  5721. if ( group !== undefined ) {
  5722. group.count = ( i * 3 ) - group.start;
  5723. groups.push( group );
  5724. }
  5725. this.groups = groups;
  5726. }
  5727. fromGeometry( geometry ) {
  5728. const faces = geometry.faces;
  5729. const vertices = geometry.vertices;
  5730. const faceVertexUvs = geometry.faceVertexUvs;
  5731. const hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  5732. const hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  5733. // morphs
  5734. const morphTargets = geometry.morphTargets;
  5735. const morphTargetsLength = morphTargets.length;
  5736. let morphTargetsPosition;
  5737. if ( morphTargetsLength > 0 ) {
  5738. morphTargetsPosition = [];
  5739. for ( let i = 0; i < morphTargetsLength; i ++ ) {
  5740. morphTargetsPosition[ i ] = {
  5741. name: morphTargets[ i ].name,
  5742. data: []
  5743. };
  5744. }
  5745. this.morphTargets.position = morphTargetsPosition;
  5746. }
  5747. const morphNormals = geometry.morphNormals;
  5748. const morphNormalsLength = morphNormals.length;
  5749. let morphTargetsNormal;
  5750. if ( morphNormalsLength > 0 ) {
  5751. morphTargetsNormal = [];
  5752. for ( let i = 0; i < morphNormalsLength; i ++ ) {
  5753. morphTargetsNormal[ i ] = {
  5754. name: morphNormals[ i ].name,
  5755. data: []
  5756. };
  5757. }
  5758. this.morphTargets.normal = morphTargetsNormal;
  5759. }
  5760. // skins
  5761. const skinIndices = geometry.skinIndices;
  5762. const skinWeights = geometry.skinWeights;
  5763. const hasSkinIndices = skinIndices.length === vertices.length;
  5764. const hasSkinWeights = skinWeights.length === vertices.length;
  5765. //
  5766. if ( vertices.length > 0 && faces.length === 0 ) {
  5767. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  5768. }
  5769. for ( let i = 0; i < faces.length; i ++ ) {
  5770. const face = faces[ i ];
  5771. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  5772. const vertexNormals = face.vertexNormals;
  5773. if ( vertexNormals.length === 3 ) {
  5774. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  5775. } else {
  5776. const normal = face.normal;
  5777. this.normals.push( normal, normal, normal );
  5778. }
  5779. const vertexColors = face.vertexColors;
  5780. if ( vertexColors.length === 3 ) {
  5781. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  5782. } else {
  5783. const color = face.color;
  5784. this.colors.push( color, color, color );
  5785. }
  5786. if ( hasFaceVertexUv === true ) {
  5787. const vertexUvs = faceVertexUvs[ 0 ][ i ];
  5788. if ( vertexUvs !== undefined ) {
  5789. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5790. } else {
  5791. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  5792. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  5793. }
  5794. }
  5795. if ( hasFaceVertexUv2 === true ) {
  5796. const vertexUvs = faceVertexUvs[ 1 ][ i ];
  5797. if ( vertexUvs !== undefined ) {
  5798. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5799. } else {
  5800. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  5801. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  5802. }
  5803. }
  5804. // morphs
  5805. for ( let j = 0; j < morphTargetsLength; j ++ ) {
  5806. const morphTarget = morphTargets[ j ].vertices;
  5807. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  5808. }
  5809. for ( let j = 0; j < morphNormalsLength; j ++ ) {
  5810. const morphNormal = morphNormals[ j ].vertexNormals[ i ];
  5811. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  5812. }
  5813. // skins
  5814. if ( hasSkinIndices ) {
  5815. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  5816. }
  5817. if ( hasSkinWeights ) {
  5818. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  5819. }
  5820. }
  5821. this.computeGroups( geometry );
  5822. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  5823. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  5824. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  5825. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  5826. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  5827. if ( geometry.boundingSphere !== null ) {
  5828. this.boundingSphere = geometry.boundingSphere.clone();
  5829. }
  5830. if ( geometry.boundingBox !== null ) {
  5831. this.boundingBox = geometry.boundingBox.clone();
  5832. }
  5833. return this;
  5834. }
  5835. }
  5836. function arrayMax( array ) {
  5837. if ( array.length === 0 ) return - Infinity;
  5838. let max = array[ 0 ];
  5839. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5840. if ( array[ i ] > max ) max = array[ i ];
  5841. }
  5842. return max;
  5843. }
  5844. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  5845. const _m1$2 = new Matrix4();
  5846. const _obj = new Object3D();
  5847. const _offset = new Vector3();
  5848. const _box$2 = new Box3();
  5849. const _boxMorphTargets = new Box3();
  5850. const _vector$4 = new Vector3();
  5851. function BufferGeometry() {
  5852. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  5853. this.uuid = MathUtils.generateUUID();
  5854. this.name = '';
  5855. this.type = 'BufferGeometry';
  5856. this.index = null;
  5857. this.attributes = {};
  5858. this.morphAttributes = {};
  5859. this.morphTargetsRelative = false;
  5860. this.groups = [];
  5861. this.boundingBox = null;
  5862. this.boundingSphere = null;
  5863. this.drawRange = { start: 0, count: Infinity };
  5864. this.userData = {};
  5865. }
  5866. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5867. constructor: BufferGeometry,
  5868. isBufferGeometry: true,
  5869. getIndex: function () {
  5870. return this.index;
  5871. },
  5872. setIndex: function ( index ) {
  5873. if ( Array.isArray( index ) ) {
  5874. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5875. } else {
  5876. this.index = index;
  5877. }
  5878. },
  5879. getAttribute: function ( name ) {
  5880. return this.attributes[ name ];
  5881. },
  5882. setAttribute: function ( name, attribute ) {
  5883. this.attributes[ name ] = attribute;
  5884. return this;
  5885. },
  5886. deleteAttribute: function ( name ) {
  5887. delete this.attributes[ name ];
  5888. return this;
  5889. },
  5890. addGroup: function ( start, count, materialIndex ) {
  5891. this.groups.push( {
  5892. start: start,
  5893. count: count,
  5894. materialIndex: materialIndex !== undefined ? materialIndex : 0
  5895. } );
  5896. },
  5897. clearGroups: function () {
  5898. this.groups = [];
  5899. },
  5900. setDrawRange: function ( start, count ) {
  5901. this.drawRange.start = start;
  5902. this.drawRange.count = count;
  5903. },
  5904. applyMatrix4: function ( matrix ) {
  5905. const position = this.attributes.position;
  5906. if ( position !== undefined ) {
  5907. position.applyMatrix4( matrix );
  5908. position.needsUpdate = true;
  5909. }
  5910. const normal = this.attributes.normal;
  5911. if ( normal !== undefined ) {
  5912. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5913. normal.applyNormalMatrix( normalMatrix );
  5914. normal.needsUpdate = true;
  5915. }
  5916. const tangent = this.attributes.tangent;
  5917. if ( tangent !== undefined ) {
  5918. tangent.transformDirection( matrix );
  5919. tangent.needsUpdate = true;
  5920. }
  5921. if ( this.boundingBox !== null ) {
  5922. this.computeBoundingBox();
  5923. }
  5924. if ( this.boundingSphere !== null ) {
  5925. this.computeBoundingSphere();
  5926. }
  5927. return this;
  5928. },
  5929. rotateX: function ( angle ) {
  5930. // rotate geometry around world x-axis
  5931. _m1$2.makeRotationX( angle );
  5932. this.applyMatrix4( _m1$2 );
  5933. return this;
  5934. },
  5935. rotateY: function ( angle ) {
  5936. // rotate geometry around world y-axis
  5937. _m1$2.makeRotationY( angle );
  5938. this.applyMatrix4( _m1$2 );
  5939. return this;
  5940. },
  5941. rotateZ: function ( angle ) {
  5942. // rotate geometry around world z-axis
  5943. _m1$2.makeRotationZ( angle );
  5944. this.applyMatrix4( _m1$2 );
  5945. return this;
  5946. },
  5947. translate: function ( x, y, z ) {
  5948. // translate geometry
  5949. _m1$2.makeTranslation( x, y, z );
  5950. this.applyMatrix4( _m1$2 );
  5951. return this;
  5952. },
  5953. scale: function ( x, y, z ) {
  5954. // scale geometry
  5955. _m1$2.makeScale( x, y, z );
  5956. this.applyMatrix4( _m1$2 );
  5957. return this;
  5958. },
  5959. lookAt: function ( vector ) {
  5960. _obj.lookAt( vector );
  5961. _obj.updateMatrix();
  5962. this.applyMatrix4( _obj.matrix );
  5963. return this;
  5964. },
  5965. center: function () {
  5966. this.computeBoundingBox();
  5967. this.boundingBox.getCenter( _offset ).negate();
  5968. this.translate( _offset.x, _offset.y, _offset.z );
  5969. return this;
  5970. },
  5971. setFromObject: function ( object ) {
  5972. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  5973. const geometry = object.geometry;
  5974. if ( object.isPoints || object.isLine ) {
  5975. const positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  5976. const colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  5977. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  5978. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  5979. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  5980. const lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  5981. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  5982. }
  5983. if ( geometry.boundingSphere !== null ) {
  5984. this.boundingSphere = geometry.boundingSphere.clone();
  5985. }
  5986. if ( geometry.boundingBox !== null ) {
  5987. this.boundingBox = geometry.boundingBox.clone();
  5988. }
  5989. } else if ( object.isMesh ) {
  5990. if ( geometry && geometry.isGeometry ) {
  5991. this.fromGeometry( geometry );
  5992. }
  5993. }
  5994. return this;
  5995. },
  5996. setFromPoints: function ( points ) {
  5997. const position = [];
  5998. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5999. const point = points[ i ];
  6000. position.push( point.x, point.y, point.z || 0 );
  6001. }
  6002. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6003. return this;
  6004. },
  6005. updateFromObject: function ( object ) {
  6006. let geometry = object.geometry;
  6007. if ( object.isMesh ) {
  6008. let direct = geometry.__directGeometry;
  6009. if ( geometry.elementsNeedUpdate === true ) {
  6010. direct = undefined;
  6011. geometry.elementsNeedUpdate = false;
  6012. }
  6013. if ( direct === undefined ) {
  6014. return this.fromGeometry( geometry );
  6015. }
  6016. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6017. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6018. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6019. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6020. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6021. geometry.verticesNeedUpdate = false;
  6022. geometry.normalsNeedUpdate = false;
  6023. geometry.colorsNeedUpdate = false;
  6024. geometry.uvsNeedUpdate = false;
  6025. geometry.groupsNeedUpdate = false;
  6026. geometry = direct;
  6027. }
  6028. if ( geometry.verticesNeedUpdate === true ) {
  6029. const attribute = this.attributes.position;
  6030. if ( attribute !== undefined ) {
  6031. attribute.copyVector3sArray( geometry.vertices );
  6032. attribute.needsUpdate = true;
  6033. }
  6034. geometry.verticesNeedUpdate = false;
  6035. }
  6036. if ( geometry.normalsNeedUpdate === true ) {
  6037. const attribute = this.attributes.normal;
  6038. if ( attribute !== undefined ) {
  6039. attribute.copyVector3sArray( geometry.normals );
  6040. attribute.needsUpdate = true;
  6041. }
  6042. geometry.normalsNeedUpdate = false;
  6043. }
  6044. if ( geometry.colorsNeedUpdate === true ) {
  6045. const attribute = this.attributes.color;
  6046. if ( attribute !== undefined ) {
  6047. attribute.copyColorsArray( geometry.colors );
  6048. attribute.needsUpdate = true;
  6049. }
  6050. geometry.colorsNeedUpdate = false;
  6051. }
  6052. if ( geometry.uvsNeedUpdate ) {
  6053. const attribute = this.attributes.uv;
  6054. if ( attribute !== undefined ) {
  6055. attribute.copyVector2sArray( geometry.uvs );
  6056. attribute.needsUpdate = true;
  6057. }
  6058. geometry.uvsNeedUpdate = false;
  6059. }
  6060. if ( geometry.lineDistancesNeedUpdate ) {
  6061. const attribute = this.attributes.lineDistance;
  6062. if ( attribute !== undefined ) {
  6063. attribute.copyArray( geometry.lineDistances );
  6064. attribute.needsUpdate = true;
  6065. }
  6066. geometry.lineDistancesNeedUpdate = false;
  6067. }
  6068. if ( geometry.groupsNeedUpdate ) {
  6069. geometry.computeGroups( object.geometry );
  6070. this.groups = geometry.groups;
  6071. geometry.groupsNeedUpdate = false;
  6072. }
  6073. return this;
  6074. },
  6075. fromGeometry: function ( geometry ) {
  6076. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  6077. return this.fromDirectGeometry( geometry.__directGeometry );
  6078. },
  6079. fromDirectGeometry: function ( geometry ) {
  6080. const positions = new Float32Array( geometry.vertices.length * 3 );
  6081. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6082. if ( geometry.normals.length > 0 ) {
  6083. const normals = new Float32Array( geometry.normals.length * 3 );
  6084. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6085. }
  6086. if ( geometry.colors.length > 0 ) {
  6087. const colors = new Float32Array( geometry.colors.length * 3 );
  6088. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6089. }
  6090. if ( geometry.uvs.length > 0 ) {
  6091. const uvs = new Float32Array( geometry.uvs.length * 2 );
  6092. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6093. }
  6094. if ( geometry.uvs2.length > 0 ) {
  6095. const uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6096. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6097. }
  6098. // groups
  6099. this.groups = geometry.groups;
  6100. // morphs
  6101. for ( const name in geometry.morphTargets ) {
  6102. const array = [];
  6103. const morphTargets = geometry.morphTargets[ name ];
  6104. for ( let i = 0, l = morphTargets.length; i < l; i ++ ) {
  6105. const morphTarget = morphTargets[ i ];
  6106. const attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  6107. attribute.name = morphTarget.name;
  6108. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  6109. }
  6110. this.morphAttributes[ name ] = array;
  6111. }
  6112. // skinning
  6113. if ( geometry.skinIndices.length > 0 ) {
  6114. const skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  6115. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6116. }
  6117. if ( geometry.skinWeights.length > 0 ) {
  6118. const skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  6119. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6120. }
  6121. //
  6122. if ( geometry.boundingSphere !== null ) {
  6123. this.boundingSphere = geometry.boundingSphere.clone();
  6124. }
  6125. if ( geometry.boundingBox !== null ) {
  6126. this.boundingBox = geometry.boundingBox.clone();
  6127. }
  6128. return this;
  6129. },
  6130. computeBoundingBox: function () {
  6131. if ( this.boundingBox === null ) {
  6132. this.boundingBox = new Box3();
  6133. }
  6134. const position = this.attributes.position;
  6135. const morphAttributesPosition = this.morphAttributes.position;
  6136. if ( position && position.isGLBufferAttribute ) {
  6137. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6138. this.boundingBox.set(
  6139. new Vector3( - Infinity, - Infinity, - Infinity ),
  6140. new Vector3( + Infinity, + Infinity, + Infinity )
  6141. );
  6142. return;
  6143. }
  6144. if ( position !== undefined ) {
  6145. this.boundingBox.setFromBufferAttribute( position );
  6146. // process morph attributes if present
  6147. if ( morphAttributesPosition ) {
  6148. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6149. const morphAttribute = morphAttributesPosition[ i ];
  6150. _box$2.setFromBufferAttribute( morphAttribute );
  6151. if ( this.morphTargetsRelative ) {
  6152. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  6153. this.boundingBox.expandByPoint( _vector$4 );
  6154. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  6155. this.boundingBox.expandByPoint( _vector$4 );
  6156. } else {
  6157. this.boundingBox.expandByPoint( _box$2.min );
  6158. this.boundingBox.expandByPoint( _box$2.max );
  6159. }
  6160. }
  6161. }
  6162. } else {
  6163. this.boundingBox.makeEmpty();
  6164. }
  6165. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6166. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6167. }
  6168. },
  6169. computeBoundingSphere: function () {
  6170. if ( this.boundingSphere === null ) {
  6171. this.boundingSphere = new Sphere();
  6172. }
  6173. const position = this.attributes.position;
  6174. const morphAttributesPosition = this.morphAttributes.position;
  6175. if ( position && position.isGLBufferAttribute ) {
  6176. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6177. this.boundingSphere.set( new Vector3(), Infinity );
  6178. return;
  6179. }
  6180. if ( position ) {
  6181. // first, find the center of the bounding sphere
  6182. const center = this.boundingSphere.center;
  6183. _box$2.setFromBufferAttribute( position );
  6184. // process morph attributes if present
  6185. if ( morphAttributesPosition ) {
  6186. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6187. const morphAttribute = morphAttributesPosition[ i ];
  6188. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6189. if ( this.morphTargetsRelative ) {
  6190. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  6191. _box$2.expandByPoint( _vector$4 );
  6192. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  6193. _box$2.expandByPoint( _vector$4 );
  6194. } else {
  6195. _box$2.expandByPoint( _boxMorphTargets.min );
  6196. _box$2.expandByPoint( _boxMorphTargets.max );
  6197. }
  6198. }
  6199. }
  6200. _box$2.getCenter( center );
  6201. // second, try to find a boundingSphere with a radius smaller than the
  6202. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6203. let maxRadiusSq = 0;
  6204. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6205. _vector$4.fromBufferAttribute( position, i );
  6206. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6207. }
  6208. // process morph attributes if present
  6209. if ( morphAttributesPosition ) {
  6210. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6211. const morphAttribute = morphAttributesPosition[ i ];
  6212. const morphTargetsRelative = this.morphTargetsRelative;
  6213. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6214. _vector$4.fromBufferAttribute( morphAttribute, j );
  6215. if ( morphTargetsRelative ) {
  6216. _offset.fromBufferAttribute( position, j );
  6217. _vector$4.add( _offset );
  6218. }
  6219. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6220. }
  6221. }
  6222. }
  6223. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6224. if ( isNaN( this.boundingSphere.radius ) ) {
  6225. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6226. }
  6227. }
  6228. },
  6229. computeFaceNormals: function () {
  6230. // backwards compatibility
  6231. },
  6232. computeVertexNormals: function () {
  6233. const index = this.index;
  6234. const positionAttribute = this.getAttribute( 'position' );
  6235. if ( positionAttribute !== undefined ) {
  6236. let normalAttribute = this.getAttribute( 'normal' );
  6237. if ( normalAttribute === undefined ) {
  6238. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6239. this.setAttribute( 'normal', normalAttribute );
  6240. } else {
  6241. // reset existing normals to zero
  6242. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6243. normalAttribute.setXYZ( i, 0, 0, 0 );
  6244. }
  6245. }
  6246. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6247. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6248. const cb = new Vector3(), ab = new Vector3();
  6249. // indexed elements
  6250. if ( index ) {
  6251. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6252. const vA = index.getX( i + 0 );
  6253. const vB = index.getX( i + 1 );
  6254. const vC = index.getX( i + 2 );
  6255. pA.fromBufferAttribute( positionAttribute, vA );
  6256. pB.fromBufferAttribute( positionAttribute, vB );
  6257. pC.fromBufferAttribute( positionAttribute, vC );
  6258. cb.subVectors( pC, pB );
  6259. ab.subVectors( pA, pB );
  6260. cb.cross( ab );
  6261. nA.fromBufferAttribute( normalAttribute, vA );
  6262. nB.fromBufferAttribute( normalAttribute, vB );
  6263. nC.fromBufferAttribute( normalAttribute, vC );
  6264. nA.add( cb );
  6265. nB.add( cb );
  6266. nC.add( cb );
  6267. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6268. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6269. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6270. }
  6271. } else {
  6272. // non-indexed elements (unconnected triangle soup)
  6273. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6274. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6275. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6276. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6277. cb.subVectors( pC, pB );
  6278. ab.subVectors( pA, pB );
  6279. cb.cross( ab );
  6280. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6281. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6282. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6283. }
  6284. }
  6285. this.normalizeNormals();
  6286. normalAttribute.needsUpdate = true;
  6287. }
  6288. },
  6289. merge: function ( geometry, offset ) {
  6290. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6291. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6292. return;
  6293. }
  6294. if ( offset === undefined ) {
  6295. offset = 0;
  6296. console.warn(
  6297. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6298. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6299. );
  6300. }
  6301. const attributes = this.attributes;
  6302. for ( const key in attributes ) {
  6303. if ( geometry.attributes[ key ] === undefined ) continue;
  6304. const attribute1 = attributes[ key ];
  6305. const attributeArray1 = attribute1.array;
  6306. const attribute2 = geometry.attributes[ key ];
  6307. const attributeArray2 = attribute2.array;
  6308. const attributeOffset = attribute2.itemSize * offset;
  6309. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6310. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6311. attributeArray1[ j ] = attributeArray2[ i ];
  6312. }
  6313. }
  6314. return this;
  6315. },
  6316. normalizeNormals: function () {
  6317. const normals = this.attributes.normal;
  6318. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6319. _vector$4.fromBufferAttribute( normals, i );
  6320. _vector$4.normalize();
  6321. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  6322. }
  6323. },
  6324. toNonIndexed: function () {
  6325. function convertBufferAttribute( attribute, indices ) {
  6326. const array = attribute.array;
  6327. const itemSize = attribute.itemSize;
  6328. const normalized = attribute.normalized;
  6329. const array2 = new array.constructor( indices.length * itemSize );
  6330. let index = 0, index2 = 0;
  6331. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6332. index = indices[ i ] * itemSize;
  6333. for ( let j = 0; j < itemSize; j ++ ) {
  6334. array2[ index2 ++ ] = array[ index ++ ];
  6335. }
  6336. }
  6337. return new BufferAttribute( array2, itemSize, normalized );
  6338. }
  6339. //
  6340. if ( this.index === null ) {
  6341. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  6342. return this;
  6343. }
  6344. const geometry2 = new BufferGeometry();
  6345. const indices = this.index.array;
  6346. const attributes = this.attributes;
  6347. // attributes
  6348. for ( const name in attributes ) {
  6349. const attribute = attributes[ name ];
  6350. const newAttribute = convertBufferAttribute( attribute, indices );
  6351. geometry2.setAttribute( name, newAttribute );
  6352. }
  6353. // morph attributes
  6354. const morphAttributes = this.morphAttributes;
  6355. for ( const name in morphAttributes ) {
  6356. const morphArray = [];
  6357. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6358. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6359. const attribute = morphAttribute[ i ];
  6360. const newAttribute = convertBufferAttribute( attribute, indices );
  6361. morphArray.push( newAttribute );
  6362. }
  6363. geometry2.morphAttributes[ name ] = morphArray;
  6364. }
  6365. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6366. // groups
  6367. const groups = this.groups;
  6368. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6369. const group = groups[ i ];
  6370. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6371. }
  6372. return geometry2;
  6373. },
  6374. toJSON: function () {
  6375. const data = {
  6376. metadata: {
  6377. version: 4.5,
  6378. type: 'BufferGeometry',
  6379. generator: 'BufferGeometry.toJSON'
  6380. }
  6381. };
  6382. // standard BufferGeometry serialization
  6383. data.uuid = this.uuid;
  6384. data.type = this.type;
  6385. if ( this.name !== '' ) data.name = this.name;
  6386. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6387. if ( this.parameters !== undefined ) {
  6388. const parameters = this.parameters;
  6389. for ( const key in parameters ) {
  6390. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6391. }
  6392. return data;
  6393. }
  6394. data.data = { attributes: {} };
  6395. const index = this.index;
  6396. if ( index !== null ) {
  6397. data.data.index = {
  6398. type: index.array.constructor.name,
  6399. array: Array.prototype.slice.call( index.array )
  6400. };
  6401. }
  6402. const attributes = this.attributes;
  6403. for ( const key in attributes ) {
  6404. const attribute = attributes[ key ];
  6405. const attributeData = attribute.toJSON( data.data );
  6406. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  6407. data.data.attributes[ key ] = attributeData;
  6408. }
  6409. const morphAttributes = {};
  6410. let hasMorphAttributes = false;
  6411. for ( const key in this.morphAttributes ) {
  6412. const attributeArray = this.morphAttributes[ key ];
  6413. const array = [];
  6414. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6415. const attribute = attributeArray[ i ];
  6416. const attributeData = attribute.toJSON( data.data );
  6417. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  6418. array.push( attributeData );
  6419. }
  6420. if ( array.length > 0 ) {
  6421. morphAttributes[ key ] = array;
  6422. hasMorphAttributes = true;
  6423. }
  6424. }
  6425. if ( hasMorphAttributes ) {
  6426. data.data.morphAttributes = morphAttributes;
  6427. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6428. }
  6429. const groups = this.groups;
  6430. if ( groups.length > 0 ) {
  6431. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6432. }
  6433. const boundingSphere = this.boundingSphere;
  6434. if ( boundingSphere !== null ) {
  6435. data.data.boundingSphere = {
  6436. center: boundingSphere.center.toArray(),
  6437. radius: boundingSphere.radius
  6438. };
  6439. }
  6440. return data;
  6441. },
  6442. clone: function () {
  6443. /*
  6444. // Handle primitives
  6445. const parameters = this.parameters;
  6446. if ( parameters !== undefined ) {
  6447. const values = [];
  6448. for ( const key in parameters ) {
  6449. values.push( parameters[ key ] );
  6450. }
  6451. const geometry = Object.create( this.constructor.prototype );
  6452. this.constructor.apply( geometry, values );
  6453. return geometry;
  6454. }
  6455. return new this.constructor().copy( this );
  6456. */
  6457. return new BufferGeometry().copy( this );
  6458. },
  6459. copy: function ( source ) {
  6460. // reset
  6461. this.index = null;
  6462. this.attributes = {};
  6463. this.morphAttributes = {};
  6464. this.groups = [];
  6465. this.boundingBox = null;
  6466. this.boundingSphere = null;
  6467. // used for storing cloned, shared data
  6468. const data = {};
  6469. // name
  6470. this.name = source.name;
  6471. // index
  6472. const index = source.index;
  6473. if ( index !== null ) {
  6474. this.setIndex( index.clone( data ) );
  6475. }
  6476. // attributes
  6477. const attributes = source.attributes;
  6478. for ( const name in attributes ) {
  6479. const attribute = attributes[ name ];
  6480. this.setAttribute( name, attribute.clone( data ) );
  6481. }
  6482. // morph attributes
  6483. const morphAttributes = source.morphAttributes;
  6484. for ( const name in morphAttributes ) {
  6485. const array = [];
  6486. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6487. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6488. array.push( morphAttribute[ i ].clone( data ) );
  6489. }
  6490. this.morphAttributes[ name ] = array;
  6491. }
  6492. this.morphTargetsRelative = source.morphTargetsRelative;
  6493. // groups
  6494. const groups = source.groups;
  6495. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6496. const group = groups[ i ];
  6497. this.addGroup( group.start, group.count, group.materialIndex );
  6498. }
  6499. // bounding box
  6500. const boundingBox = source.boundingBox;
  6501. if ( boundingBox !== null ) {
  6502. this.boundingBox = boundingBox.clone();
  6503. }
  6504. // bounding sphere
  6505. const boundingSphere = source.boundingSphere;
  6506. if ( boundingSphere !== null ) {
  6507. this.boundingSphere = boundingSphere.clone();
  6508. }
  6509. // draw range
  6510. this.drawRange.start = source.drawRange.start;
  6511. this.drawRange.count = source.drawRange.count;
  6512. // user data
  6513. this.userData = source.userData;
  6514. return this;
  6515. },
  6516. dispose: function () {
  6517. this.dispatchEvent( { type: 'dispose' } );
  6518. }
  6519. } );
  6520. const _inverseMatrix = new Matrix4();
  6521. const _ray = new Ray();
  6522. const _sphere = new Sphere();
  6523. const _vA = new Vector3();
  6524. const _vB = new Vector3();
  6525. const _vC = new Vector3();
  6526. const _tempA = new Vector3();
  6527. const _tempB = new Vector3();
  6528. const _tempC = new Vector3();
  6529. const _morphA = new Vector3();
  6530. const _morphB = new Vector3();
  6531. const _morphC = new Vector3();
  6532. const _uvA = new Vector2();
  6533. const _uvB = new Vector2();
  6534. const _uvC = new Vector2();
  6535. const _intersectionPoint = new Vector3();
  6536. const _intersectionPointWorld = new Vector3();
  6537. function Mesh( geometry, material ) {
  6538. Object3D.call( this );
  6539. this.type = 'Mesh';
  6540. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  6541. this.material = material !== undefined ? material : new MeshBasicMaterial();
  6542. this.updateMorphTargets();
  6543. }
  6544. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6545. constructor: Mesh,
  6546. isMesh: true,
  6547. copy: function ( source ) {
  6548. Object3D.prototype.copy.call( this, source );
  6549. if ( source.morphTargetInfluences !== undefined ) {
  6550. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6551. }
  6552. if ( source.morphTargetDictionary !== undefined ) {
  6553. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6554. }
  6555. this.material = source.material;
  6556. this.geometry = source.geometry;
  6557. return this;
  6558. },
  6559. updateMorphTargets: function () {
  6560. const geometry = this.geometry;
  6561. if ( geometry.isBufferGeometry ) {
  6562. const morphAttributes = geometry.morphAttributes;
  6563. const keys = Object.keys( morphAttributes );
  6564. if ( keys.length > 0 ) {
  6565. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6566. if ( morphAttribute !== undefined ) {
  6567. this.morphTargetInfluences = [];
  6568. this.morphTargetDictionary = {};
  6569. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6570. const name = morphAttribute[ m ].name || String( m );
  6571. this.morphTargetInfluences.push( 0 );
  6572. this.morphTargetDictionary[ name ] = m;
  6573. }
  6574. }
  6575. }
  6576. } else {
  6577. const morphTargets = geometry.morphTargets;
  6578. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6579. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6580. }
  6581. }
  6582. },
  6583. raycast: function ( raycaster, intersects ) {
  6584. const geometry = this.geometry;
  6585. const material = this.material;
  6586. const matrixWorld = this.matrixWorld;
  6587. if ( material === undefined ) return;
  6588. // Checking boundingSphere distance to ray
  6589. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6590. _sphere.copy( geometry.boundingSphere );
  6591. _sphere.applyMatrix4( matrixWorld );
  6592. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  6593. //
  6594. _inverseMatrix.getInverse( matrixWorld );
  6595. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  6596. // Check boundingBox before continuing
  6597. if ( geometry.boundingBox !== null ) {
  6598. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
  6599. }
  6600. let intersection;
  6601. if ( geometry.isBufferGeometry ) {
  6602. const index = geometry.index;
  6603. const position = geometry.attributes.position;
  6604. const morphPosition = geometry.morphAttributes.position;
  6605. const morphTargetsRelative = geometry.morphTargetsRelative;
  6606. const uv = geometry.attributes.uv;
  6607. const uv2 = geometry.attributes.uv2;
  6608. const groups = geometry.groups;
  6609. const drawRange = geometry.drawRange;
  6610. if ( index !== null ) {
  6611. // indexed buffer geometry
  6612. if ( Array.isArray( material ) ) {
  6613. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6614. const group = groups[ i ];
  6615. const groupMaterial = material[ group.materialIndex ];
  6616. const start = Math.max( group.start, drawRange.start );
  6617. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6618. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6619. const a = index.getX( j );
  6620. const b = index.getX( j + 1 );
  6621. const c = index.getX( j + 2 );
  6622. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6623. if ( intersection ) {
  6624. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6625. intersection.face.materialIndex = group.materialIndex;
  6626. intersects.push( intersection );
  6627. }
  6628. }
  6629. }
  6630. } else {
  6631. const start = Math.max( 0, drawRange.start );
  6632. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6633. for ( let i = start, il = end; i < il; i += 3 ) {
  6634. const a = index.getX( i );
  6635. const b = index.getX( i + 1 );
  6636. const c = index.getX( i + 2 );
  6637. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6638. if ( intersection ) {
  6639. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6640. intersects.push( intersection );
  6641. }
  6642. }
  6643. }
  6644. } else if ( position !== undefined ) {
  6645. // non-indexed buffer geometry
  6646. if ( Array.isArray( material ) ) {
  6647. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6648. const group = groups[ i ];
  6649. const groupMaterial = material[ group.materialIndex ];
  6650. const start = Math.max( group.start, drawRange.start );
  6651. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6652. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6653. const a = j;
  6654. const b = j + 1;
  6655. const c = j + 2;
  6656. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6657. if ( intersection ) {
  6658. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6659. intersection.face.materialIndex = group.materialIndex;
  6660. intersects.push( intersection );
  6661. }
  6662. }
  6663. }
  6664. } else {
  6665. const start = Math.max( 0, drawRange.start );
  6666. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6667. for ( let i = start, il = end; i < il; i += 3 ) {
  6668. const a = i;
  6669. const b = i + 1;
  6670. const c = i + 2;
  6671. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6672. if ( intersection ) {
  6673. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6674. intersects.push( intersection );
  6675. }
  6676. }
  6677. }
  6678. }
  6679. } else if ( geometry.isGeometry ) {
  6680. const isMultiMaterial = Array.isArray( material );
  6681. const vertices = geometry.vertices;
  6682. const faces = geometry.faces;
  6683. let uvs;
  6684. const faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  6685. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  6686. for ( let f = 0, fl = faces.length; f < fl; f ++ ) {
  6687. const face = faces[ f ];
  6688. const faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  6689. if ( faceMaterial === undefined ) continue;
  6690. const fvA = vertices[ face.a ];
  6691. const fvB = vertices[ face.b ];
  6692. const fvC = vertices[ face.c ];
  6693. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  6694. if ( intersection ) {
  6695. if ( uvs && uvs[ f ] ) {
  6696. const uvs_f = uvs[ f ];
  6697. _uvA.copy( uvs_f[ 0 ] );
  6698. _uvB.copy( uvs_f[ 1 ] );
  6699. _uvC.copy( uvs_f[ 2 ] );
  6700. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );
  6701. }
  6702. intersection.face = face;
  6703. intersection.faceIndex = f;
  6704. intersects.push( intersection );
  6705. }
  6706. }
  6707. }
  6708. }
  6709. } );
  6710. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6711. let intersect;
  6712. if ( material.side === BackSide ) {
  6713. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6714. } else {
  6715. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6716. }
  6717. if ( intersect === null ) return null;
  6718. _intersectionPointWorld.copy( point );
  6719. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6720. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6721. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6722. return {
  6723. distance: distance,
  6724. point: _intersectionPointWorld.clone(),
  6725. object: object
  6726. };
  6727. }
  6728. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6729. _vA.fromBufferAttribute( position, a );
  6730. _vB.fromBufferAttribute( position, b );
  6731. _vC.fromBufferAttribute( position, c );
  6732. const morphInfluences = object.morphTargetInfluences;
  6733. if ( material.morphTargets && morphPosition && morphInfluences ) {
  6734. _morphA.set( 0, 0, 0 );
  6735. _morphB.set( 0, 0, 0 );
  6736. _morphC.set( 0, 0, 0 );
  6737. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6738. const influence = morphInfluences[ i ];
  6739. const morphAttribute = morphPosition[ i ];
  6740. if ( influence === 0 ) continue;
  6741. _tempA.fromBufferAttribute( morphAttribute, a );
  6742. _tempB.fromBufferAttribute( morphAttribute, b );
  6743. _tempC.fromBufferAttribute( morphAttribute, c );
  6744. if ( morphTargetsRelative ) {
  6745. _morphA.addScaledVector( _tempA, influence );
  6746. _morphB.addScaledVector( _tempB, influence );
  6747. _morphC.addScaledVector( _tempC, influence );
  6748. } else {
  6749. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  6750. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  6751. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  6752. }
  6753. }
  6754. _vA.add( _morphA );
  6755. _vB.add( _morphB );
  6756. _vC.add( _morphC );
  6757. }
  6758. if ( object.isSkinnedMesh ) {
  6759. object.boneTransform( a, _vA );
  6760. object.boneTransform( b, _vB );
  6761. object.boneTransform( c, _vC );
  6762. }
  6763. const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  6764. if ( intersection ) {
  6765. if ( uv ) {
  6766. _uvA.fromBufferAttribute( uv, a );
  6767. _uvB.fromBufferAttribute( uv, b );
  6768. _uvC.fromBufferAttribute( uv, c );
  6769. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  6770. }
  6771. if ( uv2 ) {
  6772. _uvA.fromBufferAttribute( uv2, a );
  6773. _uvB.fromBufferAttribute( uv2, b );
  6774. _uvC.fromBufferAttribute( uv2, c );
  6775. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  6776. }
  6777. const face = new Face3( a, b, c );
  6778. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  6779. intersection.face = face;
  6780. }
  6781. return intersection;
  6782. }
  6783. let _geometryId = 0; // Geometry uses even numbers as Id
  6784. const _m1$3 = new Matrix4();
  6785. const _obj$1 = new Object3D();
  6786. const _offset$1 = new Vector3();
  6787. function Geometry() {
  6788. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  6789. this.uuid = MathUtils.generateUUID();
  6790. this.name = '';
  6791. this.type = 'Geometry';
  6792. this.vertices = [];
  6793. this.colors = [];
  6794. this.faces = [];
  6795. this.faceVertexUvs = [[]];
  6796. this.morphTargets = [];
  6797. this.morphNormals = [];
  6798. this.skinWeights = [];
  6799. this.skinIndices = [];
  6800. this.lineDistances = [];
  6801. this.boundingBox = null;
  6802. this.boundingSphere = null;
  6803. // update flags
  6804. this.elementsNeedUpdate = false;
  6805. this.verticesNeedUpdate = false;
  6806. this.uvsNeedUpdate = false;
  6807. this.normalsNeedUpdate = false;
  6808. this.colorsNeedUpdate = false;
  6809. this.lineDistancesNeedUpdate = false;
  6810. this.groupsNeedUpdate = false;
  6811. }
  6812. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6813. constructor: Geometry,
  6814. isGeometry: true,
  6815. applyMatrix4: function ( matrix ) {
  6816. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6817. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  6818. const vertex = this.vertices[ i ];
  6819. vertex.applyMatrix4( matrix );
  6820. }
  6821. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  6822. const face = this.faces[ i ];
  6823. face.normal.applyMatrix3( normalMatrix ).normalize();
  6824. for ( let j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6825. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6826. }
  6827. }
  6828. if ( this.boundingBox !== null ) {
  6829. this.computeBoundingBox();
  6830. }
  6831. if ( this.boundingSphere !== null ) {
  6832. this.computeBoundingSphere();
  6833. }
  6834. this.verticesNeedUpdate = true;
  6835. this.normalsNeedUpdate = true;
  6836. return this;
  6837. },
  6838. rotateX: function ( angle ) {
  6839. // rotate geometry around world x-axis
  6840. _m1$3.makeRotationX( angle );
  6841. this.applyMatrix4( _m1$3 );
  6842. return this;
  6843. },
  6844. rotateY: function ( angle ) {
  6845. // rotate geometry around world y-axis
  6846. _m1$3.makeRotationY( angle );
  6847. this.applyMatrix4( _m1$3 );
  6848. return this;
  6849. },
  6850. rotateZ: function ( angle ) {
  6851. // rotate geometry around world z-axis
  6852. _m1$3.makeRotationZ( angle );
  6853. this.applyMatrix4( _m1$3 );
  6854. return this;
  6855. },
  6856. translate: function ( x, y, z ) {
  6857. // translate geometry
  6858. _m1$3.makeTranslation( x, y, z );
  6859. this.applyMatrix4( _m1$3 );
  6860. return this;
  6861. },
  6862. scale: function ( x, y, z ) {
  6863. // scale geometry
  6864. _m1$3.makeScale( x, y, z );
  6865. this.applyMatrix4( _m1$3 );
  6866. return this;
  6867. },
  6868. lookAt: function ( vector ) {
  6869. _obj$1.lookAt( vector );
  6870. _obj$1.updateMatrix();
  6871. this.applyMatrix4( _obj$1.matrix );
  6872. return this;
  6873. },
  6874. fromBufferGeometry: function ( geometry ) {
  6875. const scope = this;
  6876. const index = geometry.index !== null ? geometry.index : undefined;
  6877. const attributes = geometry.attributes;
  6878. if ( attributes.position === undefined ) {
  6879. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  6880. return this;
  6881. }
  6882. const position = attributes.position;
  6883. const normal = attributes.normal;
  6884. const color = attributes.color;
  6885. const uv = attributes.uv;
  6886. const uv2 = attributes.uv2;
  6887. if ( uv2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  6888. for ( let i = 0; i < position.count; i ++ ) {
  6889. scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );
  6890. if ( color !== undefined ) {
  6891. scope.colors.push( new Color().fromBufferAttribute( color, i ) );
  6892. }
  6893. }
  6894. function addFace( a, b, c, materialIndex ) {
  6895. const vertexColors = ( color === undefined ) ? [] : [
  6896. scope.colors[ a ].clone(),
  6897. scope.colors[ b ].clone(),
  6898. scope.colors[ c ].clone()
  6899. ];
  6900. const vertexNormals = ( normal === undefined ) ? [] : [
  6901. new Vector3().fromBufferAttribute( normal, a ),
  6902. new Vector3().fromBufferAttribute( normal, b ),
  6903. new Vector3().fromBufferAttribute( normal, c )
  6904. ];
  6905. const face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  6906. scope.faces.push( face );
  6907. if ( uv !== undefined ) {
  6908. scope.faceVertexUvs[ 0 ].push( [
  6909. new Vector2().fromBufferAttribute( uv, a ),
  6910. new Vector2().fromBufferAttribute( uv, b ),
  6911. new Vector2().fromBufferAttribute( uv, c )
  6912. ] );
  6913. }
  6914. if ( uv2 !== undefined ) {
  6915. scope.faceVertexUvs[ 1 ].push( [
  6916. new Vector2().fromBufferAttribute( uv2, a ),
  6917. new Vector2().fromBufferAttribute( uv2, b ),
  6918. new Vector2().fromBufferAttribute( uv2, c )
  6919. ] );
  6920. }
  6921. }
  6922. const groups = geometry.groups;
  6923. if ( groups.length > 0 ) {
  6924. for ( let i = 0; i < groups.length; i ++ ) {
  6925. const group = groups[ i ];
  6926. const start = group.start;
  6927. const count = group.count;
  6928. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6929. if ( index !== undefined ) {
  6930. addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );
  6931. } else {
  6932. addFace( j, j + 1, j + 2, group.materialIndex );
  6933. }
  6934. }
  6935. }
  6936. } else {
  6937. if ( index !== undefined ) {
  6938. for ( let i = 0; i < index.count; i += 3 ) {
  6939. addFace( index.getX( i ), index.getX( i + 1 ), index.getX( i + 2 ) );
  6940. }
  6941. } else {
  6942. for ( let i = 0; i < position.count; i += 3 ) {
  6943. addFace( i, i + 1, i + 2 );
  6944. }
  6945. }
  6946. }
  6947. this.computeFaceNormals();
  6948. if ( geometry.boundingBox !== null ) {
  6949. this.boundingBox = geometry.boundingBox.clone();
  6950. }
  6951. if ( geometry.boundingSphere !== null ) {
  6952. this.boundingSphere = geometry.boundingSphere.clone();
  6953. }
  6954. return this;
  6955. },
  6956. center: function () {
  6957. this.computeBoundingBox();
  6958. this.boundingBox.getCenter( _offset$1 ).negate();
  6959. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  6960. return this;
  6961. },
  6962. normalize: function () {
  6963. this.computeBoundingSphere();
  6964. const center = this.boundingSphere.center;
  6965. const radius = this.boundingSphere.radius;
  6966. const s = radius === 0 ? 1 : 1.0 / radius;
  6967. const matrix = new Matrix4();
  6968. matrix.set(
  6969. s, 0, 0, - s * center.x,
  6970. 0, s, 0, - s * center.y,
  6971. 0, 0, s, - s * center.z,
  6972. 0, 0, 0, 1
  6973. );
  6974. this.applyMatrix4( matrix );
  6975. return this;
  6976. },
  6977. computeFaceNormals: function () {
  6978. const cb = new Vector3(), ab = new Vector3();
  6979. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6980. const face = this.faces[ f ];
  6981. const vA = this.vertices[ face.a ];
  6982. const vB = this.vertices[ face.b ];
  6983. const vC = this.vertices[ face.c ];
  6984. cb.subVectors( vC, vB );
  6985. ab.subVectors( vA, vB );
  6986. cb.cross( ab );
  6987. cb.normalize();
  6988. face.normal.copy( cb );
  6989. }
  6990. },
  6991. computeVertexNormals: function ( areaWeighted ) {
  6992. if ( areaWeighted === undefined ) areaWeighted = true;
  6993. const vertices = new Array( this.vertices.length );
  6994. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6995. vertices[ v ] = new Vector3();
  6996. }
  6997. if ( areaWeighted ) {
  6998. // vertex normals weighted by triangle areas
  6999. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7000. const cb = new Vector3(), ab = new Vector3();
  7001. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7002. const face = this.faces[ f ];
  7003. const vA = this.vertices[ face.a ];
  7004. const vB = this.vertices[ face.b ];
  7005. const vC = this.vertices[ face.c ];
  7006. cb.subVectors( vC, vB );
  7007. ab.subVectors( vA, vB );
  7008. cb.cross( ab );
  7009. vertices[ face.a ].add( cb );
  7010. vertices[ face.b ].add( cb );
  7011. vertices[ face.c ].add( cb );
  7012. }
  7013. } else {
  7014. this.computeFaceNormals();
  7015. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7016. const face = this.faces[ f ];
  7017. vertices[ face.a ].add( face.normal );
  7018. vertices[ face.b ].add( face.normal );
  7019. vertices[ face.c ].add( face.normal );
  7020. }
  7021. }
  7022. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7023. vertices[ v ].normalize();
  7024. }
  7025. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7026. const face = this.faces[ f ];
  7027. const vertexNormals = face.vertexNormals;
  7028. if ( vertexNormals.length === 3 ) {
  7029. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7030. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7031. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7032. } else {
  7033. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7034. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7035. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7036. }
  7037. }
  7038. if ( this.faces.length > 0 ) {
  7039. this.normalsNeedUpdate = true;
  7040. }
  7041. },
  7042. computeFlatVertexNormals: function () {
  7043. this.computeFaceNormals();
  7044. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7045. const face = this.faces[ f ];
  7046. const vertexNormals = face.vertexNormals;
  7047. if ( vertexNormals.length === 3 ) {
  7048. vertexNormals[ 0 ].copy( face.normal );
  7049. vertexNormals[ 1 ].copy( face.normal );
  7050. vertexNormals[ 2 ].copy( face.normal );
  7051. } else {
  7052. vertexNormals[ 0 ] = face.normal.clone();
  7053. vertexNormals[ 1 ] = face.normal.clone();
  7054. vertexNormals[ 2 ] = face.normal.clone();
  7055. }
  7056. }
  7057. if ( this.faces.length > 0 ) {
  7058. this.normalsNeedUpdate = true;
  7059. }
  7060. },
  7061. computeMorphNormals: function () {
  7062. // save original normals
  7063. // - create temp variables on first access
  7064. // otherwise just copy (for faster repeated calls)
  7065. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7066. const face = this.faces[ f ];
  7067. if ( ! face.__originalFaceNormal ) {
  7068. face.__originalFaceNormal = face.normal.clone();
  7069. } else {
  7070. face.__originalFaceNormal.copy( face.normal );
  7071. }
  7072. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7073. for ( let i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7074. if ( ! face.__originalVertexNormals[ i ] ) {
  7075. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7076. } else {
  7077. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7078. }
  7079. }
  7080. }
  7081. // use temp geometry to compute face and vertex normals for each morph
  7082. const tmpGeo = new Geometry();
  7083. tmpGeo.faces = this.faces;
  7084. for ( let i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7085. // create on first access
  7086. if ( ! this.morphNormals[ i ] ) {
  7087. this.morphNormals[ i ] = {};
  7088. this.morphNormals[ i ].faceNormals = [];
  7089. this.morphNormals[ i ].vertexNormals = [];
  7090. const dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7091. const dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7092. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7093. const faceNormal = new Vector3();
  7094. const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7095. dstNormalsFace.push( faceNormal );
  7096. dstNormalsVertex.push( vertexNormals );
  7097. }
  7098. }
  7099. const morphNormals = this.morphNormals[ i ];
  7100. // set vertices to morph target
  7101. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7102. // compute morph normals
  7103. tmpGeo.computeFaceNormals();
  7104. tmpGeo.computeVertexNormals();
  7105. // store morph normals
  7106. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7107. const face = this.faces[ f ];
  7108. const faceNormal = morphNormals.faceNormals[ f ];
  7109. const vertexNormals = morphNormals.vertexNormals[ f ];
  7110. faceNormal.copy( face.normal );
  7111. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7112. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7113. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7114. }
  7115. }
  7116. // restore original normals
  7117. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7118. const face = this.faces[ f ];
  7119. face.normal = face.__originalFaceNormal;
  7120. face.vertexNormals = face.__originalVertexNormals;
  7121. }
  7122. },
  7123. computeBoundingBox: function () {
  7124. if ( this.boundingBox === null ) {
  7125. this.boundingBox = new Box3();
  7126. }
  7127. this.boundingBox.setFromPoints( this.vertices );
  7128. },
  7129. computeBoundingSphere: function () {
  7130. if ( this.boundingSphere === null ) {
  7131. this.boundingSphere = new Sphere();
  7132. }
  7133. this.boundingSphere.setFromPoints( this.vertices );
  7134. },
  7135. merge: function ( geometry, matrix, materialIndexOffset ) {
  7136. if ( ! ( geometry && geometry.isGeometry ) ) {
  7137. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7138. return;
  7139. }
  7140. let normalMatrix;
  7141. const vertexOffset = this.vertices.length,
  7142. vertices1 = this.vertices,
  7143. vertices2 = geometry.vertices,
  7144. faces1 = this.faces,
  7145. faces2 = geometry.faces,
  7146. colors1 = this.colors,
  7147. colors2 = geometry.colors;
  7148. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7149. if ( matrix !== undefined ) {
  7150. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7151. }
  7152. // vertices
  7153. for ( let i = 0, il = vertices2.length; i < il; i ++ ) {
  7154. const vertex = vertices2[ i ];
  7155. const vertexCopy = vertex.clone();
  7156. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7157. vertices1.push( vertexCopy );
  7158. }
  7159. // colors
  7160. for ( let i = 0, il = colors2.length; i < il; i ++ ) {
  7161. colors1.push( colors2[ i ].clone() );
  7162. }
  7163. // faces
  7164. for ( let i = 0, il = faces2.length; i < il; i ++ ) {
  7165. const face = faces2[ i ];
  7166. let normal, color;
  7167. const faceVertexNormals = face.vertexNormals,
  7168. faceVertexColors = face.vertexColors;
  7169. const faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7170. faceCopy.normal.copy( face.normal );
  7171. if ( normalMatrix !== undefined ) {
  7172. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7173. }
  7174. for ( let j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7175. normal = faceVertexNormals[ j ].clone();
  7176. if ( normalMatrix !== undefined ) {
  7177. normal.applyMatrix3( normalMatrix ).normalize();
  7178. }
  7179. faceCopy.vertexNormals.push( normal );
  7180. }
  7181. faceCopy.color.copy( face.color );
  7182. for ( let j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7183. color = faceVertexColors[ j ];
  7184. faceCopy.vertexColors.push( color.clone() );
  7185. }
  7186. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7187. faces1.push( faceCopy );
  7188. }
  7189. // uvs
  7190. for ( let i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  7191. const faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  7192. if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];
  7193. for ( let j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  7194. const uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  7195. for ( let k = 0, kl = uvs2.length; k < kl; k ++ ) {
  7196. uvsCopy.push( uvs2[ k ].clone() );
  7197. }
  7198. this.faceVertexUvs[ i ].push( uvsCopy );
  7199. }
  7200. }
  7201. },
  7202. mergeMesh: function ( mesh ) {
  7203. if ( ! ( mesh && mesh.isMesh ) ) {
  7204. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7205. return;
  7206. }
  7207. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  7208. this.merge( mesh.geometry, mesh.matrix );
  7209. },
  7210. /*
  7211. * Checks for duplicate vertices with hashmap.
  7212. * Duplicated vertices are removed
  7213. * and faces' vertices are updated.
  7214. */
  7215. mergeVertices: function () {
  7216. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7217. const unique = [], changes = [];
  7218. const precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7219. const precision = Math.pow( 10, precisionPoints );
  7220. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  7221. const v = this.vertices[ i ];
  7222. const key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7223. if ( verticesMap[ key ] === undefined ) {
  7224. verticesMap[ key ] = i;
  7225. unique.push( this.vertices[ i ] );
  7226. changes[ i ] = unique.length - 1;
  7227. } else {
  7228. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7229. changes[ i ] = changes[ verticesMap[ key ] ];
  7230. }
  7231. }
  7232. // if faces are completely degenerate after merging vertices, we
  7233. // have to remove them from the geometry.
  7234. const faceIndicesToRemove = [];
  7235. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  7236. const face = this.faces[ i ];
  7237. face.a = changes[ face.a ];
  7238. face.b = changes[ face.b ];
  7239. face.c = changes[ face.c ];
  7240. const indices = [ face.a, face.b, face.c ];
  7241. // if any duplicate vertices are found in a Face3
  7242. // we have to remove the face as nothing can be saved
  7243. for ( let n = 0; n < 3; n ++ ) {
  7244. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7245. faceIndicesToRemove.push( i );
  7246. break;
  7247. }
  7248. }
  7249. }
  7250. for ( let i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7251. const idx = faceIndicesToRemove[ i ];
  7252. this.faces.splice( idx, 1 );
  7253. for ( let j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7254. this.faceVertexUvs[ j ].splice( idx, 1 );
  7255. }
  7256. }
  7257. // Use unique set of vertices
  7258. const diff = this.vertices.length - unique.length;
  7259. this.vertices = unique;
  7260. return diff;
  7261. },
  7262. setFromPoints: function ( points ) {
  7263. this.vertices = [];
  7264. for ( let i = 0, l = points.length; i < l; i ++ ) {
  7265. const point = points[ i ];
  7266. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  7267. }
  7268. return this;
  7269. },
  7270. sortFacesByMaterialIndex: function () {
  7271. const faces = this.faces;
  7272. const length = faces.length;
  7273. // tag faces
  7274. for ( let i = 0; i < length; i ++ ) {
  7275. faces[ i ]._id = i;
  7276. }
  7277. // sort faces
  7278. function materialIndexSort( a, b ) {
  7279. return a.materialIndex - b.materialIndex;
  7280. }
  7281. faces.sort( materialIndexSort );
  7282. // sort uvs
  7283. const uvs1 = this.faceVertexUvs[ 0 ];
  7284. const uvs2 = this.faceVertexUvs[ 1 ];
  7285. let newUvs1, newUvs2;
  7286. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7287. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7288. for ( let i = 0; i < length; i ++ ) {
  7289. const id = faces[ i ]._id;
  7290. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7291. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7292. }
  7293. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7294. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7295. },
  7296. toJSON: function () {
  7297. const data = {
  7298. metadata: {
  7299. version: 4.5,
  7300. type: 'Geometry',
  7301. generator: 'Geometry.toJSON'
  7302. }
  7303. };
  7304. // standard Geometry serialization
  7305. data.uuid = this.uuid;
  7306. data.type = this.type;
  7307. if ( this.name !== '' ) data.name = this.name;
  7308. if ( this.parameters !== undefined ) {
  7309. const parameters = this.parameters;
  7310. for ( const key in parameters ) {
  7311. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7312. }
  7313. return data;
  7314. }
  7315. const vertices = [];
  7316. for ( let i = 0; i < this.vertices.length; i ++ ) {
  7317. const vertex = this.vertices[ i ];
  7318. vertices.push( vertex.x, vertex.y, vertex.z );
  7319. }
  7320. const faces = [];
  7321. const normals = [];
  7322. const normalsHash = {};
  7323. const colors = [];
  7324. const colorsHash = {};
  7325. const uvs = [];
  7326. const uvsHash = {};
  7327. for ( let i = 0; i < this.faces.length; i ++ ) {
  7328. const face = this.faces[ i ];
  7329. const hasMaterial = true;
  7330. const hasFaceUv = false; // deprecated
  7331. const hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7332. const hasFaceNormal = face.normal.length() > 0;
  7333. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  7334. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7335. const hasFaceVertexColor = face.vertexColors.length > 0;
  7336. let faceType = 0;
  7337. faceType = setBit( faceType, 0, 0 ); // isQuad
  7338. faceType = setBit( faceType, 1, hasMaterial );
  7339. faceType = setBit( faceType, 2, hasFaceUv );
  7340. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7341. faceType = setBit( faceType, 4, hasFaceNormal );
  7342. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7343. faceType = setBit( faceType, 6, hasFaceColor );
  7344. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7345. faces.push( faceType );
  7346. faces.push( face.a, face.b, face.c );
  7347. faces.push( face.materialIndex );
  7348. if ( hasFaceVertexUv ) {
  7349. const faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7350. faces.push(
  7351. getUvIndex( faceVertexUvs[ 0 ] ),
  7352. getUvIndex( faceVertexUvs[ 1 ] ),
  7353. getUvIndex( faceVertexUvs[ 2 ] )
  7354. );
  7355. }
  7356. if ( hasFaceNormal ) {
  7357. faces.push( getNormalIndex( face.normal ) );
  7358. }
  7359. if ( hasFaceVertexNormal ) {
  7360. const vertexNormals = face.vertexNormals;
  7361. faces.push(
  7362. getNormalIndex( vertexNormals[ 0 ] ),
  7363. getNormalIndex( vertexNormals[ 1 ] ),
  7364. getNormalIndex( vertexNormals[ 2 ] )
  7365. );
  7366. }
  7367. if ( hasFaceColor ) {
  7368. faces.push( getColorIndex( face.color ) );
  7369. }
  7370. if ( hasFaceVertexColor ) {
  7371. const vertexColors = face.vertexColors;
  7372. faces.push(
  7373. getColorIndex( vertexColors[ 0 ] ),
  7374. getColorIndex( vertexColors[ 1 ] ),
  7375. getColorIndex( vertexColors[ 2 ] )
  7376. );
  7377. }
  7378. }
  7379. function setBit( value, position, enabled ) {
  7380. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7381. }
  7382. function getNormalIndex( normal ) {
  7383. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7384. if ( normalsHash[ hash ] !== undefined ) {
  7385. return normalsHash[ hash ];
  7386. }
  7387. normalsHash[ hash ] = normals.length / 3;
  7388. normals.push( normal.x, normal.y, normal.z );
  7389. return normalsHash[ hash ];
  7390. }
  7391. function getColorIndex( color ) {
  7392. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  7393. if ( colorsHash[ hash ] !== undefined ) {
  7394. return colorsHash[ hash ];
  7395. }
  7396. colorsHash[ hash ] = colors.length;
  7397. colors.push( color.getHex() );
  7398. return colorsHash[ hash ];
  7399. }
  7400. function getUvIndex( uv ) {
  7401. const hash = uv.x.toString() + uv.y.toString();
  7402. if ( uvsHash[ hash ] !== undefined ) {
  7403. return uvsHash[ hash ];
  7404. }
  7405. uvsHash[ hash ] = uvs.length / 2;
  7406. uvs.push( uv.x, uv.y );
  7407. return uvsHash[ hash ];
  7408. }
  7409. data.data = {};
  7410. data.data.vertices = vertices;
  7411. data.data.normals = normals;
  7412. if ( colors.length > 0 ) data.data.colors = colors;
  7413. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7414. data.data.faces = faces;
  7415. return data;
  7416. },
  7417. clone: function () {
  7418. /*
  7419. // Handle primitives
  7420. const parameters = this.parameters;
  7421. if ( parameters !== undefined ) {
  7422. const values = [];
  7423. for ( const key in parameters ) {
  7424. values.push( parameters[ key ] );
  7425. }
  7426. const geometry = Object.create( this.constructor.prototype );
  7427. this.constructor.apply( geometry, values );
  7428. return geometry;
  7429. }
  7430. return new this.constructor().copy( this );
  7431. */
  7432. return new Geometry().copy( this );
  7433. },
  7434. copy: function ( source ) {
  7435. // reset
  7436. this.vertices = [];
  7437. this.colors = [];
  7438. this.faces = [];
  7439. this.faceVertexUvs = [[]];
  7440. this.morphTargets = [];
  7441. this.morphNormals = [];
  7442. this.skinWeights = [];
  7443. this.skinIndices = [];
  7444. this.lineDistances = [];
  7445. this.boundingBox = null;
  7446. this.boundingSphere = null;
  7447. // name
  7448. this.name = source.name;
  7449. // vertices
  7450. const vertices = source.vertices;
  7451. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  7452. this.vertices.push( vertices[ i ].clone() );
  7453. }
  7454. // colors
  7455. const colors = source.colors;
  7456. for ( let i = 0, il = colors.length; i < il; i ++ ) {
  7457. this.colors.push( colors[ i ].clone() );
  7458. }
  7459. // faces
  7460. const faces = source.faces;
  7461. for ( let i = 0, il = faces.length; i < il; i ++ ) {
  7462. this.faces.push( faces[ i ].clone() );
  7463. }
  7464. // face vertex uvs
  7465. for ( let i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7466. const faceVertexUvs = source.faceVertexUvs[ i ];
  7467. if ( this.faceVertexUvs[ i ] === undefined ) {
  7468. this.faceVertexUvs[ i ] = [];
  7469. }
  7470. for ( let j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7471. const uvs = faceVertexUvs[ j ], uvsCopy = [];
  7472. for ( let k = 0, kl = uvs.length; k < kl; k ++ ) {
  7473. const uv = uvs[ k ];
  7474. uvsCopy.push( uv.clone() );
  7475. }
  7476. this.faceVertexUvs[ i ].push( uvsCopy );
  7477. }
  7478. }
  7479. // morph targets
  7480. const morphTargets = source.morphTargets;
  7481. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  7482. const morphTarget = {};
  7483. morphTarget.name = morphTargets[ i ].name;
  7484. // vertices
  7485. if ( morphTargets[ i ].vertices !== undefined ) {
  7486. morphTarget.vertices = [];
  7487. for ( let j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  7488. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  7489. }
  7490. }
  7491. // normals
  7492. if ( morphTargets[ i ].normals !== undefined ) {
  7493. morphTarget.normals = [];
  7494. for ( let j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  7495. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  7496. }
  7497. }
  7498. this.morphTargets.push( morphTarget );
  7499. }
  7500. // morph normals
  7501. const morphNormals = source.morphNormals;
  7502. for ( let i = 0, il = morphNormals.length; i < il; i ++ ) {
  7503. const morphNormal = {};
  7504. // vertex normals
  7505. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  7506. morphNormal.vertexNormals = [];
  7507. for ( let j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  7508. const srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  7509. const destVertexNormal = {};
  7510. destVertexNormal.a = srcVertexNormal.a.clone();
  7511. destVertexNormal.b = srcVertexNormal.b.clone();
  7512. destVertexNormal.c = srcVertexNormal.c.clone();
  7513. morphNormal.vertexNormals.push( destVertexNormal );
  7514. }
  7515. }
  7516. // face normals
  7517. if ( morphNormals[ i ].faceNormals !== undefined ) {
  7518. morphNormal.faceNormals = [];
  7519. for ( let j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  7520. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  7521. }
  7522. }
  7523. this.morphNormals.push( morphNormal );
  7524. }
  7525. // skin weights
  7526. const skinWeights = source.skinWeights;
  7527. for ( let i = 0, il = skinWeights.length; i < il; i ++ ) {
  7528. this.skinWeights.push( skinWeights[ i ].clone() );
  7529. }
  7530. // skin indices
  7531. const skinIndices = source.skinIndices;
  7532. for ( let i = 0, il = skinIndices.length; i < il; i ++ ) {
  7533. this.skinIndices.push( skinIndices[ i ].clone() );
  7534. }
  7535. // line distances
  7536. const lineDistances = source.lineDistances;
  7537. for ( let i = 0, il = lineDistances.length; i < il; i ++ ) {
  7538. this.lineDistances.push( lineDistances[ i ] );
  7539. }
  7540. // bounding box
  7541. const boundingBox = source.boundingBox;
  7542. if ( boundingBox !== null ) {
  7543. this.boundingBox = boundingBox.clone();
  7544. }
  7545. // bounding sphere
  7546. const boundingSphere = source.boundingSphere;
  7547. if ( boundingSphere !== null ) {
  7548. this.boundingSphere = boundingSphere.clone();
  7549. }
  7550. // update flags
  7551. this.elementsNeedUpdate = source.elementsNeedUpdate;
  7552. this.verticesNeedUpdate = source.verticesNeedUpdate;
  7553. this.uvsNeedUpdate = source.uvsNeedUpdate;
  7554. this.normalsNeedUpdate = source.normalsNeedUpdate;
  7555. this.colorsNeedUpdate = source.colorsNeedUpdate;
  7556. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  7557. this.groupsNeedUpdate = source.groupsNeedUpdate;
  7558. return this;
  7559. },
  7560. dispose: function () {
  7561. this.dispatchEvent( { type: 'dispose' } );
  7562. }
  7563. } );
  7564. // BoxGeometry
  7565. class BoxGeometry extends Geometry {
  7566. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  7567. super();
  7568. this.type = 'BoxGeometry';
  7569. this.parameters = {
  7570. width: width,
  7571. height: height,
  7572. depth: depth,
  7573. widthSegments: widthSegments,
  7574. heightSegments: heightSegments,
  7575. depthSegments: depthSegments
  7576. };
  7577. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  7578. this.mergeVertices();
  7579. }
  7580. }
  7581. // BoxBufferGeometry
  7582. class BoxBufferGeometry extends BufferGeometry {
  7583. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7584. super();
  7585. this.type = 'BoxBufferGeometry';
  7586. this.parameters = {
  7587. width: width,
  7588. height: height,
  7589. depth: depth,
  7590. widthSegments: widthSegments,
  7591. heightSegments: heightSegments,
  7592. depthSegments: depthSegments
  7593. };
  7594. const scope = this;
  7595. // segments
  7596. widthSegments = Math.floor( widthSegments );
  7597. heightSegments = Math.floor( heightSegments );
  7598. depthSegments = Math.floor( depthSegments );
  7599. // buffers
  7600. const indices = [];
  7601. const vertices = [];
  7602. const normals = [];
  7603. const uvs = [];
  7604. // helper variables
  7605. let numberOfVertices = 0;
  7606. let groupStart = 0;
  7607. // build each side of the box geometry
  7608. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7609. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7610. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7611. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7612. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7613. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7614. // build geometry
  7615. this.setIndex( indices );
  7616. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7617. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7618. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7619. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7620. const segmentWidth = width / gridX;
  7621. const segmentHeight = height / gridY;
  7622. const widthHalf = width / 2;
  7623. const heightHalf = height / 2;
  7624. const depthHalf = depth / 2;
  7625. const gridX1 = gridX + 1;
  7626. const gridY1 = gridY + 1;
  7627. let vertexCounter = 0;
  7628. let groupCount = 0;
  7629. const vector = new Vector3();
  7630. // generate vertices, normals and uvs
  7631. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7632. const y = iy * segmentHeight - heightHalf;
  7633. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7634. const x = ix * segmentWidth - widthHalf;
  7635. // set values to correct vector component
  7636. vector[ u ] = x * udir;
  7637. vector[ v ] = y * vdir;
  7638. vector[ w ] = depthHalf;
  7639. // now apply vector to vertex buffer
  7640. vertices.push( vector.x, vector.y, vector.z );
  7641. // set values to correct vector component
  7642. vector[ u ] = 0;
  7643. vector[ v ] = 0;
  7644. vector[ w ] = depth > 0 ? 1 : - 1;
  7645. // now apply vector to normal buffer
  7646. normals.push( vector.x, vector.y, vector.z );
  7647. // uvs
  7648. uvs.push( ix / gridX );
  7649. uvs.push( 1 - ( iy / gridY ) );
  7650. // counters
  7651. vertexCounter += 1;
  7652. }
  7653. }
  7654. // indices
  7655. // 1. you need three indices to draw a single face
  7656. // 2. a single segment consists of two faces
  7657. // 3. so we need to generate six (2*3) indices per segment
  7658. for ( let iy = 0; iy < gridY; iy ++ ) {
  7659. for ( let ix = 0; ix < gridX; ix ++ ) {
  7660. const a = numberOfVertices + ix + gridX1 * iy;
  7661. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7662. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7663. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7664. // faces
  7665. indices.push( a, b, d );
  7666. indices.push( b, c, d );
  7667. // increase counter
  7668. groupCount += 6;
  7669. }
  7670. }
  7671. // add a group to the geometry. this will ensure multi material support
  7672. scope.addGroup( groupStart, groupCount, materialIndex );
  7673. // calculate new start value for groups
  7674. groupStart += groupCount;
  7675. // update total number of vertices
  7676. numberOfVertices += vertexCounter;
  7677. }
  7678. }
  7679. }
  7680. /**
  7681. * Uniform Utilities
  7682. */
  7683. function cloneUniforms( src ) {
  7684. const dst = {};
  7685. for ( const u in src ) {
  7686. dst[ u ] = {};
  7687. for ( const p in src[ u ] ) {
  7688. const property = src[ u ][ p ];
  7689. if ( property && ( property.isColor ||
  7690. property.isMatrix3 || property.isMatrix4 ||
  7691. property.isVector2 || property.isVector3 || property.isVector4 ||
  7692. property.isTexture ) ) {
  7693. dst[ u ][ p ] = property.clone();
  7694. } else if ( Array.isArray( property ) ) {
  7695. dst[ u ][ p ] = property.slice();
  7696. } else {
  7697. dst[ u ][ p ] = property;
  7698. }
  7699. }
  7700. }
  7701. return dst;
  7702. }
  7703. function mergeUniforms( uniforms ) {
  7704. const merged = {};
  7705. for ( let u = 0; u < uniforms.length; u ++ ) {
  7706. const tmp = cloneUniforms( uniforms[ u ] );
  7707. for ( const p in tmp ) {
  7708. merged[ p ] = tmp[ p ];
  7709. }
  7710. }
  7711. return merged;
  7712. }
  7713. // Legacy
  7714. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7715. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7716. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7717. /**
  7718. * parameters = {
  7719. * defines: { "label" : "value" },
  7720. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7721. *
  7722. * fragmentShader: <string>,
  7723. * vertexShader: <string>,
  7724. *
  7725. * wireframe: <boolean>,
  7726. * wireframeLinewidth: <float>,
  7727. *
  7728. * lights: <bool>,
  7729. *
  7730. * skinning: <bool>,
  7731. * morphTargets: <bool>,
  7732. * morphNormals: <bool>
  7733. * }
  7734. */
  7735. function ShaderMaterial( parameters ) {
  7736. Material.call( this );
  7737. this.type = 'ShaderMaterial';
  7738. this.defines = {};
  7739. this.uniforms = {};
  7740. this.vertexShader = default_vertex;
  7741. this.fragmentShader = default_fragment;
  7742. this.linewidth = 1;
  7743. this.wireframe = false;
  7744. this.wireframeLinewidth = 1;
  7745. this.fog = false; // set to use scene fog
  7746. this.lights = false; // set to use scene lights
  7747. this.clipping = false; // set to use user-defined clipping planes
  7748. this.skinning = false; // set to use skinning attribute streams
  7749. this.morphTargets = false; // set to use morph targets
  7750. this.morphNormals = false; // set to use morph normals
  7751. this.extensions = {
  7752. derivatives: false, // set to use derivatives
  7753. fragDepth: false, // set to use fragment depth values
  7754. drawBuffers: false, // set to use draw buffers
  7755. shaderTextureLOD: false // set to use shader texture LOD
  7756. };
  7757. // When rendered geometry doesn't include these attributes but the material does,
  7758. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7759. this.defaultAttributeValues = {
  7760. 'color': [ 1, 1, 1 ],
  7761. 'uv': [ 0, 0 ],
  7762. 'uv2': [ 0, 0 ]
  7763. };
  7764. this.index0AttributeName = undefined;
  7765. this.uniformsNeedUpdate = false;
  7766. this.glslVersion = null;
  7767. if ( parameters !== undefined ) {
  7768. if ( parameters.attributes !== undefined ) {
  7769. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  7770. }
  7771. this.setValues( parameters );
  7772. }
  7773. }
  7774. ShaderMaterial.prototype = Object.create( Material.prototype );
  7775. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7776. ShaderMaterial.prototype.isShaderMaterial = true;
  7777. ShaderMaterial.prototype.copy = function ( source ) {
  7778. Material.prototype.copy.call( this, source );
  7779. this.fragmentShader = source.fragmentShader;
  7780. this.vertexShader = source.vertexShader;
  7781. this.uniforms = cloneUniforms( source.uniforms );
  7782. this.defines = Object.assign( {}, source.defines );
  7783. this.wireframe = source.wireframe;
  7784. this.wireframeLinewidth = source.wireframeLinewidth;
  7785. this.lights = source.lights;
  7786. this.clipping = source.clipping;
  7787. this.skinning = source.skinning;
  7788. this.morphTargets = source.morphTargets;
  7789. this.morphNormals = source.morphNormals;
  7790. this.extensions = Object.assign( {}, source.extensions );
  7791. this.glslVersion = source.glslVersion;
  7792. return this;
  7793. };
  7794. ShaderMaterial.prototype.toJSON = function ( meta ) {
  7795. const data = Material.prototype.toJSON.call( this, meta );
  7796. data.glslVersion = this.glslVersion;
  7797. data.uniforms = {};
  7798. for ( const name in this.uniforms ) {
  7799. const uniform = this.uniforms[ name ];
  7800. const value = uniform.value;
  7801. if ( value && value.isTexture ) {
  7802. data.uniforms[ name ] = {
  7803. type: 't',
  7804. value: value.toJSON( meta ).uuid
  7805. };
  7806. } else if ( value && value.isColor ) {
  7807. data.uniforms[ name ] = {
  7808. type: 'c',
  7809. value: value.getHex()
  7810. };
  7811. } else if ( value && value.isVector2 ) {
  7812. data.uniforms[ name ] = {
  7813. type: 'v2',
  7814. value: value.toArray()
  7815. };
  7816. } else if ( value && value.isVector3 ) {
  7817. data.uniforms[ name ] = {
  7818. type: 'v3',
  7819. value: value.toArray()
  7820. };
  7821. } else if ( value && value.isVector4 ) {
  7822. data.uniforms[ name ] = {
  7823. type: 'v4',
  7824. value: value.toArray()
  7825. };
  7826. } else if ( value && value.isMatrix3 ) {
  7827. data.uniforms[ name ] = {
  7828. type: 'm3',
  7829. value: value.toArray()
  7830. };
  7831. } else if ( value && value.isMatrix4 ) {
  7832. data.uniforms[ name ] = {
  7833. type: 'm4',
  7834. value: value.toArray()
  7835. };
  7836. } else {
  7837. data.uniforms[ name ] = {
  7838. value: value
  7839. };
  7840. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7841. }
  7842. }
  7843. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7844. data.vertexShader = this.vertexShader;
  7845. data.fragmentShader = this.fragmentShader;
  7846. const extensions = {};
  7847. for ( const key in this.extensions ) {
  7848. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7849. }
  7850. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7851. return data;
  7852. };
  7853. function Camera() {
  7854. Object3D.call( this );
  7855. this.type = 'Camera';
  7856. this.matrixWorldInverse = new Matrix4();
  7857. this.projectionMatrix = new Matrix4();
  7858. this.projectionMatrixInverse = new Matrix4();
  7859. }
  7860. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7861. constructor: Camera,
  7862. isCamera: true,
  7863. copy: function ( source, recursive ) {
  7864. Object3D.prototype.copy.call( this, source, recursive );
  7865. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7866. this.projectionMatrix.copy( source.projectionMatrix );
  7867. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7868. return this;
  7869. },
  7870. getWorldDirection: function ( target ) {
  7871. if ( target === undefined ) {
  7872. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  7873. target = new Vector3();
  7874. }
  7875. this.updateMatrixWorld( true );
  7876. const e = this.matrixWorld.elements;
  7877. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7878. },
  7879. updateMatrixWorld: function ( force ) {
  7880. Object3D.prototype.updateMatrixWorld.call( this, force );
  7881. this.matrixWorldInverse.getInverse( this.matrixWorld );
  7882. },
  7883. updateWorldMatrix: function ( updateParents, updateChildren ) {
  7884. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  7885. this.matrixWorldInverse.getInverse( this.matrixWorld );
  7886. },
  7887. clone: function () {
  7888. return new this.constructor().copy( this );
  7889. }
  7890. } );
  7891. function PerspectiveCamera( fov, aspect, near, far ) {
  7892. Camera.call( this );
  7893. this.type = 'PerspectiveCamera';
  7894. this.fov = fov !== undefined ? fov : 50;
  7895. this.zoom = 1;
  7896. this.near = near !== undefined ? near : 0.1;
  7897. this.far = far !== undefined ? far : 2000;
  7898. this.focus = 10;
  7899. this.aspect = aspect !== undefined ? aspect : 1;
  7900. this.view = null;
  7901. this.filmGauge = 35; // width of the film (default in millimeters)
  7902. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7903. this.updateProjectionMatrix();
  7904. }
  7905. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  7906. constructor: PerspectiveCamera,
  7907. isPerspectiveCamera: true,
  7908. copy: function ( source, recursive ) {
  7909. Camera.prototype.copy.call( this, source, recursive );
  7910. this.fov = source.fov;
  7911. this.zoom = source.zoom;
  7912. this.near = source.near;
  7913. this.far = source.far;
  7914. this.focus = source.focus;
  7915. this.aspect = source.aspect;
  7916. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7917. this.filmGauge = source.filmGauge;
  7918. this.filmOffset = source.filmOffset;
  7919. return this;
  7920. },
  7921. /**
  7922. * Sets the FOV by focal length in respect to the current .filmGauge.
  7923. *
  7924. * The default film gauge is 35, so that the focal length can be specified for
  7925. * a 35mm (full frame) camera.
  7926. *
  7927. * Values for focal length and film gauge must have the same unit.
  7928. */
  7929. setFocalLength: function ( focalLength ) {
  7930. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7931. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7932. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  7933. this.updateProjectionMatrix();
  7934. },
  7935. /**
  7936. * Calculates the focal length from the current .fov and .filmGauge.
  7937. */
  7938. getFocalLength: function () {
  7939. const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  7940. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7941. },
  7942. getEffectiveFOV: function () {
  7943. return MathUtils.RAD2DEG * 2 * Math.atan(
  7944. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7945. },
  7946. getFilmWidth: function () {
  7947. // film not completely covered in portrait format (aspect < 1)
  7948. return this.filmGauge * Math.min( this.aspect, 1 );
  7949. },
  7950. getFilmHeight: function () {
  7951. // film not completely covered in landscape format (aspect > 1)
  7952. return this.filmGauge / Math.max( this.aspect, 1 );
  7953. },
  7954. /**
  7955. * Sets an offset in a larger frustum. This is useful for multi-window or
  7956. * multi-monitor/multi-machine setups.
  7957. *
  7958. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7959. * the monitors are in grid like this
  7960. *
  7961. * +---+---+---+
  7962. * | A | B | C |
  7963. * +---+---+---+
  7964. * | D | E | F |
  7965. * +---+---+---+
  7966. *
  7967. * then for each monitor you would call it like this
  7968. *
  7969. * const w = 1920;
  7970. * const h = 1080;
  7971. * const fullWidth = w * 3;
  7972. * const fullHeight = h * 2;
  7973. *
  7974. * --A--
  7975. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7976. * --B--
  7977. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7978. * --C--
  7979. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7980. * --D--
  7981. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7982. * --E--
  7983. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7984. * --F--
  7985. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7986. *
  7987. * Note there is no reason monitors have to be the same size or in a grid.
  7988. */
  7989. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  7990. this.aspect = fullWidth / fullHeight;
  7991. if ( this.view === null ) {
  7992. this.view = {
  7993. enabled: true,
  7994. fullWidth: 1,
  7995. fullHeight: 1,
  7996. offsetX: 0,
  7997. offsetY: 0,
  7998. width: 1,
  7999. height: 1
  8000. };
  8001. }
  8002. this.view.enabled = true;
  8003. this.view.fullWidth = fullWidth;
  8004. this.view.fullHeight = fullHeight;
  8005. this.view.offsetX = x;
  8006. this.view.offsetY = y;
  8007. this.view.width = width;
  8008. this.view.height = height;
  8009. this.updateProjectionMatrix();
  8010. },
  8011. clearViewOffset: function () {
  8012. if ( this.view !== null ) {
  8013. this.view.enabled = false;
  8014. }
  8015. this.updateProjectionMatrix();
  8016. },
  8017. updateProjectionMatrix: function () {
  8018. const near = this.near;
  8019. let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom;
  8020. let height = 2 * top;
  8021. let width = this.aspect * height;
  8022. let left = - 0.5 * width;
  8023. const view = this.view;
  8024. if ( this.view !== null && this.view.enabled ) {
  8025. const fullWidth = view.fullWidth,
  8026. fullHeight = view.fullHeight;
  8027. left += view.offsetX * width / fullWidth;
  8028. top -= view.offsetY * height / fullHeight;
  8029. width *= view.width / fullWidth;
  8030. height *= view.height / fullHeight;
  8031. }
  8032. const skew = this.filmOffset;
  8033. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  8034. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  8035. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  8036. },
  8037. toJSON: function ( meta ) {
  8038. const data = Object3D.prototype.toJSON.call( this, meta );
  8039. data.object.fov = this.fov;
  8040. data.object.zoom = this.zoom;
  8041. data.object.near = this.near;
  8042. data.object.far = this.far;
  8043. data.object.focus = this.focus;
  8044. data.object.aspect = this.aspect;
  8045. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  8046. data.object.filmGauge = this.filmGauge;
  8047. data.object.filmOffset = this.filmOffset;
  8048. return data;
  8049. }
  8050. } );
  8051. const fov = 90, aspect = 1;
  8052. function CubeCamera( near, far, renderTarget ) {
  8053. Object3D.call( this );
  8054. this.type = 'CubeCamera';
  8055. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  8056. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  8057. return;
  8058. }
  8059. this.renderTarget = renderTarget;
  8060. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  8061. cameraPX.layers = this.layers;
  8062. cameraPX.up.set( 0, - 1, 0 );
  8063. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  8064. this.add( cameraPX );
  8065. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  8066. cameraNX.layers = this.layers;
  8067. cameraNX.up.set( 0, - 1, 0 );
  8068. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  8069. this.add( cameraNX );
  8070. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  8071. cameraPY.layers = this.layers;
  8072. cameraPY.up.set( 0, 0, 1 );
  8073. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  8074. this.add( cameraPY );
  8075. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  8076. cameraNY.layers = this.layers;
  8077. cameraNY.up.set( 0, 0, - 1 );
  8078. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  8079. this.add( cameraNY );
  8080. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  8081. cameraPZ.layers = this.layers;
  8082. cameraPZ.up.set( 0, - 1, 0 );
  8083. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  8084. this.add( cameraPZ );
  8085. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  8086. cameraNZ.layers = this.layers;
  8087. cameraNZ.up.set( 0, - 1, 0 );
  8088. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  8089. this.add( cameraNZ );
  8090. this.update = function ( renderer, scene ) {
  8091. if ( this.parent === null ) this.updateMatrixWorld();
  8092. const currentXrEnabled = renderer.xr.enabled;
  8093. const currentRenderTarget = renderer.getRenderTarget();
  8094. renderer.xr.enabled = false;
  8095. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8096. renderTarget.texture.generateMipmaps = false;
  8097. renderer.setRenderTarget( renderTarget, 0 );
  8098. renderer.render( scene, cameraPX );
  8099. renderer.setRenderTarget( renderTarget, 1 );
  8100. renderer.render( scene, cameraNX );
  8101. renderer.setRenderTarget( renderTarget, 2 );
  8102. renderer.render( scene, cameraPY );
  8103. renderer.setRenderTarget( renderTarget, 3 );
  8104. renderer.render( scene, cameraNY );
  8105. renderer.setRenderTarget( renderTarget, 4 );
  8106. renderer.render( scene, cameraPZ );
  8107. renderTarget.texture.generateMipmaps = generateMipmaps;
  8108. renderer.setRenderTarget( renderTarget, 5 );
  8109. renderer.render( scene, cameraNZ );
  8110. renderer.setRenderTarget( currentRenderTarget );
  8111. renderer.xr.enabled = currentXrEnabled;
  8112. };
  8113. this.clear = function ( renderer, color, depth, stencil ) {
  8114. const currentRenderTarget = renderer.getRenderTarget();
  8115. for ( let i = 0; i < 6; i ++ ) {
  8116. renderer.setRenderTarget( renderTarget, i );
  8117. renderer.clear( color, depth, stencil );
  8118. }
  8119. renderer.setRenderTarget( currentRenderTarget );
  8120. };
  8121. }
  8122. CubeCamera.prototype = Object.create( Object3D.prototype );
  8123. CubeCamera.prototype.constructor = CubeCamera;
  8124. function WebGLCubeRenderTarget( size, options, dummy ) {
  8125. if ( Number.isInteger( options ) ) {
  8126. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  8127. options = dummy;
  8128. }
  8129. WebGLRenderTarget.call( this, size, size, options );
  8130. this.texture.isWebGLCubeRenderTargetTexture = true; // HACK Why is texture not a CubeTexture?
  8131. }
  8132. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  8133. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8134. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8135. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  8136. this.texture.type = texture.type;
  8137. this.texture.format = RGBAFormat; // see #18859
  8138. this.texture.encoding = texture.encoding;
  8139. this.texture.generateMipmaps = texture.generateMipmaps;
  8140. this.texture.minFilter = texture.minFilter;
  8141. this.texture.magFilter = texture.magFilter;
  8142. const shader = {
  8143. uniforms: {
  8144. tEquirect: { value: null },
  8145. },
  8146. vertexShader: /* glsl */`
  8147. varying vec3 vWorldDirection;
  8148. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8149. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8150. }
  8151. void main() {
  8152. vWorldDirection = transformDirection( position, modelMatrix );
  8153. #include <begin_vertex>
  8154. #include <project_vertex>
  8155. }
  8156. `,
  8157. fragmentShader: /* glsl */`
  8158. uniform sampler2D tEquirect;
  8159. varying vec3 vWorldDirection;
  8160. #include <common>
  8161. void main() {
  8162. vec3 direction = normalize( vWorldDirection );
  8163. vec2 sampleUV = equirectUv( direction );
  8164. gl_FragColor = texture2D( tEquirect, sampleUV );
  8165. }
  8166. `
  8167. };
  8168. const geometry = new BoxBufferGeometry( 5, 5, 5 );
  8169. const material = new ShaderMaterial( {
  8170. name: 'CubemapFromEquirect',
  8171. uniforms: cloneUniforms( shader.uniforms ),
  8172. vertexShader: shader.vertexShader,
  8173. fragmentShader: shader.fragmentShader,
  8174. side: BackSide,
  8175. blending: NoBlending
  8176. } );
  8177. material.uniforms.tEquirect.value = texture;
  8178. const mesh = new Mesh( geometry, material );
  8179. const currentMinFilter = texture.minFilter;
  8180. // Avoid blurred poles
  8181. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  8182. const camera = new CubeCamera( 1, 10, this );
  8183. camera.update( renderer, mesh );
  8184. texture.minFilter = currentMinFilter;
  8185. mesh.geometry.dispose();
  8186. mesh.material.dispose();
  8187. return this;
  8188. };
  8189. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  8190. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8191. this.image = { data: data || null, width: width || 1, height: height || 1 };
  8192. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8193. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8194. this.generateMipmaps = false;
  8195. this.flipY = false;
  8196. this.unpackAlignment = 1;
  8197. this.needsUpdate = true;
  8198. }
  8199. DataTexture.prototype = Object.create( Texture.prototype );
  8200. DataTexture.prototype.constructor = DataTexture;
  8201. DataTexture.prototype.isDataTexture = true;
  8202. const _sphere$1 = /*@__PURE__*/ new Sphere();
  8203. const _vector$5 = /*@__PURE__*/ new Vector3();
  8204. class Frustum {
  8205. constructor( p0, p1, p2, p3, p4, p5 ) {
  8206. this.planes = [
  8207. ( p0 !== undefined ) ? p0 : new Plane(),
  8208. ( p1 !== undefined ) ? p1 : new Plane(),
  8209. ( p2 !== undefined ) ? p2 : new Plane(),
  8210. ( p3 !== undefined ) ? p3 : new Plane(),
  8211. ( p4 !== undefined ) ? p4 : new Plane(),
  8212. ( p5 !== undefined ) ? p5 : new Plane()
  8213. ];
  8214. }
  8215. set( p0, p1, p2, p3, p4, p5 ) {
  8216. const planes = this.planes;
  8217. planes[ 0 ].copy( p0 );
  8218. planes[ 1 ].copy( p1 );
  8219. planes[ 2 ].copy( p2 );
  8220. planes[ 3 ].copy( p3 );
  8221. planes[ 4 ].copy( p4 );
  8222. planes[ 5 ].copy( p5 );
  8223. return this;
  8224. }
  8225. clone() {
  8226. return new this.constructor().copy( this );
  8227. }
  8228. copy( frustum ) {
  8229. const planes = this.planes;
  8230. for ( let i = 0; i < 6; i ++ ) {
  8231. planes[ i ].copy( frustum.planes[ i ] );
  8232. }
  8233. return this;
  8234. }
  8235. setFromProjectionMatrix( m ) {
  8236. const planes = this.planes;
  8237. const me = m.elements;
  8238. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8239. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8240. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8241. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8242. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8243. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8244. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8245. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8246. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8247. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8248. return this;
  8249. }
  8250. intersectsObject( object ) {
  8251. const geometry = object.geometry;
  8252. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8253. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8254. return this.intersectsSphere( _sphere$1 );
  8255. }
  8256. intersectsSprite( sprite ) {
  8257. _sphere$1.center.set( 0, 0, 0 );
  8258. _sphere$1.radius = 0.7071067811865476;
  8259. _sphere$1.applyMatrix4( sprite.matrixWorld );
  8260. return this.intersectsSphere( _sphere$1 );
  8261. }
  8262. intersectsSphere( sphere ) {
  8263. const planes = this.planes;
  8264. const center = sphere.center;
  8265. const negRadius = - sphere.radius;
  8266. for ( let i = 0; i < 6; i ++ ) {
  8267. const distance = planes[ i ].distanceToPoint( center );
  8268. if ( distance < negRadius ) {
  8269. return false;
  8270. }
  8271. }
  8272. return true;
  8273. }
  8274. intersectsBox( box ) {
  8275. const planes = this.planes;
  8276. for ( let i = 0; i < 6; i ++ ) {
  8277. const plane = planes[ i ];
  8278. // corner at max distance
  8279. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8280. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8281. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8282. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  8283. return false;
  8284. }
  8285. }
  8286. return true;
  8287. }
  8288. containsPoint( point ) {
  8289. const planes = this.planes;
  8290. for ( let i = 0; i < 6; i ++ ) {
  8291. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8292. return false;
  8293. }
  8294. }
  8295. return true;
  8296. }
  8297. }
  8298. function WebGLAnimation() {
  8299. let context = null;
  8300. let isAnimating = false;
  8301. let animationLoop = null;
  8302. let requestId = null;
  8303. function onAnimationFrame( time, frame ) {
  8304. animationLoop( time, frame );
  8305. requestId = context.requestAnimationFrame( onAnimationFrame );
  8306. }
  8307. return {
  8308. start: function () {
  8309. if ( isAnimating === true ) return;
  8310. if ( animationLoop === null ) return;
  8311. requestId = context.requestAnimationFrame( onAnimationFrame );
  8312. isAnimating = true;
  8313. },
  8314. stop: function () {
  8315. context.cancelAnimationFrame( requestId );
  8316. isAnimating = false;
  8317. },
  8318. setAnimationLoop: function ( callback ) {
  8319. animationLoop = callback;
  8320. },
  8321. setContext: function ( value ) {
  8322. context = value;
  8323. }
  8324. };
  8325. }
  8326. function WebGLAttributes( gl, capabilities ) {
  8327. const isWebGL2 = capabilities.isWebGL2;
  8328. const buffers = new WeakMap();
  8329. function createBuffer( attribute, bufferType ) {
  8330. const array = attribute.array;
  8331. const usage = attribute.usage;
  8332. const buffer = gl.createBuffer();
  8333. gl.bindBuffer( bufferType, buffer );
  8334. gl.bufferData( bufferType, array, usage );
  8335. attribute.onUploadCallback();
  8336. let type = 5126;
  8337. if ( array instanceof Float32Array ) {
  8338. type = 5126;
  8339. } else if ( array instanceof Float64Array ) {
  8340. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8341. } else if ( array instanceof Uint16Array ) {
  8342. type = 5123;
  8343. } else if ( array instanceof Int16Array ) {
  8344. type = 5122;
  8345. } else if ( array instanceof Uint32Array ) {
  8346. type = 5125;
  8347. } else if ( array instanceof Int32Array ) {
  8348. type = 5124;
  8349. } else if ( array instanceof Int8Array ) {
  8350. type = 5120;
  8351. } else if ( array instanceof Uint8Array ) {
  8352. type = 5121;
  8353. }
  8354. return {
  8355. buffer: buffer,
  8356. type: type,
  8357. bytesPerElement: array.BYTES_PER_ELEMENT,
  8358. version: attribute.version
  8359. };
  8360. }
  8361. function updateBuffer( buffer, attribute, bufferType ) {
  8362. const array = attribute.array;
  8363. const updateRange = attribute.updateRange;
  8364. gl.bindBuffer( bufferType, buffer );
  8365. if ( updateRange.count === - 1 ) {
  8366. // Not using update ranges
  8367. gl.bufferSubData( bufferType, 0, array );
  8368. } else {
  8369. if ( isWebGL2 ) {
  8370. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8371. array, updateRange.offset, updateRange.count );
  8372. } else {
  8373. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8374. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8375. }
  8376. updateRange.count = - 1; // reset range
  8377. }
  8378. }
  8379. //
  8380. function get( attribute ) {
  8381. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8382. return buffers.get( attribute );
  8383. }
  8384. function remove( attribute ) {
  8385. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8386. const data = buffers.get( attribute );
  8387. if ( data ) {
  8388. gl.deleteBuffer( data.buffer );
  8389. buffers.delete( attribute );
  8390. }
  8391. }
  8392. function update( attribute, bufferType ) {
  8393. if ( attribute.isGLBufferAttribute ) {
  8394. var cached = buffers.get( attribute );
  8395. if ( ! cached || cached.version < attribute.version ) {
  8396. buffers.set( attribute, {
  8397. buffer: attribute.buffer,
  8398. type: attribute.type,
  8399. bytesPerElement: attribute.elementSize,
  8400. version: attribute.version
  8401. } );
  8402. }
  8403. return;
  8404. }
  8405. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8406. const data = buffers.get( attribute );
  8407. if ( data === undefined ) {
  8408. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8409. } else if ( data.version < attribute.version ) {
  8410. updateBuffer( data.buffer, attribute, bufferType );
  8411. data.version = attribute.version;
  8412. }
  8413. }
  8414. return {
  8415. get: get,
  8416. remove: remove,
  8417. update: update
  8418. };
  8419. }
  8420. // PlaneGeometry
  8421. class PlaneGeometry extends Geometry {
  8422. constructor( width, height, widthSegments, heightSegments ) {
  8423. super();
  8424. this.type = 'PlaneGeometry';
  8425. this.parameters = {
  8426. width: width,
  8427. height: height,
  8428. widthSegments: widthSegments,
  8429. heightSegments: heightSegments
  8430. };
  8431. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  8432. this.mergeVertices();
  8433. }
  8434. }
  8435. // PlaneBufferGeometry
  8436. class PlaneBufferGeometry extends BufferGeometry {
  8437. constructor( width, height, widthSegments, heightSegments ) {
  8438. super();
  8439. this.type = 'PlaneBufferGeometry';
  8440. this.parameters = {
  8441. width: width,
  8442. height: height,
  8443. widthSegments: widthSegments,
  8444. heightSegments: heightSegments
  8445. };
  8446. width = width || 1;
  8447. height = height || 1;
  8448. const width_half = width / 2;
  8449. const height_half = height / 2;
  8450. const gridX = Math.floor( widthSegments ) || 1;
  8451. const gridY = Math.floor( heightSegments ) || 1;
  8452. const gridX1 = gridX + 1;
  8453. const gridY1 = gridY + 1;
  8454. const segment_width = width / gridX;
  8455. const segment_height = height / gridY;
  8456. // buffers
  8457. const indices = [];
  8458. const vertices = [];
  8459. const normals = [];
  8460. const uvs = [];
  8461. // generate vertices, normals and uvs
  8462. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8463. const y = iy * segment_height - height_half;
  8464. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8465. const x = ix * segment_width - width_half;
  8466. vertices.push( x, - y, 0 );
  8467. normals.push( 0, 0, 1 );
  8468. uvs.push( ix / gridX );
  8469. uvs.push( 1 - ( iy / gridY ) );
  8470. }
  8471. }
  8472. // indices
  8473. for ( let iy = 0; iy < gridY; iy ++ ) {
  8474. for ( let ix = 0; ix < gridX; ix ++ ) {
  8475. const a = ix + gridX1 * iy;
  8476. const b = ix + gridX1 * ( iy + 1 );
  8477. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8478. const d = ( ix + 1 ) + gridX1 * iy;
  8479. // faces
  8480. indices.push( a, b, d );
  8481. indices.push( b, c, d );
  8482. }
  8483. }
  8484. // build geometry
  8485. this.setIndex( indices );
  8486. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8487. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8488. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8489. }
  8490. }
  8491. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8492. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8493. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8494. 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";
  8495. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8496. var begin_vertex = "vec3 transformed = vec3( position );";
  8497. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8498. 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";
  8499. 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 ) {\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 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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";
  8500. 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";
  8501. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8502. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8503. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8504. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8505. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8506. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8507. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  8508. 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}";
  8509. 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";
  8510. 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";
  8511. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8512. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8513. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8514. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8515. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8516. 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}";
  8517. 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";
  8518. 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";
  8519. 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";
  8520. 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";
  8521. 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";
  8522. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8523. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8524. 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";
  8525. 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";
  8526. 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}";
  8527. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8528. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8529. 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";
  8530. 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";
  8531. 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";
  8532. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8533. 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)";
  8534. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8535. 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)";
  8536. 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";
  8537. 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}";
  8538. 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";
  8539. 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";
  8540. 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";
  8541. 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";
  8542. 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";
  8543. 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";
  8544. 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";
  8545. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8546. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8547. 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";
  8548. 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";
  8549. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8550. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8551. 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";
  8552. 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";
  8553. 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";
  8554. var normal_fragment_begin = "#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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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;";
  8555. 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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8556. 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 ) {\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\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  8557. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8558. 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 );\n\t#endif\n#endif";
  8559. 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";
  8560. 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}";
  8561. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8562. 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;";
  8563. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8564. 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";
  8565. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8566. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8567. 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";
  8568. 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";
  8569. 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";
  8570. 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}";
  8571. 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";
  8572. 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";
  8573. 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";
  8574. 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";
  8575. 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";
  8576. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8577. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8578. 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; }";
  8579. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8580. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8581. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8582. 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";
  8583. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8584. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8585. 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";
  8586. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8587. 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";
  8588. 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}";
  8589. 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}";
  8590. 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}";
  8591. 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}";
  8592. 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}";
  8593. 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}";
  8594. 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}";
  8595. 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}";
  8596. 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}";
  8597. 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}";
  8598. 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}";
  8599. 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}";
  8600. 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}";
  8601. 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}";
  8602. 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}";
  8603. 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}";
  8604. 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}";
  8605. 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}";
  8606. 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}";
  8607. 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}";
  8608. 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}";
  8609. 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}";
  8610. 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}";
  8611. 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}";
  8612. 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}";
  8613. 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}";
  8614. 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}";
  8615. 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}";
  8616. 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}";
  8617. 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}";
  8618. 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}";
  8619. 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}";
  8620. const ShaderChunk = {
  8621. alphamap_fragment: alphamap_fragment,
  8622. alphamap_pars_fragment: alphamap_pars_fragment,
  8623. alphatest_fragment: alphatest_fragment,
  8624. aomap_fragment: aomap_fragment,
  8625. aomap_pars_fragment: aomap_pars_fragment,
  8626. begin_vertex: begin_vertex,
  8627. beginnormal_vertex: beginnormal_vertex,
  8628. bsdfs: bsdfs,
  8629. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8630. clipping_planes_fragment: clipping_planes_fragment,
  8631. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8632. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8633. clipping_planes_vertex: clipping_planes_vertex,
  8634. color_fragment: color_fragment,
  8635. color_pars_fragment: color_pars_fragment,
  8636. color_pars_vertex: color_pars_vertex,
  8637. color_vertex: color_vertex,
  8638. common: common,
  8639. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8640. defaultnormal_vertex: defaultnormal_vertex,
  8641. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8642. displacementmap_vertex: displacementmap_vertex,
  8643. emissivemap_fragment: emissivemap_fragment,
  8644. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8645. encodings_fragment: encodings_fragment,
  8646. encodings_pars_fragment: encodings_pars_fragment,
  8647. envmap_fragment: envmap_fragment,
  8648. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8649. envmap_pars_fragment: envmap_pars_fragment,
  8650. envmap_pars_vertex: envmap_pars_vertex,
  8651. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8652. envmap_vertex: envmap_vertex,
  8653. fog_vertex: fog_vertex,
  8654. fog_pars_vertex: fog_pars_vertex,
  8655. fog_fragment: fog_fragment,
  8656. fog_pars_fragment: fog_pars_fragment,
  8657. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8658. lightmap_fragment: lightmap_fragment,
  8659. lightmap_pars_fragment: lightmap_pars_fragment,
  8660. lights_lambert_vertex: lights_lambert_vertex,
  8661. lights_pars_begin: lights_pars_begin,
  8662. lights_toon_fragment: lights_toon_fragment,
  8663. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8664. lights_phong_fragment: lights_phong_fragment,
  8665. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8666. lights_physical_fragment: lights_physical_fragment,
  8667. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8668. lights_fragment_begin: lights_fragment_begin,
  8669. lights_fragment_maps: lights_fragment_maps,
  8670. lights_fragment_end: lights_fragment_end,
  8671. logdepthbuf_fragment: logdepthbuf_fragment,
  8672. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8673. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8674. logdepthbuf_vertex: logdepthbuf_vertex,
  8675. map_fragment: map_fragment,
  8676. map_pars_fragment: map_pars_fragment,
  8677. map_particle_fragment: map_particle_fragment,
  8678. map_particle_pars_fragment: map_particle_pars_fragment,
  8679. metalnessmap_fragment: metalnessmap_fragment,
  8680. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8681. morphnormal_vertex: morphnormal_vertex,
  8682. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8683. morphtarget_vertex: morphtarget_vertex,
  8684. normal_fragment_begin: normal_fragment_begin,
  8685. normal_fragment_maps: normal_fragment_maps,
  8686. normalmap_pars_fragment: normalmap_pars_fragment,
  8687. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8688. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8689. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8690. packing: packing,
  8691. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8692. project_vertex: project_vertex,
  8693. dithering_fragment: dithering_fragment,
  8694. dithering_pars_fragment: dithering_pars_fragment,
  8695. roughnessmap_fragment: roughnessmap_fragment,
  8696. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8697. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8698. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8699. shadowmap_vertex: shadowmap_vertex,
  8700. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8701. skinbase_vertex: skinbase_vertex,
  8702. skinning_pars_vertex: skinning_pars_vertex,
  8703. skinning_vertex: skinning_vertex,
  8704. skinnormal_vertex: skinnormal_vertex,
  8705. specularmap_fragment: specularmap_fragment,
  8706. specularmap_pars_fragment: specularmap_pars_fragment,
  8707. tonemapping_fragment: tonemapping_fragment,
  8708. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8709. transmissionmap_fragment: transmissionmap_fragment,
  8710. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8711. uv_pars_fragment: uv_pars_fragment,
  8712. uv_pars_vertex: uv_pars_vertex,
  8713. uv_vertex: uv_vertex,
  8714. uv2_pars_fragment: uv2_pars_fragment,
  8715. uv2_pars_vertex: uv2_pars_vertex,
  8716. uv2_vertex: uv2_vertex,
  8717. worldpos_vertex: worldpos_vertex,
  8718. background_frag: background_frag,
  8719. background_vert: background_vert,
  8720. cube_frag: cube_frag,
  8721. cube_vert: cube_vert,
  8722. depth_frag: depth_frag,
  8723. depth_vert: depth_vert,
  8724. distanceRGBA_frag: distanceRGBA_frag,
  8725. distanceRGBA_vert: distanceRGBA_vert,
  8726. equirect_frag: equirect_frag,
  8727. equirect_vert: equirect_vert,
  8728. linedashed_frag: linedashed_frag,
  8729. linedashed_vert: linedashed_vert,
  8730. meshbasic_frag: meshbasic_frag,
  8731. meshbasic_vert: meshbasic_vert,
  8732. meshlambert_frag: meshlambert_frag,
  8733. meshlambert_vert: meshlambert_vert,
  8734. meshmatcap_frag: meshmatcap_frag,
  8735. meshmatcap_vert: meshmatcap_vert,
  8736. meshtoon_frag: meshtoon_frag,
  8737. meshtoon_vert: meshtoon_vert,
  8738. meshphong_frag: meshphong_frag,
  8739. meshphong_vert: meshphong_vert,
  8740. meshphysical_frag: meshphysical_frag,
  8741. meshphysical_vert: meshphysical_vert,
  8742. normal_frag: normal_frag,
  8743. normal_vert: normal_vert,
  8744. points_frag: points_frag,
  8745. points_vert: points_vert,
  8746. shadow_frag: shadow_frag,
  8747. shadow_vert: shadow_vert,
  8748. sprite_frag: sprite_frag,
  8749. sprite_vert: sprite_vert
  8750. };
  8751. /**
  8752. * Uniforms library for shared webgl shaders
  8753. */
  8754. const UniformsLib = {
  8755. common: {
  8756. diffuse: { value: new Color( 0xeeeeee ) },
  8757. opacity: { value: 1.0 },
  8758. map: { value: null },
  8759. uvTransform: { value: new Matrix3() },
  8760. uv2Transform: { value: new Matrix3() },
  8761. alphaMap: { value: null },
  8762. },
  8763. specularmap: {
  8764. specularMap: { value: null },
  8765. },
  8766. envmap: {
  8767. envMap: { value: null },
  8768. flipEnvMap: { value: - 1 },
  8769. reflectivity: { value: 1.0 },
  8770. refractionRatio: { value: 0.98 },
  8771. maxMipLevel: { value: 0 }
  8772. },
  8773. aomap: {
  8774. aoMap: { value: null },
  8775. aoMapIntensity: { value: 1 }
  8776. },
  8777. lightmap: {
  8778. lightMap: { value: null },
  8779. lightMapIntensity: { value: 1 }
  8780. },
  8781. emissivemap: {
  8782. emissiveMap: { value: null }
  8783. },
  8784. bumpmap: {
  8785. bumpMap: { value: null },
  8786. bumpScale: { value: 1 }
  8787. },
  8788. normalmap: {
  8789. normalMap: { value: null },
  8790. normalScale: { value: new Vector2( 1, 1 ) }
  8791. },
  8792. displacementmap: {
  8793. displacementMap: { value: null },
  8794. displacementScale: { value: 1 },
  8795. displacementBias: { value: 0 }
  8796. },
  8797. roughnessmap: {
  8798. roughnessMap: { value: null }
  8799. },
  8800. metalnessmap: {
  8801. metalnessMap: { value: null }
  8802. },
  8803. gradientmap: {
  8804. gradientMap: { value: null }
  8805. },
  8806. fog: {
  8807. fogDensity: { value: 0.00025 },
  8808. fogNear: { value: 1 },
  8809. fogFar: { value: 2000 },
  8810. fogColor: { value: new Color( 0xffffff ) }
  8811. },
  8812. lights: {
  8813. ambientLightColor: { value: [] },
  8814. lightProbe: { value: [] },
  8815. directionalLights: { value: [], properties: {
  8816. direction: {},
  8817. color: {}
  8818. } },
  8819. directionalLightShadows: { value: [], properties: {
  8820. shadowBias: {},
  8821. shadowNormalBias: {},
  8822. shadowRadius: {},
  8823. shadowMapSize: {}
  8824. } },
  8825. directionalShadowMap: { value: [] },
  8826. directionalShadowMatrix: { value: [] },
  8827. spotLights: { value: [], properties: {
  8828. color: {},
  8829. position: {},
  8830. direction: {},
  8831. distance: {},
  8832. coneCos: {},
  8833. penumbraCos: {},
  8834. decay: {}
  8835. } },
  8836. spotLightShadows: { value: [], properties: {
  8837. shadowBias: {},
  8838. shadowNormalBias: {},
  8839. shadowRadius: {},
  8840. shadowMapSize: {}
  8841. } },
  8842. spotShadowMap: { value: [] },
  8843. spotShadowMatrix: { value: [] },
  8844. pointLights: { value: [], properties: {
  8845. color: {},
  8846. position: {},
  8847. decay: {},
  8848. distance: {}
  8849. } },
  8850. pointLightShadows: { value: [], properties: {
  8851. shadowBias: {},
  8852. shadowNormalBias: {},
  8853. shadowRadius: {},
  8854. shadowMapSize: {},
  8855. shadowCameraNear: {},
  8856. shadowCameraFar: {}
  8857. } },
  8858. pointShadowMap: { value: [] },
  8859. pointShadowMatrix: { value: [] },
  8860. hemisphereLights: { value: [], properties: {
  8861. direction: {},
  8862. skyColor: {},
  8863. groundColor: {}
  8864. } },
  8865. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8866. rectAreaLights: { value: [], properties: {
  8867. color: {},
  8868. position: {},
  8869. width: {},
  8870. height: {}
  8871. } },
  8872. ltc_1: { value: null },
  8873. ltc_2: { value: null }
  8874. },
  8875. points: {
  8876. diffuse: { value: new Color( 0xeeeeee ) },
  8877. opacity: { value: 1.0 },
  8878. size: { value: 1.0 },
  8879. scale: { value: 1.0 },
  8880. map: { value: null },
  8881. alphaMap: { value: null },
  8882. uvTransform: { value: new Matrix3() }
  8883. },
  8884. sprite: {
  8885. diffuse: { value: new Color( 0xeeeeee ) },
  8886. opacity: { value: 1.0 },
  8887. center: { value: new Vector2( 0.5, 0.5 ) },
  8888. rotation: { value: 0.0 },
  8889. map: { value: null },
  8890. alphaMap: { value: null },
  8891. uvTransform: { value: new Matrix3() }
  8892. }
  8893. };
  8894. const ShaderLib = {
  8895. basic: {
  8896. uniforms: mergeUniforms( [
  8897. UniformsLib.common,
  8898. UniformsLib.specularmap,
  8899. UniformsLib.envmap,
  8900. UniformsLib.aomap,
  8901. UniformsLib.lightmap,
  8902. UniformsLib.fog
  8903. ] ),
  8904. vertexShader: ShaderChunk.meshbasic_vert,
  8905. fragmentShader: ShaderChunk.meshbasic_frag
  8906. },
  8907. lambert: {
  8908. uniforms: mergeUniforms( [
  8909. UniformsLib.common,
  8910. UniformsLib.specularmap,
  8911. UniformsLib.envmap,
  8912. UniformsLib.aomap,
  8913. UniformsLib.lightmap,
  8914. UniformsLib.emissivemap,
  8915. UniformsLib.fog,
  8916. UniformsLib.lights,
  8917. {
  8918. emissive: { value: new Color( 0x000000 ) }
  8919. }
  8920. ] ),
  8921. vertexShader: ShaderChunk.meshlambert_vert,
  8922. fragmentShader: ShaderChunk.meshlambert_frag
  8923. },
  8924. phong: {
  8925. uniforms: mergeUniforms( [
  8926. UniformsLib.common,
  8927. UniformsLib.specularmap,
  8928. UniformsLib.envmap,
  8929. UniformsLib.aomap,
  8930. UniformsLib.lightmap,
  8931. UniformsLib.emissivemap,
  8932. UniformsLib.bumpmap,
  8933. UniformsLib.normalmap,
  8934. UniformsLib.displacementmap,
  8935. UniformsLib.fog,
  8936. UniformsLib.lights,
  8937. {
  8938. emissive: { value: new Color( 0x000000 ) },
  8939. specular: { value: new Color( 0x111111 ) },
  8940. shininess: { value: 30 }
  8941. }
  8942. ] ),
  8943. vertexShader: ShaderChunk.meshphong_vert,
  8944. fragmentShader: ShaderChunk.meshphong_frag
  8945. },
  8946. standard: {
  8947. uniforms: mergeUniforms( [
  8948. UniformsLib.common,
  8949. UniformsLib.envmap,
  8950. UniformsLib.aomap,
  8951. UniformsLib.lightmap,
  8952. UniformsLib.emissivemap,
  8953. UniformsLib.bumpmap,
  8954. UniformsLib.normalmap,
  8955. UniformsLib.displacementmap,
  8956. UniformsLib.roughnessmap,
  8957. UniformsLib.metalnessmap,
  8958. UniformsLib.fog,
  8959. UniformsLib.lights,
  8960. {
  8961. emissive: { value: new Color( 0x000000 ) },
  8962. roughness: { value: 1.0 },
  8963. metalness: { value: 0.0 },
  8964. envMapIntensity: { value: 1 } // temporary
  8965. }
  8966. ] ),
  8967. vertexShader: ShaderChunk.meshphysical_vert,
  8968. fragmentShader: ShaderChunk.meshphysical_frag
  8969. },
  8970. toon: {
  8971. uniforms: mergeUniforms( [
  8972. UniformsLib.common,
  8973. UniformsLib.aomap,
  8974. UniformsLib.lightmap,
  8975. UniformsLib.emissivemap,
  8976. UniformsLib.bumpmap,
  8977. UniformsLib.normalmap,
  8978. UniformsLib.displacementmap,
  8979. UniformsLib.gradientmap,
  8980. UniformsLib.fog,
  8981. UniformsLib.lights,
  8982. {
  8983. emissive: { value: new Color( 0x000000 ) }
  8984. }
  8985. ] ),
  8986. vertexShader: ShaderChunk.meshtoon_vert,
  8987. fragmentShader: ShaderChunk.meshtoon_frag
  8988. },
  8989. matcap: {
  8990. uniforms: mergeUniforms( [
  8991. UniformsLib.common,
  8992. UniformsLib.bumpmap,
  8993. UniformsLib.normalmap,
  8994. UniformsLib.displacementmap,
  8995. UniformsLib.fog,
  8996. {
  8997. matcap: { value: null }
  8998. }
  8999. ] ),
  9000. vertexShader: ShaderChunk.meshmatcap_vert,
  9001. fragmentShader: ShaderChunk.meshmatcap_frag
  9002. },
  9003. points: {
  9004. uniforms: mergeUniforms( [
  9005. UniformsLib.points,
  9006. UniformsLib.fog
  9007. ] ),
  9008. vertexShader: ShaderChunk.points_vert,
  9009. fragmentShader: ShaderChunk.points_frag
  9010. },
  9011. dashed: {
  9012. uniforms: mergeUniforms( [
  9013. UniformsLib.common,
  9014. UniformsLib.fog,
  9015. {
  9016. scale: { value: 1 },
  9017. dashSize: { value: 1 },
  9018. totalSize: { value: 2 }
  9019. }
  9020. ] ),
  9021. vertexShader: ShaderChunk.linedashed_vert,
  9022. fragmentShader: ShaderChunk.linedashed_frag
  9023. },
  9024. depth: {
  9025. uniforms: mergeUniforms( [
  9026. UniformsLib.common,
  9027. UniformsLib.displacementmap
  9028. ] ),
  9029. vertexShader: ShaderChunk.depth_vert,
  9030. fragmentShader: ShaderChunk.depth_frag
  9031. },
  9032. normal: {
  9033. uniforms: mergeUniforms( [
  9034. UniformsLib.common,
  9035. UniformsLib.bumpmap,
  9036. UniformsLib.normalmap,
  9037. UniformsLib.displacementmap,
  9038. {
  9039. opacity: { value: 1.0 }
  9040. }
  9041. ] ),
  9042. vertexShader: ShaderChunk.normal_vert,
  9043. fragmentShader: ShaderChunk.normal_frag
  9044. },
  9045. sprite: {
  9046. uniforms: mergeUniforms( [
  9047. UniformsLib.sprite,
  9048. UniformsLib.fog
  9049. ] ),
  9050. vertexShader: ShaderChunk.sprite_vert,
  9051. fragmentShader: ShaderChunk.sprite_frag
  9052. },
  9053. background: {
  9054. uniforms: {
  9055. uvTransform: { value: new Matrix3() },
  9056. t2D: { value: null },
  9057. },
  9058. vertexShader: ShaderChunk.background_vert,
  9059. fragmentShader: ShaderChunk.background_frag
  9060. },
  9061. /* -------------------------------------------------------------------------
  9062. // Cube map shader
  9063. ------------------------------------------------------------------------- */
  9064. cube: {
  9065. uniforms: mergeUniforms( [
  9066. UniformsLib.envmap,
  9067. {
  9068. opacity: { value: 1.0 }
  9069. }
  9070. ] ),
  9071. vertexShader: ShaderChunk.cube_vert,
  9072. fragmentShader: ShaderChunk.cube_frag
  9073. },
  9074. equirect: {
  9075. uniforms: {
  9076. tEquirect: { value: null },
  9077. },
  9078. vertexShader: ShaderChunk.equirect_vert,
  9079. fragmentShader: ShaderChunk.equirect_frag
  9080. },
  9081. distanceRGBA: {
  9082. uniforms: mergeUniforms( [
  9083. UniformsLib.common,
  9084. UniformsLib.displacementmap,
  9085. {
  9086. referencePosition: { value: new Vector3() },
  9087. nearDistance: { value: 1 },
  9088. farDistance: { value: 1000 }
  9089. }
  9090. ] ),
  9091. vertexShader: ShaderChunk.distanceRGBA_vert,
  9092. fragmentShader: ShaderChunk.distanceRGBA_frag
  9093. },
  9094. shadow: {
  9095. uniforms: mergeUniforms( [
  9096. UniformsLib.lights,
  9097. UniformsLib.fog,
  9098. {
  9099. color: { value: new Color( 0x00000 ) },
  9100. opacity: { value: 1.0 }
  9101. },
  9102. ] ),
  9103. vertexShader: ShaderChunk.shadow_vert,
  9104. fragmentShader: ShaderChunk.shadow_frag
  9105. }
  9106. };
  9107. ShaderLib.physical = {
  9108. uniforms: mergeUniforms( [
  9109. ShaderLib.standard.uniforms,
  9110. {
  9111. clearcoat: { value: 0 },
  9112. clearcoatMap: { value: null },
  9113. clearcoatRoughness: { value: 0 },
  9114. clearcoatRoughnessMap: { value: null },
  9115. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  9116. clearcoatNormalMap: { value: null },
  9117. sheen: { value: new Color( 0x000000 ) },
  9118. transmission: { value: 0 },
  9119. transmissionMap: { value: null },
  9120. }
  9121. ] ),
  9122. vertexShader: ShaderChunk.meshphysical_vert,
  9123. fragmentShader: ShaderChunk.meshphysical_frag
  9124. };
  9125. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  9126. const clearColor = new Color( 0x000000 );
  9127. let clearAlpha = 0;
  9128. let planeMesh;
  9129. let boxMesh;
  9130. let currentBackground = null;
  9131. let currentBackgroundVersion = 0;
  9132. let currentTonemapping = null;
  9133. function render( renderList, scene, camera, forceClear ) {
  9134. let background = scene.isScene === true ? scene.background : null;
  9135. if ( background && background.isTexture ) {
  9136. background = cubemaps.get( background );
  9137. }
  9138. // Ignore background in AR
  9139. // TODO: Reconsider this.
  9140. const xr = renderer.xr;
  9141. const session = xr.getSession && xr.getSession();
  9142. if ( session && session.environmentBlendMode === 'additive' ) {
  9143. background = null;
  9144. }
  9145. if ( background === null ) {
  9146. setClear( clearColor, clearAlpha );
  9147. } else if ( background && background.isColor ) {
  9148. setClear( background, 1 );
  9149. forceClear = true;
  9150. }
  9151. if ( renderer.autoClear || forceClear ) {
  9152. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9153. }
  9154. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.isWebGLCubeRenderTargetTexture || background.mapping === CubeUVReflectionMapping ) ) {
  9155. if ( boxMesh === undefined ) {
  9156. boxMesh = new Mesh(
  9157. new BoxBufferGeometry( 1, 1, 1 ),
  9158. new ShaderMaterial( {
  9159. name: 'BackgroundCubeMaterial',
  9160. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  9161. vertexShader: ShaderLib.cube.vertexShader,
  9162. fragmentShader: ShaderLib.cube.fragmentShader,
  9163. side: BackSide,
  9164. depthTest: false,
  9165. depthWrite: false,
  9166. fog: false
  9167. } )
  9168. );
  9169. boxMesh.geometry.deleteAttribute( 'normal' );
  9170. boxMesh.geometry.deleteAttribute( 'uv' );
  9171. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9172. this.matrixWorld.copyPosition( camera.matrixWorld );
  9173. };
  9174. // enable code injection for non-built-in material
  9175. Object.defineProperty( boxMesh.material, 'envMap', {
  9176. get: function () {
  9177. return this.uniforms.envMap.value;
  9178. }
  9179. } );
  9180. objects.update( boxMesh );
  9181. }
  9182. if ( background.isWebGLCubeRenderTarget ) {
  9183. // TODO Deprecate
  9184. background = background.texture;
  9185. }
  9186. boxMesh.material.uniforms.envMap.value = background;
  9187. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture ? - 1 : 1;
  9188. if ( currentBackground !== background ||
  9189. currentBackgroundVersion !== background.version ||
  9190. currentTonemapping !== renderer.toneMapping ) {
  9191. boxMesh.material.needsUpdate = true;
  9192. currentBackground = background;
  9193. currentBackgroundVersion = background.version;
  9194. currentTonemapping = renderer.toneMapping;
  9195. }
  9196. // push to the pre-sorted opaque render list
  9197. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9198. } else if ( background && background.isTexture ) {
  9199. if ( planeMesh === undefined ) {
  9200. planeMesh = new Mesh(
  9201. new PlaneBufferGeometry( 2, 2 ),
  9202. new ShaderMaterial( {
  9203. name: 'BackgroundMaterial',
  9204. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9205. vertexShader: ShaderLib.background.vertexShader,
  9206. fragmentShader: ShaderLib.background.fragmentShader,
  9207. side: FrontSide,
  9208. depthTest: false,
  9209. depthWrite: false,
  9210. fog: false
  9211. } )
  9212. );
  9213. planeMesh.geometry.deleteAttribute( 'normal' );
  9214. // enable code injection for non-built-in material
  9215. Object.defineProperty( planeMesh.material, 'map', {
  9216. get: function () {
  9217. return this.uniforms.t2D.value;
  9218. }
  9219. } );
  9220. objects.update( planeMesh );
  9221. }
  9222. planeMesh.material.uniforms.t2D.value = background;
  9223. if ( background.matrixAutoUpdate === true ) {
  9224. background.updateMatrix();
  9225. }
  9226. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9227. if ( currentBackground !== background ||
  9228. currentBackgroundVersion !== background.version ||
  9229. currentTonemapping !== renderer.toneMapping ) {
  9230. planeMesh.material.needsUpdate = true;
  9231. currentBackground = background;
  9232. currentBackgroundVersion = background.version;
  9233. currentTonemapping = renderer.toneMapping;
  9234. }
  9235. // push to the pre-sorted opaque render list
  9236. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9237. }
  9238. }
  9239. function setClear( color, alpha ) {
  9240. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9241. }
  9242. return {
  9243. getClearColor: function () {
  9244. return clearColor;
  9245. },
  9246. setClearColor: function ( color, alpha ) {
  9247. clearColor.set( color );
  9248. clearAlpha = alpha !== undefined ? alpha : 1;
  9249. setClear( clearColor, clearAlpha );
  9250. },
  9251. getClearAlpha: function () {
  9252. return clearAlpha;
  9253. },
  9254. setClearAlpha: function ( alpha ) {
  9255. clearAlpha = alpha;
  9256. setClear( clearColor, clearAlpha );
  9257. },
  9258. render: render
  9259. };
  9260. }
  9261. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9262. const maxVertexAttributes = gl.getParameter( 34921 );
  9263. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9264. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9265. const bindingStates = {};
  9266. const defaultState = createBindingState( null );
  9267. let currentState = defaultState;
  9268. function setup( object, material, program, geometry, index ) {
  9269. let updateBuffers = false;
  9270. if ( vaoAvailable ) {
  9271. const state = getBindingState( geometry, program, material );
  9272. if ( currentState !== state ) {
  9273. currentState = state;
  9274. bindVertexArrayObject( currentState.object );
  9275. }
  9276. updateBuffers = needsUpdate( geometry, index );
  9277. if ( updateBuffers ) saveCache( geometry, index );
  9278. } else {
  9279. const wireframe = ( material.wireframe === true );
  9280. if ( currentState.geometry !== geometry.id ||
  9281. currentState.program !== program.id ||
  9282. currentState.wireframe !== wireframe ) {
  9283. currentState.geometry = geometry.id;
  9284. currentState.program = program.id;
  9285. currentState.wireframe = wireframe;
  9286. updateBuffers = true;
  9287. }
  9288. }
  9289. if ( object.isInstancedMesh === true ) {
  9290. updateBuffers = true;
  9291. }
  9292. if ( index !== null ) {
  9293. attributes.update( index, 34963 );
  9294. }
  9295. if ( updateBuffers ) {
  9296. setupVertexAttributes( object, material, program, geometry );
  9297. if ( index !== null ) {
  9298. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  9299. }
  9300. }
  9301. }
  9302. function createVertexArrayObject() {
  9303. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9304. return extension.createVertexArrayOES();
  9305. }
  9306. function bindVertexArrayObject( vao ) {
  9307. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9308. return extension.bindVertexArrayOES( vao );
  9309. }
  9310. function deleteVertexArrayObject( vao ) {
  9311. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9312. return extension.deleteVertexArrayOES( vao );
  9313. }
  9314. function getBindingState( geometry, program, material ) {
  9315. const wireframe = ( material.wireframe === true );
  9316. let programMap = bindingStates[ geometry.id ];
  9317. if ( programMap === undefined ) {
  9318. programMap = {};
  9319. bindingStates[ geometry.id ] = programMap;
  9320. }
  9321. let stateMap = programMap[ program.id ];
  9322. if ( stateMap === undefined ) {
  9323. stateMap = {};
  9324. programMap[ program.id ] = stateMap;
  9325. }
  9326. let state = stateMap[ wireframe ];
  9327. if ( state === undefined ) {
  9328. state = createBindingState( createVertexArrayObject() );
  9329. stateMap[ wireframe ] = state;
  9330. }
  9331. return state;
  9332. }
  9333. function createBindingState( vao ) {
  9334. const newAttributes = [];
  9335. const enabledAttributes = [];
  9336. const attributeDivisors = [];
  9337. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9338. newAttributes[ i ] = 0;
  9339. enabledAttributes[ i ] = 0;
  9340. attributeDivisors[ i ] = 0;
  9341. }
  9342. return {
  9343. // for backward compatibility on non-VAO support browser
  9344. geometry: null,
  9345. program: null,
  9346. wireframe: false,
  9347. newAttributes: newAttributes,
  9348. enabledAttributes: enabledAttributes,
  9349. attributeDivisors: attributeDivisors,
  9350. object: vao,
  9351. attributes: {},
  9352. index: null
  9353. };
  9354. }
  9355. function needsUpdate( geometry, index ) {
  9356. const cachedAttributes = currentState.attributes;
  9357. const geometryAttributes = geometry.attributes;
  9358. if ( Object.keys( cachedAttributes ).length !== Object.keys( geometryAttributes ).length ) return true;
  9359. for ( const key in geometryAttributes ) {
  9360. const cachedAttribute = cachedAttributes[ key ];
  9361. const geometryAttribute = geometryAttributes[ key ];
  9362. if ( cachedAttribute === undefined ) return true;
  9363. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9364. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  9365. }
  9366. if ( currentState.index !== index ) return true;
  9367. return false;
  9368. }
  9369. function saveCache( geometry, index ) {
  9370. const cache = {};
  9371. const attributes = geometry.attributes;
  9372. for ( const key in attributes ) {
  9373. const attribute = attributes[ key ];
  9374. const data = {};
  9375. data.attribute = attribute;
  9376. if ( attribute.data ) {
  9377. data.data = attribute.data;
  9378. }
  9379. cache[ key ] = data;
  9380. }
  9381. currentState.attributes = cache;
  9382. currentState.index = index;
  9383. }
  9384. function initAttributes() {
  9385. const newAttributes = currentState.newAttributes;
  9386. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9387. newAttributes[ i ] = 0;
  9388. }
  9389. }
  9390. function enableAttribute( attribute ) {
  9391. enableAttributeAndDivisor( attribute, 0 );
  9392. }
  9393. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9394. const newAttributes = currentState.newAttributes;
  9395. const enabledAttributes = currentState.enabledAttributes;
  9396. const attributeDivisors = currentState.attributeDivisors;
  9397. newAttributes[ attribute ] = 1;
  9398. if ( enabledAttributes[ attribute ] === 0 ) {
  9399. gl.enableVertexAttribArray( attribute );
  9400. enabledAttributes[ attribute ] = 1;
  9401. }
  9402. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9403. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9404. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9405. attributeDivisors[ attribute ] = meshPerAttribute;
  9406. }
  9407. }
  9408. function disableUnusedAttributes() {
  9409. const newAttributes = currentState.newAttributes;
  9410. const enabledAttributes = currentState.enabledAttributes;
  9411. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9412. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9413. gl.disableVertexAttribArray( i );
  9414. enabledAttributes[ i ] = 0;
  9415. }
  9416. }
  9417. }
  9418. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9419. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  9420. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9421. } else {
  9422. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9423. }
  9424. }
  9425. function setupVertexAttributes( object, material, program, geometry ) {
  9426. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9427. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9428. }
  9429. initAttributes();
  9430. const geometryAttributes = geometry.attributes;
  9431. const programAttributes = program.getAttributes();
  9432. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9433. for ( const name in programAttributes ) {
  9434. const programAttribute = programAttributes[ name ];
  9435. if ( programAttribute >= 0 ) {
  9436. const geometryAttribute = geometryAttributes[ name ];
  9437. if ( geometryAttribute !== undefined ) {
  9438. const normalized = geometryAttribute.normalized;
  9439. const size = geometryAttribute.itemSize;
  9440. const attribute = attributes.get( geometryAttribute );
  9441. // TODO Attribute may not be available on context restore
  9442. if ( attribute === undefined ) continue;
  9443. const buffer = attribute.buffer;
  9444. const type = attribute.type;
  9445. const bytesPerElement = attribute.bytesPerElement;
  9446. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9447. const data = geometryAttribute.data;
  9448. const stride = data.stride;
  9449. const offset = geometryAttribute.offset;
  9450. if ( data && data.isInstancedInterleavedBuffer ) {
  9451. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  9452. if ( geometry._maxInstanceCount === undefined ) {
  9453. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9454. }
  9455. } else {
  9456. enableAttribute( programAttribute );
  9457. }
  9458. gl.bindBuffer( 34962, buffer );
  9459. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  9460. } else {
  9461. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9462. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  9463. if ( geometry._maxInstanceCount === undefined ) {
  9464. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9465. }
  9466. } else {
  9467. enableAttribute( programAttribute );
  9468. }
  9469. gl.bindBuffer( 34962, buffer );
  9470. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  9471. }
  9472. } else if ( name === 'instanceMatrix' ) {
  9473. const attribute = attributes.get( object.instanceMatrix );
  9474. // TODO Attribute may not be available on context restore
  9475. if ( attribute === undefined ) continue;
  9476. const buffer = attribute.buffer;
  9477. const type = attribute.type;
  9478. enableAttributeAndDivisor( programAttribute + 0, 1 );
  9479. enableAttributeAndDivisor( programAttribute + 1, 1 );
  9480. enableAttributeAndDivisor( programAttribute + 2, 1 );
  9481. enableAttributeAndDivisor( programAttribute + 3, 1 );
  9482. gl.bindBuffer( 34962, buffer );
  9483. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  9484. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  9485. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  9486. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  9487. } else if ( name === 'instanceColor' ) {
  9488. const attribute = attributes.get( object.instanceColor );
  9489. // TODO Attribute may not be available on context restore
  9490. if ( attribute === undefined ) continue;
  9491. const buffer = attribute.buffer;
  9492. const type = attribute.type;
  9493. enableAttributeAndDivisor( programAttribute, 1 );
  9494. gl.bindBuffer( 34962, buffer );
  9495. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  9496. } else if ( materialDefaultAttributeValues !== undefined ) {
  9497. const value = materialDefaultAttributeValues[ name ];
  9498. if ( value !== undefined ) {
  9499. switch ( value.length ) {
  9500. case 2:
  9501. gl.vertexAttrib2fv( programAttribute, value );
  9502. break;
  9503. case 3:
  9504. gl.vertexAttrib3fv( programAttribute, value );
  9505. break;
  9506. case 4:
  9507. gl.vertexAttrib4fv( programAttribute, value );
  9508. break;
  9509. default:
  9510. gl.vertexAttrib1fv( programAttribute, value );
  9511. }
  9512. }
  9513. }
  9514. }
  9515. }
  9516. disableUnusedAttributes();
  9517. }
  9518. function dispose() {
  9519. reset();
  9520. for ( const geometryId in bindingStates ) {
  9521. const programMap = bindingStates[ geometryId ];
  9522. for ( const programId in programMap ) {
  9523. const stateMap = programMap[ programId ];
  9524. for ( const wireframe in stateMap ) {
  9525. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9526. delete stateMap[ wireframe ];
  9527. }
  9528. delete programMap[ programId ];
  9529. }
  9530. delete bindingStates[ geometryId ];
  9531. }
  9532. }
  9533. function releaseStatesOfGeometry( geometry ) {
  9534. if ( bindingStates[ geometry.id ] === undefined ) return;
  9535. const programMap = bindingStates[ geometry.id ];
  9536. for ( const programId in programMap ) {
  9537. const stateMap = programMap[ programId ];
  9538. for ( const wireframe in stateMap ) {
  9539. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9540. delete stateMap[ wireframe ];
  9541. }
  9542. delete programMap[ programId ];
  9543. }
  9544. delete bindingStates[ geometry.id ];
  9545. }
  9546. function releaseStatesOfProgram( program ) {
  9547. for ( const geometryId in bindingStates ) {
  9548. const programMap = bindingStates[ geometryId ];
  9549. if ( programMap[ program.id ] === undefined ) continue;
  9550. const stateMap = programMap[ program.id ];
  9551. for ( const wireframe in stateMap ) {
  9552. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9553. delete stateMap[ wireframe ];
  9554. }
  9555. delete programMap[ program.id ];
  9556. }
  9557. }
  9558. function reset() {
  9559. resetDefaultState();
  9560. if ( currentState === defaultState ) return;
  9561. currentState = defaultState;
  9562. bindVertexArrayObject( currentState.object );
  9563. }
  9564. // for backward-compatilibity
  9565. function resetDefaultState() {
  9566. defaultState.geometry = null;
  9567. defaultState.program = null;
  9568. defaultState.wireframe = false;
  9569. }
  9570. return {
  9571. setup: setup,
  9572. reset: reset,
  9573. resetDefaultState: resetDefaultState,
  9574. dispose: dispose,
  9575. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9576. releaseStatesOfProgram: releaseStatesOfProgram,
  9577. initAttributes: initAttributes,
  9578. enableAttribute: enableAttribute,
  9579. disableUnusedAttributes: disableUnusedAttributes
  9580. };
  9581. }
  9582. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9583. const isWebGL2 = capabilities.isWebGL2;
  9584. let mode;
  9585. function setMode( value ) {
  9586. mode = value;
  9587. }
  9588. function render( start, count ) {
  9589. gl.drawArrays( mode, start, count );
  9590. info.update( count, mode, 1 );
  9591. }
  9592. function renderInstances( start, count, primcount ) {
  9593. if ( primcount === 0 ) return;
  9594. let extension, methodName;
  9595. if ( isWebGL2 ) {
  9596. extension = gl;
  9597. methodName = 'drawArraysInstanced';
  9598. } else {
  9599. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9600. methodName = 'drawArraysInstancedANGLE';
  9601. if ( extension === null ) {
  9602. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9603. return;
  9604. }
  9605. }
  9606. extension[ methodName ]( mode, start, count, primcount );
  9607. info.update( count, mode, primcount );
  9608. }
  9609. //
  9610. this.setMode = setMode;
  9611. this.render = render;
  9612. this.renderInstances = renderInstances;
  9613. }
  9614. function WebGLCapabilities( gl, extensions, parameters ) {
  9615. let maxAnisotropy;
  9616. function getMaxAnisotropy() {
  9617. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9618. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9619. if ( extension !== null ) {
  9620. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9621. } else {
  9622. maxAnisotropy = 0;
  9623. }
  9624. return maxAnisotropy;
  9625. }
  9626. function getMaxPrecision( precision ) {
  9627. if ( precision === 'highp' ) {
  9628. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9629. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9630. return 'highp';
  9631. }
  9632. precision = 'mediump';
  9633. }
  9634. if ( precision === 'mediump' ) {
  9635. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9636. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9637. return 'mediump';
  9638. }
  9639. }
  9640. return 'lowp';
  9641. }
  9642. /* eslint-disable no-undef */
  9643. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  9644. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  9645. /* eslint-enable no-undef */
  9646. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9647. const maxPrecision = getMaxPrecision( precision );
  9648. if ( maxPrecision !== precision ) {
  9649. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9650. precision = maxPrecision;
  9651. }
  9652. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9653. const maxTextures = gl.getParameter( 34930 );
  9654. const maxVertexTextures = gl.getParameter( 35660 );
  9655. const maxTextureSize = gl.getParameter( 3379 );
  9656. const maxCubemapSize = gl.getParameter( 34076 );
  9657. const maxAttributes = gl.getParameter( 34921 );
  9658. const maxVertexUniforms = gl.getParameter( 36347 );
  9659. const maxVaryings = gl.getParameter( 36348 );
  9660. const maxFragmentUniforms = gl.getParameter( 36349 );
  9661. const vertexTextures = maxVertexTextures > 0;
  9662. const floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  9663. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9664. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9665. return {
  9666. isWebGL2: isWebGL2,
  9667. getMaxAnisotropy: getMaxAnisotropy,
  9668. getMaxPrecision: getMaxPrecision,
  9669. precision: precision,
  9670. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9671. maxTextures: maxTextures,
  9672. maxVertexTextures: maxVertexTextures,
  9673. maxTextureSize: maxTextureSize,
  9674. maxCubemapSize: maxCubemapSize,
  9675. maxAttributes: maxAttributes,
  9676. maxVertexUniforms: maxVertexUniforms,
  9677. maxVaryings: maxVaryings,
  9678. maxFragmentUniforms: maxFragmentUniforms,
  9679. vertexTextures: vertexTextures,
  9680. floatFragmentTextures: floatFragmentTextures,
  9681. floatVertexTextures: floatVertexTextures,
  9682. maxSamples: maxSamples
  9683. };
  9684. }
  9685. function WebGLClipping( properties ) {
  9686. const scope = this;
  9687. let globalState = null,
  9688. numGlobalPlanes = 0,
  9689. localClippingEnabled = false,
  9690. renderingShadows = false;
  9691. const plane = new Plane(),
  9692. viewNormalMatrix = new Matrix3(),
  9693. uniform = { value: null, needsUpdate: false };
  9694. this.uniform = uniform;
  9695. this.numPlanes = 0;
  9696. this.numIntersection = 0;
  9697. this.init = function ( planes, enableLocalClipping, camera ) {
  9698. const enabled =
  9699. planes.length !== 0 ||
  9700. enableLocalClipping ||
  9701. // enable state of previous frame - the clipping code has to
  9702. // run another frame in order to reset the state:
  9703. numGlobalPlanes !== 0 ||
  9704. localClippingEnabled;
  9705. localClippingEnabled = enableLocalClipping;
  9706. globalState = projectPlanes( planes, camera, 0 );
  9707. numGlobalPlanes = planes.length;
  9708. return enabled;
  9709. };
  9710. this.beginShadows = function () {
  9711. renderingShadows = true;
  9712. projectPlanes( null );
  9713. };
  9714. this.endShadows = function () {
  9715. renderingShadows = false;
  9716. resetGlobalState();
  9717. };
  9718. this.setState = function ( material, camera, useCache ) {
  9719. const planes = material.clippingPlanes,
  9720. clipIntersection = material.clipIntersection,
  9721. clipShadows = material.clipShadows;
  9722. const materialProperties = properties.get( material );
  9723. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9724. // there's no local clipping
  9725. if ( renderingShadows ) {
  9726. // there's no global clipping
  9727. projectPlanes( null );
  9728. } else {
  9729. resetGlobalState();
  9730. }
  9731. } else {
  9732. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9733. lGlobal = nGlobal * 4;
  9734. let dstArray = materialProperties.clippingState || null;
  9735. uniform.value = dstArray; // ensure unique state
  9736. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9737. for ( let i = 0; i !== lGlobal; ++ i ) {
  9738. dstArray[ i ] = globalState[ i ];
  9739. }
  9740. materialProperties.clippingState = dstArray;
  9741. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9742. this.numPlanes += nGlobal;
  9743. }
  9744. };
  9745. function resetGlobalState() {
  9746. if ( uniform.value !== globalState ) {
  9747. uniform.value = globalState;
  9748. uniform.needsUpdate = numGlobalPlanes > 0;
  9749. }
  9750. scope.numPlanes = numGlobalPlanes;
  9751. scope.numIntersection = 0;
  9752. }
  9753. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9754. const nPlanes = planes !== null ? planes.length : 0;
  9755. let dstArray = null;
  9756. if ( nPlanes !== 0 ) {
  9757. dstArray = uniform.value;
  9758. if ( skipTransform !== true || dstArray === null ) {
  9759. const flatSize = dstOffset + nPlanes * 4,
  9760. viewMatrix = camera.matrixWorldInverse;
  9761. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9762. if ( dstArray === null || dstArray.length < flatSize ) {
  9763. dstArray = new Float32Array( flatSize );
  9764. }
  9765. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9766. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9767. plane.normal.toArray( dstArray, i4 );
  9768. dstArray[ i4 + 3 ] = plane.constant;
  9769. }
  9770. }
  9771. uniform.value = dstArray;
  9772. uniform.needsUpdate = true;
  9773. }
  9774. scope.numPlanes = nPlanes;
  9775. scope.numIntersection = 0;
  9776. return dstArray;
  9777. }
  9778. }
  9779. function WebGLCubeMaps( renderer ) {
  9780. let cubemaps = new WeakMap();
  9781. function mapTextureMapping( texture, mapping ) {
  9782. if ( mapping === EquirectangularReflectionMapping ) {
  9783. texture.mapping = CubeReflectionMapping;
  9784. } else if ( mapping === EquirectangularRefractionMapping ) {
  9785. texture.mapping = CubeRefractionMapping;
  9786. }
  9787. return texture;
  9788. }
  9789. function get( texture ) {
  9790. if ( texture && texture.isTexture ) {
  9791. const mapping = texture.mapping;
  9792. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9793. if ( cubemaps.has( texture ) ) {
  9794. const cubemap = cubemaps.get( texture ).texture;
  9795. return mapTextureMapping( cubemap, texture.mapping );
  9796. } else {
  9797. const image = texture.image;
  9798. if ( image && image.height > 0 ) {
  9799. const currentRenderList = renderer.getRenderList();
  9800. const currentRenderTarget = renderer.getRenderTarget();
  9801. const currentRenderState = renderer.getRenderState();
  9802. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9803. renderTarget.fromEquirectangularTexture( renderer, texture );
  9804. cubemaps.set( texture, renderTarget );
  9805. renderer.setRenderTarget( currentRenderTarget );
  9806. renderer.setRenderList( currentRenderList );
  9807. renderer.setRenderState( currentRenderState );
  9808. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9809. } else {
  9810. // image not yet ready. try the conversion next frame
  9811. return null;
  9812. }
  9813. }
  9814. }
  9815. }
  9816. return texture;
  9817. }
  9818. function dispose() {
  9819. cubemaps = new WeakMap();
  9820. }
  9821. return {
  9822. get: get,
  9823. dispose: dispose
  9824. };
  9825. }
  9826. function WebGLExtensions( gl ) {
  9827. const extensions = {};
  9828. return {
  9829. has: function ( name ) {
  9830. if ( extensions[ name ] !== undefined ) {
  9831. return extensions[ name ] !== null;
  9832. }
  9833. let extension;
  9834. switch ( name ) {
  9835. case 'WEBGL_depth_texture':
  9836. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9837. break;
  9838. case 'EXT_texture_filter_anisotropic':
  9839. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9840. break;
  9841. case 'WEBGL_compressed_texture_s3tc':
  9842. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9843. break;
  9844. case 'WEBGL_compressed_texture_pvrtc':
  9845. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9846. break;
  9847. default:
  9848. extension = gl.getExtension( name );
  9849. }
  9850. extensions[ name ] = extension;
  9851. return extension !== null;
  9852. },
  9853. get: function ( name ) {
  9854. if ( ! this.has( name ) ) {
  9855. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9856. }
  9857. return extensions[ name ];
  9858. }
  9859. };
  9860. }
  9861. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9862. const geometries = new WeakMap();
  9863. const wireframeAttributes = new WeakMap();
  9864. function onGeometryDispose( event ) {
  9865. const geometry = event.target;
  9866. const buffergeometry = geometries.get( geometry );
  9867. if ( buffergeometry.index !== null ) {
  9868. attributes.remove( buffergeometry.index );
  9869. }
  9870. for ( const name in buffergeometry.attributes ) {
  9871. attributes.remove( buffergeometry.attributes[ name ] );
  9872. }
  9873. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9874. geometries.delete( geometry );
  9875. const attribute = wireframeAttributes.get( buffergeometry );
  9876. if ( attribute ) {
  9877. attributes.remove( attribute );
  9878. wireframeAttributes.delete( buffergeometry );
  9879. }
  9880. bindingStates.releaseStatesOfGeometry( geometry );
  9881. if ( geometry.isInstancedBufferGeometry === true ) {
  9882. delete geometry._maxInstanceCount;
  9883. }
  9884. //
  9885. info.memory.geometries --;
  9886. }
  9887. function get( object, geometry ) {
  9888. let buffergeometry = geometries.get( geometry );
  9889. if ( buffergeometry ) return buffergeometry;
  9890. geometry.addEventListener( 'dispose', onGeometryDispose );
  9891. if ( geometry.isBufferGeometry ) {
  9892. buffergeometry = geometry;
  9893. } else if ( geometry.isGeometry ) {
  9894. if ( geometry._bufferGeometry === undefined ) {
  9895. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9896. }
  9897. buffergeometry = geometry._bufferGeometry;
  9898. }
  9899. geometries.set( geometry, buffergeometry );
  9900. info.memory.geometries ++;
  9901. return buffergeometry;
  9902. }
  9903. function update( geometry ) {
  9904. const geometryAttributes = geometry.attributes;
  9905. // Updating index buffer in VAO now. See WebGLBindingStates.
  9906. for ( const name in geometryAttributes ) {
  9907. attributes.update( geometryAttributes[ name ], 34962 );
  9908. }
  9909. // morph targets
  9910. const morphAttributes = geometry.morphAttributes;
  9911. for ( const name in morphAttributes ) {
  9912. const array = morphAttributes[ name ];
  9913. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9914. attributes.update( array[ i ], 34962 );
  9915. }
  9916. }
  9917. }
  9918. function updateWireframeAttribute( geometry ) {
  9919. const indices = [];
  9920. const geometryIndex = geometry.index;
  9921. const geometryPosition = geometry.attributes.position;
  9922. let version = 0;
  9923. if ( geometryIndex !== null ) {
  9924. const array = geometryIndex.array;
  9925. version = geometryIndex.version;
  9926. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9927. const a = array[ i + 0 ];
  9928. const b = array[ i + 1 ];
  9929. const c = array[ i + 2 ];
  9930. indices.push( a, b, b, c, c, a );
  9931. }
  9932. } else {
  9933. const array = geometryPosition.array;
  9934. version = geometryPosition.version;
  9935. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9936. const a = i + 0;
  9937. const b = i + 1;
  9938. const c = i + 2;
  9939. indices.push( a, b, b, c, c, a );
  9940. }
  9941. }
  9942. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9943. attribute.version = version;
  9944. // Updating index buffer in VAO now. See WebGLBindingStates
  9945. //
  9946. const previousAttribute = wireframeAttributes.get( geometry );
  9947. if ( previousAttribute ) attributes.remove( previousAttribute );
  9948. //
  9949. wireframeAttributes.set( geometry, attribute );
  9950. }
  9951. function getWireframeAttribute( geometry ) {
  9952. const currentAttribute = wireframeAttributes.get( geometry );
  9953. if ( currentAttribute ) {
  9954. const geometryIndex = geometry.index;
  9955. if ( geometryIndex !== null ) {
  9956. // if the attribute is obsolete, create a new one
  9957. if ( currentAttribute.version < geometryIndex.version ) {
  9958. updateWireframeAttribute( geometry );
  9959. }
  9960. }
  9961. } else {
  9962. updateWireframeAttribute( geometry );
  9963. }
  9964. return wireframeAttributes.get( geometry );
  9965. }
  9966. return {
  9967. get: get,
  9968. update: update,
  9969. getWireframeAttribute: getWireframeAttribute
  9970. };
  9971. }
  9972. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9973. const isWebGL2 = capabilities.isWebGL2;
  9974. let mode;
  9975. function setMode( value ) {
  9976. mode = value;
  9977. }
  9978. let type, bytesPerElement;
  9979. function setIndex( value ) {
  9980. type = value.type;
  9981. bytesPerElement = value.bytesPerElement;
  9982. }
  9983. function render( start, count ) {
  9984. gl.drawElements( mode, count, type, start * bytesPerElement );
  9985. info.update( count, mode, 1 );
  9986. }
  9987. function renderInstances( start, count, primcount ) {
  9988. if ( primcount === 0 ) return;
  9989. let extension, methodName;
  9990. if ( isWebGL2 ) {
  9991. extension = gl;
  9992. methodName = 'drawElementsInstanced';
  9993. } else {
  9994. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9995. methodName = 'drawElementsInstancedANGLE';
  9996. if ( extension === null ) {
  9997. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9998. return;
  9999. }
  10000. }
  10001. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10002. info.update( count, mode, primcount );
  10003. }
  10004. //
  10005. this.setMode = setMode;
  10006. this.setIndex = setIndex;
  10007. this.render = render;
  10008. this.renderInstances = renderInstances;
  10009. }
  10010. function WebGLInfo( gl ) {
  10011. const memory = {
  10012. geometries: 0,
  10013. textures: 0
  10014. };
  10015. const render = {
  10016. frame: 0,
  10017. calls: 0,
  10018. triangles: 0,
  10019. points: 0,
  10020. lines: 0
  10021. };
  10022. function update( count, mode, instanceCount ) {
  10023. render.calls ++;
  10024. switch ( mode ) {
  10025. case 4:
  10026. render.triangles += instanceCount * ( count / 3 );
  10027. break;
  10028. case 1:
  10029. render.lines += instanceCount * ( count / 2 );
  10030. break;
  10031. case 3:
  10032. render.lines += instanceCount * ( count - 1 );
  10033. break;
  10034. case 2:
  10035. render.lines += instanceCount * count;
  10036. break;
  10037. case 0:
  10038. render.points += instanceCount * count;
  10039. break;
  10040. default:
  10041. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10042. break;
  10043. }
  10044. }
  10045. function reset() {
  10046. render.frame ++;
  10047. render.calls = 0;
  10048. render.triangles = 0;
  10049. render.points = 0;
  10050. render.lines = 0;
  10051. }
  10052. return {
  10053. memory: memory,
  10054. render: render,
  10055. programs: null,
  10056. autoReset: true,
  10057. reset: reset,
  10058. update: update
  10059. };
  10060. }
  10061. function numericalSort( a, b ) {
  10062. return a[ 0 ] - b[ 0 ];
  10063. }
  10064. function absNumericalSort( a, b ) {
  10065. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10066. }
  10067. function WebGLMorphtargets( gl ) {
  10068. const influencesList = {};
  10069. const morphInfluences = new Float32Array( 8 );
  10070. const workInfluences = [];
  10071. for ( let i = 0; i < 8; i ++ ) {
  10072. workInfluences[ i ] = [ i, 0 ];
  10073. }
  10074. function update( object, geometry, material, program ) {
  10075. const objectInfluences = object.morphTargetInfluences;
  10076. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10077. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10078. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10079. let influences = influencesList[ geometry.id ];
  10080. if ( influences === undefined ) {
  10081. // initialise list
  10082. influences = [];
  10083. for ( let i = 0; i < length; i ++ ) {
  10084. influences[ i ] = [ i, 0 ];
  10085. }
  10086. influencesList[ geometry.id ] = influences;
  10087. }
  10088. // Collect influences
  10089. for ( let i = 0; i < length; i ++ ) {
  10090. const influence = influences[ i ];
  10091. influence[ 0 ] = i;
  10092. influence[ 1 ] = objectInfluences[ i ];
  10093. }
  10094. influences.sort( absNumericalSort );
  10095. for ( let i = 0; i < 8; i ++ ) {
  10096. if ( i < length && influences[ i ][ 1 ] ) {
  10097. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10098. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10099. } else {
  10100. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10101. workInfluences[ i ][ 1 ] = 0;
  10102. }
  10103. }
  10104. workInfluences.sort( numericalSort );
  10105. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10106. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10107. let morphInfluencesSum = 0;
  10108. for ( let i = 0; i < 8; i ++ ) {
  10109. const influence = workInfluences[ i ];
  10110. const index = influence[ 0 ];
  10111. const value = influence[ 1 ];
  10112. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10113. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10114. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10115. }
  10116. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10117. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10118. }
  10119. morphInfluences[ i ] = value;
  10120. morphInfluencesSum += value;
  10121. } else {
  10122. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== undefined ) {
  10123. geometry.deleteAttribute( 'morphTarget' + i );
  10124. }
  10125. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== undefined ) {
  10126. geometry.deleteAttribute( 'morphNormal' + i );
  10127. }
  10128. morphInfluences[ i ] = 0;
  10129. }
  10130. }
  10131. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10132. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10133. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10134. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10135. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10136. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10137. }
  10138. return {
  10139. update: update
  10140. };
  10141. }
  10142. function WebGLObjects( gl, geometries, attributes, info ) {
  10143. let updateMap = new WeakMap();
  10144. function update( object ) {
  10145. const frame = info.render.frame;
  10146. const geometry = object.geometry;
  10147. const buffergeometry = geometries.get( object, geometry );
  10148. // Update once per frame
  10149. if ( updateMap.get( buffergeometry ) !== frame ) {
  10150. if ( geometry.isGeometry ) {
  10151. buffergeometry.updateFromObject( object );
  10152. }
  10153. geometries.update( buffergeometry );
  10154. updateMap.set( buffergeometry, frame );
  10155. }
  10156. if ( object.isInstancedMesh ) {
  10157. attributes.update( object.instanceMatrix, 34962 );
  10158. if ( object.instanceColor !== null ) {
  10159. attributes.update( object.instanceColor, 34962 );
  10160. }
  10161. }
  10162. return buffergeometry;
  10163. }
  10164. function dispose() {
  10165. updateMap = new WeakMap();
  10166. }
  10167. return {
  10168. update: update,
  10169. dispose: dispose
  10170. };
  10171. }
  10172. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  10173. images = images !== undefined ? images : [];
  10174. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  10175. format = format !== undefined ? format : RGBFormat;
  10176. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  10177. this.flipY = false;
  10178. }
  10179. CubeTexture.prototype = Object.create( Texture.prototype );
  10180. CubeTexture.prototype.constructor = CubeTexture;
  10181. CubeTexture.prototype.isCubeTexture = true;
  10182. Object.defineProperty( CubeTexture.prototype, 'images', {
  10183. get: function () {
  10184. return this.image;
  10185. },
  10186. set: function ( value ) {
  10187. this.image = value;
  10188. }
  10189. } );
  10190. function DataTexture2DArray( data, width, height, depth ) {
  10191. Texture.call( this, null );
  10192. this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
  10193. this.magFilter = NearestFilter;
  10194. this.minFilter = NearestFilter;
  10195. this.wrapR = ClampToEdgeWrapping;
  10196. this.generateMipmaps = false;
  10197. this.flipY = false;
  10198. this.needsUpdate = true;
  10199. }
  10200. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  10201. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10202. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10203. function DataTexture3D( data, width, height, depth ) {
  10204. // We're going to add .setXXX() methods for setting properties later.
  10205. // Users can still set in DataTexture3D directly.
  10206. //
  10207. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10208. // texture.anisotropy = 16;
  10209. //
  10210. // See #14839
  10211. Texture.call( this, null );
  10212. this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
  10213. this.magFilter = NearestFilter;
  10214. this.minFilter = NearestFilter;
  10215. this.wrapR = ClampToEdgeWrapping;
  10216. this.generateMipmaps = false;
  10217. this.flipY = false;
  10218. this.needsUpdate = true;
  10219. }
  10220. DataTexture3D.prototype = Object.create( Texture.prototype );
  10221. DataTexture3D.prototype.constructor = DataTexture3D;
  10222. DataTexture3D.prototype.isDataTexture3D = true;
  10223. /**
  10224. * Uniforms of a program.
  10225. * Those form a tree structure with a special top-level container for the root,
  10226. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10227. *
  10228. *
  10229. * Properties of inner nodes including the top-level container:
  10230. *
  10231. * .seq - array of nested uniforms
  10232. * .map - nested uniforms by name
  10233. *
  10234. *
  10235. * Methods of all nodes except the top-level container:
  10236. *
  10237. * .setValue( gl, value, [textures] )
  10238. *
  10239. * uploads a uniform value(s)
  10240. * the 'textures' parameter is needed for sampler uniforms
  10241. *
  10242. *
  10243. * Static methods of the top-level container (textures factorizations):
  10244. *
  10245. * .upload( gl, seq, values, textures )
  10246. *
  10247. * sets uniforms in 'seq' to 'values[id].value'
  10248. *
  10249. * .seqWithValue( seq, values ) : filteredSeq
  10250. *
  10251. * filters 'seq' entries with corresponding entry in values
  10252. *
  10253. *
  10254. * Methods of the top-level container (textures factorizations):
  10255. *
  10256. * .setValue( gl, name, value, textures )
  10257. *
  10258. * sets uniform with name 'name' to 'value'
  10259. *
  10260. * .setOptional( gl, obj, prop )
  10261. *
  10262. * like .set for an optional property of the object
  10263. *
  10264. */
  10265. const emptyTexture = new Texture();
  10266. const emptyTexture2dArray = new DataTexture2DArray();
  10267. const emptyTexture3d = new DataTexture3D();
  10268. const emptyCubeTexture = new CubeTexture();
  10269. // --- Utilities ---
  10270. // Array Caches (provide typed arrays for temporary by size)
  10271. const arrayCacheF32 = [];
  10272. const arrayCacheI32 = [];
  10273. // Float32Array caches used for uploading Matrix uniforms
  10274. const mat4array = new Float32Array( 16 );
  10275. const mat3array = new Float32Array( 9 );
  10276. const mat2array = new Float32Array( 4 );
  10277. // Flattening for arrays of vectors and matrices
  10278. function flatten( array, nBlocks, blockSize ) {
  10279. const firstElem = array[ 0 ];
  10280. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10281. // unoptimized: ! isNaN( firstElem )
  10282. // see http://jacksondunstan.com/articles/983
  10283. const n = nBlocks * blockSize;
  10284. let r = arrayCacheF32[ n ];
  10285. if ( r === undefined ) {
  10286. r = new Float32Array( n );
  10287. arrayCacheF32[ n ] = r;
  10288. }
  10289. if ( nBlocks !== 0 ) {
  10290. firstElem.toArray( r, 0 );
  10291. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10292. offset += blockSize;
  10293. array[ i ].toArray( r, offset );
  10294. }
  10295. }
  10296. return r;
  10297. }
  10298. function arraysEqual( a, b ) {
  10299. if ( a.length !== b.length ) return false;
  10300. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10301. if ( a[ i ] !== b[ i ] ) return false;
  10302. }
  10303. return true;
  10304. }
  10305. function copyArray( a, b ) {
  10306. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10307. a[ i ] = b[ i ];
  10308. }
  10309. }
  10310. // Texture unit allocation
  10311. function allocTexUnits( textures, n ) {
  10312. let r = arrayCacheI32[ n ];
  10313. if ( r === undefined ) {
  10314. r = new Int32Array( n );
  10315. arrayCacheI32[ n ] = r;
  10316. }
  10317. for ( let i = 0; i !== n; ++ i ) {
  10318. r[ i ] = textures.allocateTextureUnit();
  10319. }
  10320. return r;
  10321. }
  10322. // --- Setters ---
  10323. // Note: Defining these methods externally, because they come in a bunch
  10324. // and this way their names minify.
  10325. // Single scalar
  10326. function setValueV1f( gl, v ) {
  10327. const cache = this.cache;
  10328. if ( cache[ 0 ] === v ) return;
  10329. gl.uniform1f( this.addr, v );
  10330. cache[ 0 ] = v;
  10331. }
  10332. // Single float vector (from flat array or THREE.VectorN)
  10333. function setValueV2f( gl, v ) {
  10334. const cache = this.cache;
  10335. if ( v.x !== undefined ) {
  10336. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10337. gl.uniform2f( this.addr, v.x, v.y );
  10338. cache[ 0 ] = v.x;
  10339. cache[ 1 ] = v.y;
  10340. }
  10341. } else {
  10342. if ( arraysEqual( cache, v ) ) return;
  10343. gl.uniform2fv( this.addr, v );
  10344. copyArray( cache, v );
  10345. }
  10346. }
  10347. function setValueV3f( gl, v ) {
  10348. const cache = this.cache;
  10349. if ( v.x !== undefined ) {
  10350. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10351. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10352. cache[ 0 ] = v.x;
  10353. cache[ 1 ] = v.y;
  10354. cache[ 2 ] = v.z;
  10355. }
  10356. } else if ( v.r !== undefined ) {
  10357. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10358. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10359. cache[ 0 ] = v.r;
  10360. cache[ 1 ] = v.g;
  10361. cache[ 2 ] = v.b;
  10362. }
  10363. } else {
  10364. if ( arraysEqual( cache, v ) ) return;
  10365. gl.uniform3fv( this.addr, v );
  10366. copyArray( cache, v );
  10367. }
  10368. }
  10369. function setValueV4f( gl, v ) {
  10370. const cache = this.cache;
  10371. if ( v.x !== undefined ) {
  10372. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10373. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10374. cache[ 0 ] = v.x;
  10375. cache[ 1 ] = v.y;
  10376. cache[ 2 ] = v.z;
  10377. cache[ 3 ] = v.w;
  10378. }
  10379. } else {
  10380. if ( arraysEqual( cache, v ) ) return;
  10381. gl.uniform4fv( this.addr, v );
  10382. copyArray( cache, v );
  10383. }
  10384. }
  10385. // Single matrix (from flat array or MatrixN)
  10386. function setValueM2( gl, v ) {
  10387. const cache = this.cache;
  10388. const elements = v.elements;
  10389. if ( elements === undefined ) {
  10390. if ( arraysEqual( cache, v ) ) return;
  10391. gl.uniformMatrix2fv( this.addr, false, v );
  10392. copyArray( cache, v );
  10393. } else {
  10394. if ( arraysEqual( cache, elements ) ) return;
  10395. mat2array.set( elements );
  10396. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10397. copyArray( cache, elements );
  10398. }
  10399. }
  10400. function setValueM3( gl, v ) {
  10401. const cache = this.cache;
  10402. const elements = v.elements;
  10403. if ( elements === undefined ) {
  10404. if ( arraysEqual( cache, v ) ) return;
  10405. gl.uniformMatrix3fv( this.addr, false, v );
  10406. copyArray( cache, v );
  10407. } else {
  10408. if ( arraysEqual( cache, elements ) ) return;
  10409. mat3array.set( elements );
  10410. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10411. copyArray( cache, elements );
  10412. }
  10413. }
  10414. function setValueM4( gl, v ) {
  10415. const cache = this.cache;
  10416. const elements = v.elements;
  10417. if ( elements === undefined ) {
  10418. if ( arraysEqual( cache, v ) ) return;
  10419. gl.uniformMatrix4fv( this.addr, false, v );
  10420. copyArray( cache, v );
  10421. } else {
  10422. if ( arraysEqual( cache, elements ) ) return;
  10423. mat4array.set( elements );
  10424. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10425. copyArray( cache, elements );
  10426. }
  10427. }
  10428. // Single texture (2D / Cube)
  10429. function setValueT1( gl, v, textures ) {
  10430. const cache = this.cache;
  10431. const unit = textures.allocateTextureUnit();
  10432. if ( cache[ 0 ] !== unit ) {
  10433. gl.uniform1i( this.addr, unit );
  10434. cache[ 0 ] = unit;
  10435. }
  10436. textures.safeSetTexture2D( v || emptyTexture, unit );
  10437. }
  10438. function setValueT2DArray1( gl, v, textures ) {
  10439. const cache = this.cache;
  10440. const unit = textures.allocateTextureUnit();
  10441. if ( cache[ 0 ] !== unit ) {
  10442. gl.uniform1i( this.addr, unit );
  10443. cache[ 0 ] = unit;
  10444. }
  10445. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10446. }
  10447. function setValueT3D1( gl, v, textures ) {
  10448. const cache = this.cache;
  10449. const unit = textures.allocateTextureUnit();
  10450. if ( cache[ 0 ] !== unit ) {
  10451. gl.uniform1i( this.addr, unit );
  10452. cache[ 0 ] = unit;
  10453. }
  10454. textures.setTexture3D( v || emptyTexture3d, unit );
  10455. }
  10456. function setValueT6( gl, v, textures ) {
  10457. const cache = this.cache;
  10458. const unit = textures.allocateTextureUnit();
  10459. if ( cache[ 0 ] !== unit ) {
  10460. gl.uniform1i( this.addr, unit );
  10461. cache[ 0 ] = unit;
  10462. }
  10463. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10464. }
  10465. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10466. function setValueV1i( gl, v ) {
  10467. const cache = this.cache;
  10468. if ( cache[ 0 ] === v ) return;
  10469. gl.uniform1i( this.addr, v );
  10470. cache[ 0 ] = v;
  10471. }
  10472. function setValueV2i( gl, v ) {
  10473. const cache = this.cache;
  10474. if ( arraysEqual( cache, v ) ) return;
  10475. gl.uniform2iv( this.addr, v );
  10476. copyArray( cache, v );
  10477. }
  10478. function setValueV3i( gl, v ) {
  10479. const cache = this.cache;
  10480. if ( arraysEqual( cache, v ) ) return;
  10481. gl.uniform3iv( this.addr, v );
  10482. copyArray( cache, v );
  10483. }
  10484. function setValueV4i( gl, v ) {
  10485. const cache = this.cache;
  10486. if ( arraysEqual( cache, v ) ) return;
  10487. gl.uniform4iv( this.addr, v );
  10488. copyArray( cache, v );
  10489. }
  10490. // uint
  10491. function setValueV1ui( gl, v ) {
  10492. const cache = this.cache;
  10493. if ( cache[ 0 ] === v ) return;
  10494. gl.uniform1ui( this.addr, v );
  10495. cache[ 0 ] = v;
  10496. }
  10497. // Helper to pick the right setter for the singular case
  10498. function getSingularSetter( type ) {
  10499. switch ( type ) {
  10500. case 0x1406: return setValueV1f; // FLOAT
  10501. case 0x8b50: return setValueV2f; // _VEC2
  10502. case 0x8b51: return setValueV3f; // _VEC3
  10503. case 0x8b52: return setValueV4f; // _VEC4
  10504. case 0x8b5a: return setValueM2; // _MAT2
  10505. case 0x8b5b: return setValueM3; // _MAT3
  10506. case 0x8b5c: return setValueM4; // _MAT4
  10507. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10508. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10509. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10510. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10511. case 0x1405: return setValueV1ui; // UINT
  10512. case 0x8b5e: // SAMPLER_2D
  10513. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10514. case 0x8dca: // INT_SAMPLER_2D
  10515. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10516. case 0x8b62: // SAMPLER_2D_SHADOW
  10517. return setValueT1;
  10518. case 0x8b5f: // SAMPLER_3D
  10519. case 0x8dcb: // INT_SAMPLER_3D
  10520. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10521. return setValueT3D1;
  10522. case 0x8b60: // SAMPLER_CUBE
  10523. case 0x8dcc: // INT_SAMPLER_CUBE
  10524. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10525. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10526. return setValueT6;
  10527. case 0x8dc1: // SAMPLER_2D_ARRAY
  10528. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10529. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10530. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10531. return setValueT2DArray1;
  10532. }
  10533. }
  10534. // Array of scalars
  10535. function setValueV1fArray( gl, v ) {
  10536. gl.uniform1fv( this.addr, v );
  10537. }
  10538. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10539. function setValueV1iArray( gl, v ) {
  10540. gl.uniform1iv( this.addr, v );
  10541. }
  10542. function setValueV2iArray( gl, v ) {
  10543. gl.uniform2iv( this.addr, v );
  10544. }
  10545. function setValueV3iArray( gl, v ) {
  10546. gl.uniform3iv( this.addr, v );
  10547. }
  10548. function setValueV4iArray( gl, v ) {
  10549. gl.uniform4iv( this.addr, v );
  10550. }
  10551. // Array of vectors (flat or from THREE classes)
  10552. function setValueV2fArray( gl, v ) {
  10553. const data = flatten( v, this.size, 2 );
  10554. gl.uniform2fv( this.addr, data );
  10555. }
  10556. function setValueV3fArray( gl, v ) {
  10557. const data = flatten( v, this.size, 3 );
  10558. gl.uniform3fv( this.addr, data );
  10559. }
  10560. function setValueV4fArray( gl, v ) {
  10561. const data = flatten( v, this.size, 4 );
  10562. gl.uniform4fv( this.addr, data );
  10563. }
  10564. // Array of matrices (flat or from THREE clases)
  10565. function setValueM2Array( gl, v ) {
  10566. const data = flatten( v, this.size, 4 );
  10567. gl.uniformMatrix2fv( this.addr, false, data );
  10568. }
  10569. function setValueM3Array( gl, v ) {
  10570. const data = flatten( v, this.size, 9 );
  10571. gl.uniformMatrix3fv( this.addr, false, data );
  10572. }
  10573. function setValueM4Array( gl, v ) {
  10574. const data = flatten( v, this.size, 16 );
  10575. gl.uniformMatrix4fv( this.addr, false, data );
  10576. }
  10577. // Array of textures (2D / Cube)
  10578. function setValueT1Array( gl, v, textures ) {
  10579. const n = v.length;
  10580. const units = allocTexUnits( textures, n );
  10581. gl.uniform1iv( this.addr, units );
  10582. for ( let i = 0; i !== n; ++ i ) {
  10583. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10584. }
  10585. }
  10586. function setValueT6Array( gl, v, textures ) {
  10587. const n = v.length;
  10588. const units = allocTexUnits( textures, n );
  10589. gl.uniform1iv( this.addr, units );
  10590. for ( let i = 0; i !== n; ++ i ) {
  10591. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10592. }
  10593. }
  10594. // Helper to pick the right setter for a pure (bottom-level) array
  10595. function getPureArraySetter( type ) {
  10596. switch ( type ) {
  10597. case 0x1406: return setValueV1fArray; // FLOAT
  10598. case 0x8b50: return setValueV2fArray; // _VEC2
  10599. case 0x8b51: return setValueV3fArray; // _VEC3
  10600. case 0x8b52: return setValueV4fArray; // _VEC4
  10601. case 0x8b5a: return setValueM2Array; // _MAT2
  10602. case 0x8b5b: return setValueM3Array; // _MAT3
  10603. case 0x8b5c: return setValueM4Array; // _MAT4
  10604. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10605. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10606. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10607. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10608. case 0x8b5e: // SAMPLER_2D
  10609. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10610. case 0x8dca: // INT_SAMPLER_2D
  10611. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10612. case 0x8b62: // SAMPLER_2D_SHADOW
  10613. return setValueT1Array;
  10614. case 0x8b60: // SAMPLER_CUBE
  10615. case 0x8dcc: // INT_SAMPLER_CUBE
  10616. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10617. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10618. return setValueT6Array;
  10619. }
  10620. }
  10621. // --- Uniform Classes ---
  10622. function SingleUniform( id, activeInfo, addr ) {
  10623. this.id = id;
  10624. this.addr = addr;
  10625. this.cache = [];
  10626. this.setValue = getSingularSetter( activeInfo.type );
  10627. // this.path = activeInfo.name; // DEBUG
  10628. }
  10629. function PureArrayUniform( id, activeInfo, addr ) {
  10630. this.id = id;
  10631. this.addr = addr;
  10632. this.cache = [];
  10633. this.size = activeInfo.size;
  10634. this.setValue = getPureArraySetter( activeInfo.type );
  10635. // this.path = activeInfo.name; // DEBUG
  10636. }
  10637. PureArrayUniform.prototype.updateCache = function ( data ) {
  10638. const cache = this.cache;
  10639. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10640. this.cache = new Float32Array( data.length );
  10641. }
  10642. copyArray( cache, data );
  10643. };
  10644. function StructuredUniform( id ) {
  10645. this.id = id;
  10646. this.seq = [];
  10647. this.map = {};
  10648. }
  10649. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10650. const seq = this.seq;
  10651. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10652. const u = seq[ i ];
  10653. u.setValue( gl, value[ u.id ], textures );
  10654. }
  10655. };
  10656. // --- Top-level ---
  10657. // Parser - builds up the property tree from the path strings
  10658. const RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  10659. // extracts
  10660. // - the identifier (member name or array index)
  10661. // - followed by an optional right bracket (found when array index)
  10662. // - followed by an optional left bracket or dot (type of subscript)
  10663. //
  10664. // Note: These portions can be read in a non-overlapping fashion and
  10665. // allow straightforward parsing of the hierarchy that WebGL encodes
  10666. // in the uniform names.
  10667. function addUniform( container, uniformObject ) {
  10668. container.seq.push( uniformObject );
  10669. container.map[ uniformObject.id ] = uniformObject;
  10670. }
  10671. function parseUniform( activeInfo, addr, container ) {
  10672. const path = activeInfo.name,
  10673. pathLength = path.length;
  10674. // reset RegExp object, because of the early exit of a previous run
  10675. RePathPart.lastIndex = 0;
  10676. while ( true ) {
  10677. const match = RePathPart.exec( path ),
  10678. matchEnd = RePathPart.lastIndex;
  10679. let id = match[ 1 ];
  10680. const idIsIndex = match[ 2 ] === ']',
  10681. subscript = match[ 3 ];
  10682. if ( idIsIndex ) id = id | 0; // convert to integer
  10683. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10684. // bare name or "pure" bottom-level array "[0]" suffix
  10685. addUniform( container, subscript === undefined ?
  10686. new SingleUniform( id, activeInfo, addr ) :
  10687. new PureArrayUniform( id, activeInfo, addr ) );
  10688. break;
  10689. } else {
  10690. // step into inner node / create it in case it doesn't exist
  10691. const map = container.map;
  10692. let next = map[ id ];
  10693. if ( next === undefined ) {
  10694. next = new StructuredUniform( id );
  10695. addUniform( container, next );
  10696. }
  10697. container = next;
  10698. }
  10699. }
  10700. }
  10701. // Root Container
  10702. function WebGLUniforms( gl, program ) {
  10703. this.seq = [];
  10704. this.map = {};
  10705. const n = gl.getProgramParameter( program, 35718 );
  10706. for ( let i = 0; i < n; ++ i ) {
  10707. const info = gl.getActiveUniform( program, i ),
  10708. addr = gl.getUniformLocation( program, info.name );
  10709. parseUniform( info, addr, this );
  10710. }
  10711. }
  10712. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10713. const u = this.map[ name ];
  10714. if ( u !== undefined ) u.setValue( gl, value, textures );
  10715. };
  10716. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10717. const v = object[ name ];
  10718. if ( v !== undefined ) this.setValue( gl, name, v );
  10719. };
  10720. // Static interface
  10721. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10722. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10723. const u = seq[ i ],
  10724. v = values[ u.id ];
  10725. if ( v.needsUpdate !== false ) {
  10726. // note: always updating when .needsUpdate is undefined
  10727. u.setValue( gl, v.value, textures );
  10728. }
  10729. }
  10730. };
  10731. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10732. const r = [];
  10733. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10734. const u = seq[ i ];
  10735. if ( u.id in values ) r.push( u );
  10736. }
  10737. return r;
  10738. };
  10739. function WebGLShader( gl, type, string ) {
  10740. const shader = gl.createShader( type );
  10741. gl.shaderSource( shader, string );
  10742. gl.compileShader( shader );
  10743. return shader;
  10744. }
  10745. let programIdCount = 0;
  10746. function addLineNumbers( string ) {
  10747. const lines = string.split( '\n' );
  10748. for ( let i = 0; i < lines.length; i ++ ) {
  10749. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10750. }
  10751. return lines.join( '\n' );
  10752. }
  10753. function getEncodingComponents( encoding ) {
  10754. switch ( encoding ) {
  10755. case LinearEncoding:
  10756. return [ 'Linear', '( value )' ];
  10757. case sRGBEncoding:
  10758. return [ 'sRGB', '( value )' ];
  10759. case RGBEEncoding:
  10760. return [ 'RGBE', '( value )' ];
  10761. case RGBM7Encoding:
  10762. return [ 'RGBM', '( value, 7.0 )' ];
  10763. case RGBM16Encoding:
  10764. return [ 'RGBM', '( value, 16.0 )' ];
  10765. case RGBDEncoding:
  10766. return [ 'RGBD', '( value, 256.0 )' ];
  10767. case GammaEncoding:
  10768. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10769. case LogLuvEncoding:
  10770. return [ 'LogLuv', '( value )' ];
  10771. default:
  10772. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10773. return [ 'Linear', '( value )' ];
  10774. }
  10775. }
  10776. function getShaderErrors( gl, shader, type ) {
  10777. const status = gl.getShaderParameter( shader, 35713 );
  10778. const log = gl.getShaderInfoLog( shader ).trim();
  10779. if ( status && log === '' ) return '';
  10780. // --enable-privileged-webgl-extension
  10781. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10782. const source = gl.getShaderSource( shader );
  10783. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  10784. }
  10785. function getTexelDecodingFunction( functionName, encoding ) {
  10786. const components = getEncodingComponents( encoding );
  10787. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10788. }
  10789. function getTexelEncodingFunction( functionName, encoding ) {
  10790. const components = getEncodingComponents( encoding );
  10791. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10792. }
  10793. function getToneMappingFunction( functionName, toneMapping ) {
  10794. let toneMappingName;
  10795. switch ( toneMapping ) {
  10796. case LinearToneMapping:
  10797. toneMappingName = 'Linear';
  10798. break;
  10799. case ReinhardToneMapping:
  10800. toneMappingName = 'Reinhard';
  10801. break;
  10802. case CineonToneMapping:
  10803. toneMappingName = 'OptimizedCineon';
  10804. break;
  10805. case ACESFilmicToneMapping:
  10806. toneMappingName = 'ACESFilmic';
  10807. break;
  10808. case CustomToneMapping:
  10809. toneMappingName = 'Custom';
  10810. break;
  10811. default:
  10812. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10813. toneMappingName = 'Linear';
  10814. }
  10815. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10816. }
  10817. function generateExtensions( parameters ) {
  10818. const chunks = [
  10819. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10820. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10821. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10822. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10823. ];
  10824. return chunks.filter( filterEmptyLine ).join( '\n' );
  10825. }
  10826. function generateDefines( defines ) {
  10827. const chunks = [];
  10828. for ( const name in defines ) {
  10829. const value = defines[ name ];
  10830. if ( value === false ) continue;
  10831. chunks.push( '#define ' + name + ' ' + value );
  10832. }
  10833. return chunks.join( '\n' );
  10834. }
  10835. function fetchAttributeLocations( gl, program ) {
  10836. const attributes = {};
  10837. const n = gl.getProgramParameter( program, 35721 );
  10838. for ( let i = 0; i < n; i ++ ) {
  10839. const info = gl.getActiveAttrib( program, i );
  10840. const name = info.name;
  10841. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10842. attributes[ name ] = gl.getAttribLocation( program, name );
  10843. }
  10844. return attributes;
  10845. }
  10846. function filterEmptyLine( string ) {
  10847. return string !== '';
  10848. }
  10849. function replaceLightNums( string, parameters ) {
  10850. return string
  10851. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10852. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10853. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10854. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10855. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10856. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10857. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10858. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10859. }
  10860. function replaceClippingPlaneNums( string, parameters ) {
  10861. return string
  10862. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10863. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10864. }
  10865. // Resolve Includes
  10866. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10867. function resolveIncludes( string ) {
  10868. return string.replace( includePattern, includeReplacer );
  10869. }
  10870. function includeReplacer( match, include ) {
  10871. const string = ShaderChunk[ include ];
  10872. if ( string === undefined ) {
  10873. throw new Error( 'Can not resolve #include <' + include + '>' );
  10874. }
  10875. return resolveIncludes( string );
  10876. }
  10877. // Unroll Loops
  10878. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10879. 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;
  10880. function unrollLoops( string ) {
  10881. return string
  10882. .replace( unrollLoopPattern, loopReplacer )
  10883. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10884. }
  10885. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10886. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10887. return loopReplacer( match, start, end, snippet );
  10888. }
  10889. function loopReplacer( match, start, end, snippet ) {
  10890. let string = '';
  10891. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10892. string += snippet
  10893. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10894. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10895. }
  10896. return string;
  10897. }
  10898. //
  10899. function generatePrecision( parameters ) {
  10900. let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  10901. if ( parameters.precision === "highp" ) {
  10902. precisionstring += "\n#define HIGH_PRECISION";
  10903. } else if ( parameters.precision === "mediump" ) {
  10904. precisionstring += "\n#define MEDIUM_PRECISION";
  10905. } else if ( parameters.precision === "lowp" ) {
  10906. precisionstring += "\n#define LOW_PRECISION";
  10907. }
  10908. return precisionstring;
  10909. }
  10910. function generateShadowMapTypeDefine( parameters ) {
  10911. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10912. if ( parameters.shadowMapType === PCFShadowMap ) {
  10913. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10914. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10915. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10916. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10917. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10918. }
  10919. return shadowMapTypeDefine;
  10920. }
  10921. function generateEnvMapTypeDefine( parameters ) {
  10922. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10923. if ( parameters.envMap ) {
  10924. switch ( parameters.envMapMode ) {
  10925. case CubeReflectionMapping:
  10926. case CubeRefractionMapping:
  10927. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10928. break;
  10929. case CubeUVReflectionMapping:
  10930. case CubeUVRefractionMapping:
  10931. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10932. break;
  10933. }
  10934. }
  10935. return envMapTypeDefine;
  10936. }
  10937. function generateEnvMapModeDefine( parameters ) {
  10938. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10939. if ( parameters.envMap ) {
  10940. switch ( parameters.envMapMode ) {
  10941. case CubeRefractionMapping:
  10942. case CubeUVRefractionMapping:
  10943. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10944. break;
  10945. }
  10946. }
  10947. return envMapModeDefine;
  10948. }
  10949. function generateEnvMapBlendingDefine( parameters ) {
  10950. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10951. if ( parameters.envMap ) {
  10952. switch ( parameters.combine ) {
  10953. case MultiplyOperation:
  10954. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10955. break;
  10956. case MixOperation:
  10957. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10958. break;
  10959. case AddOperation:
  10960. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10961. break;
  10962. }
  10963. }
  10964. return envMapBlendingDefine;
  10965. }
  10966. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10967. const gl = renderer.getContext();
  10968. const defines = parameters.defines;
  10969. let vertexShader = parameters.vertexShader;
  10970. let fragmentShader = parameters.fragmentShader;
  10971. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10972. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10973. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10974. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10975. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10976. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10977. const customDefines = generateDefines( defines );
  10978. const program = gl.createProgram();
  10979. let prefixVertex, prefixFragment;
  10980. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + "\n" : '';
  10981. if ( parameters.isRawShaderMaterial ) {
  10982. prefixVertex = [
  10983. customDefines
  10984. ].filter( filterEmptyLine ).join( '\n' );
  10985. if ( prefixVertex.length > 0 ) {
  10986. prefixVertex += '\n';
  10987. }
  10988. prefixFragment = [
  10989. customExtensions,
  10990. customDefines
  10991. ].filter( filterEmptyLine ).join( '\n' );
  10992. if ( prefixFragment.length > 0 ) {
  10993. prefixFragment += '\n';
  10994. }
  10995. } else {
  10996. prefixVertex = [
  10997. generatePrecision( parameters ),
  10998. '#define SHADER_NAME ' + parameters.shaderName,
  10999. customDefines,
  11000. parameters.instancing ? '#define USE_INSTANCING' : '',
  11001. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11002. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11003. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11004. '#define MAX_BONES ' + parameters.maxBones,
  11005. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11006. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11007. parameters.map ? '#define USE_MAP' : '',
  11008. parameters.envMap ? '#define USE_ENVMAP' : '',
  11009. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11010. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11011. parameters.aoMap ? '#define USE_AOMAP' : '',
  11012. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11013. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11014. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11015. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11016. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11017. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11018. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11019. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11020. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11021. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11022. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11023. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11024. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11025. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11026. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11027. parameters.vertexColors ? '#define USE_COLOR' : '',
  11028. parameters.vertexUvs ? '#define USE_UV' : '',
  11029. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11030. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11031. parameters.skinning ? '#define USE_SKINNING' : '',
  11032. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  11033. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11034. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11035. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11036. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11037. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11038. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11039. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11040. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11041. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11042. 'uniform mat4 modelMatrix;',
  11043. 'uniform mat4 modelViewMatrix;',
  11044. 'uniform mat4 projectionMatrix;',
  11045. 'uniform mat4 viewMatrix;',
  11046. 'uniform mat3 normalMatrix;',
  11047. 'uniform vec3 cameraPosition;',
  11048. 'uniform bool isOrthographic;',
  11049. '#ifdef USE_INSTANCING',
  11050. ' attribute mat4 instanceMatrix;',
  11051. '#endif',
  11052. '#ifdef USE_INSTANCING_COLOR',
  11053. ' attribute vec3 instanceColor;',
  11054. '#endif',
  11055. 'attribute vec3 position;',
  11056. 'attribute vec3 normal;',
  11057. 'attribute vec2 uv;',
  11058. '#ifdef USE_TANGENT',
  11059. ' attribute vec4 tangent;',
  11060. '#endif',
  11061. '#ifdef USE_COLOR',
  11062. ' attribute vec3 color;',
  11063. '#endif',
  11064. '#ifdef USE_MORPHTARGETS',
  11065. ' attribute vec3 morphTarget0;',
  11066. ' attribute vec3 morphTarget1;',
  11067. ' attribute vec3 morphTarget2;',
  11068. ' attribute vec3 morphTarget3;',
  11069. ' #ifdef USE_MORPHNORMALS',
  11070. ' attribute vec3 morphNormal0;',
  11071. ' attribute vec3 morphNormal1;',
  11072. ' attribute vec3 morphNormal2;',
  11073. ' attribute vec3 morphNormal3;',
  11074. ' #else',
  11075. ' attribute vec3 morphTarget4;',
  11076. ' attribute vec3 morphTarget5;',
  11077. ' attribute vec3 morphTarget6;',
  11078. ' attribute vec3 morphTarget7;',
  11079. ' #endif',
  11080. '#endif',
  11081. '#ifdef USE_SKINNING',
  11082. ' attribute vec4 skinIndex;',
  11083. ' attribute vec4 skinWeight;',
  11084. '#endif',
  11085. '\n'
  11086. ].filter( filterEmptyLine ).join( '\n' );
  11087. prefixFragment = [
  11088. customExtensions,
  11089. generatePrecision( parameters ),
  11090. '#define SHADER_NAME ' + parameters.shaderName,
  11091. customDefines,
  11092. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  11093. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11094. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11095. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11096. parameters.map ? '#define USE_MAP' : '',
  11097. parameters.matcap ? '#define USE_MATCAP' : '',
  11098. parameters.envMap ? '#define USE_ENVMAP' : '',
  11099. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11100. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11101. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11102. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11103. parameters.aoMap ? '#define USE_AOMAP' : '',
  11104. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11105. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11106. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11107. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11108. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11109. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11110. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11111. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11112. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11113. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11114. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11115. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11116. parameters.sheen ? '#define USE_SHEEN' : '',
  11117. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11118. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11119. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11120. parameters.vertexUvs ? '#define USE_UV' : '',
  11121. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11122. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11123. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11124. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11125. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11126. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11127. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11128. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11129. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11130. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11131. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11132. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11133. 'uniform mat4 viewMatrix;',
  11134. 'uniform vec3 cameraPosition;',
  11135. 'uniform bool isOrthographic;',
  11136. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11137. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11138. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11139. parameters.dithering ? '#define DITHERING' : '',
  11140. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11141. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11142. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11143. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11144. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11145. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11146. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11147. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11148. '\n'
  11149. ].filter( filterEmptyLine ).join( '\n' );
  11150. }
  11151. vertexShader = resolveIncludes( vertexShader );
  11152. vertexShader = replaceLightNums( vertexShader, parameters );
  11153. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11154. fragmentShader = resolveIncludes( fragmentShader );
  11155. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11156. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11157. vertexShader = unrollLoops( vertexShader );
  11158. fragmentShader = unrollLoops( fragmentShader );
  11159. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11160. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11161. versionString = '#version 300 es\n';
  11162. prefixVertex = [
  11163. '#define attribute in',
  11164. '#define varying out',
  11165. '#define texture2D texture'
  11166. ].join( '\n' ) + '\n' + prefixVertex;
  11167. prefixFragment = [
  11168. '#define varying in',
  11169. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11170. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11171. '#define gl_FragDepthEXT gl_FragDepth',
  11172. '#define texture2D texture',
  11173. '#define textureCube texture',
  11174. '#define texture2DProj textureProj',
  11175. '#define texture2DLodEXT textureLod',
  11176. '#define texture2DProjLodEXT textureProjLod',
  11177. '#define textureCubeLodEXT textureLod',
  11178. '#define texture2DGradEXT textureGrad',
  11179. '#define texture2DProjGradEXT textureProjGrad',
  11180. '#define textureCubeGradEXT textureGrad'
  11181. ].join( '\n' ) + '\n' + prefixFragment;
  11182. }
  11183. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11184. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11185. // console.log( '*VERTEX*', vertexGlsl );
  11186. // console.log( '*FRAGMENT*', fragmentGlsl );
  11187. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11188. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11189. gl.attachShader( program, glVertexShader );
  11190. gl.attachShader( program, glFragmentShader );
  11191. // Force a particular attribute to index 0.
  11192. if ( parameters.index0AttributeName !== undefined ) {
  11193. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11194. } else if ( parameters.morphTargets === true ) {
  11195. // programs with morphTargets displace position out of attribute 0
  11196. gl.bindAttribLocation( program, 0, 'position' );
  11197. }
  11198. gl.linkProgram( program );
  11199. // check for link errors
  11200. if ( renderer.debug.checkShaderErrors ) {
  11201. const programLog = gl.getProgramInfoLog( program ).trim();
  11202. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11203. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11204. let runnable = true;
  11205. let haveDiagnostics = true;
  11206. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11207. runnable = false;
  11208. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11209. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11210. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  11211. } else if ( programLog !== '' ) {
  11212. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  11213. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11214. haveDiagnostics = false;
  11215. }
  11216. if ( haveDiagnostics ) {
  11217. this.diagnostics = {
  11218. runnable: runnable,
  11219. programLog: programLog,
  11220. vertexShader: {
  11221. log: vertexLog,
  11222. prefix: prefixVertex
  11223. },
  11224. fragmentShader: {
  11225. log: fragmentLog,
  11226. prefix: prefixFragment
  11227. }
  11228. };
  11229. }
  11230. }
  11231. // Clean up
  11232. // Crashes in iOS9 and iOS10. #18402
  11233. // gl.detachShader( program, glVertexShader );
  11234. // gl.detachShader( program, glFragmentShader );
  11235. gl.deleteShader( glVertexShader );
  11236. gl.deleteShader( glFragmentShader );
  11237. // set up caching for uniform locations
  11238. let cachedUniforms;
  11239. this.getUniforms = function () {
  11240. if ( cachedUniforms === undefined ) {
  11241. cachedUniforms = new WebGLUniforms( gl, program );
  11242. }
  11243. return cachedUniforms;
  11244. };
  11245. // set up caching for attribute locations
  11246. let cachedAttributes;
  11247. this.getAttributes = function () {
  11248. if ( cachedAttributes === undefined ) {
  11249. cachedAttributes = fetchAttributeLocations( gl, program );
  11250. }
  11251. return cachedAttributes;
  11252. };
  11253. // free resource
  11254. this.destroy = function () {
  11255. bindingStates.releaseStatesOfProgram( this );
  11256. gl.deleteProgram( program );
  11257. this.program = undefined;
  11258. };
  11259. //
  11260. this.name = parameters.shaderName;
  11261. this.id = programIdCount ++;
  11262. this.cacheKey = cacheKey;
  11263. this.usedTimes = 1;
  11264. this.program = program;
  11265. this.vertexShader = glVertexShader;
  11266. this.fragmentShader = glFragmentShader;
  11267. return this;
  11268. }
  11269. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  11270. const programs = [];
  11271. const isWebGL2 = capabilities.isWebGL2;
  11272. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11273. const floatVertexTextures = capabilities.floatVertexTextures;
  11274. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11275. const vertexTextures = capabilities.vertexTextures;
  11276. let precision = capabilities.precision;
  11277. const shaderIDs = {
  11278. MeshDepthMaterial: 'depth',
  11279. MeshDistanceMaterial: 'distanceRGBA',
  11280. MeshNormalMaterial: 'normal',
  11281. MeshBasicMaterial: 'basic',
  11282. MeshLambertMaterial: 'lambert',
  11283. MeshPhongMaterial: 'phong',
  11284. MeshToonMaterial: 'toon',
  11285. MeshStandardMaterial: 'physical',
  11286. MeshPhysicalMaterial: 'physical',
  11287. MeshMatcapMaterial: 'matcap',
  11288. LineBasicMaterial: 'basic',
  11289. LineDashedMaterial: 'dashed',
  11290. PointsMaterial: 'points',
  11291. ShadowMaterial: 'shadow',
  11292. SpriteMaterial: 'sprite'
  11293. };
  11294. const parameterNames = [
  11295. "precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "instancingColor",
  11296. "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
  11297. "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap",
  11298. "roughnessMap", "metalnessMap", "gradientMap",
  11299. "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2",
  11300. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  11301. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  11302. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  11303. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  11304. "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
  11305. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  11306. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
  11307. "sheen", "transmissionMap"
  11308. ];
  11309. function getMaxBones( object ) {
  11310. const skeleton = object.skeleton;
  11311. const bones = skeleton.bones;
  11312. if ( floatVertexTextures ) {
  11313. return 1024;
  11314. } else {
  11315. // default for when object is not specified
  11316. // ( for example when prebuilding shader to be used with multiple objects )
  11317. //
  11318. // - leave some extra space for other uniforms
  11319. // - limit here is ANGLE's 254 max uniform vectors
  11320. // (up to 54 should be safe)
  11321. const nVertexUniforms = maxVertexUniforms;
  11322. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11323. const maxBones = Math.min( nVertexMatrices, bones.length );
  11324. if ( maxBones < bones.length ) {
  11325. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11326. return 0;
  11327. }
  11328. return maxBones;
  11329. }
  11330. }
  11331. function getTextureEncodingFromMap( map ) {
  11332. let encoding;
  11333. if ( ! map ) {
  11334. encoding = LinearEncoding;
  11335. } else if ( map.isTexture ) {
  11336. encoding = map.encoding;
  11337. } else if ( map.isWebGLRenderTarget ) {
  11338. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  11339. encoding = map.texture.encoding;
  11340. }
  11341. return encoding;
  11342. }
  11343. function getParameters( material, lights, shadows, scene, object ) {
  11344. const fog = scene.fog;
  11345. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11346. const envMap = cubemaps.get( material.envMap || environment );
  11347. const shaderID = shaderIDs[ material.type ];
  11348. // heuristics to create shader parameters according to lights in the scene
  11349. // (not to blow over maxLights budget)
  11350. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11351. if ( material.precision !== null ) {
  11352. precision = capabilities.getMaxPrecision( material.precision );
  11353. if ( precision !== material.precision ) {
  11354. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11355. }
  11356. }
  11357. let vertexShader, fragmentShader;
  11358. if ( shaderID ) {
  11359. const shader = ShaderLib[ shaderID ];
  11360. vertexShader = shader.vertexShader;
  11361. fragmentShader = shader.fragmentShader;
  11362. } else {
  11363. vertexShader = material.vertexShader;
  11364. fragmentShader = material.fragmentShader;
  11365. }
  11366. const currentRenderTarget = renderer.getRenderTarget();
  11367. const parameters = {
  11368. isWebGL2: isWebGL2,
  11369. shaderID: shaderID,
  11370. shaderName: material.type,
  11371. vertexShader: vertexShader,
  11372. fragmentShader: fragmentShader,
  11373. defines: material.defines,
  11374. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11375. glslVersion: material.glslVersion,
  11376. precision: precision,
  11377. instancing: object.isInstancedMesh === true,
  11378. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11379. supportsVertexTextures: vertexTextures,
  11380. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11381. map: !! material.map,
  11382. mapEncoding: getTextureEncodingFromMap( material.map ),
  11383. matcap: !! material.matcap,
  11384. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11385. envMap: !! envMap,
  11386. envMapMode: envMap && envMap.mapping,
  11387. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11388. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11389. lightMap: !! material.lightMap,
  11390. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11391. aoMap: !! material.aoMap,
  11392. emissiveMap: !! material.emissiveMap,
  11393. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11394. bumpMap: !! material.bumpMap,
  11395. normalMap: !! material.normalMap,
  11396. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11397. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11398. clearcoatMap: !! material.clearcoatMap,
  11399. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  11400. clearcoatNormalMap: !! material.clearcoatNormalMap,
  11401. displacementMap: !! material.displacementMap,
  11402. roughnessMap: !! material.roughnessMap,
  11403. metalnessMap: !! material.metalnessMap,
  11404. specularMap: !! material.specularMap,
  11405. alphaMap: !! material.alphaMap,
  11406. gradientMap: !! material.gradientMap,
  11407. sheen: !! material.sheen,
  11408. transmissionMap: !! material.transmissionMap,
  11409. combine: material.combine,
  11410. vertexTangents: ( material.normalMap && material.vertexTangents ),
  11411. vertexColors: material.vertexColors,
  11412. 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,
  11413. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  11414. fog: !! fog,
  11415. useFog: material.fog,
  11416. fogExp2: ( fog && fog.isFogExp2 ),
  11417. flatShading: material.flatShading,
  11418. sizeAttenuation: material.sizeAttenuation,
  11419. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11420. skinning: material.skinning && maxBones > 0,
  11421. maxBones: maxBones,
  11422. useVertexTexture: floatVertexTextures,
  11423. morphTargets: material.morphTargets,
  11424. morphNormals: material.morphNormals,
  11425. maxMorphTargets: renderer.maxMorphTargets,
  11426. maxMorphNormals: renderer.maxMorphNormals,
  11427. numDirLights: lights.directional.length,
  11428. numPointLights: lights.point.length,
  11429. numSpotLights: lights.spot.length,
  11430. numRectAreaLights: lights.rectArea.length,
  11431. numHemiLights: lights.hemi.length,
  11432. numDirLightShadows: lights.directionalShadowMap.length,
  11433. numPointLightShadows: lights.pointShadowMap.length,
  11434. numSpotLightShadows: lights.spotShadowMap.length,
  11435. numClippingPlanes: clipping.numPlanes,
  11436. numClipIntersection: clipping.numIntersection,
  11437. dithering: material.dithering,
  11438. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11439. shadowMapType: renderer.shadowMap.type,
  11440. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11441. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11442. premultipliedAlpha: material.premultipliedAlpha,
  11443. alphaTest: material.alphaTest,
  11444. doubleSided: material.side === DoubleSide,
  11445. flipSided: material.side === BackSide,
  11446. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11447. index0AttributeName: material.index0AttributeName,
  11448. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11449. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11450. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11451. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11452. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11453. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11454. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11455. customProgramCacheKey: material.customProgramCacheKey()
  11456. };
  11457. return parameters;
  11458. }
  11459. function getProgramCacheKey( parameters ) {
  11460. const array = [];
  11461. if ( parameters.shaderID ) {
  11462. array.push( parameters.shaderID );
  11463. } else {
  11464. array.push( parameters.fragmentShader );
  11465. array.push( parameters.vertexShader );
  11466. }
  11467. if ( parameters.defines !== undefined ) {
  11468. for ( const name in parameters.defines ) {
  11469. array.push( name );
  11470. array.push( parameters.defines[ name ] );
  11471. }
  11472. }
  11473. if ( parameters.isRawShaderMaterial === false ) {
  11474. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11475. array.push( parameters[ parameterNames[ i ] ] );
  11476. }
  11477. array.push( renderer.outputEncoding );
  11478. array.push( renderer.gammaFactor );
  11479. }
  11480. array.push( parameters.customProgramCacheKey );
  11481. return array.join();
  11482. }
  11483. function getUniforms( material ) {
  11484. const shaderID = shaderIDs[ material.type ];
  11485. let uniforms;
  11486. if ( shaderID ) {
  11487. const shader = ShaderLib[ shaderID ];
  11488. uniforms = UniformsUtils.clone( shader.uniforms );
  11489. } else {
  11490. uniforms = material.uniforms;
  11491. }
  11492. return uniforms;
  11493. }
  11494. function acquireProgram( parameters, cacheKey ) {
  11495. let program;
  11496. // Check if code has been already compiled
  11497. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11498. const preexistingProgram = programs[ p ];
  11499. if ( preexistingProgram.cacheKey === cacheKey ) {
  11500. program = preexistingProgram;
  11501. ++ program.usedTimes;
  11502. break;
  11503. }
  11504. }
  11505. if ( program === undefined ) {
  11506. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11507. programs.push( program );
  11508. }
  11509. return program;
  11510. }
  11511. function releaseProgram( program ) {
  11512. if ( -- program.usedTimes === 0 ) {
  11513. // Remove from unordered set
  11514. const i = programs.indexOf( program );
  11515. programs[ i ] = programs[ programs.length - 1 ];
  11516. programs.pop();
  11517. // Free WebGL resources
  11518. program.destroy();
  11519. }
  11520. }
  11521. return {
  11522. getParameters: getParameters,
  11523. getProgramCacheKey: getProgramCacheKey,
  11524. getUniforms: getUniforms,
  11525. acquireProgram: acquireProgram,
  11526. releaseProgram: releaseProgram,
  11527. // Exposed for resource monitoring & error feedback via renderer.info:
  11528. programs: programs
  11529. };
  11530. }
  11531. function WebGLProperties() {
  11532. let properties = new WeakMap();
  11533. function get( object ) {
  11534. let map = properties.get( object );
  11535. if ( map === undefined ) {
  11536. map = {};
  11537. properties.set( object, map );
  11538. }
  11539. return map;
  11540. }
  11541. function remove( object ) {
  11542. properties.delete( object );
  11543. }
  11544. function update( object, key, value ) {
  11545. properties.get( object )[ key ] = value;
  11546. }
  11547. function dispose() {
  11548. properties = new WeakMap();
  11549. }
  11550. return {
  11551. get: get,
  11552. remove: remove,
  11553. update: update,
  11554. dispose: dispose
  11555. };
  11556. }
  11557. function painterSortStable( a, b ) {
  11558. if ( a.groupOrder !== b.groupOrder ) {
  11559. return a.groupOrder - b.groupOrder;
  11560. } else if ( a.renderOrder !== b.renderOrder ) {
  11561. return a.renderOrder - b.renderOrder;
  11562. } else if ( a.program !== b.program ) {
  11563. return a.program.id - b.program.id;
  11564. } else if ( a.material.id !== b.material.id ) {
  11565. return a.material.id - b.material.id;
  11566. } else if ( a.z !== b.z ) {
  11567. return a.z - b.z;
  11568. } else {
  11569. return a.id - b.id;
  11570. }
  11571. }
  11572. function reversePainterSortStable( a, b ) {
  11573. if ( a.groupOrder !== b.groupOrder ) {
  11574. return a.groupOrder - b.groupOrder;
  11575. } else if ( a.renderOrder !== b.renderOrder ) {
  11576. return a.renderOrder - b.renderOrder;
  11577. } else if ( a.z !== b.z ) {
  11578. return b.z - a.z;
  11579. } else {
  11580. return a.id - b.id;
  11581. }
  11582. }
  11583. function WebGLRenderList( properties ) {
  11584. const renderItems = [];
  11585. let renderItemsIndex = 0;
  11586. const opaque = [];
  11587. const transparent = [];
  11588. const defaultProgram = { id: - 1 };
  11589. function init() {
  11590. renderItemsIndex = 0;
  11591. opaque.length = 0;
  11592. transparent.length = 0;
  11593. }
  11594. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11595. let renderItem = renderItems[ renderItemsIndex ];
  11596. const materialProperties = properties.get( material );
  11597. if ( renderItem === undefined ) {
  11598. renderItem = {
  11599. id: object.id,
  11600. object: object,
  11601. geometry: geometry,
  11602. material: material,
  11603. program: materialProperties.program || defaultProgram,
  11604. groupOrder: groupOrder,
  11605. renderOrder: object.renderOrder,
  11606. z: z,
  11607. group: group
  11608. };
  11609. renderItems[ renderItemsIndex ] = renderItem;
  11610. } else {
  11611. renderItem.id = object.id;
  11612. renderItem.object = object;
  11613. renderItem.geometry = geometry;
  11614. renderItem.material = material;
  11615. renderItem.program = materialProperties.program || defaultProgram;
  11616. renderItem.groupOrder = groupOrder;
  11617. renderItem.renderOrder = object.renderOrder;
  11618. renderItem.z = z;
  11619. renderItem.group = group;
  11620. }
  11621. renderItemsIndex ++;
  11622. return renderItem;
  11623. }
  11624. function push( object, geometry, material, groupOrder, z, group ) {
  11625. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11626. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  11627. }
  11628. function unshift( object, geometry, material, groupOrder, z, group ) {
  11629. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11630. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  11631. }
  11632. function sort( customOpaqueSort, customTransparentSort ) {
  11633. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11634. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11635. }
  11636. function finish() {
  11637. // Clear references from inactive renderItems in the list
  11638. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11639. const renderItem = renderItems[ i ];
  11640. if ( renderItem.id === null ) break;
  11641. renderItem.id = null;
  11642. renderItem.object = null;
  11643. renderItem.geometry = null;
  11644. renderItem.material = null;
  11645. renderItem.program = null;
  11646. renderItem.group = null;
  11647. }
  11648. }
  11649. return {
  11650. opaque: opaque,
  11651. transparent: transparent,
  11652. init: init,
  11653. push: push,
  11654. unshift: unshift,
  11655. finish: finish,
  11656. sort: sort
  11657. };
  11658. }
  11659. function WebGLRenderLists( properties ) {
  11660. let lists = new WeakMap();
  11661. function get( scene, camera ) {
  11662. const cameras = lists.get( scene );
  11663. let list;
  11664. if ( cameras === undefined ) {
  11665. list = new WebGLRenderList( properties );
  11666. lists.set( scene, new WeakMap() );
  11667. lists.get( scene ).set( camera, list );
  11668. } else {
  11669. list = cameras.get( camera );
  11670. if ( list === undefined ) {
  11671. list = new WebGLRenderList( properties );
  11672. cameras.set( camera, list );
  11673. }
  11674. }
  11675. return list;
  11676. }
  11677. function dispose() {
  11678. lists = new WeakMap();
  11679. }
  11680. return {
  11681. get: get,
  11682. dispose: dispose
  11683. };
  11684. }
  11685. function UniformsCache() {
  11686. const lights = {};
  11687. return {
  11688. get: function ( light ) {
  11689. if ( lights[ light.id ] !== undefined ) {
  11690. return lights[ light.id ];
  11691. }
  11692. let uniforms;
  11693. switch ( light.type ) {
  11694. case 'DirectionalLight':
  11695. uniforms = {
  11696. direction: new Vector3(),
  11697. color: new Color()
  11698. };
  11699. break;
  11700. case 'SpotLight':
  11701. uniforms = {
  11702. position: new Vector3(),
  11703. direction: new Vector3(),
  11704. color: new Color(),
  11705. distance: 0,
  11706. coneCos: 0,
  11707. penumbraCos: 0,
  11708. decay: 0
  11709. };
  11710. break;
  11711. case 'PointLight':
  11712. uniforms = {
  11713. position: new Vector3(),
  11714. color: new Color(),
  11715. distance: 0,
  11716. decay: 0
  11717. };
  11718. break;
  11719. case 'HemisphereLight':
  11720. uniforms = {
  11721. direction: new Vector3(),
  11722. skyColor: new Color(),
  11723. groundColor: new Color()
  11724. };
  11725. break;
  11726. case 'RectAreaLight':
  11727. uniforms = {
  11728. color: new Color(),
  11729. position: new Vector3(),
  11730. halfWidth: new Vector3(),
  11731. halfHeight: new Vector3()
  11732. };
  11733. break;
  11734. }
  11735. lights[ light.id ] = uniforms;
  11736. return uniforms;
  11737. }
  11738. };
  11739. }
  11740. function ShadowUniformsCache() {
  11741. const lights = {};
  11742. return {
  11743. get: function ( light ) {
  11744. if ( lights[ light.id ] !== undefined ) {
  11745. return lights[ light.id ];
  11746. }
  11747. let uniforms;
  11748. switch ( light.type ) {
  11749. case 'DirectionalLight':
  11750. uniforms = {
  11751. shadowBias: 0,
  11752. shadowNormalBias: 0,
  11753. shadowRadius: 1,
  11754. shadowMapSize: new Vector2()
  11755. };
  11756. break;
  11757. case 'SpotLight':
  11758. uniforms = {
  11759. shadowBias: 0,
  11760. shadowNormalBias: 0,
  11761. shadowRadius: 1,
  11762. shadowMapSize: new Vector2()
  11763. };
  11764. break;
  11765. case 'PointLight':
  11766. uniforms = {
  11767. shadowBias: 0,
  11768. shadowNormalBias: 0,
  11769. shadowRadius: 1,
  11770. shadowMapSize: new Vector2(),
  11771. shadowCameraNear: 1,
  11772. shadowCameraFar: 1000
  11773. };
  11774. break;
  11775. // TODO (abelnation): set RectAreaLight shadow uniforms
  11776. }
  11777. lights[ light.id ] = uniforms;
  11778. return uniforms;
  11779. }
  11780. };
  11781. }
  11782. let nextVersion = 0;
  11783. function shadowCastingLightsFirst( lightA, lightB ) {
  11784. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11785. }
  11786. function WebGLLights() {
  11787. const cache = new UniformsCache();
  11788. const shadowCache = ShadowUniformsCache();
  11789. const state = {
  11790. version: 0,
  11791. hash: {
  11792. directionalLength: - 1,
  11793. pointLength: - 1,
  11794. spotLength: - 1,
  11795. rectAreaLength: - 1,
  11796. hemiLength: - 1,
  11797. numDirectionalShadows: - 1,
  11798. numPointShadows: - 1,
  11799. numSpotShadows: - 1
  11800. },
  11801. ambient: [ 0, 0, 0 ],
  11802. probe: [],
  11803. directional: [],
  11804. directionalShadow: [],
  11805. directionalShadowMap: [],
  11806. directionalShadowMatrix: [],
  11807. spot: [],
  11808. spotShadow: [],
  11809. spotShadowMap: [],
  11810. spotShadowMatrix: [],
  11811. rectArea: [],
  11812. rectAreaLTC1: null,
  11813. rectAreaLTC2: null,
  11814. point: [],
  11815. pointShadow: [],
  11816. pointShadowMap: [],
  11817. pointShadowMatrix: [],
  11818. hemi: []
  11819. };
  11820. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11821. const vector3 = new Vector3();
  11822. const matrix4 = new Matrix4();
  11823. const matrix42 = new Matrix4();
  11824. function setup( lights, shadows, camera ) {
  11825. let r = 0, g = 0, b = 0;
  11826. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11827. let directionalLength = 0;
  11828. let pointLength = 0;
  11829. let spotLength = 0;
  11830. let rectAreaLength = 0;
  11831. let hemiLength = 0;
  11832. let numDirectionalShadows = 0;
  11833. let numPointShadows = 0;
  11834. let numSpotShadows = 0;
  11835. const viewMatrix = camera.matrixWorldInverse;
  11836. lights.sort( shadowCastingLightsFirst );
  11837. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11838. const light = lights[ i ];
  11839. const color = light.color;
  11840. const intensity = light.intensity;
  11841. const distance = light.distance;
  11842. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11843. if ( light.isAmbientLight ) {
  11844. r += color.r * intensity;
  11845. g += color.g * intensity;
  11846. b += color.b * intensity;
  11847. } else if ( light.isLightProbe ) {
  11848. for ( let j = 0; j < 9; j ++ ) {
  11849. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11850. }
  11851. } else if ( light.isDirectionalLight ) {
  11852. const uniforms = cache.get( light );
  11853. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11854. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11855. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11856. uniforms.direction.sub( vector3 );
  11857. uniforms.direction.transformDirection( viewMatrix );
  11858. if ( light.castShadow ) {
  11859. const shadow = light.shadow;
  11860. const shadowUniforms = shadowCache.get( light );
  11861. shadowUniforms.shadowBias = shadow.bias;
  11862. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11863. shadowUniforms.shadowRadius = shadow.radius;
  11864. shadowUniforms.shadowMapSize = shadow.mapSize;
  11865. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11866. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11867. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11868. numDirectionalShadows ++;
  11869. }
  11870. state.directional[ directionalLength ] = uniforms;
  11871. directionalLength ++;
  11872. } else if ( light.isSpotLight ) {
  11873. const uniforms = cache.get( light );
  11874. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11875. uniforms.position.applyMatrix4( viewMatrix );
  11876. uniforms.color.copy( color ).multiplyScalar( intensity );
  11877. uniforms.distance = distance;
  11878. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11879. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11880. uniforms.direction.sub( vector3 );
  11881. uniforms.direction.transformDirection( viewMatrix );
  11882. uniforms.coneCos = Math.cos( light.angle );
  11883. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11884. uniforms.decay = light.decay;
  11885. if ( light.castShadow ) {
  11886. const shadow = light.shadow;
  11887. const shadowUniforms = shadowCache.get( light );
  11888. shadowUniforms.shadowBias = shadow.bias;
  11889. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11890. shadowUniforms.shadowRadius = shadow.radius;
  11891. shadowUniforms.shadowMapSize = shadow.mapSize;
  11892. state.spotShadow[ spotLength ] = shadowUniforms;
  11893. state.spotShadowMap[ spotLength ] = shadowMap;
  11894. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11895. numSpotShadows ++;
  11896. }
  11897. state.spot[ spotLength ] = uniforms;
  11898. spotLength ++;
  11899. } else if ( light.isRectAreaLight ) {
  11900. const uniforms = cache.get( light );
  11901. // (a) intensity is the total visible light emitted
  11902. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11903. // (b) intensity is the brightness of the light
  11904. uniforms.color.copy( color ).multiplyScalar( intensity );
  11905. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11906. uniforms.position.applyMatrix4( viewMatrix );
  11907. // extract local rotation of light to derive width/height half vectors
  11908. matrix42.identity();
  11909. matrix4.copy( light.matrixWorld );
  11910. matrix4.premultiply( viewMatrix );
  11911. matrix42.extractRotation( matrix4 );
  11912. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11913. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11914. uniforms.halfWidth.applyMatrix4( matrix42 );
  11915. uniforms.halfHeight.applyMatrix4( matrix42 );
  11916. // TODO (abelnation): RectAreaLight distance?
  11917. // uniforms.distance = distance;
  11918. state.rectArea[ rectAreaLength ] = uniforms;
  11919. rectAreaLength ++;
  11920. } else if ( light.isPointLight ) {
  11921. const uniforms = cache.get( light );
  11922. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11923. uniforms.position.applyMatrix4( viewMatrix );
  11924. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11925. uniforms.distance = light.distance;
  11926. uniforms.decay = light.decay;
  11927. if ( light.castShadow ) {
  11928. const shadow = light.shadow;
  11929. const shadowUniforms = shadowCache.get( light );
  11930. shadowUniforms.shadowBias = shadow.bias;
  11931. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11932. shadowUniforms.shadowRadius = shadow.radius;
  11933. shadowUniforms.shadowMapSize = shadow.mapSize;
  11934. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11935. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11936. state.pointShadow[ pointLength ] = shadowUniforms;
  11937. state.pointShadowMap[ pointLength ] = shadowMap;
  11938. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11939. numPointShadows ++;
  11940. }
  11941. state.point[ pointLength ] = uniforms;
  11942. pointLength ++;
  11943. } else if ( light.isHemisphereLight ) {
  11944. const uniforms = cache.get( light );
  11945. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11946. uniforms.direction.transformDirection( viewMatrix );
  11947. uniforms.direction.normalize();
  11948. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  11949. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  11950. state.hemi[ hemiLength ] = uniforms;
  11951. hemiLength ++;
  11952. }
  11953. }
  11954. if ( rectAreaLength > 0 ) {
  11955. state.rectAreaLTC1 = UniformsLib.LTC_1;
  11956. state.rectAreaLTC2 = UniformsLib.LTC_2;
  11957. }
  11958. state.ambient[ 0 ] = r;
  11959. state.ambient[ 1 ] = g;
  11960. state.ambient[ 2 ] = b;
  11961. const hash = state.hash;
  11962. if ( hash.directionalLength !== directionalLength ||
  11963. hash.pointLength !== pointLength ||
  11964. hash.spotLength !== spotLength ||
  11965. hash.rectAreaLength !== rectAreaLength ||
  11966. hash.hemiLength !== hemiLength ||
  11967. hash.numDirectionalShadows !== numDirectionalShadows ||
  11968. hash.numPointShadows !== numPointShadows ||
  11969. hash.numSpotShadows !== numSpotShadows ) {
  11970. state.directional.length = directionalLength;
  11971. state.spot.length = spotLength;
  11972. state.rectArea.length = rectAreaLength;
  11973. state.point.length = pointLength;
  11974. state.hemi.length = hemiLength;
  11975. state.directionalShadow.length = numDirectionalShadows;
  11976. state.directionalShadowMap.length = numDirectionalShadows;
  11977. state.pointShadow.length = numPointShadows;
  11978. state.pointShadowMap.length = numPointShadows;
  11979. state.spotShadow.length = numSpotShadows;
  11980. state.spotShadowMap.length = numSpotShadows;
  11981. state.directionalShadowMatrix.length = numDirectionalShadows;
  11982. state.pointShadowMatrix.length = numPointShadows;
  11983. state.spotShadowMatrix.length = numSpotShadows;
  11984. hash.directionalLength = directionalLength;
  11985. hash.pointLength = pointLength;
  11986. hash.spotLength = spotLength;
  11987. hash.rectAreaLength = rectAreaLength;
  11988. hash.hemiLength = hemiLength;
  11989. hash.numDirectionalShadows = numDirectionalShadows;
  11990. hash.numPointShadows = numPointShadows;
  11991. hash.numSpotShadows = numSpotShadows;
  11992. state.version = nextVersion ++;
  11993. }
  11994. }
  11995. return {
  11996. setup: setup,
  11997. state: state
  11998. };
  11999. }
  12000. function WebGLRenderState() {
  12001. const lights = new WebGLLights();
  12002. const lightsArray = [];
  12003. const shadowsArray = [];
  12004. function init() {
  12005. lightsArray.length = 0;
  12006. shadowsArray.length = 0;
  12007. }
  12008. function pushLight( light ) {
  12009. lightsArray.push( light );
  12010. }
  12011. function pushShadow( shadowLight ) {
  12012. shadowsArray.push( shadowLight );
  12013. }
  12014. function setupLights( camera ) {
  12015. lights.setup( lightsArray, shadowsArray, camera );
  12016. }
  12017. const state = {
  12018. lightsArray: lightsArray,
  12019. shadowsArray: shadowsArray,
  12020. lights: lights
  12021. };
  12022. return {
  12023. init: init,
  12024. state: state,
  12025. setupLights: setupLights,
  12026. pushLight: pushLight,
  12027. pushShadow: pushShadow
  12028. };
  12029. }
  12030. function WebGLRenderStates() {
  12031. let renderStates = new WeakMap();
  12032. function get( scene, camera ) {
  12033. let renderState;
  12034. if ( renderStates.has( scene ) === false ) {
  12035. renderState = new WebGLRenderState();
  12036. renderStates.set( scene, new WeakMap() );
  12037. renderStates.get( scene ).set( camera, renderState );
  12038. } else {
  12039. if ( renderStates.get( scene ).has( camera ) === false ) {
  12040. renderState = new WebGLRenderState();
  12041. renderStates.get( scene ).set( camera, renderState );
  12042. } else {
  12043. renderState = renderStates.get( scene ).get( camera );
  12044. }
  12045. }
  12046. return renderState;
  12047. }
  12048. function dispose() {
  12049. renderStates = new WeakMap();
  12050. }
  12051. return {
  12052. get: get,
  12053. dispose: dispose
  12054. };
  12055. }
  12056. /**
  12057. * parameters = {
  12058. *
  12059. * opacity: <float>,
  12060. *
  12061. * map: new THREE.Texture( <Image> ),
  12062. *
  12063. * alphaMap: new THREE.Texture( <Image> ),
  12064. *
  12065. * displacementMap: new THREE.Texture( <Image> ),
  12066. * displacementScale: <float>,
  12067. * displacementBias: <float>,
  12068. *
  12069. * wireframe: <boolean>,
  12070. * wireframeLinewidth: <float>
  12071. * }
  12072. */
  12073. function MeshDepthMaterial( parameters ) {
  12074. Material.call( this );
  12075. this.type = 'MeshDepthMaterial';
  12076. this.depthPacking = BasicDepthPacking;
  12077. this.skinning = false;
  12078. this.morphTargets = false;
  12079. this.map = null;
  12080. this.alphaMap = null;
  12081. this.displacementMap = null;
  12082. this.displacementScale = 1;
  12083. this.displacementBias = 0;
  12084. this.wireframe = false;
  12085. this.wireframeLinewidth = 1;
  12086. this.fog = false;
  12087. this.setValues( parameters );
  12088. }
  12089. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  12090. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12091. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12092. MeshDepthMaterial.prototype.copy = function ( source ) {
  12093. Material.prototype.copy.call( this, source );
  12094. this.depthPacking = source.depthPacking;
  12095. this.skinning = source.skinning;
  12096. this.morphTargets = source.morphTargets;
  12097. this.map = source.map;
  12098. this.alphaMap = source.alphaMap;
  12099. this.displacementMap = source.displacementMap;
  12100. this.displacementScale = source.displacementScale;
  12101. this.displacementBias = source.displacementBias;
  12102. this.wireframe = source.wireframe;
  12103. this.wireframeLinewidth = source.wireframeLinewidth;
  12104. return this;
  12105. };
  12106. /**
  12107. * parameters = {
  12108. *
  12109. * referencePosition: <float>,
  12110. * nearDistance: <float>,
  12111. * farDistance: <float>,
  12112. *
  12113. * skinning: <bool>,
  12114. * morphTargets: <bool>,
  12115. *
  12116. * map: new THREE.Texture( <Image> ),
  12117. *
  12118. * alphaMap: new THREE.Texture( <Image> ),
  12119. *
  12120. * displacementMap: new THREE.Texture( <Image> ),
  12121. * displacementScale: <float>,
  12122. * displacementBias: <float>
  12123. *
  12124. * }
  12125. */
  12126. function MeshDistanceMaterial( parameters ) {
  12127. Material.call( this );
  12128. this.type = 'MeshDistanceMaterial';
  12129. this.referencePosition = new Vector3();
  12130. this.nearDistance = 1;
  12131. this.farDistance = 1000;
  12132. this.skinning = false;
  12133. this.morphTargets = false;
  12134. this.map = null;
  12135. this.alphaMap = null;
  12136. this.displacementMap = null;
  12137. this.displacementScale = 1;
  12138. this.displacementBias = 0;
  12139. this.fog = false;
  12140. this.setValues( parameters );
  12141. }
  12142. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  12143. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12144. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12145. MeshDistanceMaterial.prototype.copy = function ( source ) {
  12146. Material.prototype.copy.call( this, source );
  12147. this.referencePosition.copy( source.referencePosition );
  12148. this.nearDistance = source.nearDistance;
  12149. this.farDistance = source.farDistance;
  12150. this.skinning = source.skinning;
  12151. this.morphTargets = source.morphTargets;
  12152. this.map = source.map;
  12153. this.alphaMap = source.alphaMap;
  12154. this.displacementMap = source.displacementMap;
  12155. this.displacementScale = source.displacementScale;
  12156. this.displacementBias = source.displacementBias;
  12157. return this;
  12158. };
  12159. 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 HORIZONAL_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}";
  12160. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12161. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  12162. let _frustum = new Frustum();
  12163. const _shadowMapSize = new Vector2(),
  12164. _viewportSize = new Vector2(),
  12165. _viewport = new Vector4(),
  12166. _depthMaterials = [],
  12167. _distanceMaterials = [],
  12168. _materialCache = {};
  12169. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12170. const shadowMaterialVertical = new ShaderMaterial( {
  12171. defines: {
  12172. SAMPLE_RATE: 2.0 / 8.0,
  12173. HALF_SAMPLE_RATE: 1.0 / 8.0
  12174. },
  12175. uniforms: {
  12176. shadow_pass: { value: null },
  12177. resolution: { value: new Vector2() },
  12178. radius: { value: 4.0 }
  12179. },
  12180. vertexShader: vsm_vert,
  12181. fragmentShader: vsm_frag
  12182. } );
  12183. const shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12184. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12185. const fullScreenTri = new BufferGeometry();
  12186. fullScreenTri.setAttribute(
  12187. "position",
  12188. new BufferAttribute(
  12189. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12190. 3
  12191. )
  12192. );
  12193. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12194. const scope = this;
  12195. this.enabled = false;
  12196. this.autoUpdate = true;
  12197. this.needsUpdate = false;
  12198. this.type = PCFShadowMap;
  12199. this.render = function ( lights, scene, camera ) {
  12200. if ( scope.enabled === false ) return;
  12201. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12202. if ( lights.length === 0 ) return;
  12203. const currentRenderTarget = _renderer.getRenderTarget();
  12204. const activeCubeFace = _renderer.getActiveCubeFace();
  12205. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12206. const _state = _renderer.state;
  12207. // Set GL state for depth map.
  12208. _state.setBlending( NoBlending );
  12209. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12210. _state.buffers.depth.setTest( true );
  12211. _state.setScissorTest( false );
  12212. // render depth map
  12213. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12214. const light = lights[ i ];
  12215. const shadow = light.shadow;
  12216. if ( shadow === undefined ) {
  12217. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12218. continue;
  12219. }
  12220. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12221. _shadowMapSize.copy( shadow.mapSize );
  12222. const shadowFrameExtents = shadow.getFrameExtents();
  12223. _shadowMapSize.multiply( shadowFrameExtents );
  12224. _viewportSize.copy( shadow.mapSize );
  12225. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  12226. if ( _shadowMapSize.x > maxTextureSize ) {
  12227. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  12228. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12229. shadow.mapSize.x = _viewportSize.x;
  12230. }
  12231. if ( _shadowMapSize.y > maxTextureSize ) {
  12232. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  12233. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12234. shadow.mapSize.y = _viewportSize.y;
  12235. }
  12236. }
  12237. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12238. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12239. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12240. shadow.map.texture.name = light.name + ".shadowMap";
  12241. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12242. shadow.camera.updateProjectionMatrix();
  12243. }
  12244. if ( shadow.map === null ) {
  12245. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12246. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12247. shadow.map.texture.name = light.name + ".shadowMap";
  12248. shadow.camera.updateProjectionMatrix();
  12249. }
  12250. _renderer.setRenderTarget( shadow.map );
  12251. _renderer.clear();
  12252. const viewportCount = shadow.getViewportCount();
  12253. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12254. const viewport = shadow.getViewport( vp );
  12255. _viewport.set(
  12256. _viewportSize.x * viewport.x,
  12257. _viewportSize.y * viewport.y,
  12258. _viewportSize.x * viewport.z,
  12259. _viewportSize.y * viewport.w
  12260. );
  12261. _state.viewport( _viewport );
  12262. shadow.updateMatrices( light, vp );
  12263. _frustum = shadow.getFrustum();
  12264. renderObject( scene, camera, shadow.camera, light, this.type );
  12265. }
  12266. // do blur pass for VSM
  12267. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12268. VSMPass( shadow, camera );
  12269. }
  12270. shadow.needsUpdate = false;
  12271. }
  12272. scope.needsUpdate = false;
  12273. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12274. };
  12275. function VSMPass( shadow, camera ) {
  12276. const geometry = _objects.update( fullScreenMesh );
  12277. // vertical pass
  12278. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12279. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12280. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12281. _renderer.setRenderTarget( shadow.mapPass );
  12282. _renderer.clear();
  12283. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12284. // horizonal pass
  12285. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12286. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12287. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12288. _renderer.setRenderTarget( shadow.map );
  12289. _renderer.clear();
  12290. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );
  12291. }
  12292. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12293. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12294. let material = _depthMaterials[ index ];
  12295. if ( material === undefined ) {
  12296. material = new MeshDepthMaterial( {
  12297. depthPacking: RGBADepthPacking,
  12298. morphTargets: useMorphing,
  12299. skinning: useSkinning
  12300. } );
  12301. _depthMaterials[ index ] = material;
  12302. }
  12303. return material;
  12304. }
  12305. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12306. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12307. let material = _distanceMaterials[ index ];
  12308. if ( material === undefined ) {
  12309. material = new MeshDistanceMaterial( {
  12310. morphTargets: useMorphing,
  12311. skinning: useSkinning
  12312. } );
  12313. _distanceMaterials[ index ] = material;
  12314. }
  12315. return material;
  12316. }
  12317. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12318. let result = null;
  12319. let getMaterialVariant = getDepthMaterialVariant;
  12320. let customMaterial = object.customDepthMaterial;
  12321. if ( light.isPointLight === true ) {
  12322. getMaterialVariant = getDistanceMaterialVariant;
  12323. customMaterial = object.customDistanceMaterial;
  12324. }
  12325. if ( customMaterial === undefined ) {
  12326. let useMorphing = false;
  12327. if ( material.morphTargets === true ) {
  12328. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12329. }
  12330. let useSkinning = false;
  12331. if ( object.isSkinnedMesh === true ) {
  12332. if ( material.skinning === true ) {
  12333. useSkinning = true;
  12334. } else {
  12335. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  12336. }
  12337. }
  12338. const useInstancing = object.isInstancedMesh === true;
  12339. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  12340. } else {
  12341. result = customMaterial;
  12342. }
  12343. if ( _renderer.localClippingEnabled &&
  12344. material.clipShadows === true &&
  12345. material.clippingPlanes.length !== 0 ) {
  12346. // in this case we need a unique material instance reflecting the
  12347. // appropriate state
  12348. const keyA = result.uuid, keyB = material.uuid;
  12349. let materialsForVariant = _materialCache[ keyA ];
  12350. if ( materialsForVariant === undefined ) {
  12351. materialsForVariant = {};
  12352. _materialCache[ keyA ] = materialsForVariant;
  12353. }
  12354. let cachedMaterial = materialsForVariant[ keyB ];
  12355. if ( cachedMaterial === undefined ) {
  12356. cachedMaterial = result.clone();
  12357. materialsForVariant[ keyB ] = cachedMaterial;
  12358. }
  12359. result = cachedMaterial;
  12360. }
  12361. result.visible = material.visible;
  12362. result.wireframe = material.wireframe;
  12363. if ( type === VSMShadowMap ) {
  12364. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12365. } else {
  12366. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12367. }
  12368. result.clipShadows = material.clipShadows;
  12369. result.clippingPlanes = material.clippingPlanes;
  12370. result.clipIntersection = material.clipIntersection;
  12371. result.wireframeLinewidth = material.wireframeLinewidth;
  12372. result.linewidth = material.linewidth;
  12373. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12374. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12375. result.nearDistance = shadowCameraNear;
  12376. result.farDistance = shadowCameraFar;
  12377. }
  12378. return result;
  12379. }
  12380. function renderObject( object, camera, shadowCamera, light, type ) {
  12381. if ( object.visible === false ) return;
  12382. const visible = object.layers.test( camera.layers );
  12383. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12384. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12385. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12386. const geometry = _objects.update( object );
  12387. const material = object.material;
  12388. if ( Array.isArray( material ) ) {
  12389. const groups = geometry.groups;
  12390. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12391. const group = groups[ k ];
  12392. const groupMaterial = material[ group.materialIndex ];
  12393. if ( groupMaterial && groupMaterial.visible ) {
  12394. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12395. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12396. }
  12397. }
  12398. } else if ( material.visible ) {
  12399. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12400. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12401. }
  12402. }
  12403. }
  12404. const children = object.children;
  12405. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12406. renderObject( children[ i ], camera, shadowCamera, light, type );
  12407. }
  12408. }
  12409. }
  12410. function WebGLState( gl, extensions, capabilities ) {
  12411. const isWebGL2 = capabilities.isWebGL2;
  12412. function ColorBuffer() {
  12413. let locked = false;
  12414. const color = new Vector4();
  12415. let currentColorMask = null;
  12416. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12417. return {
  12418. setMask: function ( colorMask ) {
  12419. if ( currentColorMask !== colorMask && ! locked ) {
  12420. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12421. currentColorMask = colorMask;
  12422. }
  12423. },
  12424. setLocked: function ( lock ) {
  12425. locked = lock;
  12426. },
  12427. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12428. if ( premultipliedAlpha === true ) {
  12429. r *= a; g *= a; b *= a;
  12430. }
  12431. color.set( r, g, b, a );
  12432. if ( currentColorClear.equals( color ) === false ) {
  12433. gl.clearColor( r, g, b, a );
  12434. currentColorClear.copy( color );
  12435. }
  12436. },
  12437. reset: function () {
  12438. locked = false;
  12439. currentColorMask = null;
  12440. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12441. }
  12442. };
  12443. }
  12444. function DepthBuffer() {
  12445. let locked = false;
  12446. let currentDepthMask = null;
  12447. let currentDepthFunc = null;
  12448. let currentDepthClear = null;
  12449. return {
  12450. setTest: function ( depthTest ) {
  12451. if ( depthTest ) {
  12452. enable( 2929 );
  12453. } else {
  12454. disable( 2929 );
  12455. }
  12456. },
  12457. setMask: function ( depthMask ) {
  12458. if ( currentDepthMask !== depthMask && ! locked ) {
  12459. gl.depthMask( depthMask );
  12460. currentDepthMask = depthMask;
  12461. }
  12462. },
  12463. setFunc: function ( depthFunc ) {
  12464. if ( currentDepthFunc !== depthFunc ) {
  12465. if ( depthFunc ) {
  12466. switch ( depthFunc ) {
  12467. case NeverDepth:
  12468. gl.depthFunc( 512 );
  12469. break;
  12470. case AlwaysDepth:
  12471. gl.depthFunc( 519 );
  12472. break;
  12473. case LessDepth:
  12474. gl.depthFunc( 513 );
  12475. break;
  12476. case LessEqualDepth:
  12477. gl.depthFunc( 515 );
  12478. break;
  12479. case EqualDepth:
  12480. gl.depthFunc( 514 );
  12481. break;
  12482. case GreaterEqualDepth:
  12483. gl.depthFunc( 518 );
  12484. break;
  12485. case GreaterDepth:
  12486. gl.depthFunc( 516 );
  12487. break;
  12488. case NotEqualDepth:
  12489. gl.depthFunc( 517 );
  12490. break;
  12491. default:
  12492. gl.depthFunc( 515 );
  12493. }
  12494. } else {
  12495. gl.depthFunc( 515 );
  12496. }
  12497. currentDepthFunc = depthFunc;
  12498. }
  12499. },
  12500. setLocked: function ( lock ) {
  12501. locked = lock;
  12502. },
  12503. setClear: function ( depth ) {
  12504. if ( currentDepthClear !== depth ) {
  12505. gl.clearDepth( depth );
  12506. currentDepthClear = depth;
  12507. }
  12508. },
  12509. reset: function () {
  12510. locked = false;
  12511. currentDepthMask = null;
  12512. currentDepthFunc = null;
  12513. currentDepthClear = null;
  12514. }
  12515. };
  12516. }
  12517. function StencilBuffer() {
  12518. let locked = false;
  12519. let currentStencilMask = null;
  12520. let currentStencilFunc = null;
  12521. let currentStencilRef = null;
  12522. let currentStencilFuncMask = null;
  12523. let currentStencilFail = null;
  12524. let currentStencilZFail = null;
  12525. let currentStencilZPass = null;
  12526. let currentStencilClear = null;
  12527. return {
  12528. setTest: function ( stencilTest ) {
  12529. if ( ! locked ) {
  12530. if ( stencilTest ) {
  12531. enable( 2960 );
  12532. } else {
  12533. disable( 2960 );
  12534. }
  12535. }
  12536. },
  12537. setMask: function ( stencilMask ) {
  12538. if ( currentStencilMask !== stencilMask && ! locked ) {
  12539. gl.stencilMask( stencilMask );
  12540. currentStencilMask = stencilMask;
  12541. }
  12542. },
  12543. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12544. if ( currentStencilFunc !== stencilFunc ||
  12545. currentStencilRef !== stencilRef ||
  12546. currentStencilFuncMask !== stencilMask ) {
  12547. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12548. currentStencilFunc = stencilFunc;
  12549. currentStencilRef = stencilRef;
  12550. currentStencilFuncMask = stencilMask;
  12551. }
  12552. },
  12553. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12554. if ( currentStencilFail !== stencilFail ||
  12555. currentStencilZFail !== stencilZFail ||
  12556. currentStencilZPass !== stencilZPass ) {
  12557. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12558. currentStencilFail = stencilFail;
  12559. currentStencilZFail = stencilZFail;
  12560. currentStencilZPass = stencilZPass;
  12561. }
  12562. },
  12563. setLocked: function ( lock ) {
  12564. locked = lock;
  12565. },
  12566. setClear: function ( stencil ) {
  12567. if ( currentStencilClear !== stencil ) {
  12568. gl.clearStencil( stencil );
  12569. currentStencilClear = stencil;
  12570. }
  12571. },
  12572. reset: function () {
  12573. locked = false;
  12574. currentStencilMask = null;
  12575. currentStencilFunc = null;
  12576. currentStencilRef = null;
  12577. currentStencilFuncMask = null;
  12578. currentStencilFail = null;
  12579. currentStencilZFail = null;
  12580. currentStencilZPass = null;
  12581. currentStencilClear = null;
  12582. }
  12583. };
  12584. }
  12585. //
  12586. const colorBuffer = new ColorBuffer();
  12587. const depthBuffer = new DepthBuffer();
  12588. const stencilBuffer = new StencilBuffer();
  12589. let enabledCapabilities = {};
  12590. let currentProgram = null;
  12591. let currentBlendingEnabled = null;
  12592. let currentBlending = null;
  12593. let currentBlendEquation = null;
  12594. let currentBlendSrc = null;
  12595. let currentBlendDst = null;
  12596. let currentBlendEquationAlpha = null;
  12597. let currentBlendSrcAlpha = null;
  12598. let currentBlendDstAlpha = null;
  12599. let currentPremultipledAlpha = false;
  12600. let currentFlipSided = null;
  12601. let currentCullFace = null;
  12602. let currentLineWidth = null;
  12603. let currentPolygonOffsetFactor = null;
  12604. let currentPolygonOffsetUnits = null;
  12605. const maxTextures = gl.getParameter( 35661 );
  12606. let lineWidthAvailable = false;
  12607. let version = 0;
  12608. const glVersion = gl.getParameter( 7938 );
  12609. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12610. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  12611. lineWidthAvailable = ( version >= 1.0 );
  12612. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12613. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  12614. lineWidthAvailable = ( version >= 2.0 );
  12615. }
  12616. let currentTextureSlot = null;
  12617. let currentBoundTextures = {};
  12618. const currentScissor = new Vector4();
  12619. const currentViewport = new Vector4();
  12620. function createTexture( type, target, count ) {
  12621. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12622. const texture = gl.createTexture();
  12623. gl.bindTexture( type, texture );
  12624. gl.texParameteri( type, 10241, 9728 );
  12625. gl.texParameteri( type, 10240, 9728 );
  12626. for ( let i = 0; i < count; i ++ ) {
  12627. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12628. }
  12629. return texture;
  12630. }
  12631. const emptyTextures = {};
  12632. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12633. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12634. // init
  12635. colorBuffer.setClear( 0, 0, 0, 1 );
  12636. depthBuffer.setClear( 1 );
  12637. stencilBuffer.setClear( 0 );
  12638. enable( 2929 );
  12639. depthBuffer.setFunc( LessEqualDepth );
  12640. setFlipSided( false );
  12641. setCullFace( CullFaceBack );
  12642. enable( 2884 );
  12643. setBlending( NoBlending );
  12644. //
  12645. function enable( id ) {
  12646. if ( enabledCapabilities[ id ] !== true ) {
  12647. gl.enable( id );
  12648. enabledCapabilities[ id ] = true;
  12649. }
  12650. }
  12651. function disable( id ) {
  12652. if ( enabledCapabilities[ id ] !== false ) {
  12653. gl.disable( id );
  12654. enabledCapabilities[ id ] = false;
  12655. }
  12656. }
  12657. function useProgram( program ) {
  12658. if ( currentProgram !== program ) {
  12659. gl.useProgram( program );
  12660. currentProgram = program;
  12661. return true;
  12662. }
  12663. return false;
  12664. }
  12665. const equationToGL = {
  12666. [ AddEquation ]: 32774,
  12667. [ SubtractEquation ]: 32778,
  12668. [ ReverseSubtractEquation ]: 32779
  12669. };
  12670. if ( isWebGL2 ) {
  12671. equationToGL[ MinEquation ] = 32775;
  12672. equationToGL[ MaxEquation ] = 32776;
  12673. } else {
  12674. const extension = extensions.get( 'EXT_blend_minmax' );
  12675. if ( extension !== null ) {
  12676. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12677. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12678. }
  12679. }
  12680. const factorToGL = {
  12681. [ ZeroFactor ]: 0,
  12682. [ OneFactor ]: 1,
  12683. [ SrcColorFactor ]: 768,
  12684. [ SrcAlphaFactor ]: 770,
  12685. [ SrcAlphaSaturateFactor ]: 776,
  12686. [ DstColorFactor ]: 774,
  12687. [ DstAlphaFactor ]: 772,
  12688. [ OneMinusSrcColorFactor ]: 769,
  12689. [ OneMinusSrcAlphaFactor ]: 771,
  12690. [ OneMinusDstColorFactor ]: 775,
  12691. [ OneMinusDstAlphaFactor ]: 773
  12692. };
  12693. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12694. if ( blending === NoBlending ) {
  12695. if ( currentBlendingEnabled ) {
  12696. disable( 3042 );
  12697. currentBlendingEnabled = false;
  12698. }
  12699. return;
  12700. }
  12701. if ( ! currentBlendingEnabled ) {
  12702. enable( 3042 );
  12703. currentBlendingEnabled = true;
  12704. }
  12705. if ( blending !== CustomBlending ) {
  12706. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12707. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12708. gl.blendEquation( 32774 );
  12709. currentBlendEquation = AddEquation;
  12710. currentBlendEquationAlpha = AddEquation;
  12711. }
  12712. if ( premultipliedAlpha ) {
  12713. switch ( blending ) {
  12714. case NormalBlending:
  12715. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12716. break;
  12717. case AdditiveBlending:
  12718. gl.blendFunc( 1, 1 );
  12719. break;
  12720. case SubtractiveBlending:
  12721. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12722. break;
  12723. case MultiplyBlending:
  12724. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12725. break;
  12726. default:
  12727. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12728. break;
  12729. }
  12730. } else {
  12731. switch ( blending ) {
  12732. case NormalBlending:
  12733. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12734. break;
  12735. case AdditiveBlending:
  12736. gl.blendFunc( 770, 1 );
  12737. break;
  12738. case SubtractiveBlending:
  12739. gl.blendFunc( 0, 769 );
  12740. break;
  12741. case MultiplyBlending:
  12742. gl.blendFunc( 0, 768 );
  12743. break;
  12744. default:
  12745. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12746. break;
  12747. }
  12748. }
  12749. currentBlendSrc = null;
  12750. currentBlendDst = null;
  12751. currentBlendSrcAlpha = null;
  12752. currentBlendDstAlpha = null;
  12753. currentBlending = blending;
  12754. currentPremultipledAlpha = premultipliedAlpha;
  12755. }
  12756. return;
  12757. }
  12758. // custom blending
  12759. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12760. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12761. blendDstAlpha = blendDstAlpha || blendDst;
  12762. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12763. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12764. currentBlendEquation = blendEquation;
  12765. currentBlendEquationAlpha = blendEquationAlpha;
  12766. }
  12767. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12768. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12769. currentBlendSrc = blendSrc;
  12770. currentBlendDst = blendDst;
  12771. currentBlendSrcAlpha = blendSrcAlpha;
  12772. currentBlendDstAlpha = blendDstAlpha;
  12773. }
  12774. currentBlending = blending;
  12775. currentPremultipledAlpha = null;
  12776. }
  12777. function setMaterial( material, frontFaceCW ) {
  12778. material.side === DoubleSide
  12779. ? disable( 2884 )
  12780. : enable( 2884 );
  12781. let flipSided = ( material.side === BackSide );
  12782. if ( frontFaceCW ) flipSided = ! flipSided;
  12783. setFlipSided( flipSided );
  12784. ( material.blending === NormalBlending && material.transparent === false )
  12785. ? setBlending( NoBlending )
  12786. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12787. depthBuffer.setFunc( material.depthFunc );
  12788. depthBuffer.setTest( material.depthTest );
  12789. depthBuffer.setMask( material.depthWrite );
  12790. colorBuffer.setMask( material.colorWrite );
  12791. const stencilWrite = material.stencilWrite;
  12792. stencilBuffer.setTest( stencilWrite );
  12793. if ( stencilWrite ) {
  12794. stencilBuffer.setMask( material.stencilWriteMask );
  12795. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12796. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12797. }
  12798. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12799. }
  12800. //
  12801. function setFlipSided( flipSided ) {
  12802. if ( currentFlipSided !== flipSided ) {
  12803. if ( flipSided ) {
  12804. gl.frontFace( 2304 );
  12805. } else {
  12806. gl.frontFace( 2305 );
  12807. }
  12808. currentFlipSided = flipSided;
  12809. }
  12810. }
  12811. function setCullFace( cullFace ) {
  12812. if ( cullFace !== CullFaceNone ) {
  12813. enable( 2884 );
  12814. if ( cullFace !== currentCullFace ) {
  12815. if ( cullFace === CullFaceBack ) {
  12816. gl.cullFace( 1029 );
  12817. } else if ( cullFace === CullFaceFront ) {
  12818. gl.cullFace( 1028 );
  12819. } else {
  12820. gl.cullFace( 1032 );
  12821. }
  12822. }
  12823. } else {
  12824. disable( 2884 );
  12825. }
  12826. currentCullFace = cullFace;
  12827. }
  12828. function setLineWidth( width ) {
  12829. if ( width !== currentLineWidth ) {
  12830. if ( lineWidthAvailable ) gl.lineWidth( width );
  12831. currentLineWidth = width;
  12832. }
  12833. }
  12834. function setPolygonOffset( polygonOffset, factor, units ) {
  12835. if ( polygonOffset ) {
  12836. enable( 32823 );
  12837. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12838. gl.polygonOffset( factor, units );
  12839. currentPolygonOffsetFactor = factor;
  12840. currentPolygonOffsetUnits = units;
  12841. }
  12842. } else {
  12843. disable( 32823 );
  12844. }
  12845. }
  12846. function setScissorTest( scissorTest ) {
  12847. if ( scissorTest ) {
  12848. enable( 3089 );
  12849. } else {
  12850. disable( 3089 );
  12851. }
  12852. }
  12853. // texture
  12854. function activeTexture( webglSlot ) {
  12855. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12856. if ( currentTextureSlot !== webglSlot ) {
  12857. gl.activeTexture( webglSlot );
  12858. currentTextureSlot = webglSlot;
  12859. }
  12860. }
  12861. function bindTexture( webglType, webglTexture ) {
  12862. if ( currentTextureSlot === null ) {
  12863. activeTexture();
  12864. }
  12865. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12866. if ( boundTexture === undefined ) {
  12867. boundTexture = { type: undefined, texture: undefined };
  12868. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12869. }
  12870. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12871. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12872. boundTexture.type = webglType;
  12873. boundTexture.texture = webglTexture;
  12874. }
  12875. }
  12876. function unbindTexture() {
  12877. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12878. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12879. gl.bindTexture( boundTexture.type, null );
  12880. boundTexture.type = undefined;
  12881. boundTexture.texture = undefined;
  12882. }
  12883. }
  12884. function compressedTexImage2D() {
  12885. try {
  12886. gl.compressedTexImage2D.apply( gl, arguments );
  12887. } catch ( error ) {
  12888. console.error( 'THREE.WebGLState:', error );
  12889. }
  12890. }
  12891. function texImage2D() {
  12892. try {
  12893. gl.texImage2D.apply( gl, arguments );
  12894. } catch ( error ) {
  12895. console.error( 'THREE.WebGLState:', error );
  12896. }
  12897. }
  12898. function texImage3D() {
  12899. try {
  12900. gl.texImage3D.apply( gl, arguments );
  12901. } catch ( error ) {
  12902. console.error( 'THREE.WebGLState:', error );
  12903. }
  12904. }
  12905. //
  12906. function scissor( scissor ) {
  12907. if ( currentScissor.equals( scissor ) === false ) {
  12908. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12909. currentScissor.copy( scissor );
  12910. }
  12911. }
  12912. function viewport( viewport ) {
  12913. if ( currentViewport.equals( viewport ) === false ) {
  12914. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12915. currentViewport.copy( viewport );
  12916. }
  12917. }
  12918. //
  12919. function reset() {
  12920. enabledCapabilities = {};
  12921. currentTextureSlot = null;
  12922. currentBoundTextures = {};
  12923. currentProgram = null;
  12924. currentBlending = null;
  12925. currentFlipSided = null;
  12926. currentCullFace = null;
  12927. colorBuffer.reset();
  12928. depthBuffer.reset();
  12929. stencilBuffer.reset();
  12930. }
  12931. return {
  12932. buffers: {
  12933. color: colorBuffer,
  12934. depth: depthBuffer,
  12935. stencil: stencilBuffer
  12936. },
  12937. enable: enable,
  12938. disable: disable,
  12939. useProgram: useProgram,
  12940. setBlending: setBlending,
  12941. setMaterial: setMaterial,
  12942. setFlipSided: setFlipSided,
  12943. setCullFace: setCullFace,
  12944. setLineWidth: setLineWidth,
  12945. setPolygonOffset: setPolygonOffset,
  12946. setScissorTest: setScissorTest,
  12947. activeTexture: activeTexture,
  12948. bindTexture: bindTexture,
  12949. unbindTexture: unbindTexture,
  12950. compressedTexImage2D: compressedTexImage2D,
  12951. texImage2D: texImage2D,
  12952. texImage3D: texImage3D,
  12953. scissor: scissor,
  12954. viewport: viewport,
  12955. reset: reset
  12956. };
  12957. }
  12958. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12959. const isWebGL2 = capabilities.isWebGL2;
  12960. const maxTextures = capabilities.maxTextures;
  12961. const maxCubemapSize = capabilities.maxCubemapSize;
  12962. const maxTextureSize = capabilities.maxTextureSize;
  12963. const maxSamples = capabilities.maxSamples;
  12964. const _videoTextures = new WeakMap();
  12965. let _canvas;
  12966. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12967. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12968. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12969. let useOffscreenCanvas = false;
  12970. try {
  12971. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12972. && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;
  12973. } catch ( err ) {
  12974. // Ignore any errors
  12975. }
  12976. function createCanvas( width, height ) {
  12977. // Use OffscreenCanvas when available. Specially needed in web workers
  12978. return useOffscreenCanvas ?
  12979. new OffscreenCanvas( width, height ) :
  12980. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  12981. }
  12982. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  12983. let scale = 1;
  12984. // handle case if texture exceeds max size
  12985. if ( image.width > maxSize || image.height > maxSize ) {
  12986. scale = maxSize / Math.max( image.width, image.height );
  12987. }
  12988. // only perform resize if necessary
  12989. if ( scale < 1 || needsPowerOfTwo === true ) {
  12990. // only perform resize for certain image types
  12991. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  12992. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  12993. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  12994. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  12995. const width = floor( scale * image.width );
  12996. const height = floor( scale * image.height );
  12997. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  12998. // cube textures can't reuse the same canvas
  12999. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13000. canvas.width = width;
  13001. canvas.height = height;
  13002. const context = canvas.getContext( '2d' );
  13003. context.drawImage( image, 0, 0, width, height );
  13004. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13005. return canvas;
  13006. } else {
  13007. if ( 'data' in image ) {
  13008. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13009. }
  13010. return image;
  13011. }
  13012. }
  13013. return image;
  13014. }
  13015. function isPowerOfTwo( image ) {
  13016. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  13017. }
  13018. function textureNeedsPowerOfTwo( texture ) {
  13019. if ( isWebGL2 ) return false;
  13020. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13021. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13022. }
  13023. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13024. return texture.generateMipmaps && supportsMips &&
  13025. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13026. }
  13027. function generateMipmap( target, texture, width, height ) {
  13028. _gl.generateMipmap( target );
  13029. const textureProperties = properties.get( texture );
  13030. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13031. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  13032. }
  13033. function getInternalFormat( internalFormatName, glFormat, glType ) {
  13034. if ( isWebGL2 === false ) return glFormat;
  13035. if ( internalFormatName !== null ) {
  13036. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13037. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13038. }
  13039. let internalFormat = glFormat;
  13040. if ( glFormat === 6403 ) {
  13041. if ( glType === 5126 ) internalFormat = 33326;
  13042. if ( glType === 5131 ) internalFormat = 33325;
  13043. if ( glType === 5121 ) internalFormat = 33321;
  13044. }
  13045. if ( glFormat === 6407 ) {
  13046. if ( glType === 5126 ) internalFormat = 34837;
  13047. if ( glType === 5131 ) internalFormat = 34843;
  13048. if ( glType === 5121 ) internalFormat = 32849;
  13049. }
  13050. if ( glFormat === 6408 ) {
  13051. if ( glType === 5126 ) internalFormat = 34836;
  13052. if ( glType === 5131 ) internalFormat = 34842;
  13053. if ( glType === 5121 ) internalFormat = 32856;
  13054. }
  13055. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13056. internalFormat === 34842 || internalFormat === 34836 ) {
  13057. extensions.get( 'EXT_color_buffer_float' );
  13058. }
  13059. return internalFormat;
  13060. }
  13061. // Fallback filters for non-power-of-2 textures
  13062. function filterFallback( f ) {
  13063. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13064. return 9728;
  13065. }
  13066. return 9729;
  13067. }
  13068. //
  13069. function onTextureDispose( event ) {
  13070. const texture = event.target;
  13071. texture.removeEventListener( 'dispose', onTextureDispose );
  13072. deallocateTexture( texture );
  13073. if ( texture.isVideoTexture ) {
  13074. _videoTextures.delete( texture );
  13075. }
  13076. info.memory.textures --;
  13077. }
  13078. function onRenderTargetDispose( event ) {
  13079. const renderTarget = event.target;
  13080. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13081. deallocateRenderTarget( renderTarget );
  13082. info.memory.textures --;
  13083. }
  13084. //
  13085. function deallocateTexture( texture ) {
  13086. const textureProperties = properties.get( texture );
  13087. if ( textureProperties.__webglInit === undefined ) return;
  13088. _gl.deleteTexture( textureProperties.__webglTexture );
  13089. properties.remove( texture );
  13090. }
  13091. function deallocateRenderTarget( renderTarget ) {
  13092. const renderTargetProperties = properties.get( renderTarget );
  13093. const textureProperties = properties.get( renderTarget.texture );
  13094. if ( ! renderTarget ) return;
  13095. if ( textureProperties.__webglTexture !== undefined ) {
  13096. _gl.deleteTexture( textureProperties.__webglTexture );
  13097. }
  13098. if ( renderTarget.depthTexture ) {
  13099. renderTarget.depthTexture.dispose();
  13100. }
  13101. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13102. for ( let i = 0; i < 6; i ++ ) {
  13103. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13104. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13105. }
  13106. } else {
  13107. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13108. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13109. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13110. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13111. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13112. }
  13113. properties.remove( renderTarget.texture );
  13114. properties.remove( renderTarget );
  13115. }
  13116. //
  13117. let textureUnits = 0;
  13118. function resetTextureUnits() {
  13119. textureUnits = 0;
  13120. }
  13121. function allocateTextureUnit() {
  13122. const textureUnit = textureUnits;
  13123. if ( textureUnit >= maxTextures ) {
  13124. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13125. }
  13126. textureUnits += 1;
  13127. return textureUnit;
  13128. }
  13129. //
  13130. function setTexture2D( texture, slot ) {
  13131. const textureProperties = properties.get( texture );
  13132. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13133. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13134. const image = texture.image;
  13135. if ( image === undefined ) {
  13136. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13137. } else if ( image.complete === false ) {
  13138. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13139. } else {
  13140. uploadTexture( textureProperties, texture, slot );
  13141. return;
  13142. }
  13143. }
  13144. state.activeTexture( 33984 + slot );
  13145. state.bindTexture( 3553, textureProperties.__webglTexture );
  13146. }
  13147. function setTexture2DArray( texture, slot ) {
  13148. const textureProperties = properties.get( texture );
  13149. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13150. uploadTexture( textureProperties, texture, slot );
  13151. return;
  13152. }
  13153. state.activeTexture( 33984 + slot );
  13154. state.bindTexture( 35866, textureProperties.__webglTexture );
  13155. }
  13156. function setTexture3D( texture, slot ) {
  13157. const textureProperties = properties.get( texture );
  13158. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13159. uploadTexture( textureProperties, texture, slot );
  13160. return;
  13161. }
  13162. state.activeTexture( 33984 + slot );
  13163. state.bindTexture( 32879, textureProperties.__webglTexture );
  13164. }
  13165. function setTextureCube( texture, slot ) {
  13166. if ( texture.image.length !== 6 ) return;
  13167. const textureProperties = properties.get( texture );
  13168. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13169. initTexture( textureProperties, texture );
  13170. state.activeTexture( 33984 + slot );
  13171. state.bindTexture( 34067, textureProperties.__webglTexture );
  13172. _gl.pixelStorei( 37440, texture.flipY );
  13173. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13174. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13175. const cubeImage = [];
  13176. for ( let i = 0; i < 6; i ++ ) {
  13177. if ( ! isCompressed && ! isDataTexture ) {
  13178. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13179. } else {
  13180. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13181. }
  13182. }
  13183. const image = cubeImage[ 0 ],
  13184. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13185. glFormat = utils.convert( texture.format ),
  13186. glType = utils.convert( texture.type ),
  13187. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13188. setTextureParameters( 34067, texture, supportsMips );
  13189. let mipmaps;
  13190. if ( isCompressed ) {
  13191. for ( let i = 0; i < 6; i ++ ) {
  13192. mipmaps = cubeImage[ i ].mipmaps;
  13193. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13194. const mipmap = mipmaps[ j ];
  13195. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13196. if ( glFormat !== null ) {
  13197. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13198. } else {
  13199. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13200. }
  13201. } else {
  13202. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13203. }
  13204. }
  13205. }
  13206. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13207. } else {
  13208. mipmaps = texture.mipmaps;
  13209. for ( let i = 0; i < 6; i ++ ) {
  13210. if ( isDataTexture ) {
  13211. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13212. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13213. const mipmap = mipmaps[ j ];
  13214. const mipmapImage = mipmap.image[ i ].image;
  13215. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13216. }
  13217. } else {
  13218. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13219. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13220. const mipmap = mipmaps[ j ];
  13221. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13222. }
  13223. }
  13224. }
  13225. textureProperties.__maxMipLevel = mipmaps.length;
  13226. }
  13227. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13228. // We assume images for cube map have the same size.
  13229. generateMipmap( 34067, texture, image.width, image.height );
  13230. }
  13231. textureProperties.__version = texture.version;
  13232. if ( texture.onUpdate ) texture.onUpdate( texture );
  13233. } else {
  13234. state.activeTexture( 33984 + slot );
  13235. state.bindTexture( 34067, textureProperties.__webglTexture );
  13236. }
  13237. }
  13238. function setTextureCubeDynamic( texture, slot ) {
  13239. state.activeTexture( 33984 + slot );
  13240. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  13241. }
  13242. const wrappingToGL = {
  13243. [ RepeatWrapping ]: 10497,
  13244. [ ClampToEdgeWrapping ]: 33071,
  13245. [ MirroredRepeatWrapping ]: 33648
  13246. };
  13247. const filterToGL = {
  13248. [ NearestFilter ]: 9728,
  13249. [ NearestMipmapNearestFilter ]: 9984,
  13250. [ NearestMipmapLinearFilter ]: 9986,
  13251. [ LinearFilter ]: 9729,
  13252. [ LinearMipmapNearestFilter ]: 9985,
  13253. [ LinearMipmapLinearFilter ]: 9987
  13254. };
  13255. function setTextureParameters( textureType, texture, supportsMips ) {
  13256. if ( supportsMips ) {
  13257. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13258. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13259. if ( textureType === 32879 || textureType === 35866 ) {
  13260. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13261. }
  13262. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13263. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13264. } else {
  13265. _gl.texParameteri( textureType, 10242, 33071 );
  13266. _gl.texParameteri( textureType, 10243, 33071 );
  13267. if ( textureType === 32879 || textureType === 35866 ) {
  13268. _gl.texParameteri( textureType, 32882, 33071 );
  13269. }
  13270. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13271. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13272. }
  13273. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13274. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13275. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13276. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13277. }
  13278. }
  13279. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13280. if ( extension ) {
  13281. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  13282. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  13283. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13284. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13285. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13286. }
  13287. }
  13288. }
  13289. function initTexture( textureProperties, texture ) {
  13290. if ( textureProperties.__webglInit === undefined ) {
  13291. textureProperties.__webglInit = true;
  13292. texture.addEventListener( 'dispose', onTextureDispose );
  13293. textureProperties.__webglTexture = _gl.createTexture();
  13294. info.memory.textures ++;
  13295. }
  13296. }
  13297. function uploadTexture( textureProperties, texture, slot ) {
  13298. let textureType = 3553;
  13299. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13300. if ( texture.isDataTexture3D ) textureType = 32879;
  13301. initTexture( textureProperties, texture );
  13302. state.activeTexture( 33984 + slot );
  13303. state.bindTexture( textureType, textureProperties.__webglTexture );
  13304. _gl.pixelStorei( 37440, texture.flipY );
  13305. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13306. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13307. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  13308. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13309. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13310. glFormat = utils.convert( texture.format );
  13311. let glType = utils.convert( texture.type ),
  13312. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13313. setTextureParameters( textureType, texture, supportsMips );
  13314. let mipmap;
  13315. const mipmaps = texture.mipmaps;
  13316. if ( texture.isDepthTexture ) {
  13317. // populate depth texture with dummy data
  13318. glInternalFormat = 6402;
  13319. if ( isWebGL2 ) {
  13320. if ( texture.type === FloatType ) {
  13321. glInternalFormat = 36012;
  13322. } else if ( texture.type === UnsignedIntType ) {
  13323. glInternalFormat = 33190;
  13324. } else if ( texture.type === UnsignedInt248Type ) {
  13325. glInternalFormat = 35056;
  13326. } else {
  13327. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13328. }
  13329. } else {
  13330. if ( texture.type === FloatType ) {
  13331. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13332. }
  13333. }
  13334. // validation checks for WebGL 1
  13335. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13336. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13337. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13338. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13339. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13340. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13341. texture.type = UnsignedShortType;
  13342. glType = utils.convert( texture.type );
  13343. }
  13344. }
  13345. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13346. // Depth stencil textures need the DEPTH_STENCIL internal format
  13347. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13348. glInternalFormat = 34041;
  13349. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13350. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13351. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13352. if ( texture.type !== UnsignedInt248Type ) {
  13353. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13354. texture.type = UnsignedInt248Type;
  13355. glType = utils.convert( texture.type );
  13356. }
  13357. }
  13358. //
  13359. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13360. } else if ( texture.isDataTexture ) {
  13361. // use manually created mipmaps if available
  13362. // if there are no manual mipmaps
  13363. // set 0 level mipmap and then use GL to generate other mipmap levels
  13364. if ( mipmaps.length > 0 && supportsMips ) {
  13365. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13366. mipmap = mipmaps[ i ];
  13367. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13368. }
  13369. texture.generateMipmaps = false;
  13370. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13371. } else {
  13372. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13373. textureProperties.__maxMipLevel = 0;
  13374. }
  13375. } else if ( texture.isCompressedTexture ) {
  13376. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13377. mipmap = mipmaps[ i ];
  13378. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13379. if ( glFormat !== null ) {
  13380. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13381. } else {
  13382. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13383. }
  13384. } else {
  13385. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13386. }
  13387. }
  13388. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13389. } else if ( texture.isDataTexture2DArray ) {
  13390. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13391. textureProperties.__maxMipLevel = 0;
  13392. } else if ( texture.isDataTexture3D ) {
  13393. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13394. textureProperties.__maxMipLevel = 0;
  13395. } else {
  13396. // regular Texture (image, video, canvas)
  13397. // use manually created mipmaps if available
  13398. // if there are no manual mipmaps
  13399. // set 0 level mipmap and then use GL to generate other mipmap levels
  13400. if ( mipmaps.length > 0 && supportsMips ) {
  13401. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13402. mipmap = mipmaps[ i ];
  13403. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13404. }
  13405. texture.generateMipmaps = false;
  13406. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13407. } else {
  13408. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13409. textureProperties.__maxMipLevel = 0;
  13410. }
  13411. }
  13412. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13413. generateMipmap( textureType, texture, image.width, image.height );
  13414. }
  13415. textureProperties.__version = texture.version;
  13416. if ( texture.onUpdate ) texture.onUpdate( texture );
  13417. }
  13418. // Render targets
  13419. // Setup storage for target texture and bind it to correct framebuffer
  13420. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  13421. const glFormat = utils.convert( renderTarget.texture.format );
  13422. const glType = utils.convert( renderTarget.texture.type );
  13423. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13424. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13425. _gl.bindFramebuffer( 36160, framebuffer );
  13426. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  13427. _gl.bindFramebuffer( 36160, null );
  13428. }
  13429. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13430. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13431. _gl.bindRenderbuffer( 36161, renderbuffer );
  13432. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13433. let glInternalFormat = 33189;
  13434. if ( isMultisample ) {
  13435. const depthTexture = renderTarget.depthTexture;
  13436. if ( depthTexture && depthTexture.isDepthTexture ) {
  13437. if ( depthTexture.type === FloatType ) {
  13438. glInternalFormat = 36012;
  13439. } else if ( depthTexture.type === UnsignedIntType ) {
  13440. glInternalFormat = 33190;
  13441. }
  13442. }
  13443. const samples = getRenderTargetSamples( renderTarget );
  13444. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13445. } else {
  13446. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13447. }
  13448. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13449. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13450. if ( isMultisample ) {
  13451. const samples = getRenderTargetSamples( renderTarget );
  13452. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13453. } else {
  13454. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13455. }
  13456. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13457. } else {
  13458. const glFormat = utils.convert( renderTarget.texture.format );
  13459. const glType = utils.convert( renderTarget.texture.type );
  13460. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13461. if ( isMultisample ) {
  13462. const samples = getRenderTargetSamples( renderTarget );
  13463. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13464. } else {
  13465. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13466. }
  13467. }
  13468. _gl.bindRenderbuffer( 36161, null );
  13469. }
  13470. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13471. function setupDepthTexture( framebuffer, renderTarget ) {
  13472. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13473. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13474. _gl.bindFramebuffer( 36160, framebuffer );
  13475. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13476. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13477. }
  13478. // upload an empty depth texture with framebuffer size
  13479. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13480. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13481. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13482. renderTarget.depthTexture.image.width = renderTarget.width;
  13483. renderTarget.depthTexture.image.height = renderTarget.height;
  13484. renderTarget.depthTexture.needsUpdate = true;
  13485. }
  13486. setTexture2D( renderTarget.depthTexture, 0 );
  13487. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13488. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13489. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13490. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13491. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13492. } else {
  13493. throw new Error( 'Unknown depthTexture format' );
  13494. }
  13495. }
  13496. // Setup GL resources for a non-texture depth buffer
  13497. function setupDepthRenderbuffer( renderTarget ) {
  13498. const renderTargetProperties = properties.get( renderTarget );
  13499. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13500. if ( renderTarget.depthTexture ) {
  13501. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13502. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13503. } else {
  13504. if ( isCube ) {
  13505. renderTargetProperties.__webglDepthbuffer = [];
  13506. for ( let i = 0; i < 6; i ++ ) {
  13507. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13508. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13509. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13510. }
  13511. } else {
  13512. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13513. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13514. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13515. }
  13516. }
  13517. _gl.bindFramebuffer( 36160, null );
  13518. }
  13519. // Set up GL resources for the render target
  13520. function setupRenderTarget( renderTarget ) {
  13521. const renderTargetProperties = properties.get( renderTarget );
  13522. const textureProperties = properties.get( renderTarget.texture );
  13523. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13524. textureProperties.__webglTexture = _gl.createTexture();
  13525. info.memory.textures ++;
  13526. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13527. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  13528. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13529. // Handles WebGL2 RGBFormat fallback - #18858
  13530. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  13531. renderTarget.texture.format = RGBAFormat;
  13532. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13533. }
  13534. // Setup framebuffer
  13535. if ( isCube ) {
  13536. renderTargetProperties.__webglFramebuffer = [];
  13537. for ( let i = 0; i < 6; i ++ ) {
  13538. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13539. }
  13540. } else {
  13541. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13542. if ( isMultisample ) {
  13543. if ( isWebGL2 ) {
  13544. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13545. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13546. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13547. const glFormat = utils.convert( renderTarget.texture.format );
  13548. const glType = utils.convert( renderTarget.texture.type );
  13549. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13550. const samples = getRenderTargetSamples( renderTarget );
  13551. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13552. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13553. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13554. _gl.bindRenderbuffer( 36161, null );
  13555. if ( renderTarget.depthBuffer ) {
  13556. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13557. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13558. }
  13559. _gl.bindFramebuffer( 36160, null );
  13560. } else {
  13561. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13562. }
  13563. }
  13564. }
  13565. // Setup color buffer
  13566. if ( isCube ) {
  13567. state.bindTexture( 34067, textureProperties.__webglTexture );
  13568. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  13569. for ( let i = 0; i < 6; i ++ ) {
  13570. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  13571. }
  13572. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13573. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  13574. }
  13575. state.bindTexture( 34067, null );
  13576. } else {
  13577. state.bindTexture( 3553, textureProperties.__webglTexture );
  13578. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  13579. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  13580. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13581. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  13582. }
  13583. state.bindTexture( 3553, null );
  13584. }
  13585. // Setup depth and stencil buffers
  13586. if ( renderTarget.depthBuffer ) {
  13587. setupDepthRenderbuffer( renderTarget );
  13588. }
  13589. }
  13590. function updateRenderTargetMipmap( renderTarget ) {
  13591. const texture = renderTarget.texture;
  13592. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13593. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13594. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13595. const webglTexture = properties.get( texture ).__webglTexture;
  13596. state.bindTexture( target, webglTexture );
  13597. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  13598. state.bindTexture( target, null );
  13599. }
  13600. }
  13601. function updateMultisampleRenderTarget( renderTarget ) {
  13602. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  13603. if ( isWebGL2 ) {
  13604. const renderTargetProperties = properties.get( renderTarget );
  13605. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  13606. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  13607. const width = renderTarget.width;
  13608. const height = renderTarget.height;
  13609. let mask = 16384;
  13610. if ( renderTarget.depthBuffer ) mask |= 256;
  13611. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13612. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  13613. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  13614. } else {
  13615. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13616. }
  13617. }
  13618. }
  13619. function getRenderTargetSamples( renderTarget ) {
  13620. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  13621. Math.min( maxSamples, renderTarget.samples ) : 0;
  13622. }
  13623. function updateVideoTexture( texture ) {
  13624. const frame = info.render.frame;
  13625. // Check the last frame we updated the VideoTexture
  13626. if ( _videoTextures.get( texture ) !== frame ) {
  13627. _videoTextures.set( texture, frame );
  13628. texture.update();
  13629. }
  13630. }
  13631. // backwards compatibility
  13632. let warnedTexture2D = false;
  13633. let warnedTextureCube = false;
  13634. function safeSetTexture2D( texture, slot ) {
  13635. if ( texture && texture.isWebGLRenderTarget ) {
  13636. if ( warnedTexture2D === false ) {
  13637. console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13638. warnedTexture2D = true;
  13639. }
  13640. texture = texture.texture;
  13641. }
  13642. setTexture2D( texture, slot );
  13643. }
  13644. function safeSetTextureCube( texture, slot ) {
  13645. if ( texture && texture.isWebGLCubeRenderTarget ) {
  13646. if ( warnedTextureCube === false ) {
  13647. console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13648. warnedTextureCube = true;
  13649. }
  13650. texture = texture.texture;
  13651. }
  13652. // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
  13653. // TODO: unify these code paths
  13654. if ( ( texture && texture.isCubeTexture ) ||
  13655. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13656. // CompressedTexture can have Array in image :/
  13657. // this function alone should take care of cube textures
  13658. setTextureCube( texture, slot );
  13659. } else {
  13660. // assumed: texture property of THREE.WebGLCubeRenderTarget
  13661. setTextureCubeDynamic( texture, slot );
  13662. }
  13663. }
  13664. //
  13665. this.allocateTextureUnit = allocateTextureUnit;
  13666. this.resetTextureUnits = resetTextureUnits;
  13667. this.setTexture2D = setTexture2D;
  13668. this.setTexture2DArray = setTexture2DArray;
  13669. this.setTexture3D = setTexture3D;
  13670. this.setTextureCube = setTextureCube;
  13671. this.setTextureCubeDynamic = setTextureCubeDynamic;
  13672. this.setupRenderTarget = setupRenderTarget;
  13673. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13674. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13675. this.safeSetTexture2D = safeSetTexture2D;
  13676. this.safeSetTextureCube = safeSetTextureCube;
  13677. }
  13678. function WebGLUtils( gl, extensions, capabilities ) {
  13679. const isWebGL2 = capabilities.isWebGL2;
  13680. function convert( p ) {
  13681. let extension;
  13682. if ( p === UnsignedByteType ) return 5121;
  13683. if ( p === UnsignedShort4444Type ) return 32819;
  13684. if ( p === UnsignedShort5551Type ) return 32820;
  13685. if ( p === UnsignedShort565Type ) return 33635;
  13686. if ( p === ByteType ) return 5120;
  13687. if ( p === ShortType ) return 5122;
  13688. if ( p === UnsignedShortType ) return 5123;
  13689. if ( p === IntType ) return 5124;
  13690. if ( p === UnsignedIntType ) return 5125;
  13691. if ( p === FloatType ) return 5126;
  13692. if ( p === HalfFloatType ) {
  13693. if ( isWebGL2 ) return 5131;
  13694. extension = extensions.get( 'OES_texture_half_float' );
  13695. if ( extension !== null ) {
  13696. return extension.HALF_FLOAT_OES;
  13697. } else {
  13698. return null;
  13699. }
  13700. }
  13701. if ( p === AlphaFormat ) return 6406;
  13702. if ( p === RGBFormat ) return 6407;
  13703. if ( p === RGBAFormat ) return 6408;
  13704. if ( p === LuminanceFormat ) return 6409;
  13705. if ( p === LuminanceAlphaFormat ) return 6410;
  13706. if ( p === DepthFormat ) return 6402;
  13707. if ( p === DepthStencilFormat ) return 34041;
  13708. if ( p === RedFormat ) return 6403;
  13709. // WebGL2 formats.
  13710. if ( p === RedIntegerFormat ) return 36244;
  13711. if ( p === RGFormat ) return 33319;
  13712. if ( p === RGIntegerFormat ) return 33320;
  13713. if ( p === RGBIntegerFormat ) return 36248;
  13714. if ( p === RGBAIntegerFormat ) return 36249;
  13715. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13716. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13717. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13718. if ( extension !== null ) {
  13719. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13720. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13721. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13722. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13723. } else {
  13724. return null;
  13725. }
  13726. }
  13727. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13728. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13729. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13730. if ( extension !== null ) {
  13731. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13732. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13733. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13734. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13735. } else {
  13736. return null;
  13737. }
  13738. }
  13739. if ( p === RGB_ETC1_Format ) {
  13740. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13741. if ( extension !== null ) {
  13742. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13743. } else {
  13744. return null;
  13745. }
  13746. }
  13747. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13748. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13749. if ( extension !== null ) {
  13750. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13751. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13752. }
  13753. }
  13754. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13755. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13756. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13757. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13758. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13759. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13760. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13761. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13762. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13763. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13764. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13765. if ( extension !== null ) {
  13766. // TODO Complete?
  13767. return p;
  13768. } else {
  13769. return null;
  13770. }
  13771. }
  13772. if ( p === RGBA_BPTC_Format ) {
  13773. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13774. if ( extension !== null ) {
  13775. // TODO Complete?
  13776. return p;
  13777. } else {
  13778. return null;
  13779. }
  13780. }
  13781. if ( p === UnsignedInt248Type ) {
  13782. if ( isWebGL2 ) return 34042;
  13783. extension = extensions.get( 'WEBGL_depth_texture' );
  13784. if ( extension !== null ) {
  13785. return extension.UNSIGNED_INT_24_8_WEBGL;
  13786. } else {
  13787. return null;
  13788. }
  13789. }
  13790. }
  13791. return { convert: convert };
  13792. }
  13793. function ArrayCamera( array ) {
  13794. PerspectiveCamera.call( this );
  13795. this.cameras = array || [];
  13796. }
  13797. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  13798. constructor: ArrayCamera,
  13799. isArrayCamera: true
  13800. } );
  13801. function Group() {
  13802. Object3D.call( this );
  13803. this.type = 'Group';
  13804. }
  13805. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13806. constructor: Group,
  13807. isGroup: true
  13808. } );
  13809. function WebXRController() {
  13810. this._targetRay = null;
  13811. this._grip = null;
  13812. this._hand = null;
  13813. }
  13814. Object.assign( WebXRController.prototype, {
  13815. constructor: WebXRController,
  13816. getHandSpace: function () {
  13817. if ( this._hand === null ) {
  13818. this._hand = new Group();
  13819. this._hand.matrixAutoUpdate = false;
  13820. this._hand.visible = false;
  13821. this._hand.joints = [];
  13822. this._hand.inputState = { pinching: false };
  13823. if ( window.XRHand ) {
  13824. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13825. // The transform of this joint will be updated with the joint pose on each frame
  13826. const joint = new Group();
  13827. joint.matrixAutoUpdate = false;
  13828. joint.visible = false;
  13829. this._hand.joints.push( joint );
  13830. // ??
  13831. this._hand.add( joint );
  13832. }
  13833. }
  13834. }
  13835. return this._hand;
  13836. },
  13837. getTargetRaySpace: function () {
  13838. if ( this._targetRay === null ) {
  13839. this._targetRay = new Group();
  13840. this._targetRay.matrixAutoUpdate = false;
  13841. this._targetRay.visible = false;
  13842. }
  13843. return this._targetRay;
  13844. },
  13845. getGripSpace: function () {
  13846. if ( this._grip === null ) {
  13847. this._grip = new Group();
  13848. this._grip.matrixAutoUpdate = false;
  13849. this._grip.visible = false;
  13850. }
  13851. return this._grip;
  13852. },
  13853. dispatchEvent: function ( event ) {
  13854. if ( this._targetRay !== null ) {
  13855. this._targetRay.dispatchEvent( event );
  13856. }
  13857. if ( this._grip !== null ) {
  13858. this._grip.dispatchEvent( event );
  13859. }
  13860. if ( this._hand !== null ) {
  13861. this._hand.dispatchEvent( event );
  13862. }
  13863. return this;
  13864. },
  13865. disconnect: function ( inputSource ) {
  13866. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13867. if ( this._targetRay !== null ) {
  13868. this._targetRay.visible = false;
  13869. }
  13870. if ( this._grip !== null ) {
  13871. this._grip.visible = false;
  13872. }
  13873. if ( this._hand !== null ) {
  13874. this._hand.visible = false;
  13875. }
  13876. return this;
  13877. },
  13878. update: function ( inputSource, frame, referenceSpace ) {
  13879. let inputPose = null;
  13880. let gripPose = null;
  13881. let handPose = null;
  13882. const targetRay = this._targetRay;
  13883. const grip = this._grip;
  13884. const hand = this._hand;
  13885. if ( inputSource ) {
  13886. if ( hand && inputSource.hand ) {
  13887. handPose = true;
  13888. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13889. if ( inputSource.hand[ i ] ) {
  13890. // Update the joints groups with the XRJoint poses
  13891. const jointPose = frame.getJointPose( inputSource.hand[ i ], referenceSpace );
  13892. const joint = hand.joints[ i ];
  13893. if ( jointPose !== null ) {
  13894. joint.matrix.fromArray( jointPose.transform.matrix );
  13895. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13896. joint.jointRadius = jointPose.radius;
  13897. }
  13898. joint.visible = jointPose !== null;
  13899. // Custom events
  13900. // Check pinch
  13901. const indexTip = hand.joints[ window.XRHand.INDEX_PHALANX_TIP ];
  13902. const thumbTip = hand.joints[ window.XRHand.THUMB_PHALANX_TIP ];
  13903. const distance = indexTip.position.distanceTo( thumbTip.position );
  13904. const distanceToPinch = 0.02;
  13905. const threshold = 0.005;
  13906. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13907. hand.inputState.pinching = false;
  13908. this.dispatchEvent( {
  13909. type: "pinchend",
  13910. handedness: inputSource.handedness,
  13911. target: this
  13912. } );
  13913. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13914. hand.inputState.pinching = true;
  13915. this.dispatchEvent( {
  13916. type: "pinchstart",
  13917. handedness: inputSource.handedness,
  13918. target: this
  13919. } );
  13920. }
  13921. }
  13922. }
  13923. } else {
  13924. if ( targetRay !== null ) {
  13925. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13926. if ( inputPose !== null ) {
  13927. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13928. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13929. }
  13930. }
  13931. if ( grip !== null && inputSource.gripSpace ) {
  13932. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13933. if ( gripPose !== null ) {
  13934. grip.matrix.fromArray( gripPose.transform.matrix );
  13935. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13936. }
  13937. }
  13938. }
  13939. }
  13940. if ( targetRay !== null ) {
  13941. targetRay.visible = ( inputPose !== null );
  13942. }
  13943. if ( grip !== null ) {
  13944. grip.visible = ( gripPose !== null );
  13945. }
  13946. if ( hand !== null ) {
  13947. hand.visible = ( handPose !== null );
  13948. }
  13949. return this;
  13950. }
  13951. } );
  13952. function WebXRManager( renderer, gl ) {
  13953. const scope = this;
  13954. let session = null;
  13955. let framebufferScaleFactor = 1.0;
  13956. let referenceSpace = null;
  13957. let referenceSpaceType = 'local-floor';
  13958. let pose = null;
  13959. const controllers = [];
  13960. const inputSourcesMap = new Map();
  13961. //
  13962. const cameraL = new PerspectiveCamera();
  13963. cameraL.layers.enable( 1 );
  13964. cameraL.viewport = new Vector4();
  13965. const cameraR = new PerspectiveCamera();
  13966. cameraR.layers.enable( 2 );
  13967. cameraR.viewport = new Vector4();
  13968. const cameras = [ cameraL, cameraR ];
  13969. const cameraVR = new ArrayCamera();
  13970. cameraVR.layers.enable( 1 );
  13971. cameraVR.layers.enable( 2 );
  13972. let _currentDepthNear = null;
  13973. let _currentDepthFar = null;
  13974. //
  13975. this.enabled = false;
  13976. this.isPresenting = false;
  13977. this.getController = function ( index ) {
  13978. let controller = controllers[ index ];
  13979. if ( controller === undefined ) {
  13980. controller = new WebXRController();
  13981. controllers[ index ] = controller;
  13982. }
  13983. return controller.getTargetRaySpace();
  13984. };
  13985. this.getControllerGrip = function ( index ) {
  13986. let controller = controllers[ index ];
  13987. if ( controller === undefined ) {
  13988. controller = new WebXRController();
  13989. controllers[ index ] = controller;
  13990. }
  13991. return controller.getGripSpace();
  13992. };
  13993. this.getHand = function ( index ) {
  13994. let controller = controllers[ index ];
  13995. if ( controller === undefined ) {
  13996. controller = new WebXRController();
  13997. controllers[ index ] = controller;
  13998. }
  13999. return controller.getHandSpace();
  14000. };
  14001. //
  14002. function onSessionEvent( event ) {
  14003. const controller = inputSourcesMap.get( event.inputSource );
  14004. if ( controller ) {
  14005. controller.dispatchEvent( { type: event.type } );
  14006. }
  14007. }
  14008. function onSessionEnd() {
  14009. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14010. controller.disconnect( inputSource );
  14011. } );
  14012. inputSourcesMap.clear();
  14013. //
  14014. renderer.setFramebuffer( null );
  14015. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  14016. animation.stop();
  14017. scope.isPresenting = false;
  14018. scope.dispatchEvent( { type: 'sessionend' } );
  14019. }
  14020. function onRequestReferenceSpace( value ) {
  14021. referenceSpace = value;
  14022. animation.setContext( session );
  14023. animation.start();
  14024. scope.isPresenting = true;
  14025. scope.dispatchEvent( { type: 'sessionstart' } );
  14026. }
  14027. this.setFramebufferScaleFactor = function ( value ) {
  14028. framebufferScaleFactor = value;
  14029. if ( scope.isPresenting === true ) {
  14030. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14031. }
  14032. };
  14033. this.setReferenceSpaceType = function ( value ) {
  14034. referenceSpaceType = value;
  14035. if ( scope.isPresenting === true ) {
  14036. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14037. }
  14038. };
  14039. this.getReferenceSpace = function () {
  14040. return referenceSpace;
  14041. };
  14042. this.getSession = function () {
  14043. return session;
  14044. };
  14045. this.setSession = function ( value ) {
  14046. session = value;
  14047. if ( session !== null ) {
  14048. session.addEventListener( 'select', onSessionEvent );
  14049. session.addEventListener( 'selectstart', onSessionEvent );
  14050. session.addEventListener( 'selectend', onSessionEvent );
  14051. session.addEventListener( 'squeeze', onSessionEvent );
  14052. session.addEventListener( 'squeezestart', onSessionEvent );
  14053. session.addEventListener( 'squeezeend', onSessionEvent );
  14054. session.addEventListener( 'end', onSessionEnd );
  14055. const attributes = gl.getContextAttributes();
  14056. if ( attributes.xrCompatible !== true ) {
  14057. gl.makeXRCompatible();
  14058. }
  14059. const layerInit = {
  14060. antialias: attributes.antialias,
  14061. alpha: attributes.alpha,
  14062. depth: attributes.depth,
  14063. stencil: attributes.stencil,
  14064. framebufferScaleFactor: framebufferScaleFactor
  14065. };
  14066. // eslint-disable-next-line no-undef
  14067. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  14068. session.updateRenderState( { baseLayer: baseLayer } );
  14069. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  14070. //
  14071. session.addEventListener( 'inputsourceschange', updateInputSources );
  14072. }
  14073. };
  14074. function updateInputSources( event ) {
  14075. const inputSources = session.inputSources;
  14076. // Assign inputSources to available controllers
  14077. for ( let i = 0; i < controllers.length; i ++ ) {
  14078. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14079. }
  14080. // Notify disconnected
  14081. for ( let i = 0; i < event.removed.length; i ++ ) {
  14082. const inputSource = event.removed[ i ];
  14083. const controller = inputSourcesMap.get( inputSource );
  14084. if ( controller ) {
  14085. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14086. inputSourcesMap.delete( inputSource );
  14087. }
  14088. }
  14089. // Notify connected
  14090. for ( let i = 0; i < event.added.length; i ++ ) {
  14091. const inputSource = event.added[ i ];
  14092. const controller = inputSourcesMap.get( inputSource );
  14093. if ( controller ) {
  14094. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14095. }
  14096. }
  14097. }
  14098. //
  14099. const cameraLPos = new Vector3();
  14100. const cameraRPos = new Vector3();
  14101. /**
  14102. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14103. * the cameras' projection and world matrices have already been set.
  14104. * And that near and far planes are identical for both cameras.
  14105. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14106. */
  14107. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14108. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14109. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14110. const ipd = cameraLPos.distanceTo( cameraRPos );
  14111. const projL = cameraL.projectionMatrix.elements;
  14112. const projR = cameraR.projectionMatrix.elements;
  14113. // VR systems will have identical far and near planes, and
  14114. // most likely identical top and bottom frustum extents.
  14115. // Use the left camera for these values.
  14116. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14117. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14118. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14119. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14120. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14121. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14122. const left = near * leftFov;
  14123. const right = near * rightFov;
  14124. // Calculate the new camera's position offset from the
  14125. // left camera. xOffset should be roughly half `ipd`.
  14126. const zOffset = ipd / ( - leftFov + rightFov );
  14127. const xOffset = zOffset * - leftFov;
  14128. // TODO: Better way to apply this offset?
  14129. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14130. camera.translateX( xOffset );
  14131. camera.translateZ( zOffset );
  14132. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14133. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14134. // Find the union of the frustum values of the cameras and scale
  14135. // the values so that the near plane's position does not change in world space,
  14136. // although must now be relative to the new union camera.
  14137. const near2 = near + zOffset;
  14138. const far2 = far + zOffset;
  14139. const left2 = left - xOffset;
  14140. const right2 = right + ( ipd - xOffset );
  14141. const top2 = topFov * far / far2 * near2;
  14142. const bottom2 = bottomFov * far / far2 * near2;
  14143. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14144. }
  14145. function updateCamera( camera, parent ) {
  14146. if ( parent === null ) {
  14147. camera.matrixWorld.copy( camera.matrix );
  14148. } else {
  14149. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14150. }
  14151. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14152. }
  14153. this.getCamera = function ( camera ) {
  14154. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14155. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14156. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14157. // Note that the new renderState won't apply until the next frame. See #18320
  14158. session.updateRenderState( {
  14159. depthNear: cameraVR.near,
  14160. depthFar: cameraVR.far
  14161. } );
  14162. _currentDepthNear = cameraVR.near;
  14163. _currentDepthFar = cameraVR.far;
  14164. }
  14165. const parent = camera.parent;
  14166. const cameras = cameraVR.cameras;
  14167. updateCamera( cameraVR, parent );
  14168. for ( let i = 0; i < cameras.length; i ++ ) {
  14169. updateCamera( cameras[ i ], parent );
  14170. }
  14171. // update camera and its children
  14172. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14173. const children = camera.children;
  14174. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14175. children[ i ].updateMatrixWorld( true );
  14176. }
  14177. // update projection matrix for proper view frustum culling
  14178. if ( cameras.length === 2 ) {
  14179. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14180. } else {
  14181. // assume single camera setup (AR)
  14182. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14183. }
  14184. return cameraVR;
  14185. };
  14186. // Animation Loop
  14187. let onAnimationFrameCallback = null;
  14188. function onAnimationFrame( time, frame ) {
  14189. pose = frame.getViewerPose( referenceSpace );
  14190. if ( pose !== null ) {
  14191. const views = pose.views;
  14192. const baseLayer = session.renderState.baseLayer;
  14193. renderer.setFramebuffer( baseLayer.framebuffer );
  14194. let cameraVRNeedsUpdate = false;
  14195. // check if it's necessary to rebuild cameraVR's camera list
  14196. if ( views.length !== cameraVR.cameras.length ) {
  14197. cameraVR.cameras.length = 0;
  14198. cameraVRNeedsUpdate = true;
  14199. }
  14200. for ( let i = 0; i < views.length; i ++ ) {
  14201. const view = views[ i ];
  14202. const viewport = baseLayer.getViewport( view );
  14203. const camera = cameras[ i ];
  14204. camera.matrix.fromArray( view.transform.matrix );
  14205. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14206. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14207. if ( i === 0 ) {
  14208. cameraVR.matrix.copy( camera.matrix );
  14209. }
  14210. if ( cameraVRNeedsUpdate === true ) {
  14211. cameraVR.cameras.push( camera );
  14212. }
  14213. }
  14214. }
  14215. //
  14216. const inputSources = session.inputSources;
  14217. for ( let i = 0; i < controllers.length; i ++ ) {
  14218. const controller = controllers[ i ];
  14219. const inputSource = inputSources[ i ];
  14220. controller.update( inputSource, frame, referenceSpace );
  14221. }
  14222. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14223. }
  14224. const animation = new WebGLAnimation();
  14225. animation.setAnimationLoop( onAnimationFrame );
  14226. this.setAnimationLoop = function ( callback ) {
  14227. onAnimationFrameCallback = callback;
  14228. };
  14229. this.dispose = function () {};
  14230. }
  14231. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  14232. function WebGLMaterials( properties ) {
  14233. function refreshFogUniforms( uniforms, fog ) {
  14234. uniforms.fogColor.value.copy( fog.color );
  14235. if ( fog.isFog ) {
  14236. uniforms.fogNear.value = fog.near;
  14237. uniforms.fogFar.value = fog.far;
  14238. } else if ( fog.isFogExp2 ) {
  14239. uniforms.fogDensity.value = fog.density;
  14240. }
  14241. }
  14242. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  14243. if ( material.isMeshBasicMaterial ) {
  14244. refreshUniformsCommon( uniforms, material );
  14245. } else if ( material.isMeshLambertMaterial ) {
  14246. refreshUniformsCommon( uniforms, material );
  14247. refreshUniformsLambert( uniforms, material );
  14248. } else if ( material.isMeshToonMaterial ) {
  14249. refreshUniformsCommon( uniforms, material );
  14250. refreshUniformsToon( uniforms, material );
  14251. } else if ( material.isMeshPhongMaterial ) {
  14252. refreshUniformsCommon( uniforms, material );
  14253. refreshUniformsPhong( uniforms, material );
  14254. } else if ( material.isMeshStandardMaterial ) {
  14255. refreshUniformsCommon( uniforms, material );
  14256. if ( material.isMeshPhysicalMaterial ) {
  14257. refreshUniformsPhysical( uniforms, material );
  14258. } else {
  14259. refreshUniformsStandard( uniforms, material );
  14260. }
  14261. } else if ( material.isMeshMatcapMaterial ) {
  14262. refreshUniformsCommon( uniforms, material );
  14263. refreshUniformsMatcap( uniforms, material );
  14264. } else if ( material.isMeshDepthMaterial ) {
  14265. refreshUniformsCommon( uniforms, material );
  14266. refreshUniformsDepth( uniforms, material );
  14267. } else if ( material.isMeshDistanceMaterial ) {
  14268. refreshUniformsCommon( uniforms, material );
  14269. refreshUniformsDistance( uniforms, material );
  14270. } else if ( material.isMeshNormalMaterial ) {
  14271. refreshUniformsCommon( uniforms, material );
  14272. refreshUniformsNormal( uniforms, material );
  14273. } else if ( material.isLineBasicMaterial ) {
  14274. refreshUniformsLine( uniforms, material );
  14275. if ( material.isLineDashedMaterial ) {
  14276. refreshUniformsDash( uniforms, material );
  14277. }
  14278. } else if ( material.isPointsMaterial ) {
  14279. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14280. } else if ( material.isSpriteMaterial ) {
  14281. refreshUniformsSprites( uniforms, material );
  14282. } else if ( material.isShadowMaterial ) {
  14283. uniforms.color.value.copy( material.color );
  14284. uniforms.opacity.value = material.opacity;
  14285. } else if ( material.isShaderMaterial ) {
  14286. material.uniformsNeedUpdate = false; // #15581
  14287. }
  14288. }
  14289. function refreshUniformsCommon( uniforms, material ) {
  14290. uniforms.opacity.value = material.opacity;
  14291. if ( material.color ) {
  14292. uniforms.diffuse.value.copy( material.color );
  14293. }
  14294. if ( material.emissive ) {
  14295. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14296. }
  14297. if ( material.map ) {
  14298. uniforms.map.value = material.map;
  14299. }
  14300. if ( material.alphaMap ) {
  14301. uniforms.alphaMap.value = material.alphaMap;
  14302. }
  14303. if ( material.specularMap ) {
  14304. uniforms.specularMap.value = material.specularMap;
  14305. }
  14306. const envMap = properties.get( material ).envMap;
  14307. if ( envMap ) {
  14308. uniforms.envMap.value = envMap;
  14309. uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;
  14310. uniforms.reflectivity.value = material.reflectivity;
  14311. uniforms.refractionRatio.value = material.refractionRatio;
  14312. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  14313. if ( maxMipLevel !== undefined ) {
  14314. uniforms.maxMipLevel.value = maxMipLevel;
  14315. }
  14316. }
  14317. if ( material.lightMap ) {
  14318. uniforms.lightMap.value = material.lightMap;
  14319. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14320. }
  14321. if ( material.aoMap ) {
  14322. uniforms.aoMap.value = material.aoMap;
  14323. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14324. }
  14325. // uv repeat and offset setting priorities
  14326. // 1. color map
  14327. // 2. specular map
  14328. // 3. displacementMap map
  14329. // 4. normal map
  14330. // 5. bump map
  14331. // 6. roughnessMap map
  14332. // 7. metalnessMap map
  14333. // 8. alphaMap map
  14334. // 9. emissiveMap map
  14335. // 10. clearcoat map
  14336. // 11. clearcoat normal map
  14337. // 12. clearcoat roughnessMap map
  14338. let uvScaleMap;
  14339. if ( material.map ) {
  14340. uvScaleMap = material.map;
  14341. } else if ( material.specularMap ) {
  14342. uvScaleMap = material.specularMap;
  14343. } else if ( material.displacementMap ) {
  14344. uvScaleMap = material.displacementMap;
  14345. } else if ( material.normalMap ) {
  14346. uvScaleMap = material.normalMap;
  14347. } else if ( material.bumpMap ) {
  14348. uvScaleMap = material.bumpMap;
  14349. } else if ( material.roughnessMap ) {
  14350. uvScaleMap = material.roughnessMap;
  14351. } else if ( material.metalnessMap ) {
  14352. uvScaleMap = material.metalnessMap;
  14353. } else if ( material.alphaMap ) {
  14354. uvScaleMap = material.alphaMap;
  14355. } else if ( material.emissiveMap ) {
  14356. uvScaleMap = material.emissiveMap;
  14357. } else if ( material.clearcoatMap ) {
  14358. uvScaleMap = material.clearcoatMap;
  14359. } else if ( material.clearcoatNormalMap ) {
  14360. uvScaleMap = material.clearcoatNormalMap;
  14361. } else if ( material.clearcoatRoughnessMap ) {
  14362. uvScaleMap = material.clearcoatRoughnessMap;
  14363. }
  14364. if ( uvScaleMap !== undefined ) {
  14365. // backwards compatibility
  14366. if ( uvScaleMap.isWebGLRenderTarget ) {
  14367. uvScaleMap = uvScaleMap.texture;
  14368. }
  14369. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14370. uvScaleMap.updateMatrix();
  14371. }
  14372. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14373. }
  14374. // uv repeat and offset setting priorities for uv2
  14375. // 1. ao map
  14376. // 2. light map
  14377. let uv2ScaleMap;
  14378. if ( material.aoMap ) {
  14379. uv2ScaleMap = material.aoMap;
  14380. } else if ( material.lightMap ) {
  14381. uv2ScaleMap = material.lightMap;
  14382. }
  14383. if ( uv2ScaleMap !== undefined ) {
  14384. // backwards compatibility
  14385. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14386. uv2ScaleMap = uv2ScaleMap.texture;
  14387. }
  14388. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14389. uv2ScaleMap.updateMatrix();
  14390. }
  14391. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14392. }
  14393. }
  14394. function refreshUniformsLine( uniforms, material ) {
  14395. uniforms.diffuse.value.copy( material.color );
  14396. uniforms.opacity.value = material.opacity;
  14397. }
  14398. function refreshUniformsDash( uniforms, material ) {
  14399. uniforms.dashSize.value = material.dashSize;
  14400. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14401. uniforms.scale.value = material.scale;
  14402. }
  14403. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14404. uniforms.diffuse.value.copy( material.color );
  14405. uniforms.opacity.value = material.opacity;
  14406. uniforms.size.value = material.size * pixelRatio;
  14407. uniforms.scale.value = height * 0.5;
  14408. if ( material.map ) {
  14409. uniforms.map.value = material.map;
  14410. }
  14411. if ( material.alphaMap ) {
  14412. uniforms.alphaMap.value = material.alphaMap;
  14413. }
  14414. // uv repeat and offset setting priorities
  14415. // 1. color map
  14416. // 2. alpha map
  14417. let uvScaleMap;
  14418. if ( material.map ) {
  14419. uvScaleMap = material.map;
  14420. } else if ( material.alphaMap ) {
  14421. uvScaleMap = material.alphaMap;
  14422. }
  14423. if ( uvScaleMap !== undefined ) {
  14424. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14425. uvScaleMap.updateMatrix();
  14426. }
  14427. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14428. }
  14429. }
  14430. function refreshUniformsSprites( uniforms, material ) {
  14431. uniforms.diffuse.value.copy( material.color );
  14432. uniforms.opacity.value = material.opacity;
  14433. uniforms.rotation.value = material.rotation;
  14434. if ( material.map ) {
  14435. uniforms.map.value = material.map;
  14436. }
  14437. if ( material.alphaMap ) {
  14438. uniforms.alphaMap.value = material.alphaMap;
  14439. }
  14440. // uv repeat and offset setting priorities
  14441. // 1. color map
  14442. // 2. alpha map
  14443. let uvScaleMap;
  14444. if ( material.map ) {
  14445. uvScaleMap = material.map;
  14446. } else if ( material.alphaMap ) {
  14447. uvScaleMap = material.alphaMap;
  14448. }
  14449. if ( uvScaleMap !== undefined ) {
  14450. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14451. uvScaleMap.updateMatrix();
  14452. }
  14453. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14454. }
  14455. }
  14456. function refreshUniformsLambert( uniforms, material ) {
  14457. if ( material.emissiveMap ) {
  14458. uniforms.emissiveMap.value = material.emissiveMap;
  14459. }
  14460. }
  14461. function refreshUniformsPhong( uniforms, material ) {
  14462. uniforms.specular.value.copy( material.specular );
  14463. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14464. if ( material.emissiveMap ) {
  14465. uniforms.emissiveMap.value = material.emissiveMap;
  14466. }
  14467. if ( material.bumpMap ) {
  14468. uniforms.bumpMap.value = material.bumpMap;
  14469. uniforms.bumpScale.value = material.bumpScale;
  14470. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14471. }
  14472. if ( material.normalMap ) {
  14473. uniforms.normalMap.value = material.normalMap;
  14474. uniforms.normalScale.value.copy( material.normalScale );
  14475. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14476. }
  14477. if ( material.displacementMap ) {
  14478. uniforms.displacementMap.value = material.displacementMap;
  14479. uniforms.displacementScale.value = material.displacementScale;
  14480. uniforms.displacementBias.value = material.displacementBias;
  14481. }
  14482. }
  14483. function refreshUniformsToon( uniforms, material ) {
  14484. if ( material.gradientMap ) {
  14485. uniforms.gradientMap.value = material.gradientMap;
  14486. }
  14487. if ( material.emissiveMap ) {
  14488. uniforms.emissiveMap.value = material.emissiveMap;
  14489. }
  14490. if ( material.bumpMap ) {
  14491. uniforms.bumpMap.value = material.bumpMap;
  14492. uniforms.bumpScale.value = material.bumpScale;
  14493. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14494. }
  14495. if ( material.normalMap ) {
  14496. uniforms.normalMap.value = material.normalMap;
  14497. uniforms.normalScale.value.copy( material.normalScale );
  14498. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14499. }
  14500. if ( material.displacementMap ) {
  14501. uniforms.displacementMap.value = material.displacementMap;
  14502. uniforms.displacementScale.value = material.displacementScale;
  14503. uniforms.displacementBias.value = material.displacementBias;
  14504. }
  14505. }
  14506. function refreshUniformsStandard( uniforms, material ) {
  14507. uniforms.roughness.value = material.roughness;
  14508. uniforms.metalness.value = material.metalness;
  14509. if ( material.roughnessMap ) {
  14510. uniforms.roughnessMap.value = material.roughnessMap;
  14511. }
  14512. if ( material.metalnessMap ) {
  14513. uniforms.metalnessMap.value = material.metalnessMap;
  14514. }
  14515. if ( material.emissiveMap ) {
  14516. uniforms.emissiveMap.value = material.emissiveMap;
  14517. }
  14518. if ( material.bumpMap ) {
  14519. uniforms.bumpMap.value = material.bumpMap;
  14520. uniforms.bumpScale.value = material.bumpScale;
  14521. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14522. }
  14523. if ( material.normalMap ) {
  14524. uniforms.normalMap.value = material.normalMap;
  14525. uniforms.normalScale.value.copy( material.normalScale );
  14526. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14527. }
  14528. if ( material.displacementMap ) {
  14529. uniforms.displacementMap.value = material.displacementMap;
  14530. uniforms.displacementScale.value = material.displacementScale;
  14531. uniforms.displacementBias.value = material.displacementBias;
  14532. }
  14533. const envMap = properties.get( material ).envMap;
  14534. if ( envMap ) {
  14535. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14536. uniforms.envMapIntensity.value = material.envMapIntensity;
  14537. }
  14538. }
  14539. function refreshUniformsPhysical( uniforms, material ) {
  14540. refreshUniformsStandard( uniforms, material );
  14541. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14542. uniforms.clearcoat.value = material.clearcoat;
  14543. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14544. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  14545. if ( material.clearcoatMap ) {
  14546. uniforms.clearcoatMap.value = material.clearcoatMap;
  14547. }
  14548. if ( material.clearcoatRoughnessMap ) {
  14549. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14550. }
  14551. if ( material.clearcoatNormalMap ) {
  14552. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  14553. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14554. if ( material.side === BackSide ) {
  14555. uniforms.clearcoatNormalScale.value.negate();
  14556. }
  14557. }
  14558. uniforms.transmission.value = material.transmission;
  14559. if ( material.transmissionMap ) {
  14560. uniforms.transmissionMap.value = material.transmissionMap;
  14561. }
  14562. }
  14563. function refreshUniformsMatcap( uniforms, material ) {
  14564. if ( material.matcap ) {
  14565. uniforms.matcap.value = material.matcap;
  14566. }
  14567. if ( material.bumpMap ) {
  14568. uniforms.bumpMap.value = material.bumpMap;
  14569. uniforms.bumpScale.value = material.bumpScale;
  14570. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14571. }
  14572. if ( material.normalMap ) {
  14573. uniforms.normalMap.value = material.normalMap;
  14574. uniforms.normalScale.value.copy( material.normalScale );
  14575. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14576. }
  14577. if ( material.displacementMap ) {
  14578. uniforms.displacementMap.value = material.displacementMap;
  14579. uniforms.displacementScale.value = material.displacementScale;
  14580. uniforms.displacementBias.value = material.displacementBias;
  14581. }
  14582. }
  14583. function refreshUniformsDepth( uniforms, material ) {
  14584. if ( material.displacementMap ) {
  14585. uniforms.displacementMap.value = material.displacementMap;
  14586. uniforms.displacementScale.value = material.displacementScale;
  14587. uniforms.displacementBias.value = material.displacementBias;
  14588. }
  14589. }
  14590. function refreshUniformsDistance( uniforms, material ) {
  14591. if ( material.displacementMap ) {
  14592. uniforms.displacementMap.value = material.displacementMap;
  14593. uniforms.displacementScale.value = material.displacementScale;
  14594. uniforms.displacementBias.value = material.displacementBias;
  14595. }
  14596. uniforms.referencePosition.value.copy( material.referencePosition );
  14597. uniforms.nearDistance.value = material.nearDistance;
  14598. uniforms.farDistance.value = material.farDistance;
  14599. }
  14600. function refreshUniformsNormal( uniforms, material ) {
  14601. if ( material.bumpMap ) {
  14602. uniforms.bumpMap.value = material.bumpMap;
  14603. uniforms.bumpScale.value = material.bumpScale;
  14604. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14605. }
  14606. if ( material.normalMap ) {
  14607. uniforms.normalMap.value = material.normalMap;
  14608. uniforms.normalScale.value.copy( material.normalScale );
  14609. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14610. }
  14611. if ( material.displacementMap ) {
  14612. uniforms.displacementMap.value = material.displacementMap;
  14613. uniforms.displacementScale.value = material.displacementScale;
  14614. uniforms.displacementBias.value = material.displacementBias;
  14615. }
  14616. }
  14617. return {
  14618. refreshFogUniforms: refreshFogUniforms,
  14619. refreshMaterialUniforms: refreshMaterialUniforms
  14620. };
  14621. }
  14622. function WebGLRenderer( parameters ) {
  14623. parameters = parameters || {};
  14624. const _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  14625. _context = parameters.context !== undefined ? parameters.context : null,
  14626. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14627. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14628. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14629. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14630. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14631. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14632. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14633. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14634. let currentRenderList = null;
  14635. let currentRenderState = null;
  14636. // public properties
  14637. this.domElement = _canvas;
  14638. // Debug configuration container
  14639. this.debug = {
  14640. /**
  14641. * Enables error checking and reporting when shader programs are being compiled
  14642. * @type {boolean}
  14643. */
  14644. checkShaderErrors: true
  14645. };
  14646. // clearing
  14647. this.autoClear = true;
  14648. this.autoClearColor = true;
  14649. this.autoClearDepth = true;
  14650. this.autoClearStencil = true;
  14651. // scene graph
  14652. this.sortObjects = true;
  14653. // user-defined clipping
  14654. this.clippingPlanes = [];
  14655. this.localClippingEnabled = false;
  14656. // physically based shading
  14657. this.gammaFactor = 2.0; // for backwards compatibility
  14658. this.outputEncoding = LinearEncoding;
  14659. // physical lights
  14660. this.physicallyCorrectLights = false;
  14661. // tone mapping
  14662. this.toneMapping = NoToneMapping;
  14663. this.toneMappingExposure = 1.0;
  14664. // morphs
  14665. this.maxMorphTargets = 8;
  14666. this.maxMorphNormals = 4;
  14667. // internal properties
  14668. const _this = this;
  14669. let _isContextLost = false;
  14670. // internal state cache
  14671. let _framebuffer = null;
  14672. let _currentActiveCubeFace = 0;
  14673. let _currentActiveMipmapLevel = 0;
  14674. let _currentRenderTarget = null;
  14675. let _currentFramebuffer = null;
  14676. let _currentMaterialId = - 1;
  14677. let _currentCamera = null;
  14678. let _currentArrayCamera = null;
  14679. const _currentViewport = new Vector4();
  14680. const _currentScissor = new Vector4();
  14681. let _currentScissorTest = null;
  14682. //
  14683. let _width = _canvas.width;
  14684. let _height = _canvas.height;
  14685. let _pixelRatio = 1;
  14686. let _opaqueSort = null;
  14687. let _transparentSort = null;
  14688. const _viewport = new Vector4( 0, 0, _width, _height );
  14689. const _scissor = new Vector4( 0, 0, _width, _height );
  14690. let _scissorTest = false;
  14691. // frustum
  14692. const _frustum = new Frustum();
  14693. // clipping
  14694. let _clippingEnabled = false;
  14695. let _localClippingEnabled = false;
  14696. // camera matrices cache
  14697. const _projScreenMatrix = new Matrix4();
  14698. const _vector3 = new Vector3();
  14699. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  14700. function getTargetPixelRatio() {
  14701. return _currentRenderTarget === null ? _pixelRatio : 1;
  14702. }
  14703. // initialize
  14704. let _gl = _context;
  14705. function getContext( contextNames, contextAttributes ) {
  14706. for ( let i = 0; i < contextNames.length; i ++ ) {
  14707. const contextName = contextNames[ i ];
  14708. const context = _canvas.getContext( contextName, contextAttributes );
  14709. if ( context !== null ) return context;
  14710. }
  14711. return null;
  14712. }
  14713. try {
  14714. const contextAttributes = {
  14715. alpha: _alpha,
  14716. depth: _depth,
  14717. stencil: _stencil,
  14718. antialias: _antialias,
  14719. premultipliedAlpha: _premultipliedAlpha,
  14720. preserveDrawingBuffer: _preserveDrawingBuffer,
  14721. powerPreference: _powerPreference,
  14722. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14723. };
  14724. // event listeners must be registered before WebGL context is created, see #12753
  14725. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14726. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14727. if ( _gl === null ) {
  14728. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14729. if ( _this.isWebGL1Renderer === true ) {
  14730. contextNames.shift();
  14731. }
  14732. _gl = getContext( contextNames, contextAttributes );
  14733. if ( _gl === null ) {
  14734. if ( getContext( contextNames ) ) {
  14735. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14736. } else {
  14737. throw new Error( 'Error creating WebGL context.' );
  14738. }
  14739. }
  14740. }
  14741. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14742. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14743. _gl.getShaderPrecisionFormat = function () {
  14744. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14745. };
  14746. }
  14747. } catch ( error ) {
  14748. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14749. throw error;
  14750. }
  14751. let extensions, capabilities, state, info;
  14752. let properties, textures, cubemaps, attributes, geometries, objects;
  14753. let programCache, materials, renderLists, renderStates, clipping;
  14754. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14755. let utils, bindingStates;
  14756. function initGLContext() {
  14757. extensions = new WebGLExtensions( _gl );
  14758. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14759. if ( capabilities.isWebGL2 === false ) {
  14760. extensions.get( 'WEBGL_depth_texture' );
  14761. extensions.get( 'OES_texture_float' );
  14762. extensions.get( 'OES_texture_half_float' );
  14763. extensions.get( 'OES_texture_half_float_linear' );
  14764. extensions.get( 'OES_standard_derivatives' );
  14765. extensions.get( 'OES_element_index_uint' );
  14766. extensions.get( 'OES_vertex_array_object' );
  14767. extensions.get( 'ANGLE_instanced_arrays' );
  14768. }
  14769. extensions.get( 'OES_texture_float_linear' );
  14770. utils = new WebGLUtils( _gl, extensions, capabilities );
  14771. state = new WebGLState( _gl, extensions, capabilities );
  14772. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14773. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14774. info = new WebGLInfo( _gl );
  14775. properties = new WebGLProperties();
  14776. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14777. cubemaps = new WebGLCubeMaps( _this );
  14778. attributes = new WebGLAttributes( _gl, capabilities );
  14779. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14780. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14781. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14782. morphtargets = new WebGLMorphtargets( _gl );
  14783. clipping = new WebGLClipping( properties );
  14784. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14785. materials = new WebGLMaterials( properties );
  14786. renderLists = new WebGLRenderLists( properties );
  14787. renderStates = new WebGLRenderStates();
  14788. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14789. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14790. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14791. info.programs = programCache.programs;
  14792. _this.capabilities = capabilities;
  14793. _this.extensions = extensions;
  14794. _this.properties = properties;
  14795. _this.renderLists = renderLists;
  14796. _this.state = state;
  14797. _this.info = info;
  14798. }
  14799. initGLContext();
  14800. // xr
  14801. const xr = new WebXRManager( _this, _gl );
  14802. this.xr = xr;
  14803. // shadow map
  14804. const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  14805. this.shadowMap = shadowMap;
  14806. // API
  14807. this.getContext = function () {
  14808. return _gl;
  14809. };
  14810. this.getContextAttributes = function () {
  14811. return _gl.getContextAttributes();
  14812. };
  14813. this.forceContextLoss = function () {
  14814. const extension = extensions.get( 'WEBGL_lose_context' );
  14815. if ( extension ) extension.loseContext();
  14816. };
  14817. this.forceContextRestore = function () {
  14818. const extension = extensions.get( 'WEBGL_lose_context' );
  14819. if ( extension ) extension.restoreContext();
  14820. };
  14821. this.getPixelRatio = function () {
  14822. return _pixelRatio;
  14823. };
  14824. this.setPixelRatio = function ( value ) {
  14825. if ( value === undefined ) return;
  14826. _pixelRatio = value;
  14827. this.setSize( _width, _height, false );
  14828. };
  14829. this.getSize = function ( target ) {
  14830. if ( target === undefined ) {
  14831. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  14832. target = new Vector2();
  14833. }
  14834. return target.set( _width, _height );
  14835. };
  14836. this.setSize = function ( width, height, updateStyle ) {
  14837. if ( xr.isPresenting ) {
  14838. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14839. return;
  14840. }
  14841. _width = width;
  14842. _height = height;
  14843. _canvas.width = Math.floor( width * _pixelRatio );
  14844. _canvas.height = Math.floor( height * _pixelRatio );
  14845. if ( updateStyle !== false ) {
  14846. _canvas.style.width = width + 'px';
  14847. _canvas.style.height = height + 'px';
  14848. }
  14849. this.setViewport( 0, 0, width, height );
  14850. };
  14851. this.getDrawingBufferSize = function ( target ) {
  14852. if ( target === undefined ) {
  14853. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  14854. target = new Vector2();
  14855. }
  14856. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14857. };
  14858. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14859. _width = width;
  14860. _height = height;
  14861. _pixelRatio = pixelRatio;
  14862. _canvas.width = Math.floor( width * pixelRatio );
  14863. _canvas.height = Math.floor( height * pixelRatio );
  14864. this.setViewport( 0, 0, width, height );
  14865. };
  14866. this.getCurrentViewport = function ( target ) {
  14867. if ( target === undefined ) {
  14868. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14869. target = new Vector4();
  14870. }
  14871. return target.copy( _currentViewport );
  14872. };
  14873. this.getViewport = function ( target ) {
  14874. return target.copy( _viewport );
  14875. };
  14876. this.setViewport = function ( x, y, width, height ) {
  14877. if ( x.isVector4 ) {
  14878. _viewport.set( x.x, x.y, x.z, x.w );
  14879. } else {
  14880. _viewport.set( x, y, width, height );
  14881. }
  14882. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14883. };
  14884. this.getScissor = function ( target ) {
  14885. return target.copy( _scissor );
  14886. };
  14887. this.setScissor = function ( x, y, width, height ) {
  14888. if ( x.isVector4 ) {
  14889. _scissor.set( x.x, x.y, x.z, x.w );
  14890. } else {
  14891. _scissor.set( x, y, width, height );
  14892. }
  14893. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14894. };
  14895. this.getScissorTest = function () {
  14896. return _scissorTest;
  14897. };
  14898. this.setScissorTest = function ( boolean ) {
  14899. state.setScissorTest( _scissorTest = boolean );
  14900. };
  14901. this.setOpaqueSort = function ( method ) {
  14902. _opaqueSort = method;
  14903. };
  14904. this.setTransparentSort = function ( method ) {
  14905. _transparentSort = method;
  14906. };
  14907. // Clearing
  14908. this.getClearColor = function () {
  14909. return background.getClearColor();
  14910. };
  14911. this.setClearColor = function () {
  14912. background.setClearColor.apply( background, arguments );
  14913. };
  14914. this.getClearAlpha = function () {
  14915. return background.getClearAlpha();
  14916. };
  14917. this.setClearAlpha = function () {
  14918. background.setClearAlpha.apply( background, arguments );
  14919. };
  14920. this.clear = function ( color, depth, stencil ) {
  14921. let bits = 0;
  14922. if ( color === undefined || color ) bits |= 16384;
  14923. if ( depth === undefined || depth ) bits |= 256;
  14924. if ( stencil === undefined || stencil ) bits |= 1024;
  14925. _gl.clear( bits );
  14926. };
  14927. this.clearColor = function () {
  14928. this.clear( true, false, false );
  14929. };
  14930. this.clearDepth = function () {
  14931. this.clear( false, true, false );
  14932. };
  14933. this.clearStencil = function () {
  14934. this.clear( false, false, true );
  14935. };
  14936. //
  14937. this.dispose = function () {
  14938. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14939. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14940. renderLists.dispose();
  14941. renderStates.dispose();
  14942. properties.dispose();
  14943. cubemaps.dispose();
  14944. objects.dispose();
  14945. bindingStates.dispose();
  14946. xr.dispose();
  14947. animation.stop();
  14948. };
  14949. // Events
  14950. function onContextLost( event ) {
  14951. event.preventDefault();
  14952. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14953. _isContextLost = true;
  14954. }
  14955. function onContextRestore( /* event */ ) {
  14956. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14957. _isContextLost = false;
  14958. initGLContext();
  14959. }
  14960. function onMaterialDispose( event ) {
  14961. const material = event.target;
  14962. material.removeEventListener( 'dispose', onMaterialDispose );
  14963. deallocateMaterial( material );
  14964. }
  14965. // Buffer deallocation
  14966. function deallocateMaterial( material ) {
  14967. releaseMaterialProgramReference( material );
  14968. properties.remove( material );
  14969. }
  14970. function releaseMaterialProgramReference( material ) {
  14971. const programInfo = properties.get( material ).program;
  14972. if ( programInfo !== undefined ) {
  14973. programCache.releaseProgram( programInfo );
  14974. }
  14975. }
  14976. // Buffer rendering
  14977. function renderObjectImmediate( object, program ) {
  14978. object.render( function ( object ) {
  14979. _this.renderBufferImmediate( object, program );
  14980. } );
  14981. }
  14982. this.renderBufferImmediate = function ( object, program ) {
  14983. bindingStates.initAttributes();
  14984. const buffers = properties.get( object );
  14985. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14986. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14987. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14988. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14989. const programAttributes = program.getAttributes();
  14990. if ( object.hasPositions ) {
  14991. _gl.bindBuffer( 34962, buffers.position );
  14992. _gl.bufferData( 34962, object.positionArray, 35048 );
  14993. bindingStates.enableAttribute( programAttributes.position );
  14994. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  14995. }
  14996. if ( object.hasNormals ) {
  14997. _gl.bindBuffer( 34962, buffers.normal );
  14998. _gl.bufferData( 34962, object.normalArray, 35048 );
  14999. bindingStates.enableAttribute( programAttributes.normal );
  15000. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  15001. }
  15002. if ( object.hasUvs ) {
  15003. _gl.bindBuffer( 34962, buffers.uv );
  15004. _gl.bufferData( 34962, object.uvArray, 35048 );
  15005. bindingStates.enableAttribute( programAttributes.uv );
  15006. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  15007. }
  15008. if ( object.hasColors ) {
  15009. _gl.bindBuffer( 34962, buffers.color );
  15010. _gl.bufferData( 34962, object.colorArray, 35048 );
  15011. bindingStates.enableAttribute( programAttributes.color );
  15012. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  15013. }
  15014. bindingStates.disableUnusedAttributes();
  15015. _gl.drawArrays( 4, 0, object.count );
  15016. object.count = 0;
  15017. };
  15018. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15019. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15020. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15021. const program = setProgram( camera, scene, material, object );
  15022. state.setMaterial( material, frontFaceCW );
  15023. //
  15024. let index = geometry.index;
  15025. const position = geometry.attributes.position;
  15026. //
  15027. if ( index === null ) {
  15028. if ( position === undefined || position.count === 0 ) return;
  15029. } else if ( index.count === 0 ) {
  15030. return;
  15031. }
  15032. //
  15033. let rangeFactor = 1;
  15034. if ( material.wireframe === true ) {
  15035. index = geometries.getWireframeAttribute( geometry );
  15036. rangeFactor = 2;
  15037. }
  15038. if ( material.morphTargets || material.morphNormals ) {
  15039. morphtargets.update( object, geometry, material, program );
  15040. }
  15041. bindingStates.setup( object, material, program, geometry, index );
  15042. let attribute;
  15043. let renderer = bufferRenderer;
  15044. if ( index !== null ) {
  15045. attribute = attributes.get( index );
  15046. renderer = indexedBufferRenderer;
  15047. renderer.setIndex( attribute );
  15048. }
  15049. //
  15050. const dataCount = ( index !== null ) ? index.count : position.count;
  15051. const rangeStart = geometry.drawRange.start * rangeFactor;
  15052. const rangeCount = geometry.drawRange.count * rangeFactor;
  15053. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15054. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15055. const drawStart = Math.max( rangeStart, groupStart );
  15056. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15057. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15058. if ( drawCount === 0 ) return;
  15059. //
  15060. if ( object.isMesh ) {
  15061. if ( material.wireframe === true ) {
  15062. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15063. renderer.setMode( 1 );
  15064. } else {
  15065. renderer.setMode( 4 );
  15066. }
  15067. } else if ( object.isLine ) {
  15068. let lineWidth = material.linewidth;
  15069. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15070. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15071. if ( object.isLineSegments ) {
  15072. renderer.setMode( 1 );
  15073. } else if ( object.isLineLoop ) {
  15074. renderer.setMode( 2 );
  15075. } else {
  15076. renderer.setMode( 3 );
  15077. }
  15078. } else if ( object.isPoints ) {
  15079. renderer.setMode( 0 );
  15080. } else if ( object.isSprite ) {
  15081. renderer.setMode( 4 );
  15082. }
  15083. if ( object.isInstancedMesh ) {
  15084. renderer.renderInstances( drawStart, drawCount, object.count );
  15085. } else if ( geometry.isInstancedBufferGeometry ) {
  15086. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15087. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15088. } else {
  15089. renderer.render( drawStart, drawCount );
  15090. }
  15091. };
  15092. // Compile
  15093. this.compile = function ( scene, camera ) {
  15094. currentRenderState = renderStates.get( scene, camera );
  15095. currentRenderState.init();
  15096. scene.traverse( function ( object ) {
  15097. if ( object.isLight ) {
  15098. currentRenderState.pushLight( object );
  15099. if ( object.castShadow ) {
  15100. currentRenderState.pushShadow( object );
  15101. }
  15102. }
  15103. } );
  15104. currentRenderState.setupLights( camera );
  15105. const compiled = new WeakMap();
  15106. scene.traverse( function ( object ) {
  15107. const material = object.material;
  15108. if ( material ) {
  15109. if ( Array.isArray( material ) ) {
  15110. for ( let i = 0; i < material.length; i ++ ) {
  15111. const material2 = material[ i ];
  15112. if ( compiled.has( material2 ) === false ) {
  15113. initMaterial( material2, scene, object );
  15114. compiled.set( material2 );
  15115. }
  15116. }
  15117. } else if ( compiled.has( material ) === false ) {
  15118. initMaterial( material, scene, object );
  15119. compiled.set( material );
  15120. }
  15121. }
  15122. } );
  15123. };
  15124. // Animation Loop
  15125. let onAnimationFrameCallback = null;
  15126. function onAnimationFrame( time ) {
  15127. if ( xr.isPresenting ) return;
  15128. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15129. }
  15130. const animation = new WebGLAnimation();
  15131. animation.setAnimationLoop( onAnimationFrame );
  15132. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15133. this.setAnimationLoop = function ( callback ) {
  15134. onAnimationFrameCallback = callback;
  15135. xr.setAnimationLoop( callback );
  15136. ( callback === null ) ? animation.stop() : animation.start();
  15137. };
  15138. // Rendering
  15139. this.render = function ( scene, camera ) {
  15140. let renderTarget, forceClear;
  15141. if ( arguments[ 2 ] !== undefined ) {
  15142. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  15143. renderTarget = arguments[ 2 ];
  15144. }
  15145. if ( arguments[ 3 ] !== undefined ) {
  15146. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  15147. forceClear = arguments[ 3 ];
  15148. }
  15149. if ( camera !== undefined && camera.isCamera !== true ) {
  15150. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15151. return;
  15152. }
  15153. if ( _isContextLost === true ) return;
  15154. // reset caching for this frame
  15155. bindingStates.resetDefaultState();
  15156. _currentMaterialId = - 1;
  15157. _currentCamera = null;
  15158. // update scene graph
  15159. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15160. // update camera matrices and frustum
  15161. if ( camera.parent === null ) camera.updateMatrixWorld();
  15162. if ( xr.enabled === true && xr.isPresenting === true ) {
  15163. camera = xr.getCamera( camera );
  15164. }
  15165. //
  15166. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  15167. currentRenderState = renderStates.get( scene, camera );
  15168. currentRenderState.init();
  15169. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15170. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15171. _localClippingEnabled = this.localClippingEnabled;
  15172. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15173. currentRenderList = renderLists.get( scene, camera );
  15174. currentRenderList.init();
  15175. projectObject( scene, camera, 0, _this.sortObjects );
  15176. currentRenderList.finish();
  15177. if ( _this.sortObjects === true ) {
  15178. currentRenderList.sort( _opaqueSort, _transparentSort );
  15179. }
  15180. //
  15181. if ( _clippingEnabled === true ) clipping.beginShadows();
  15182. const shadowsArray = currentRenderState.state.shadowsArray;
  15183. shadowMap.render( shadowsArray, scene, camera );
  15184. currentRenderState.setupLights( camera );
  15185. if ( _clippingEnabled === true ) clipping.endShadows();
  15186. //
  15187. if ( this.info.autoReset === true ) this.info.reset();
  15188. if ( renderTarget !== undefined ) {
  15189. this.setRenderTarget( renderTarget );
  15190. }
  15191. //
  15192. background.render( currentRenderList, scene, camera, forceClear );
  15193. // render scene
  15194. const opaqueObjects = currentRenderList.opaque;
  15195. const transparentObjects = currentRenderList.transparent;
  15196. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15197. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15198. //
  15199. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15200. //
  15201. if ( _currentRenderTarget !== null ) {
  15202. // Generate mipmap if we're using any kind of mipmap filtering
  15203. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15204. // resolve multisample renderbuffers to a single-sample texture if necessary
  15205. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15206. }
  15207. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15208. state.buffers.depth.setTest( true );
  15209. state.buffers.depth.setMask( true );
  15210. state.buffers.color.setMask( true );
  15211. state.setPolygonOffset( false );
  15212. // _gl.finish();
  15213. currentRenderList = null;
  15214. currentRenderState = null;
  15215. };
  15216. function projectObject( object, camera, groupOrder, sortObjects ) {
  15217. if ( object.visible === false ) return;
  15218. const visible = object.layers.test( camera.layers );
  15219. if ( visible ) {
  15220. if ( object.isGroup ) {
  15221. groupOrder = object.renderOrder;
  15222. } else if ( object.isLOD ) {
  15223. if ( object.autoUpdate === true ) object.update( camera );
  15224. } else if ( object.isLight ) {
  15225. currentRenderState.pushLight( object );
  15226. if ( object.castShadow ) {
  15227. currentRenderState.pushShadow( object );
  15228. }
  15229. } else if ( object.isSprite ) {
  15230. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15231. if ( sortObjects ) {
  15232. _vector3.setFromMatrixPosition( object.matrixWorld )
  15233. .applyMatrix4( _projScreenMatrix );
  15234. }
  15235. const geometry = objects.update( object );
  15236. const material = object.material;
  15237. if ( material.visible ) {
  15238. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15239. }
  15240. }
  15241. } else if ( object.isImmediateRenderObject ) {
  15242. if ( sortObjects ) {
  15243. _vector3.setFromMatrixPosition( object.matrixWorld )
  15244. .applyMatrix4( _projScreenMatrix );
  15245. }
  15246. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  15247. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15248. if ( object.isSkinnedMesh ) {
  15249. // update skeleton only once in a frame
  15250. if ( object.skeleton.frame !== info.render.frame ) {
  15251. object.skeleton.update();
  15252. object.skeleton.frame = info.render.frame;
  15253. }
  15254. }
  15255. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15256. if ( sortObjects ) {
  15257. _vector3.setFromMatrixPosition( object.matrixWorld )
  15258. .applyMatrix4( _projScreenMatrix );
  15259. }
  15260. const geometry = objects.update( object );
  15261. const material = object.material;
  15262. if ( Array.isArray( material ) ) {
  15263. const groups = geometry.groups;
  15264. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15265. const group = groups[ i ];
  15266. const groupMaterial = material[ group.materialIndex ];
  15267. if ( groupMaterial && groupMaterial.visible ) {
  15268. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15269. }
  15270. }
  15271. } else if ( material.visible ) {
  15272. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15273. }
  15274. }
  15275. }
  15276. }
  15277. const children = object.children;
  15278. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15279. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15280. }
  15281. }
  15282. function renderObjects( renderList, scene, camera ) {
  15283. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15284. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15285. const renderItem = renderList[ i ];
  15286. const object = renderItem.object;
  15287. const geometry = renderItem.geometry;
  15288. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15289. const group = renderItem.group;
  15290. if ( camera.isArrayCamera ) {
  15291. _currentArrayCamera = camera;
  15292. const cameras = camera.cameras;
  15293. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  15294. const camera2 = cameras[ j ];
  15295. if ( object.layers.test( camera2.layers ) ) {
  15296. state.viewport( _currentViewport.copy( camera2.viewport ) );
  15297. currentRenderState.setupLights( camera2 );
  15298. renderObject( object, scene, camera2, geometry, material, group );
  15299. }
  15300. }
  15301. } else {
  15302. _currentArrayCamera = null;
  15303. renderObject( object, scene, camera, geometry, material, group );
  15304. }
  15305. }
  15306. }
  15307. function renderObject( object, scene, camera, geometry, material, group ) {
  15308. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15309. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  15310. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15311. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15312. if ( object.isImmediateRenderObject ) {
  15313. const program = setProgram( camera, scene, material, object );
  15314. state.setMaterial( material );
  15315. bindingStates.reset();
  15316. renderObjectImmediate( object, program );
  15317. } else {
  15318. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15319. }
  15320. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15321. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  15322. }
  15323. function initMaterial( material, scene, object ) {
  15324. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15325. const materialProperties = properties.get( material );
  15326. const lights = currentRenderState.state.lights;
  15327. const shadowsArray = currentRenderState.state.shadowsArray;
  15328. const lightsStateVersion = lights.state.version;
  15329. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15330. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15331. let program = materialProperties.program;
  15332. let programChange = true;
  15333. if ( program === undefined ) {
  15334. // new material
  15335. material.addEventListener( 'dispose', onMaterialDispose );
  15336. } else if ( program.cacheKey !== programCacheKey ) {
  15337. // changed glsl or parameters
  15338. releaseMaterialProgramReference( material );
  15339. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  15340. programChange = false;
  15341. } else if ( parameters.shaderID !== undefined ) {
  15342. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15343. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15344. materialProperties.envMap = cubemaps.get( material.envMap || environment );
  15345. return;
  15346. } else {
  15347. // only rebuild uniform list
  15348. programChange = false;
  15349. }
  15350. if ( programChange ) {
  15351. parameters.uniforms = programCache.getUniforms( material );
  15352. material.onBeforeCompile( parameters, _this );
  15353. program = programCache.acquireProgram( parameters, programCacheKey );
  15354. materialProperties.program = program;
  15355. materialProperties.uniforms = parameters.uniforms;
  15356. materialProperties.outputEncoding = parameters.outputEncoding;
  15357. }
  15358. const uniforms = materialProperties.uniforms;
  15359. if ( ! material.isShaderMaterial &&
  15360. ! material.isRawShaderMaterial ||
  15361. material.clipping === true ) {
  15362. materialProperties.numClippingPlanes = clipping.numPlanes;
  15363. materialProperties.numIntersection = clipping.numIntersection;
  15364. uniforms.clippingPlanes = clipping.uniform;
  15365. }
  15366. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15367. materialProperties.fog = scene.fog;
  15368. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  15369. // store the light setup it was created for
  15370. materialProperties.needsLights = materialNeedsLights( material );
  15371. materialProperties.lightsStateVersion = lightsStateVersion;
  15372. if ( materialProperties.needsLights ) {
  15373. // wire up the material to this renderer's lighting state
  15374. uniforms.ambientLightColor.value = lights.state.ambient;
  15375. uniforms.lightProbe.value = lights.state.probe;
  15376. uniforms.directionalLights.value = lights.state.directional;
  15377. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15378. uniforms.spotLights.value = lights.state.spot;
  15379. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15380. uniforms.rectAreaLights.value = lights.state.rectArea;
  15381. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15382. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15383. uniforms.pointLights.value = lights.state.point;
  15384. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15385. uniforms.hemisphereLights.value = lights.state.hemi;
  15386. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15387. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15388. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15389. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15390. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15391. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15392. // TODO (abelnation): add area lights shadow info to uniforms
  15393. }
  15394. const progUniforms = materialProperties.program.getUniforms();
  15395. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15396. materialProperties.uniformsList = uniformsList;
  15397. }
  15398. function setProgram( camera, scene, material, object ) {
  15399. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15400. textures.resetTextureUnits();
  15401. const fog = scene.fog;
  15402. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15403. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15404. const envMap = cubemaps.get( material.envMap || environment );
  15405. const materialProperties = properties.get( material );
  15406. const lights = currentRenderState.state.lights;
  15407. if ( _clippingEnabled === true ) {
  15408. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  15409. const useCache =
  15410. camera === _currentCamera &&
  15411. material.id === _currentMaterialId;
  15412. // we might want to call this function with some ClippingGroup
  15413. // object instead of the material, once it becomes feasible
  15414. // (#8465, #8379)
  15415. clipping.setState( material, camera, useCache );
  15416. }
  15417. }
  15418. if ( material.version === materialProperties.__version ) {
  15419. if ( material.fog && materialProperties.fog !== fog ) {
  15420. initMaterial( material, scene, object );
  15421. } else if ( materialProperties.environment !== environment ) {
  15422. initMaterial( material, scene, object );
  15423. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  15424. initMaterial( material, scene, object );
  15425. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15426. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  15427. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  15428. initMaterial( material, scene, object );
  15429. } else if ( materialProperties.outputEncoding !== encoding ) {
  15430. initMaterial( material, scene, object );
  15431. } else if ( materialProperties.envMap !== envMap ) {
  15432. initMaterial( material, scene, object );
  15433. }
  15434. } else {
  15435. initMaterial( material, scene, object );
  15436. materialProperties.__version = material.version;
  15437. }
  15438. let refreshProgram = false;
  15439. let refreshMaterial = false;
  15440. let refreshLights = false;
  15441. const program = materialProperties.program,
  15442. p_uniforms = program.getUniforms(),
  15443. m_uniforms = materialProperties.uniforms;
  15444. if ( state.useProgram( program.program ) ) {
  15445. refreshProgram = true;
  15446. refreshMaterial = true;
  15447. refreshLights = true;
  15448. }
  15449. if ( material.id !== _currentMaterialId ) {
  15450. _currentMaterialId = material.id;
  15451. refreshMaterial = true;
  15452. }
  15453. if ( refreshProgram || _currentCamera !== camera ) {
  15454. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  15455. if ( capabilities.logarithmicDepthBuffer ) {
  15456. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15457. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15458. }
  15459. if ( _currentCamera !== camera ) {
  15460. _currentCamera = camera;
  15461. // lighting uniforms depend on the camera so enforce an update
  15462. // now, in case this material supports lights - or later, when
  15463. // the next material that does gets activated:
  15464. refreshMaterial = true; // set to true on material change
  15465. refreshLights = true; // remains set until update done
  15466. }
  15467. // load material specific uniforms
  15468. // (shader material also gets them for the sake of genericity)
  15469. if ( material.isShaderMaterial ||
  15470. material.isMeshPhongMaterial ||
  15471. material.isMeshToonMaterial ||
  15472. material.isMeshStandardMaterial ||
  15473. material.envMap ) {
  15474. const uCamPos = p_uniforms.map.cameraPosition;
  15475. if ( uCamPos !== undefined ) {
  15476. uCamPos.setValue( _gl,
  15477. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15478. }
  15479. }
  15480. if ( material.isMeshPhongMaterial ||
  15481. material.isMeshToonMaterial ||
  15482. material.isMeshLambertMaterial ||
  15483. material.isMeshBasicMaterial ||
  15484. material.isMeshStandardMaterial ||
  15485. material.isShaderMaterial ) {
  15486. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  15487. }
  15488. if ( material.isMeshPhongMaterial ||
  15489. material.isMeshToonMaterial ||
  15490. material.isMeshLambertMaterial ||
  15491. material.isMeshBasicMaterial ||
  15492. material.isMeshStandardMaterial ||
  15493. material.isShaderMaterial ||
  15494. material.isShadowMaterial ||
  15495. material.skinning ) {
  15496. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15497. }
  15498. }
  15499. // skinning uniforms must be set even if material didn't change
  15500. // auto-setting of texture unit for bone texture must go before other textures
  15501. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15502. if ( material.skinning ) {
  15503. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15504. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15505. const skeleton = object.skeleton;
  15506. if ( skeleton ) {
  15507. const bones = skeleton.bones;
  15508. if ( capabilities.floatVertexTextures ) {
  15509. if ( skeleton.boneTexture === undefined ) {
  15510. // layout (1 matrix = 4 pixels)
  15511. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15512. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15513. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15514. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15515. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15516. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  15517. size = MathUtils.ceilPowerOfTwo( size );
  15518. size = Math.max( size, 4 );
  15519. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15520. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  15521. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  15522. skeleton.boneMatrices = boneMatrices;
  15523. skeleton.boneTexture = boneTexture;
  15524. skeleton.boneTextureSize = size;
  15525. }
  15526. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  15527. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  15528. } else {
  15529. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15530. }
  15531. }
  15532. }
  15533. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  15534. materialProperties.receiveShadow = object.receiveShadow;
  15535. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  15536. }
  15537. if ( refreshMaterial ) {
  15538. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  15539. if ( materialProperties.needsLights ) {
  15540. // the current material requires lighting info
  15541. // note: all lighting uniforms are always set correctly
  15542. // they simply reference the renderer's state for their
  15543. // values
  15544. //
  15545. // use the current material's .needsUpdate flags to set
  15546. // the GL state when required
  15547. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15548. }
  15549. // refresh uniforms common to several materials
  15550. if ( fog && material.fog ) {
  15551. materials.refreshFogUniforms( m_uniforms, fog );
  15552. }
  15553. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  15554. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15555. }
  15556. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  15557. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15558. material.uniformsNeedUpdate = false;
  15559. }
  15560. if ( material.isSpriteMaterial ) {
  15561. p_uniforms.setValue( _gl, 'center', object.center );
  15562. }
  15563. // common matrices
  15564. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  15565. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  15566. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15567. return program;
  15568. }
  15569. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15570. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  15571. uniforms.ambientLightColor.needsUpdate = value;
  15572. uniforms.lightProbe.needsUpdate = value;
  15573. uniforms.directionalLights.needsUpdate = value;
  15574. uniforms.directionalLightShadows.needsUpdate = value;
  15575. uniforms.pointLights.needsUpdate = value;
  15576. uniforms.pointLightShadows.needsUpdate = value;
  15577. uniforms.spotLights.needsUpdate = value;
  15578. uniforms.spotLightShadows.needsUpdate = value;
  15579. uniforms.rectAreaLights.needsUpdate = value;
  15580. uniforms.hemisphereLights.needsUpdate = value;
  15581. }
  15582. function materialNeedsLights( material ) {
  15583. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  15584. material.isMeshStandardMaterial || material.isShadowMaterial ||
  15585. ( material.isShaderMaterial && material.lights === true );
  15586. }
  15587. //
  15588. this.setFramebuffer = function ( value ) {
  15589. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );
  15590. _framebuffer = value;
  15591. };
  15592. this.getActiveCubeFace = function () {
  15593. return _currentActiveCubeFace;
  15594. };
  15595. this.getActiveMipmapLevel = function () {
  15596. return _currentActiveMipmapLevel;
  15597. };
  15598. this.getRenderList = function () {
  15599. return currentRenderList;
  15600. };
  15601. this.setRenderList = function ( renderList ) {
  15602. currentRenderList = renderList;
  15603. };
  15604. this.getRenderState = function () {
  15605. return currentRenderState;
  15606. };
  15607. this.setRenderState = function ( renderState ) {
  15608. currentRenderState = renderState;
  15609. };
  15610. this.getRenderTarget = function () {
  15611. return _currentRenderTarget;
  15612. };
  15613. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  15614. _currentRenderTarget = renderTarget;
  15615. _currentActiveCubeFace = activeCubeFace;
  15616. _currentActiveMipmapLevel = activeMipmapLevel;
  15617. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  15618. textures.setupRenderTarget( renderTarget );
  15619. }
  15620. let framebuffer = _framebuffer;
  15621. let isCube = false;
  15622. if ( renderTarget ) {
  15623. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15624. if ( renderTarget.isWebGLCubeRenderTarget ) {
  15625. framebuffer = __webglFramebuffer[ activeCubeFace ];
  15626. isCube = true;
  15627. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15628. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  15629. } else {
  15630. framebuffer = __webglFramebuffer;
  15631. }
  15632. _currentViewport.copy( renderTarget.viewport );
  15633. _currentScissor.copy( renderTarget.scissor );
  15634. _currentScissorTest = renderTarget.scissorTest;
  15635. } else {
  15636. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  15637. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  15638. _currentScissorTest = _scissorTest;
  15639. }
  15640. if ( _currentFramebuffer !== framebuffer ) {
  15641. _gl.bindFramebuffer( 36160, framebuffer );
  15642. _currentFramebuffer = framebuffer;
  15643. }
  15644. state.viewport( _currentViewport );
  15645. state.scissor( _currentScissor );
  15646. state.setScissorTest( _currentScissorTest );
  15647. if ( isCube ) {
  15648. const textureProperties = properties.get( renderTarget.texture );
  15649. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  15650. }
  15651. };
  15652. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  15653. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  15654. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  15655. return;
  15656. }
  15657. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15658. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  15659. framebuffer = framebuffer[ activeCubeFaceIndex ];
  15660. }
  15661. if ( framebuffer ) {
  15662. let restore = false;
  15663. if ( framebuffer !== _currentFramebuffer ) {
  15664. _gl.bindFramebuffer( 36160, framebuffer );
  15665. restore = true;
  15666. }
  15667. try {
  15668. const texture = renderTarget.texture;
  15669. const textureFormat = texture.format;
  15670. const textureType = texture.type;
  15671. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  15672. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  15673. return;
  15674. }
  15675. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15676. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  15677. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  15678. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  15679. return;
  15680. }
  15681. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  15682. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15683. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  15684. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  15685. }
  15686. } else {
  15687. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  15688. }
  15689. } finally {
  15690. if ( restore ) {
  15691. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  15692. }
  15693. }
  15694. }
  15695. };
  15696. this.copyFramebufferToTexture = function ( position, texture, level ) {
  15697. if ( level === undefined ) level = 0;
  15698. const levelScale = Math.pow( 2, - level );
  15699. const width = Math.floor( texture.image.width * levelScale );
  15700. const height = Math.floor( texture.image.height * levelScale );
  15701. const glFormat = utils.convert( texture.format );
  15702. textures.setTexture2D( texture, 0 );
  15703. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  15704. state.unbindTexture();
  15705. };
  15706. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  15707. if ( level === undefined ) level = 0;
  15708. const width = srcTexture.image.width;
  15709. const height = srcTexture.image.height;
  15710. const glFormat = utils.convert( dstTexture.format );
  15711. const glType = utils.convert( dstTexture.type );
  15712. textures.setTexture2D( dstTexture, 0 );
  15713. // As another texture upload may have changed pixelStorei
  15714. // parameters, make sure they are correct for the dstTexture
  15715. _gl.pixelStorei( 37440, dstTexture.flipY );
  15716. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15717. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15718. if ( srcTexture.isDataTexture ) {
  15719. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  15720. } else {
  15721. if ( srcTexture.isCompressedTexture ) {
  15722. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  15723. } else {
  15724. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  15725. }
  15726. }
  15727. // Generate mipmaps only when copying level 0
  15728. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15729. state.unbindTexture();
  15730. };
  15731. this.initTexture = function ( texture ) {
  15732. textures.setTexture2D( texture, 0 );
  15733. state.unbindTexture();
  15734. };
  15735. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15736. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15737. }
  15738. }
  15739. function WebGL1Renderer( parameters ) {
  15740. WebGLRenderer.call( this, parameters );
  15741. }
  15742. WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {
  15743. constructor: WebGL1Renderer,
  15744. isWebGL1Renderer: true
  15745. } );
  15746. class FogExp2 {
  15747. constructor( color, density ) {
  15748. Object.defineProperty( this, 'isFogExp2', { value: true } );
  15749. this.name = '';
  15750. this.color = new Color( color );
  15751. this.density = ( density !== undefined ) ? density : 0.00025;
  15752. }
  15753. clone() {
  15754. return new FogExp2( this.color, this.density );
  15755. }
  15756. toJSON( /* meta */ ) {
  15757. return {
  15758. type: 'FogExp2',
  15759. color: this.color.getHex(),
  15760. density: this.density
  15761. };
  15762. }
  15763. }
  15764. class Fog {
  15765. constructor( color, near, far ) {
  15766. Object.defineProperty( this, 'isFog', { value: true } );
  15767. this.name = '';
  15768. this.color = new Color( color );
  15769. this.near = ( near !== undefined ) ? near : 1;
  15770. this.far = ( far !== undefined ) ? far : 1000;
  15771. }
  15772. clone() {
  15773. return new Fog( this.color, this.near, this.far );
  15774. }
  15775. toJSON( /* meta */ ) {
  15776. return {
  15777. type: 'Fog',
  15778. color: this.color.getHex(),
  15779. near: this.near,
  15780. far: this.far
  15781. };
  15782. }
  15783. }
  15784. class Scene extends Object3D {
  15785. constructor() {
  15786. super();
  15787. Object.defineProperty( this, 'isScene', { value: true } );
  15788. this.type = 'Scene';
  15789. this.background = null;
  15790. this.environment = null;
  15791. this.fog = null;
  15792. this.overrideMaterial = null;
  15793. this.autoUpdate = true; // checked by the renderer
  15794. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15795. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15796. }
  15797. }
  15798. copy( source, recursive ) {
  15799. super.copy( source, recursive );
  15800. if ( source.background !== null ) this.background = source.background.clone();
  15801. if ( source.environment !== null ) this.environment = source.environment.clone();
  15802. if ( source.fog !== null ) this.fog = source.fog.clone();
  15803. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15804. this.autoUpdate = source.autoUpdate;
  15805. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15806. return this;
  15807. }
  15808. toJSON( meta ) {
  15809. const data = super.toJSON( meta );
  15810. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15811. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15812. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15813. return data;
  15814. }
  15815. }
  15816. function InterleavedBuffer( array, stride ) {
  15817. this.array = array;
  15818. this.stride = stride;
  15819. this.count = array !== undefined ? array.length / stride : 0;
  15820. this.usage = StaticDrawUsage;
  15821. this.updateRange = { offset: 0, count: - 1 };
  15822. this.version = 0;
  15823. this.uuid = MathUtils.generateUUID();
  15824. }
  15825. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  15826. set: function ( value ) {
  15827. if ( value === true ) this.version ++;
  15828. }
  15829. } );
  15830. Object.assign( InterleavedBuffer.prototype, {
  15831. isInterleavedBuffer: true,
  15832. onUploadCallback: function () {},
  15833. setUsage: function ( value ) {
  15834. this.usage = value;
  15835. return this;
  15836. },
  15837. copy: function ( source ) {
  15838. this.array = new source.array.constructor( source.array );
  15839. this.count = source.count;
  15840. this.stride = source.stride;
  15841. this.usage = source.usage;
  15842. return this;
  15843. },
  15844. copyAt: function ( index1, attribute, index2 ) {
  15845. index1 *= this.stride;
  15846. index2 *= attribute.stride;
  15847. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15848. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15849. }
  15850. return this;
  15851. },
  15852. set: function ( value, offset ) {
  15853. if ( offset === undefined ) offset = 0;
  15854. this.array.set( value, offset );
  15855. return this;
  15856. },
  15857. clone: function ( data ) {
  15858. if ( data.arrayBuffers === undefined ) {
  15859. data.arrayBuffers = {};
  15860. }
  15861. if ( this.array.buffer._uuid === undefined ) {
  15862. this.array.buffer._uuid = MathUtils.generateUUID();
  15863. }
  15864. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15865. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15866. }
  15867. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15868. const ib = new InterleavedBuffer( array, this.stride );
  15869. ib.setUsage( this.usage );
  15870. return ib;
  15871. },
  15872. onUpload: function ( callback ) {
  15873. this.onUploadCallback = callback;
  15874. return this;
  15875. },
  15876. toJSON: function ( data ) {
  15877. if ( data.arrayBuffers === undefined ) {
  15878. data.arrayBuffers = {};
  15879. }
  15880. // generate UUID for array buffer if necessary
  15881. if ( this.array.buffer._uuid === undefined ) {
  15882. this.array.buffer._uuid = MathUtils.generateUUID();
  15883. }
  15884. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15885. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15886. }
  15887. //
  15888. return {
  15889. uuid: this.uuid,
  15890. buffer: this.array.buffer._uuid,
  15891. type: this.array.constructor.name,
  15892. stride: this.stride
  15893. };
  15894. }
  15895. } );
  15896. const _vector$6 = new Vector3();
  15897. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  15898. this.name = '';
  15899. this.data = interleavedBuffer;
  15900. this.itemSize = itemSize;
  15901. this.offset = offset;
  15902. this.normalized = normalized === true;
  15903. }
  15904. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  15905. count: {
  15906. get: function () {
  15907. return this.data.count;
  15908. }
  15909. },
  15910. array: {
  15911. get: function () {
  15912. return this.data.array;
  15913. }
  15914. },
  15915. needsUpdate: {
  15916. set: function ( value ) {
  15917. this.data.needsUpdate = value;
  15918. }
  15919. }
  15920. } );
  15921. Object.assign( InterleavedBufferAttribute.prototype, {
  15922. isInterleavedBufferAttribute: true,
  15923. applyMatrix4: function ( m ) {
  15924. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15925. _vector$6.x = this.getX( i );
  15926. _vector$6.y = this.getY( i );
  15927. _vector$6.z = this.getZ( i );
  15928. _vector$6.applyMatrix4( m );
  15929. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15930. }
  15931. return this;
  15932. },
  15933. setX: function ( index, x ) {
  15934. this.data.array[ index * this.data.stride + this.offset ] = x;
  15935. return this;
  15936. },
  15937. setY: function ( index, y ) {
  15938. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15939. return this;
  15940. },
  15941. setZ: function ( index, z ) {
  15942. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15943. return this;
  15944. },
  15945. setW: function ( index, w ) {
  15946. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15947. return this;
  15948. },
  15949. getX: function ( index ) {
  15950. return this.data.array[ index * this.data.stride + this.offset ];
  15951. },
  15952. getY: function ( index ) {
  15953. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15954. },
  15955. getZ: function ( index ) {
  15956. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15957. },
  15958. getW: function ( index ) {
  15959. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15960. },
  15961. setXY: function ( index, x, y ) {
  15962. index = index * this.data.stride + this.offset;
  15963. this.data.array[ index + 0 ] = x;
  15964. this.data.array[ index + 1 ] = y;
  15965. return this;
  15966. },
  15967. setXYZ: function ( index, x, y, z ) {
  15968. index = index * this.data.stride + this.offset;
  15969. this.data.array[ index + 0 ] = x;
  15970. this.data.array[ index + 1 ] = y;
  15971. this.data.array[ index + 2 ] = z;
  15972. return this;
  15973. },
  15974. setXYZW: function ( index, x, y, z, w ) {
  15975. index = index * this.data.stride + this.offset;
  15976. this.data.array[ index + 0 ] = x;
  15977. this.data.array[ index + 1 ] = y;
  15978. this.data.array[ index + 2 ] = z;
  15979. this.data.array[ index + 3 ] = w;
  15980. return this;
  15981. },
  15982. clone: function ( data ) {
  15983. if ( data === undefined ) {
  15984. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  15985. const array = [];
  15986. for ( let i = 0; i < this.count; i ++ ) {
  15987. const index = i * this.data.stride + this.offset;
  15988. for ( let j = 0; j < this.itemSize; j ++ ) {
  15989. array.push( this.data.array[ index + j ] );
  15990. }
  15991. }
  15992. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15993. } else {
  15994. if ( data.interleavedBuffers === undefined ) {
  15995. data.interleavedBuffers = {};
  15996. }
  15997. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15998. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15999. }
  16000. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16001. }
  16002. },
  16003. toJSON: function ( data ) {
  16004. if ( data === undefined ) {
  16005. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16006. const array = [];
  16007. for ( let i = 0; i < this.count; i ++ ) {
  16008. const index = i * this.data.stride + this.offset;
  16009. for ( let j = 0; j < this.itemSize; j ++ ) {
  16010. array.push( this.data.array[ index + j ] );
  16011. }
  16012. }
  16013. // deinterleave data and save it as an ordinary buffer attribute for now
  16014. return {
  16015. itemSize: this.itemSize,
  16016. type: this.array.constructor.name,
  16017. array: array,
  16018. normalized: this.normalized
  16019. };
  16020. } else {
  16021. // save as true interlaved attribtue
  16022. if ( data.interleavedBuffers === undefined ) {
  16023. data.interleavedBuffers = {};
  16024. }
  16025. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16026. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16027. }
  16028. return {
  16029. isInterleavedBufferAttribute: true,
  16030. itemSize: this.itemSize,
  16031. data: this.data.uuid,
  16032. offset: this.offset,
  16033. normalized: this.normalized
  16034. };
  16035. }
  16036. }
  16037. } );
  16038. /**
  16039. * parameters = {
  16040. * color: <hex>,
  16041. * map: new THREE.Texture( <Image> ),
  16042. * alphaMap: new THREE.Texture( <Image> ),
  16043. * rotation: <float>,
  16044. * sizeAttenuation: <bool>
  16045. * }
  16046. */
  16047. function SpriteMaterial( parameters ) {
  16048. Material.call( this );
  16049. this.type = 'SpriteMaterial';
  16050. this.color = new Color( 0xffffff );
  16051. this.map = null;
  16052. this.alphaMap = null;
  16053. this.rotation = 0;
  16054. this.sizeAttenuation = true;
  16055. this.transparent = true;
  16056. this.setValues( parameters );
  16057. }
  16058. SpriteMaterial.prototype = Object.create( Material.prototype );
  16059. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16060. SpriteMaterial.prototype.isSpriteMaterial = true;
  16061. SpriteMaterial.prototype.copy = function ( source ) {
  16062. Material.prototype.copy.call( this, source );
  16063. this.color.copy( source.color );
  16064. this.map = source.map;
  16065. this.alphaMap = source.alphaMap;
  16066. this.rotation = source.rotation;
  16067. this.sizeAttenuation = source.sizeAttenuation;
  16068. return this;
  16069. };
  16070. let _geometry;
  16071. const _intersectPoint = new Vector3();
  16072. const _worldScale = new Vector3();
  16073. const _mvPosition = new Vector3();
  16074. const _alignedPosition = new Vector2();
  16075. const _rotatedPosition = new Vector2();
  16076. const _viewWorldMatrix = new Matrix4();
  16077. const _vA$1 = new Vector3();
  16078. const _vB$1 = new Vector3();
  16079. const _vC$1 = new Vector3();
  16080. const _uvA$1 = new Vector2();
  16081. const _uvB$1 = new Vector2();
  16082. const _uvC$1 = new Vector2();
  16083. function Sprite( material ) {
  16084. Object3D.call( this );
  16085. this.type = 'Sprite';
  16086. if ( _geometry === undefined ) {
  16087. _geometry = new BufferGeometry();
  16088. const float32Array = new Float32Array( [
  16089. - 0.5, - 0.5, 0, 0, 0,
  16090. 0.5, - 0.5, 0, 1, 0,
  16091. 0.5, 0.5, 0, 1, 1,
  16092. - 0.5, 0.5, 0, 0, 1
  16093. ] );
  16094. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16095. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16096. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16097. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16098. }
  16099. this.geometry = _geometry;
  16100. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16101. this.center = new Vector2( 0.5, 0.5 );
  16102. }
  16103. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16104. constructor: Sprite,
  16105. isSprite: true,
  16106. raycast: function ( raycaster, intersects ) {
  16107. if ( raycaster.camera === null ) {
  16108. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16109. }
  16110. _worldScale.setFromMatrixScale( this.matrixWorld );
  16111. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16112. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16113. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16114. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16115. _worldScale.multiplyScalar( - _mvPosition.z );
  16116. }
  16117. const rotation = this.material.rotation;
  16118. let sin, cos;
  16119. if ( rotation !== 0 ) {
  16120. cos = Math.cos( rotation );
  16121. sin = Math.sin( rotation );
  16122. }
  16123. const center = this.center;
  16124. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16125. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16126. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16127. _uvA$1.set( 0, 0 );
  16128. _uvB$1.set( 1, 0 );
  16129. _uvC$1.set( 1, 1 );
  16130. // check first triangle
  16131. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16132. if ( intersect === null ) {
  16133. // check second triangle
  16134. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16135. _uvB$1.set( 0, 1 );
  16136. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16137. if ( intersect === null ) {
  16138. return;
  16139. }
  16140. }
  16141. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16142. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16143. intersects.push( {
  16144. distance: distance,
  16145. point: _intersectPoint.clone(),
  16146. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
  16147. face: null,
  16148. object: this
  16149. } );
  16150. },
  16151. copy: function ( source ) {
  16152. Object3D.prototype.copy.call( this, source );
  16153. if ( source.center !== undefined ) this.center.copy( source.center );
  16154. this.material = source.material;
  16155. return this;
  16156. }
  16157. } );
  16158. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16159. // compute position in camera space
  16160. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16161. // to check if rotation is not zero
  16162. if ( sin !== undefined ) {
  16163. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16164. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16165. } else {
  16166. _rotatedPosition.copy( _alignedPosition );
  16167. }
  16168. vertexPosition.copy( mvPosition );
  16169. vertexPosition.x += _rotatedPosition.x;
  16170. vertexPosition.y += _rotatedPosition.y;
  16171. // transform to world space
  16172. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16173. }
  16174. const _v1$4 = new Vector3();
  16175. const _v2$2 = new Vector3();
  16176. function LOD() {
  16177. Object3D.call( this );
  16178. this._currentLevel = 0;
  16179. this.type = 'LOD';
  16180. Object.defineProperties( this, {
  16181. levels: {
  16182. enumerable: true,
  16183. value: []
  16184. }
  16185. } );
  16186. this.autoUpdate = true;
  16187. }
  16188. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16189. constructor: LOD,
  16190. isLOD: true,
  16191. copy: function ( source ) {
  16192. Object3D.prototype.copy.call( this, source, false );
  16193. const levels = source.levels;
  16194. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16195. const level = levels[ i ];
  16196. this.addLevel( level.object.clone(), level.distance );
  16197. }
  16198. this.autoUpdate = source.autoUpdate;
  16199. return this;
  16200. },
  16201. addLevel: function ( object, distance ) {
  16202. if ( distance === undefined ) distance = 0;
  16203. distance = Math.abs( distance );
  16204. const levels = this.levels;
  16205. let l;
  16206. for ( l = 0; l < levels.length; l ++ ) {
  16207. if ( distance < levels[ l ].distance ) {
  16208. break;
  16209. }
  16210. }
  16211. levels.splice( l, 0, { distance: distance, object: object } );
  16212. this.add( object );
  16213. return this;
  16214. },
  16215. getCurrentLevel: function () {
  16216. return this._currentLevel;
  16217. },
  16218. getObjectForDistance: function ( distance ) {
  16219. const levels = this.levels;
  16220. if ( levels.length > 0 ) {
  16221. let i, l;
  16222. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16223. if ( distance < levels[ i ].distance ) {
  16224. break;
  16225. }
  16226. }
  16227. return levels[ i - 1 ].object;
  16228. }
  16229. return null;
  16230. },
  16231. raycast: function ( raycaster, intersects ) {
  16232. const levels = this.levels;
  16233. if ( levels.length > 0 ) {
  16234. _v1$4.setFromMatrixPosition( this.matrixWorld );
  16235. const distance = raycaster.ray.origin.distanceTo( _v1$4 );
  16236. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16237. }
  16238. },
  16239. update: function ( camera ) {
  16240. const levels = this.levels;
  16241. if ( levels.length > 1 ) {
  16242. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  16243. _v2$2.setFromMatrixPosition( this.matrixWorld );
  16244. const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  16245. levels[ 0 ].object.visible = true;
  16246. let i, l;
  16247. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16248. if ( distance >= levels[ i ].distance ) {
  16249. levels[ i - 1 ].object.visible = false;
  16250. levels[ i ].object.visible = true;
  16251. } else {
  16252. break;
  16253. }
  16254. }
  16255. this._currentLevel = i - 1;
  16256. for ( ; i < l; i ++ ) {
  16257. levels[ i ].object.visible = false;
  16258. }
  16259. }
  16260. },
  16261. toJSON: function ( meta ) {
  16262. const data = Object3D.prototype.toJSON.call( this, meta );
  16263. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16264. data.object.levels = [];
  16265. const levels = this.levels;
  16266. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16267. const level = levels[ i ];
  16268. data.object.levels.push( {
  16269. object: level.object.uuid,
  16270. distance: level.distance
  16271. } );
  16272. }
  16273. return data;
  16274. }
  16275. } );
  16276. function SkinnedMesh( geometry, material ) {
  16277. if ( geometry && geometry.isGeometry ) {
  16278. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16279. }
  16280. Mesh.call( this, geometry, material );
  16281. this.type = 'SkinnedMesh';
  16282. this.bindMode = 'attached';
  16283. this.bindMatrix = new Matrix4();
  16284. this.bindMatrixInverse = new Matrix4();
  16285. }
  16286. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16287. constructor: SkinnedMesh,
  16288. isSkinnedMesh: true,
  16289. copy: function ( source ) {
  16290. Mesh.prototype.copy.call( this, source );
  16291. this.bindMode = source.bindMode;
  16292. this.bindMatrix.copy( source.bindMatrix );
  16293. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  16294. this.skeleton = source.skeleton;
  16295. return this;
  16296. },
  16297. bind: function ( skeleton, bindMatrix ) {
  16298. this.skeleton = skeleton;
  16299. if ( bindMatrix === undefined ) {
  16300. this.updateMatrixWorld( true );
  16301. this.skeleton.calculateInverses();
  16302. bindMatrix = this.matrixWorld;
  16303. }
  16304. this.bindMatrix.copy( bindMatrix );
  16305. this.bindMatrixInverse.getInverse( bindMatrix );
  16306. },
  16307. pose: function () {
  16308. this.skeleton.pose();
  16309. },
  16310. normalizeSkinWeights: function () {
  16311. const vector = new Vector4();
  16312. const skinWeight = this.geometry.attributes.skinWeight;
  16313. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  16314. vector.x = skinWeight.getX( i );
  16315. vector.y = skinWeight.getY( i );
  16316. vector.z = skinWeight.getZ( i );
  16317. vector.w = skinWeight.getW( i );
  16318. const scale = 1.0 / vector.manhattanLength();
  16319. if ( scale !== Infinity ) {
  16320. vector.multiplyScalar( scale );
  16321. } else {
  16322. vector.set( 1, 0, 0, 0 ); // do something reasonable
  16323. }
  16324. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  16325. }
  16326. },
  16327. updateMatrixWorld: function ( force ) {
  16328. Mesh.prototype.updateMatrixWorld.call( this, force );
  16329. if ( this.bindMode === 'attached' ) {
  16330. this.bindMatrixInverse.getInverse( this.matrixWorld );
  16331. } else if ( this.bindMode === 'detached' ) {
  16332. this.bindMatrixInverse.getInverse( this.bindMatrix );
  16333. } else {
  16334. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  16335. }
  16336. },
  16337. boneTransform: ( function () {
  16338. const basePosition = new Vector3();
  16339. const skinIndex = new Vector4();
  16340. const skinWeight = new Vector4();
  16341. const vector = new Vector3();
  16342. const matrix = new Matrix4();
  16343. return function ( index, target ) {
  16344. const skeleton = this.skeleton;
  16345. const geometry = this.geometry;
  16346. skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  16347. skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  16348. basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  16349. target.set( 0, 0, 0 );
  16350. for ( let i = 0; i < 4; i ++ ) {
  16351. const weight = skinWeight.getComponent( i );
  16352. if ( weight !== 0 ) {
  16353. const boneIndex = skinIndex.getComponent( i );
  16354. matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  16355. target.addScaledVector( vector.copy( basePosition ).applyMatrix4( matrix ), weight );
  16356. }
  16357. }
  16358. return target.applyMatrix4( this.bindMatrixInverse );
  16359. };
  16360. }() )
  16361. } );
  16362. const _offsetMatrix = new Matrix4();
  16363. const _identityMatrix = new Matrix4();
  16364. function Skeleton( bones, boneInverses ) {
  16365. // copy the bone array
  16366. bones = bones || [];
  16367. this.bones = bones.slice( 0 );
  16368. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  16369. this.frame = - 1;
  16370. // use the supplied bone inverses or calculate the inverses
  16371. if ( boneInverses === undefined ) {
  16372. this.calculateInverses();
  16373. } else {
  16374. if ( this.bones.length === boneInverses.length ) {
  16375. this.boneInverses = boneInverses.slice( 0 );
  16376. } else {
  16377. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  16378. this.boneInverses = [];
  16379. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16380. this.boneInverses.push( new Matrix4() );
  16381. }
  16382. }
  16383. }
  16384. }
  16385. Object.assign( Skeleton.prototype, {
  16386. calculateInverses: function () {
  16387. this.boneInverses = [];
  16388. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16389. const inverse = new Matrix4();
  16390. if ( this.bones[ i ] ) {
  16391. inverse.getInverse( this.bones[ i ].matrixWorld );
  16392. }
  16393. this.boneInverses.push( inverse );
  16394. }
  16395. },
  16396. pose: function () {
  16397. // recover the bind-time world matrices
  16398. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16399. const bone = this.bones[ i ];
  16400. if ( bone ) {
  16401. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  16402. }
  16403. }
  16404. // compute the local matrices, positions, rotations and scales
  16405. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16406. const bone = this.bones[ i ];
  16407. if ( bone ) {
  16408. if ( bone.parent && bone.parent.isBone ) {
  16409. bone.matrix.getInverse( bone.parent.matrixWorld );
  16410. bone.matrix.multiply( bone.matrixWorld );
  16411. } else {
  16412. bone.matrix.copy( bone.matrixWorld );
  16413. }
  16414. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  16415. }
  16416. }
  16417. },
  16418. update: function () {
  16419. const bones = this.bones;
  16420. const boneInverses = this.boneInverses;
  16421. const boneMatrices = this.boneMatrices;
  16422. const boneTexture = this.boneTexture;
  16423. // flatten bone matrices to array
  16424. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  16425. // compute the offset between the current and the original transform
  16426. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  16427. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  16428. _offsetMatrix.toArray( boneMatrices, i * 16 );
  16429. }
  16430. if ( boneTexture !== undefined ) {
  16431. boneTexture.needsUpdate = true;
  16432. }
  16433. },
  16434. clone: function () {
  16435. return new Skeleton( this.bones, this.boneInverses );
  16436. },
  16437. getBoneByName: function ( name ) {
  16438. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16439. const bone = this.bones[ i ];
  16440. if ( bone.name === name ) {
  16441. return bone;
  16442. }
  16443. }
  16444. return undefined;
  16445. },
  16446. dispose: function ( ) {
  16447. if ( this.boneTexture ) {
  16448. this.boneTexture.dispose();
  16449. this.boneTexture = undefined;
  16450. }
  16451. }
  16452. } );
  16453. function Bone() {
  16454. Object3D.call( this );
  16455. this.type = 'Bone';
  16456. }
  16457. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16458. constructor: Bone,
  16459. isBone: true
  16460. } );
  16461. const _instanceLocalMatrix = new Matrix4();
  16462. const _instanceWorldMatrix = new Matrix4();
  16463. const _instanceIntersects = [];
  16464. const _mesh = new Mesh();
  16465. function InstancedMesh( geometry, material, count ) {
  16466. Mesh.call( this, geometry, material );
  16467. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  16468. this.instanceColor = null;
  16469. this.count = count;
  16470. this.frustumCulled = false;
  16471. }
  16472. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16473. constructor: InstancedMesh,
  16474. isInstancedMesh: true,
  16475. copy: function ( source ) {
  16476. Mesh.prototype.copy.call( this, source );
  16477. this.instanceMatrix.copy( source.instanceMatrix );
  16478. this.count = source.count;
  16479. return this;
  16480. },
  16481. setColorAt: function ( index, color ) {
  16482. if ( this.instanceColor === null ) {
  16483. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  16484. }
  16485. color.toArray( this.instanceColor.array, index * 3 );
  16486. },
  16487. getMatrixAt: function ( index, matrix ) {
  16488. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  16489. },
  16490. raycast: function ( raycaster, intersects ) {
  16491. const matrixWorld = this.matrixWorld;
  16492. const raycastTimes = this.count;
  16493. _mesh.geometry = this.geometry;
  16494. _mesh.material = this.material;
  16495. if ( _mesh.material === undefined ) return;
  16496. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  16497. // calculate the world matrix for each instance
  16498. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  16499. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  16500. // the mesh represents this single instance
  16501. _mesh.matrixWorld = _instanceWorldMatrix;
  16502. _mesh.raycast( raycaster, _instanceIntersects );
  16503. // process the result of raycast
  16504. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  16505. const intersect = _instanceIntersects[ i ];
  16506. intersect.instanceId = instanceId;
  16507. intersect.object = this;
  16508. intersects.push( intersect );
  16509. }
  16510. _instanceIntersects.length = 0;
  16511. }
  16512. },
  16513. setMatrixAt: function ( index, matrix ) {
  16514. matrix.toArray( this.instanceMatrix.array, index * 16 );
  16515. },
  16516. updateMorphTargets: function () {
  16517. }
  16518. } );
  16519. /**
  16520. * parameters = {
  16521. * color: <hex>,
  16522. * opacity: <float>,
  16523. *
  16524. * linewidth: <float>,
  16525. * linecap: "round",
  16526. * linejoin: "round"
  16527. * }
  16528. */
  16529. function LineBasicMaterial( parameters ) {
  16530. Material.call( this );
  16531. this.type = 'LineBasicMaterial';
  16532. this.color = new Color( 0xffffff );
  16533. this.linewidth = 1;
  16534. this.linecap = 'round';
  16535. this.linejoin = 'round';
  16536. this.morphTargets = false;
  16537. this.setValues( parameters );
  16538. }
  16539. LineBasicMaterial.prototype = Object.create( Material.prototype );
  16540. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16541. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16542. LineBasicMaterial.prototype.copy = function ( source ) {
  16543. Material.prototype.copy.call( this, source );
  16544. this.color.copy( source.color );
  16545. this.linewidth = source.linewidth;
  16546. this.linecap = source.linecap;
  16547. this.linejoin = source.linejoin;
  16548. this.morphTargets = source.morphTargets;
  16549. return this;
  16550. };
  16551. const _start = new Vector3();
  16552. const _end = new Vector3();
  16553. const _inverseMatrix$1 = new Matrix4();
  16554. const _ray$1 = new Ray();
  16555. const _sphere$2 = new Sphere();
  16556. function Line( geometry, material, mode ) {
  16557. if ( mode === 1 ) {
  16558. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  16559. }
  16560. Object3D.call( this );
  16561. this.type = 'Line';
  16562. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16563. this.material = material !== undefined ? material : new LineBasicMaterial();
  16564. this.updateMorphTargets();
  16565. }
  16566. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16567. constructor: Line,
  16568. isLine: true,
  16569. copy: function ( source ) {
  16570. Object3D.prototype.copy.call( this, source );
  16571. this.material = source.material;
  16572. this.geometry = source.geometry;
  16573. return this;
  16574. },
  16575. computeLineDistances: function () {
  16576. const geometry = this.geometry;
  16577. if ( geometry.isBufferGeometry ) {
  16578. // we assume non-indexed geometry
  16579. if ( geometry.index === null ) {
  16580. const positionAttribute = geometry.attributes.position;
  16581. const lineDistances = [ 0 ];
  16582. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16583. _start.fromBufferAttribute( positionAttribute, i - 1 );
  16584. _end.fromBufferAttribute( positionAttribute, i );
  16585. lineDistances[ i ] = lineDistances[ i - 1 ];
  16586. lineDistances[ i ] += _start.distanceTo( _end );
  16587. }
  16588. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16589. } else {
  16590. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16591. }
  16592. } else if ( geometry.isGeometry ) {
  16593. const vertices = geometry.vertices;
  16594. const lineDistances = geometry.lineDistances;
  16595. lineDistances[ 0 ] = 0;
  16596. for ( let i = 1, l = vertices.length; i < l; i ++ ) {
  16597. lineDistances[ i ] = lineDistances[ i - 1 ];
  16598. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  16599. }
  16600. }
  16601. return this;
  16602. },
  16603. raycast: function ( raycaster, intersects ) {
  16604. const geometry = this.geometry;
  16605. const matrixWorld = this.matrixWorld;
  16606. const threshold = raycaster.params.Line.threshold;
  16607. // Checking boundingSphere distance to ray
  16608. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16609. _sphere$2.copy( geometry.boundingSphere );
  16610. _sphere$2.applyMatrix4( matrixWorld );
  16611. _sphere$2.radius += threshold;
  16612. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  16613. //
  16614. _inverseMatrix$1.getInverse( matrixWorld );
  16615. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16616. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16617. const localThresholdSq = localThreshold * localThreshold;
  16618. const vStart = new Vector3();
  16619. const vEnd = new Vector3();
  16620. const interSegment = new Vector3();
  16621. const interRay = new Vector3();
  16622. const step = ( this && this.isLineSegments ) ? 2 : 1;
  16623. if ( geometry.isBufferGeometry ) {
  16624. const index = geometry.index;
  16625. const attributes = geometry.attributes;
  16626. const positions = attributes.position.array;
  16627. if ( index !== null ) {
  16628. const indices = index.array;
  16629. for ( let i = 0, l = indices.length - 1; i < l; i += step ) {
  16630. const a = indices[ i ];
  16631. const b = indices[ i + 1 ];
  16632. vStart.fromArray( positions, a * 3 );
  16633. vEnd.fromArray( positions, b * 3 );
  16634. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16635. if ( distSq > localThresholdSq ) continue;
  16636. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16637. const distance = raycaster.ray.origin.distanceTo( interRay );
  16638. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16639. intersects.push( {
  16640. distance: distance,
  16641. // What do we want? intersection point on the ray or on the segment??
  16642. // point: raycaster.ray.at( distance ),
  16643. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16644. index: i,
  16645. face: null,
  16646. faceIndex: null,
  16647. object: this
  16648. } );
  16649. }
  16650. } else {
  16651. for ( let i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  16652. vStart.fromArray( positions, 3 * i );
  16653. vEnd.fromArray( positions, 3 * i + 3 );
  16654. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16655. if ( distSq > localThresholdSq ) continue;
  16656. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16657. const distance = raycaster.ray.origin.distanceTo( interRay );
  16658. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16659. intersects.push( {
  16660. distance: distance,
  16661. // What do we want? intersection point on the ray or on the segment??
  16662. // point: raycaster.ray.at( distance ),
  16663. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16664. index: i,
  16665. face: null,
  16666. faceIndex: null,
  16667. object: this
  16668. } );
  16669. }
  16670. }
  16671. } else if ( geometry.isGeometry ) {
  16672. const vertices = geometry.vertices;
  16673. const nbVertices = vertices.length;
  16674. for ( let i = 0; i < nbVertices - 1; i += step ) {
  16675. const distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  16676. if ( distSq > localThresholdSq ) continue;
  16677. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16678. const distance = raycaster.ray.origin.distanceTo( interRay );
  16679. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16680. intersects.push( {
  16681. distance: distance,
  16682. // What do we want? intersection point on the ray or on the segment??
  16683. // point: raycaster.ray.at( distance ),
  16684. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16685. index: i,
  16686. face: null,
  16687. faceIndex: null,
  16688. object: this
  16689. } );
  16690. }
  16691. }
  16692. },
  16693. updateMorphTargets: function () {
  16694. const geometry = this.geometry;
  16695. if ( geometry.isBufferGeometry ) {
  16696. const morphAttributes = geometry.morphAttributes;
  16697. const keys = Object.keys( morphAttributes );
  16698. if ( keys.length > 0 ) {
  16699. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16700. if ( morphAttribute !== undefined ) {
  16701. this.morphTargetInfluences = [];
  16702. this.morphTargetDictionary = {};
  16703. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16704. const name = morphAttribute[ m ].name || String( m );
  16705. this.morphTargetInfluences.push( 0 );
  16706. this.morphTargetDictionary[ name ] = m;
  16707. }
  16708. }
  16709. }
  16710. } else {
  16711. const morphTargets = geometry.morphTargets;
  16712. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16713. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16714. }
  16715. }
  16716. }
  16717. } );
  16718. const _start$1 = new Vector3();
  16719. const _end$1 = new Vector3();
  16720. function LineSegments( geometry, material ) {
  16721. Line.call( this, geometry, material );
  16722. this.type = 'LineSegments';
  16723. }
  16724. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  16725. constructor: LineSegments,
  16726. isLineSegments: true,
  16727. computeLineDistances: function () {
  16728. const geometry = this.geometry;
  16729. if ( geometry.isBufferGeometry ) {
  16730. // we assume non-indexed geometry
  16731. if ( geometry.index === null ) {
  16732. const positionAttribute = geometry.attributes.position;
  16733. const lineDistances = [];
  16734. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16735. _start$1.fromBufferAttribute( positionAttribute, i );
  16736. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  16737. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16738. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16739. }
  16740. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16741. } else {
  16742. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16743. }
  16744. } else if ( geometry.isGeometry ) {
  16745. const vertices = geometry.vertices;
  16746. const lineDistances = geometry.lineDistances;
  16747. for ( let i = 0, l = vertices.length; i < l; i += 2 ) {
  16748. _start$1.copy( vertices[ i ] );
  16749. _end$1.copy( vertices[ i + 1 ] );
  16750. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16751. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16752. }
  16753. }
  16754. return this;
  16755. }
  16756. } );
  16757. function LineLoop( geometry, material ) {
  16758. Line.call( this, geometry, material );
  16759. this.type = 'LineLoop';
  16760. }
  16761. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  16762. constructor: LineLoop,
  16763. isLineLoop: true,
  16764. } );
  16765. /**
  16766. * parameters = {
  16767. * color: <hex>,
  16768. * opacity: <float>,
  16769. * map: new THREE.Texture( <Image> ),
  16770. * alphaMap: new THREE.Texture( <Image> ),
  16771. *
  16772. * size: <float>,
  16773. * sizeAttenuation: <bool>
  16774. *
  16775. * morphTargets: <bool>
  16776. * }
  16777. */
  16778. function PointsMaterial( parameters ) {
  16779. Material.call( this );
  16780. this.type = 'PointsMaterial';
  16781. this.color = new Color( 0xffffff );
  16782. this.map = null;
  16783. this.alphaMap = null;
  16784. this.size = 1;
  16785. this.sizeAttenuation = true;
  16786. this.morphTargets = false;
  16787. this.setValues( parameters );
  16788. }
  16789. PointsMaterial.prototype = Object.create( Material.prototype );
  16790. PointsMaterial.prototype.constructor = PointsMaterial;
  16791. PointsMaterial.prototype.isPointsMaterial = true;
  16792. PointsMaterial.prototype.copy = function ( source ) {
  16793. Material.prototype.copy.call( this, source );
  16794. this.color.copy( source.color );
  16795. this.map = source.map;
  16796. this.alphaMap = source.alphaMap;
  16797. this.size = source.size;
  16798. this.sizeAttenuation = source.sizeAttenuation;
  16799. this.morphTargets = source.morphTargets;
  16800. return this;
  16801. };
  16802. const _inverseMatrix$2 = new Matrix4();
  16803. const _ray$2 = new Ray();
  16804. const _sphere$3 = new Sphere();
  16805. const _position$1 = new Vector3();
  16806. function Points( geometry, material ) {
  16807. Object3D.call( this );
  16808. this.type = 'Points';
  16809. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16810. this.material = material !== undefined ? material : new PointsMaterial();
  16811. this.updateMorphTargets();
  16812. }
  16813. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16814. constructor: Points,
  16815. isPoints: true,
  16816. copy: function ( source ) {
  16817. Object3D.prototype.copy.call( this, source );
  16818. this.material = source.material;
  16819. this.geometry = source.geometry;
  16820. return this;
  16821. },
  16822. raycast: function ( raycaster, intersects ) {
  16823. const geometry = this.geometry;
  16824. const matrixWorld = this.matrixWorld;
  16825. const threshold = raycaster.params.Points.threshold;
  16826. // Checking boundingSphere distance to ray
  16827. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16828. _sphere$3.copy( geometry.boundingSphere );
  16829. _sphere$3.applyMatrix4( matrixWorld );
  16830. _sphere$3.radius += threshold;
  16831. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  16832. //
  16833. _inverseMatrix$2.getInverse( matrixWorld );
  16834. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  16835. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16836. const localThresholdSq = localThreshold * localThreshold;
  16837. if ( geometry.isBufferGeometry ) {
  16838. const index = geometry.index;
  16839. const attributes = geometry.attributes;
  16840. const positions = attributes.position.array;
  16841. if ( index !== null ) {
  16842. const indices = index.array;
  16843. for ( let i = 0, il = indices.length; i < il; i ++ ) {
  16844. const a = indices[ i ];
  16845. _position$1.fromArray( positions, a * 3 );
  16846. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16847. }
  16848. } else {
  16849. for ( let i = 0, l = positions.length / 3; i < l; i ++ ) {
  16850. _position$1.fromArray( positions, i * 3 );
  16851. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16852. }
  16853. }
  16854. } else {
  16855. const vertices = geometry.vertices;
  16856. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  16857. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16858. }
  16859. }
  16860. },
  16861. updateMorphTargets: function () {
  16862. const geometry = this.geometry;
  16863. if ( geometry.isBufferGeometry ) {
  16864. const morphAttributes = geometry.morphAttributes;
  16865. const keys = Object.keys( morphAttributes );
  16866. if ( keys.length > 0 ) {
  16867. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16868. if ( morphAttribute !== undefined ) {
  16869. this.morphTargetInfluences = [];
  16870. this.morphTargetDictionary = {};
  16871. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16872. const name = morphAttribute[ m ].name || String( m );
  16873. this.morphTargetInfluences.push( 0 );
  16874. this.morphTargetDictionary[ name ] = m;
  16875. }
  16876. }
  16877. }
  16878. } else {
  16879. const morphTargets = geometry.morphTargets;
  16880. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16881. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16882. }
  16883. }
  16884. }
  16885. } );
  16886. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16887. const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  16888. if ( rayPointDistanceSq < localThresholdSq ) {
  16889. const intersectPoint = new Vector3();
  16890. _ray$2.closestPointToPoint( point, intersectPoint );
  16891. intersectPoint.applyMatrix4( matrixWorld );
  16892. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16893. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16894. intersects.push( {
  16895. distance: distance,
  16896. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16897. point: intersectPoint,
  16898. index: index,
  16899. face: null,
  16900. object: object
  16901. } );
  16902. }
  16903. }
  16904. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16905. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16906. this.format = format !== undefined ? format : RGBFormat;
  16907. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16908. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16909. this.generateMipmaps = false;
  16910. const scope = this;
  16911. function updateVideo() {
  16912. scope.needsUpdate = true;
  16913. video.requestVideoFrameCallback( updateVideo );
  16914. }
  16915. if ( 'requestVideoFrameCallback' in video ) {
  16916. video.requestVideoFrameCallback( updateVideo );
  16917. }
  16918. }
  16919. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  16920. constructor: VideoTexture,
  16921. isVideoTexture: true,
  16922. update: function () {
  16923. const video = this.image;
  16924. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16925. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16926. this.needsUpdate = true;
  16927. }
  16928. }
  16929. } );
  16930. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16931. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16932. this.image = { width: width, height: height };
  16933. this.mipmaps = mipmaps;
  16934. // no flipping for cube textures
  16935. // (also flipping doesn't work for compressed textures )
  16936. this.flipY = false;
  16937. // can't generate mipmaps for compressed textures
  16938. // mips must be embedded in DDS files
  16939. this.generateMipmaps = false;
  16940. }
  16941. CompressedTexture.prototype = Object.create( Texture.prototype );
  16942. CompressedTexture.prototype.constructor = CompressedTexture;
  16943. CompressedTexture.prototype.isCompressedTexture = true;
  16944. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16945. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16946. this.needsUpdate = true;
  16947. }
  16948. CanvasTexture.prototype = Object.create( Texture.prototype );
  16949. CanvasTexture.prototype.constructor = CanvasTexture;
  16950. CanvasTexture.prototype.isCanvasTexture = true;
  16951. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  16952. format = format !== undefined ? format : DepthFormat;
  16953. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16954. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16955. }
  16956. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  16957. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  16958. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16959. this.image = { width: width, height: height };
  16960. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16961. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16962. this.flipY = false;
  16963. this.generateMipmaps = false;
  16964. }
  16965. DepthTexture.prototype = Object.create( Texture.prototype );
  16966. DepthTexture.prototype.constructor = DepthTexture;
  16967. DepthTexture.prototype.isDepthTexture = true;
  16968. class WireframeGeometry extends BufferGeometry {
  16969. constructor( geometry ) {
  16970. super();
  16971. this.type = 'WireframeGeometry';
  16972. // buffer
  16973. const vertices = [];
  16974. // helper variables
  16975. const edge = [ 0, 0 ], edges = {};
  16976. const keys = [ 'a', 'b', 'c' ];
  16977. // different logic for Geometry and BufferGeometry
  16978. if ( geometry && geometry.isGeometry ) {
  16979. // create a data structure that contains all edges without duplicates
  16980. const faces = geometry.faces;
  16981. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  16982. const face = faces[ i ];
  16983. for ( let j = 0; j < 3; j ++ ) {
  16984. const edge1 = face[ keys[ j ] ];
  16985. const edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16986. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  16987. edge[ 1 ] = Math.max( edge1, edge2 );
  16988. const key = edge[ 0 ] + ',' + edge[ 1 ];
  16989. if ( edges[ key ] === undefined ) {
  16990. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  16991. }
  16992. }
  16993. }
  16994. // generate vertices
  16995. for ( const key in edges ) {
  16996. const e = edges[ key ];
  16997. let vertex = geometry.vertices[ e.index1 ];
  16998. vertices.push( vertex.x, vertex.y, vertex.z );
  16999. vertex = geometry.vertices[ e.index2 ];
  17000. vertices.push( vertex.x, vertex.y, vertex.z );
  17001. }
  17002. } else if ( geometry && geometry.isBufferGeometry ) {
  17003. const vertex = new Vector3();
  17004. if ( geometry.index !== null ) {
  17005. // indexed BufferGeometry
  17006. const position = geometry.attributes.position;
  17007. const indices = geometry.index;
  17008. let groups = geometry.groups;
  17009. if ( groups.length === 0 ) {
  17010. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  17011. }
  17012. // create a data structure that contains all eges without duplicates
  17013. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  17014. const group = groups[ o ];
  17015. const start = group.start;
  17016. const count = group.count;
  17017. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  17018. for ( let j = 0; j < 3; j ++ ) {
  17019. const edge1 = indices.getX( i + j );
  17020. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  17021. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  17022. edge[ 1 ] = Math.max( edge1, edge2 );
  17023. const key = edge[ 0 ] + ',' + edge[ 1 ];
  17024. if ( edges[ key ] === undefined ) {
  17025. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  17026. }
  17027. }
  17028. }
  17029. }
  17030. // generate vertices
  17031. for ( const key in edges ) {
  17032. const e = edges[ key ];
  17033. vertex.fromBufferAttribute( position, e.index1 );
  17034. vertices.push( vertex.x, vertex.y, vertex.z );
  17035. vertex.fromBufferAttribute( position, e.index2 );
  17036. vertices.push( vertex.x, vertex.y, vertex.z );
  17037. }
  17038. } else {
  17039. // non-indexed BufferGeometry
  17040. const position = geometry.attributes.position;
  17041. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  17042. for ( let j = 0; j < 3; j ++ ) {
  17043. // three edges per triangle, an edge is represented as (index1, index2)
  17044. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  17045. const index1 = 3 * i + j;
  17046. vertex.fromBufferAttribute( position, index1 );
  17047. vertices.push( vertex.x, vertex.y, vertex.z );
  17048. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  17049. vertex.fromBufferAttribute( position, index2 );
  17050. vertices.push( vertex.x, vertex.y, vertex.z );
  17051. }
  17052. }
  17053. }
  17054. }
  17055. // build geometry
  17056. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17057. }
  17058. }
  17059. /**
  17060. * Parametric Surfaces Geometry
  17061. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17062. */
  17063. // ParametricGeometry
  17064. function ParametricGeometry( func, slices, stacks ) {
  17065. Geometry.call( this );
  17066. this.type = 'ParametricGeometry';
  17067. this.parameters = {
  17068. func: func,
  17069. slices: slices,
  17070. stacks: stacks
  17071. };
  17072. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  17073. this.mergeVertices();
  17074. }
  17075. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  17076. ParametricGeometry.prototype.constructor = ParametricGeometry;
  17077. // ParametricBufferGeometry
  17078. function ParametricBufferGeometry( func, slices, stacks ) {
  17079. BufferGeometry.call( this );
  17080. this.type = 'ParametricBufferGeometry';
  17081. this.parameters = {
  17082. func: func,
  17083. slices: slices,
  17084. stacks: stacks
  17085. };
  17086. // buffers
  17087. const indices = [];
  17088. const vertices = [];
  17089. const normals = [];
  17090. const uvs = [];
  17091. const EPS = 0.00001;
  17092. const normal = new Vector3();
  17093. const p0 = new Vector3(), p1 = new Vector3();
  17094. const pu = new Vector3(), pv = new Vector3();
  17095. if ( func.length < 3 ) {
  17096. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  17097. }
  17098. // generate vertices, normals and uvs
  17099. const sliceCount = slices + 1;
  17100. for ( let i = 0; i <= stacks; i ++ ) {
  17101. const v = i / stacks;
  17102. for ( let j = 0; j <= slices; j ++ ) {
  17103. const u = j / slices;
  17104. // vertex
  17105. func( u, v, p0 );
  17106. vertices.push( p0.x, p0.y, p0.z );
  17107. // normal
  17108. // approximate tangent vectors via finite differences
  17109. if ( u - EPS >= 0 ) {
  17110. func( u - EPS, v, p1 );
  17111. pu.subVectors( p0, p1 );
  17112. } else {
  17113. func( u + EPS, v, p1 );
  17114. pu.subVectors( p1, p0 );
  17115. }
  17116. if ( v - EPS >= 0 ) {
  17117. func( u, v - EPS, p1 );
  17118. pv.subVectors( p0, p1 );
  17119. } else {
  17120. func( u, v + EPS, p1 );
  17121. pv.subVectors( p1, p0 );
  17122. }
  17123. // cross product of tangent vectors returns surface normal
  17124. normal.crossVectors( pu, pv ).normalize();
  17125. normals.push( normal.x, normal.y, normal.z );
  17126. // uv
  17127. uvs.push( u, v );
  17128. }
  17129. }
  17130. // generate indices
  17131. for ( let i = 0; i < stacks; i ++ ) {
  17132. for ( let j = 0; j < slices; j ++ ) {
  17133. const a = i * sliceCount + j;
  17134. const b = i * sliceCount + j + 1;
  17135. const c = ( i + 1 ) * sliceCount + j + 1;
  17136. const d = ( i + 1 ) * sliceCount + j;
  17137. // faces one and two
  17138. indices.push( a, b, d );
  17139. indices.push( b, c, d );
  17140. }
  17141. }
  17142. // build geometry
  17143. this.setIndex( indices );
  17144. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17145. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17146. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17147. }
  17148. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17149. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  17150. // PolyhedronGeometry
  17151. class PolyhedronGeometry extends Geometry {
  17152. constructor( vertices, indices, radius, detail ) {
  17153. super();
  17154. this.type = 'PolyhedronGeometry';
  17155. this.parameters = {
  17156. vertices: vertices,
  17157. indices: indices,
  17158. radius: radius,
  17159. detail: detail
  17160. };
  17161. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  17162. this.mergeVertices();
  17163. }
  17164. }
  17165. // PolyhedronBufferGeometry
  17166. class PolyhedronBufferGeometry extends BufferGeometry {
  17167. constructor( vertices, indices, radius, detail ) {
  17168. super();
  17169. this.type = 'PolyhedronBufferGeometry';
  17170. this.parameters = {
  17171. vertices: vertices,
  17172. indices: indices,
  17173. radius: radius,
  17174. detail: detail
  17175. };
  17176. radius = radius || 1;
  17177. detail = detail || 0;
  17178. // default buffer data
  17179. const vertexBuffer = [];
  17180. const uvBuffer = [];
  17181. // the subdivision creates the vertex buffer data
  17182. subdivide( detail );
  17183. // all vertices should lie on a conceptual sphere with a given radius
  17184. applyRadius( radius );
  17185. // finally, create the uv data
  17186. generateUVs();
  17187. // build non-indexed geometry
  17188. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  17189. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  17190. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  17191. if ( detail === 0 ) {
  17192. this.computeVertexNormals(); // flat normals
  17193. } else {
  17194. this.normalizeNormals(); // smooth normals
  17195. }
  17196. // helper functions
  17197. function subdivide( detail ) {
  17198. const a = new Vector3();
  17199. const b = new Vector3();
  17200. const c = new Vector3();
  17201. // iterate over all faces and apply a subdivison with the given detail value
  17202. for ( let i = 0; i < indices.length; i += 3 ) {
  17203. // get the vertices of the face
  17204. getVertexByIndex( indices[ i + 0 ], a );
  17205. getVertexByIndex( indices[ i + 1 ], b );
  17206. getVertexByIndex( indices[ i + 2 ], c );
  17207. // perform subdivision
  17208. subdivideFace( a, b, c, detail );
  17209. }
  17210. }
  17211. function subdivideFace( a, b, c, detail ) {
  17212. const cols = detail + 1;
  17213. // we use this multidimensional array as a data structure for creating the subdivision
  17214. const v = [];
  17215. // construct all of the vertices for this subdivision
  17216. for ( let i = 0; i <= cols; i ++ ) {
  17217. v[ i ] = [];
  17218. const aj = a.clone().lerp( c, i / cols );
  17219. const bj = b.clone().lerp( c, i / cols );
  17220. const rows = cols - i;
  17221. for ( let j = 0; j <= rows; j ++ ) {
  17222. if ( j === 0 && i === cols ) {
  17223. v[ i ][ j ] = aj;
  17224. } else {
  17225. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  17226. }
  17227. }
  17228. }
  17229. // construct all of the faces
  17230. for ( let i = 0; i < cols; i ++ ) {
  17231. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  17232. const k = Math.floor( j / 2 );
  17233. if ( j % 2 === 0 ) {
  17234. pushVertex( v[ i ][ k + 1 ] );
  17235. pushVertex( v[ i + 1 ][ k ] );
  17236. pushVertex( v[ i ][ k ] );
  17237. } else {
  17238. pushVertex( v[ i ][ k + 1 ] );
  17239. pushVertex( v[ i + 1 ][ k + 1 ] );
  17240. pushVertex( v[ i + 1 ][ k ] );
  17241. }
  17242. }
  17243. }
  17244. }
  17245. function applyRadius( radius ) {
  17246. const vertex = new Vector3();
  17247. // iterate over the entire buffer and apply the radius to each vertex
  17248. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17249. vertex.x = vertexBuffer[ i + 0 ];
  17250. vertex.y = vertexBuffer[ i + 1 ];
  17251. vertex.z = vertexBuffer[ i + 2 ];
  17252. vertex.normalize().multiplyScalar( radius );
  17253. vertexBuffer[ i + 0 ] = vertex.x;
  17254. vertexBuffer[ i + 1 ] = vertex.y;
  17255. vertexBuffer[ i + 2 ] = vertex.z;
  17256. }
  17257. }
  17258. function generateUVs() {
  17259. const vertex = new Vector3();
  17260. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17261. vertex.x = vertexBuffer[ i + 0 ];
  17262. vertex.y = vertexBuffer[ i + 1 ];
  17263. vertex.z = vertexBuffer[ i + 2 ];
  17264. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  17265. const v = inclination( vertex ) / Math.PI + 0.5;
  17266. uvBuffer.push( u, 1 - v );
  17267. }
  17268. correctUVs();
  17269. correctSeam();
  17270. }
  17271. function correctSeam() {
  17272. // handle case when face straddles the seam, see #3269
  17273. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  17274. // uv data of a single face
  17275. const x0 = uvBuffer[ i + 0 ];
  17276. const x1 = uvBuffer[ i + 2 ];
  17277. const x2 = uvBuffer[ i + 4 ];
  17278. const max = Math.max( x0, x1, x2 );
  17279. const min = Math.min( x0, x1, x2 );
  17280. // 0.9 is somewhat arbitrary
  17281. if ( max > 0.9 && min < 0.1 ) {
  17282. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  17283. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  17284. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  17285. }
  17286. }
  17287. }
  17288. function pushVertex( vertex ) {
  17289. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  17290. }
  17291. function getVertexByIndex( index, vertex ) {
  17292. const stride = index * 3;
  17293. vertex.x = vertices[ stride + 0 ];
  17294. vertex.y = vertices[ stride + 1 ];
  17295. vertex.z = vertices[ stride + 2 ];
  17296. }
  17297. function correctUVs() {
  17298. const a = new Vector3();
  17299. const b = new Vector3();
  17300. const c = new Vector3();
  17301. const centroid = new Vector3();
  17302. const uvA = new Vector2();
  17303. const uvB = new Vector2();
  17304. const uvC = new Vector2();
  17305. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  17306. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  17307. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  17308. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  17309. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  17310. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  17311. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  17312. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  17313. const azi = azimuth( centroid );
  17314. correctUV( uvA, j + 0, a, azi );
  17315. correctUV( uvB, j + 2, b, azi );
  17316. correctUV( uvC, j + 4, c, azi );
  17317. }
  17318. }
  17319. function correctUV( uv, stride, vector, azimuth ) {
  17320. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  17321. uvBuffer[ stride ] = uv.x - 1;
  17322. }
  17323. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  17324. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  17325. }
  17326. }
  17327. // Angle around the Y axis, counter-clockwise when looking from above.
  17328. function azimuth( vector ) {
  17329. return Math.atan2( vector.z, - vector.x );
  17330. }
  17331. // Angle above the XZ plane.
  17332. function inclination( vector ) {
  17333. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  17334. }
  17335. }
  17336. }
  17337. // TetrahedronGeometry
  17338. class TetrahedronGeometry extends Geometry {
  17339. constructor( radius, detail ) {
  17340. super();
  17341. this.type = 'TetrahedronGeometry';
  17342. this.parameters = {
  17343. radius: radius,
  17344. detail: detail
  17345. };
  17346. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  17347. this.mergeVertices();
  17348. }
  17349. }
  17350. // TetrahedronBufferGeometry
  17351. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  17352. constructor( radius, detail ) {
  17353. const vertices = [
  17354. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  17355. ];
  17356. const indices = [
  17357. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  17358. ];
  17359. super( vertices, indices, radius, detail );
  17360. this.type = 'TetrahedronBufferGeometry';
  17361. this.parameters = {
  17362. radius: radius,
  17363. detail: detail
  17364. };
  17365. }
  17366. }
  17367. // OctahedronGeometry
  17368. class OctahedronGeometry extends Geometry {
  17369. constructor( radius, detail ) {
  17370. super();
  17371. this.type = 'OctahedronGeometry';
  17372. this.parameters = {
  17373. radius: radius,
  17374. detail: detail
  17375. };
  17376. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  17377. this.mergeVertices();
  17378. }
  17379. }
  17380. // OctahedronBufferGeometry
  17381. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  17382. constructor( radius, detail ) {
  17383. const vertices = [
  17384. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  17385. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  17386. ];
  17387. const indices = [
  17388. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  17389. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  17390. 1, 3, 4, 1, 4, 2
  17391. ];
  17392. super( vertices, indices, radius, detail );
  17393. this.type = 'OctahedronBufferGeometry';
  17394. this.parameters = {
  17395. radius: radius,
  17396. detail: detail
  17397. };
  17398. }
  17399. }
  17400. // IcosahedronGeometry
  17401. class IcosahedronGeometry extends Geometry {
  17402. constructor( radius, detail ) {
  17403. super();
  17404. this.type = 'IcosahedronGeometry';
  17405. this.parameters = {
  17406. radius: radius,
  17407. detail: detail
  17408. };
  17409. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  17410. this.mergeVertices();
  17411. }
  17412. }
  17413. // IcosahedronBufferGeometry
  17414. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  17415. constructor( radius, detail ) {
  17416. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17417. const vertices = [
  17418. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  17419. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  17420. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  17421. ];
  17422. const indices = [
  17423. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  17424. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  17425. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  17426. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  17427. ];
  17428. super( vertices, indices, radius, detail );
  17429. this.type = 'IcosahedronBufferGeometry';
  17430. this.parameters = {
  17431. radius: radius,
  17432. detail: detail
  17433. };
  17434. }
  17435. }
  17436. // DodecahedronGeometry
  17437. class DodecahedronGeometry extends Geometry {
  17438. constructor( radius, detail ) {
  17439. super();
  17440. this.type = 'DodecahedronGeometry';
  17441. this.parameters = {
  17442. radius: radius,
  17443. detail: detail
  17444. };
  17445. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  17446. this.mergeVertices();
  17447. }
  17448. }
  17449. // DodecahedronBufferGeometry
  17450. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  17451. constructor( radius, detail ) {
  17452. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17453. const r = 1 / t;
  17454. const vertices = [
  17455. // (±1, ±1, ±1)
  17456. - 1, - 1, - 1, - 1, - 1, 1,
  17457. - 1, 1, - 1, - 1, 1, 1,
  17458. 1, - 1, - 1, 1, - 1, 1,
  17459. 1, 1, - 1, 1, 1, 1,
  17460. // (0, ±1/φ, ±φ)
  17461. 0, - r, - t, 0, - r, t,
  17462. 0, r, - t, 0, r, t,
  17463. // (±1/φ, ±φ, 0)
  17464. - r, - t, 0, - r, t, 0,
  17465. r, - t, 0, r, t, 0,
  17466. // (±φ, 0, ±1/φ)
  17467. - t, 0, - r, t, 0, - r,
  17468. - t, 0, r, t, 0, r
  17469. ];
  17470. const indices = [
  17471. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  17472. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  17473. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  17474. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  17475. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  17476. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  17477. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  17478. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  17479. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  17480. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  17481. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  17482. 1, 12, 14, 1, 14, 5, 1, 5, 9
  17483. ];
  17484. super( vertices, indices, radius, detail );
  17485. this.type = 'DodecahedronBufferGeometry';
  17486. this.parameters = {
  17487. radius: radius,
  17488. detail: detail
  17489. };
  17490. }
  17491. }
  17492. // TubeGeometry
  17493. class TubeGeometry extends Geometry {
  17494. constructor( path, tubularSegments, radius, radialSegments, closed, taper ) {
  17495. super();
  17496. this.type = 'TubeGeometry';
  17497. this.parameters = {
  17498. path: path,
  17499. tubularSegments: tubularSegments,
  17500. radius: radius,
  17501. radialSegments: radialSegments,
  17502. closed: closed
  17503. };
  17504. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  17505. const bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  17506. // expose internals
  17507. this.tangents = bufferGeometry.tangents;
  17508. this.normals = bufferGeometry.normals;
  17509. this.binormals = bufferGeometry.binormals;
  17510. // create geometry
  17511. this.fromBufferGeometry( bufferGeometry );
  17512. this.mergeVertices();
  17513. }
  17514. }
  17515. // TubeBufferGeometry
  17516. class TubeBufferGeometry extends BufferGeometry {
  17517. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  17518. super();
  17519. this.type = 'TubeBufferGeometry';
  17520. this.parameters = {
  17521. path: path,
  17522. tubularSegments: tubularSegments,
  17523. radius: radius,
  17524. radialSegments: radialSegments,
  17525. closed: closed
  17526. };
  17527. tubularSegments = tubularSegments || 64;
  17528. radius = radius || 1;
  17529. radialSegments = radialSegments || 8;
  17530. closed = closed || false;
  17531. const frames = path.computeFrenetFrames( tubularSegments, closed );
  17532. // expose internals
  17533. this.tangents = frames.tangents;
  17534. this.normals = frames.normals;
  17535. this.binormals = frames.binormals;
  17536. // helper variables
  17537. const vertex = new Vector3();
  17538. const normal = new Vector3();
  17539. const uv = new Vector2();
  17540. let P = new Vector3();
  17541. // buffer
  17542. const vertices = [];
  17543. const normals = [];
  17544. const uvs = [];
  17545. const indices = [];
  17546. // create buffer data
  17547. generateBufferData();
  17548. // build geometry
  17549. this.setIndex( indices );
  17550. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17551. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17552. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17553. // functions
  17554. function generateBufferData() {
  17555. for ( let i = 0; i < tubularSegments; i ++ ) {
  17556. generateSegment( i );
  17557. }
  17558. // if the geometry is not closed, generate the last row of vertices and normals
  17559. // at the regular position on the given path
  17560. //
  17561. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  17562. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  17563. // uvs are generated in a separate function.
  17564. // this makes it easy compute correct values for closed geometries
  17565. generateUVs();
  17566. // finally create faces
  17567. generateIndices();
  17568. }
  17569. function generateSegment( i ) {
  17570. // we use getPointAt to sample evenly distributed points from the given path
  17571. P = path.getPointAt( i / tubularSegments, P );
  17572. // retrieve corresponding normal and binormal
  17573. const N = frames.normals[ i ];
  17574. const B = frames.binormals[ i ];
  17575. // generate normals and vertices for the current segment
  17576. for ( let j = 0; j <= radialSegments; j ++ ) {
  17577. const v = j / radialSegments * Math.PI * 2;
  17578. const sin = Math.sin( v );
  17579. const cos = - Math.cos( v );
  17580. // normal
  17581. normal.x = ( cos * N.x + sin * B.x );
  17582. normal.y = ( cos * N.y + sin * B.y );
  17583. normal.z = ( cos * N.z + sin * B.z );
  17584. normal.normalize();
  17585. normals.push( normal.x, normal.y, normal.z );
  17586. // vertex
  17587. vertex.x = P.x + radius * normal.x;
  17588. vertex.y = P.y + radius * normal.y;
  17589. vertex.z = P.z + radius * normal.z;
  17590. vertices.push( vertex.x, vertex.y, vertex.z );
  17591. }
  17592. }
  17593. function generateIndices() {
  17594. for ( let j = 1; j <= tubularSegments; j ++ ) {
  17595. for ( let i = 1; i <= radialSegments; i ++ ) {
  17596. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  17597. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  17598. const c = ( radialSegments + 1 ) * j + i;
  17599. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  17600. // faces
  17601. indices.push( a, b, d );
  17602. indices.push( b, c, d );
  17603. }
  17604. }
  17605. }
  17606. function generateUVs() {
  17607. for ( let i = 0; i <= tubularSegments; i ++ ) {
  17608. for ( let j = 0; j <= radialSegments; j ++ ) {
  17609. uv.x = i / tubularSegments;
  17610. uv.y = j / radialSegments;
  17611. uvs.push( uv.x, uv.y );
  17612. }
  17613. }
  17614. }
  17615. }
  17616. toJSON() {
  17617. const data = BufferGeometry.prototype.toJSON.call( this );
  17618. data.path = this.parameters.path.toJSON();
  17619. return data;
  17620. }
  17621. }
  17622. // TorusKnotGeometry
  17623. class TorusKnotGeometry extends Geometry {
  17624. constructor( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  17625. super();
  17626. this.type = 'TorusKnotGeometry';
  17627. this.parameters = {
  17628. radius: radius,
  17629. tube: tube,
  17630. tubularSegments: tubularSegments,
  17631. radialSegments: radialSegments,
  17632. p: p,
  17633. q: q
  17634. };
  17635. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  17636. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  17637. this.mergeVertices();
  17638. }
  17639. }
  17640. // TorusKnotBufferGeometry
  17641. class TorusKnotBufferGeometry extends BufferGeometry {
  17642. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  17643. super();
  17644. this.type = 'TorusKnotBufferGeometry';
  17645. this.parameters = {
  17646. radius: radius,
  17647. tube: tube,
  17648. tubularSegments: tubularSegments,
  17649. radialSegments: radialSegments,
  17650. p: p,
  17651. q: q
  17652. };
  17653. radius = radius || 1;
  17654. tube = tube || 0.4;
  17655. tubularSegments = Math.floor( tubularSegments ) || 64;
  17656. radialSegments = Math.floor( radialSegments ) || 8;
  17657. p = p || 2;
  17658. q = q || 3;
  17659. // buffers
  17660. const indices = [];
  17661. const vertices = [];
  17662. const normals = [];
  17663. const uvs = [];
  17664. // helper variables
  17665. const vertex = new Vector3();
  17666. const normal = new Vector3();
  17667. const P1 = new Vector3();
  17668. const P2 = new Vector3();
  17669. const B = new Vector3();
  17670. const T = new Vector3();
  17671. const N = new Vector3();
  17672. // generate vertices, normals and uvs
  17673. for ( let i = 0; i <= tubularSegments; ++ i ) {
  17674. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17675. const u = i / tubularSegments * p * Math.PI * 2;
  17676. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  17677. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17678. calculatePositionOnCurve( u, p, q, radius, P1 );
  17679. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  17680. // calculate orthonormal basis
  17681. T.subVectors( P2, P1 );
  17682. N.addVectors( P2, P1 );
  17683. B.crossVectors( T, N );
  17684. N.crossVectors( B, T );
  17685. // normalize B, N. T can be ignored, we don't use it
  17686. B.normalize();
  17687. N.normalize();
  17688. for ( let j = 0; j <= radialSegments; ++ j ) {
  17689. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17690. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17691. const v = j / radialSegments * Math.PI * 2;
  17692. const cx = - tube * Math.cos( v );
  17693. const cy = tube * Math.sin( v );
  17694. // now calculate the final vertex position.
  17695. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17696. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  17697. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  17698. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  17699. vertices.push( vertex.x, vertex.y, vertex.z );
  17700. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  17701. normal.subVectors( vertex, P1 ).normalize();
  17702. normals.push( normal.x, normal.y, normal.z );
  17703. // uv
  17704. uvs.push( i / tubularSegments );
  17705. uvs.push( j / radialSegments );
  17706. }
  17707. }
  17708. // generate indices
  17709. for ( let j = 1; j <= tubularSegments; j ++ ) {
  17710. for ( let i = 1; i <= radialSegments; i ++ ) {
  17711. // indices
  17712. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  17713. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  17714. const c = ( radialSegments + 1 ) * j + i;
  17715. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  17716. // faces
  17717. indices.push( a, b, d );
  17718. indices.push( b, c, d );
  17719. }
  17720. }
  17721. // build geometry
  17722. this.setIndex( indices );
  17723. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17724. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17725. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17726. // this function calculates the current position on the torus curve
  17727. function calculatePositionOnCurve( u, p, q, radius, position ) {
  17728. const cu = Math.cos( u );
  17729. const su = Math.sin( u );
  17730. const quOverP = q / p * u;
  17731. const cs = Math.cos( quOverP );
  17732. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  17733. position.y = radius * ( 2 + cs ) * su * 0.5;
  17734. position.z = radius * Math.sin( quOverP ) * 0.5;
  17735. }
  17736. }
  17737. }
  17738. // TorusGeometry
  17739. class TorusGeometry extends Geometry {
  17740. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  17741. super();
  17742. this.type = 'TorusGeometry';
  17743. this.parameters = {
  17744. radius: radius,
  17745. tube: tube,
  17746. radialSegments: radialSegments,
  17747. tubularSegments: tubularSegments,
  17748. arc: arc
  17749. };
  17750. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  17751. this.mergeVertices();
  17752. }
  17753. }
  17754. // TorusBufferGeometry
  17755. class TorusBufferGeometry extends BufferGeometry {
  17756. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  17757. super();
  17758. this.type = 'TorusBufferGeometry';
  17759. this.parameters = {
  17760. radius: radius,
  17761. tube: tube,
  17762. radialSegments: radialSegments,
  17763. tubularSegments: tubularSegments,
  17764. arc: arc
  17765. };
  17766. radius = radius || 1;
  17767. tube = tube || 0.4;
  17768. radialSegments = Math.floor( radialSegments ) || 8;
  17769. tubularSegments = Math.floor( tubularSegments ) || 6;
  17770. arc = arc || Math.PI * 2;
  17771. // buffers
  17772. const indices = [];
  17773. const vertices = [];
  17774. const normals = [];
  17775. const uvs = [];
  17776. // helper variables
  17777. const center = new Vector3();
  17778. const vertex = new Vector3();
  17779. const normal = new Vector3();
  17780. // generate vertices, normals and uvs
  17781. for ( let j = 0; j <= radialSegments; j ++ ) {
  17782. for ( let i = 0; i <= tubularSegments; i ++ ) {
  17783. const u = i / tubularSegments * arc;
  17784. const v = j / radialSegments * Math.PI * 2;
  17785. // vertex
  17786. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  17787. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  17788. vertex.z = tube * Math.sin( v );
  17789. vertices.push( vertex.x, vertex.y, vertex.z );
  17790. // normal
  17791. center.x = radius * Math.cos( u );
  17792. center.y = radius * Math.sin( u );
  17793. normal.subVectors( vertex, center ).normalize();
  17794. normals.push( normal.x, normal.y, normal.z );
  17795. // uv
  17796. uvs.push( i / tubularSegments );
  17797. uvs.push( j / radialSegments );
  17798. }
  17799. }
  17800. // generate indices
  17801. for ( let j = 1; j <= radialSegments; j ++ ) {
  17802. for ( let i = 1; i <= tubularSegments; i ++ ) {
  17803. // indices
  17804. const a = ( tubularSegments + 1 ) * j + i - 1;
  17805. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  17806. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  17807. const d = ( tubularSegments + 1 ) * j + i;
  17808. // faces
  17809. indices.push( a, b, d );
  17810. indices.push( b, c, d );
  17811. }
  17812. }
  17813. // build geometry
  17814. this.setIndex( indices );
  17815. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17816. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17817. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17818. }
  17819. }
  17820. /**
  17821. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17822. */
  17823. const Earcut = {
  17824. triangulate: function ( data, holeIndices, dim ) {
  17825. dim = dim || 2;
  17826. const hasHoles = holeIndices && holeIndices.length;
  17827. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  17828. let outerNode = linkedList( data, 0, outerLen, dim, true );
  17829. const triangles = [];
  17830. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  17831. let minX, minY, maxX, maxY, x, y, invSize;
  17832. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  17833. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  17834. if ( data.length > 80 * dim ) {
  17835. minX = maxX = data[ 0 ];
  17836. minY = maxY = data[ 1 ];
  17837. for ( let i = dim; i < outerLen; i += dim ) {
  17838. x = data[ i ];
  17839. y = data[ i + 1 ];
  17840. if ( x < minX ) minX = x;
  17841. if ( y < minY ) minY = y;
  17842. if ( x > maxX ) maxX = x;
  17843. if ( y > maxY ) maxY = y;
  17844. }
  17845. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17846. invSize = Math.max( maxX - minX, maxY - minY );
  17847. invSize = invSize !== 0 ? 1 / invSize : 0;
  17848. }
  17849. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  17850. return triangles;
  17851. }
  17852. };
  17853. // create a circular doubly linked list from polygon points in the specified winding order
  17854. function linkedList( data, start, end, dim, clockwise ) {
  17855. let i, last;
  17856. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  17857. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17858. } else {
  17859. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17860. }
  17861. if ( last && equals( last, last.next ) ) {
  17862. removeNode( last );
  17863. last = last.next;
  17864. }
  17865. return last;
  17866. }
  17867. // eliminate colinear or duplicate points
  17868. function filterPoints( start, end ) {
  17869. if ( ! start ) return start;
  17870. if ( ! end ) end = start;
  17871. let p = start,
  17872. again;
  17873. do {
  17874. again = false;
  17875. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  17876. removeNode( p );
  17877. p = end = p.prev;
  17878. if ( p === p.next ) break;
  17879. again = true;
  17880. } else {
  17881. p = p.next;
  17882. }
  17883. } while ( again || p !== end );
  17884. return end;
  17885. }
  17886. // main ear slicing loop which triangulates a polygon (given as a linked list)
  17887. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  17888. if ( ! ear ) return;
  17889. // interlink polygon nodes in z-order
  17890. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  17891. let stop = ear,
  17892. prev, next;
  17893. // iterate through ears, slicing them one by one
  17894. while ( ear.prev !== ear.next ) {
  17895. prev = ear.prev;
  17896. next = ear.next;
  17897. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  17898. // cut off the triangle
  17899. triangles.push( prev.i / dim );
  17900. triangles.push( ear.i / dim );
  17901. triangles.push( next.i / dim );
  17902. removeNode( ear );
  17903. // skipping the next vertex leads to less sliver triangles
  17904. ear = next.next;
  17905. stop = next.next;
  17906. continue;
  17907. }
  17908. ear = next;
  17909. // if we looped through the whole remaining polygon and can't find any more ears
  17910. if ( ear === stop ) {
  17911. // try filtering points and slicing again
  17912. if ( ! pass ) {
  17913. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  17914. // if this didn't work, try curing all small self-intersections locally
  17915. } else if ( pass === 1 ) {
  17916. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  17917. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  17918. // as a last resort, try splitting the remaining polygon into two
  17919. } else if ( pass === 2 ) {
  17920. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  17921. }
  17922. break;
  17923. }
  17924. }
  17925. }
  17926. // check whether a polygon node forms a valid ear with adjacent nodes
  17927. function isEar( ear ) {
  17928. const a = ear.prev,
  17929. b = ear,
  17930. c = ear.next;
  17931. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17932. // now make sure we don't have other points inside the potential ear
  17933. let p = ear.next.next;
  17934. while ( p !== ear.prev ) {
  17935. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17936. area( p.prev, p, p.next ) >= 0 ) return false;
  17937. p = p.next;
  17938. }
  17939. return true;
  17940. }
  17941. function isEarHashed( ear, minX, minY, invSize ) {
  17942. const a = ear.prev,
  17943. b = ear,
  17944. c = ear.next;
  17945. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17946. // triangle bbox; min & max are calculated like this for speed
  17947. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  17948. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  17949. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  17950. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  17951. // z-order range for the current triangle bbox;
  17952. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  17953. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  17954. let p = ear.prevZ,
  17955. n = ear.nextZ;
  17956. // look for points inside the triangle in both directions
  17957. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  17958. if ( p !== ear.prev && p !== ear.next &&
  17959. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17960. area( p.prev, p, p.next ) >= 0 ) return false;
  17961. p = p.prevZ;
  17962. if ( n !== ear.prev && n !== ear.next &&
  17963. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17964. area( n.prev, n, n.next ) >= 0 ) return false;
  17965. n = n.nextZ;
  17966. }
  17967. // look for remaining points in decreasing z-order
  17968. while ( p && p.z >= minZ ) {
  17969. if ( p !== ear.prev && p !== ear.next &&
  17970. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17971. area( p.prev, p, p.next ) >= 0 ) return false;
  17972. p = p.prevZ;
  17973. }
  17974. // look for remaining points in increasing z-order
  17975. while ( n && n.z <= maxZ ) {
  17976. if ( n !== ear.prev && n !== ear.next &&
  17977. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17978. area( n.prev, n, n.next ) >= 0 ) return false;
  17979. n = n.nextZ;
  17980. }
  17981. return true;
  17982. }
  17983. // go through all polygon nodes and cure small local self-intersections
  17984. function cureLocalIntersections( start, triangles, dim ) {
  17985. let p = start;
  17986. do {
  17987. const a = p.prev,
  17988. b = p.next.next;
  17989. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  17990. triangles.push( a.i / dim );
  17991. triangles.push( p.i / dim );
  17992. triangles.push( b.i / dim );
  17993. // remove two nodes involved
  17994. removeNode( p );
  17995. removeNode( p.next );
  17996. p = start = b;
  17997. }
  17998. p = p.next;
  17999. } while ( p !== start );
  18000. return filterPoints( p );
  18001. }
  18002. // try splitting polygon into two and triangulate them independently
  18003. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  18004. // look for a valid diagonal that divides the polygon into two
  18005. let a = start;
  18006. do {
  18007. let b = a.next.next;
  18008. while ( b !== a.prev ) {
  18009. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  18010. // split the polygon in two by the diagonal
  18011. let c = splitPolygon( a, b );
  18012. // filter colinear points around the cuts
  18013. a = filterPoints( a, a.next );
  18014. c = filterPoints( c, c.next );
  18015. // run earcut on each half
  18016. earcutLinked( a, triangles, dim, minX, minY, invSize );
  18017. earcutLinked( c, triangles, dim, minX, minY, invSize );
  18018. return;
  18019. }
  18020. b = b.next;
  18021. }
  18022. a = a.next;
  18023. } while ( a !== start );
  18024. }
  18025. // link every hole into the outer loop, producing a single-ring polygon without holes
  18026. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  18027. const queue = [];
  18028. let i, len, start, end, list;
  18029. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  18030. start = holeIndices[ i ] * dim;
  18031. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  18032. list = linkedList( data, start, end, dim, false );
  18033. if ( list === list.next ) list.steiner = true;
  18034. queue.push( getLeftmost( list ) );
  18035. }
  18036. queue.sort( compareX );
  18037. // process holes from left to right
  18038. for ( i = 0; i < queue.length; i ++ ) {
  18039. eliminateHole( queue[ i ], outerNode );
  18040. outerNode = filterPoints( outerNode, outerNode.next );
  18041. }
  18042. return outerNode;
  18043. }
  18044. function compareX( a, b ) {
  18045. return a.x - b.x;
  18046. }
  18047. // find a bridge between vertices that connects hole with an outer ring and and link it
  18048. function eliminateHole( hole, outerNode ) {
  18049. outerNode = findHoleBridge( hole, outerNode );
  18050. if ( outerNode ) {
  18051. const b = splitPolygon( outerNode, hole );
  18052. // filter collinear points around the cuts
  18053. filterPoints( outerNode, outerNode.next );
  18054. filterPoints( b, b.next );
  18055. }
  18056. }
  18057. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18058. function findHoleBridge( hole, outerNode ) {
  18059. let p = outerNode;
  18060. const hx = hole.x;
  18061. const hy = hole.y;
  18062. let qx = - Infinity, m;
  18063. // find a segment intersected by a ray from the hole's leftmost point to the left;
  18064. // segment's endpoint with lesser x will be potential connection point
  18065. do {
  18066. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  18067. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  18068. if ( x <= hx && x > qx ) {
  18069. qx = x;
  18070. if ( x === hx ) {
  18071. if ( hy === p.y ) return p;
  18072. if ( hy === p.next.y ) return p.next;
  18073. }
  18074. m = p.x < p.next.x ? p : p.next;
  18075. }
  18076. }
  18077. p = p.next;
  18078. } while ( p !== outerNode );
  18079. if ( ! m ) return null;
  18080. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  18081. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18082. // if there are no points found, we have a valid connection;
  18083. // otherwise choose the point of the minimum angle with the ray as connection point
  18084. const stop = m,
  18085. mx = m.x,
  18086. my = m.y;
  18087. let tanMin = Infinity, tan;
  18088. p = m;
  18089. do {
  18090. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  18091. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  18092. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  18093. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  18094. m = p;
  18095. tanMin = tan;
  18096. }
  18097. }
  18098. p = p.next;
  18099. } while ( p !== stop );
  18100. return m;
  18101. }
  18102. // whether sector in vertex m contains sector in vertex p in the same coordinates
  18103. function sectorContainsSector( m, p ) {
  18104. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  18105. }
  18106. // interlink polygon nodes in z-order
  18107. function indexCurve( start, minX, minY, invSize ) {
  18108. let p = start;
  18109. do {
  18110. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  18111. p.prevZ = p.prev;
  18112. p.nextZ = p.next;
  18113. p = p.next;
  18114. } while ( p !== start );
  18115. p.prevZ.nextZ = null;
  18116. p.prevZ = null;
  18117. sortLinked( p );
  18118. }
  18119. // Simon Tatham's linked list merge sort algorithm
  18120. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18121. function sortLinked( list ) {
  18122. let i, p, q, e, tail, numMerges, pSize, qSize,
  18123. inSize = 1;
  18124. do {
  18125. p = list;
  18126. list = null;
  18127. tail = null;
  18128. numMerges = 0;
  18129. while ( p ) {
  18130. numMerges ++;
  18131. q = p;
  18132. pSize = 0;
  18133. for ( i = 0; i < inSize; i ++ ) {
  18134. pSize ++;
  18135. q = q.nextZ;
  18136. if ( ! q ) break;
  18137. }
  18138. qSize = inSize;
  18139. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  18140. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  18141. e = p;
  18142. p = p.nextZ;
  18143. pSize --;
  18144. } else {
  18145. e = q;
  18146. q = q.nextZ;
  18147. qSize --;
  18148. }
  18149. if ( tail ) tail.nextZ = e;
  18150. else list = e;
  18151. e.prevZ = tail;
  18152. tail = e;
  18153. }
  18154. p = q;
  18155. }
  18156. tail.nextZ = null;
  18157. inSize *= 2;
  18158. } while ( numMerges > 1 );
  18159. return list;
  18160. }
  18161. // z-order of a point given coords and inverse of the longer side of data bbox
  18162. function zOrder( x, y, minX, minY, invSize ) {
  18163. // coords are transformed into non-negative 15-bit integer range
  18164. x = 32767 * ( x - minX ) * invSize;
  18165. y = 32767 * ( y - minY ) * invSize;
  18166. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  18167. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  18168. x = ( x | ( x << 2 ) ) & 0x33333333;
  18169. x = ( x | ( x << 1 ) ) & 0x55555555;
  18170. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  18171. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  18172. y = ( y | ( y << 2 ) ) & 0x33333333;
  18173. y = ( y | ( y << 1 ) ) & 0x55555555;
  18174. return x | ( y << 1 );
  18175. }
  18176. // find the leftmost node of a polygon ring
  18177. function getLeftmost( start ) {
  18178. let p = start,
  18179. leftmost = start;
  18180. do {
  18181. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  18182. p = p.next;
  18183. } while ( p !== start );
  18184. return leftmost;
  18185. }
  18186. // check if a point lies within a convex triangle
  18187. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  18188. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  18189. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  18190. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  18191. }
  18192. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18193. function isValidDiagonal( a, b ) {
  18194. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  18195. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  18196. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  18197. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  18198. }
  18199. // signed area of a triangle
  18200. function area( p, q, r ) {
  18201. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  18202. }
  18203. // check if two points are equal
  18204. function equals( p1, p2 ) {
  18205. return p1.x === p2.x && p1.y === p2.y;
  18206. }
  18207. // check if two segments intersect
  18208. function intersects( p1, q1, p2, q2 ) {
  18209. const o1 = sign( area( p1, q1, p2 ) );
  18210. const o2 = sign( area( p1, q1, q2 ) );
  18211. const o3 = sign( area( p2, q2, p1 ) );
  18212. const o4 = sign( area( p2, q2, q1 ) );
  18213. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  18214. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18215. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18216. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18217. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18218. return false;
  18219. }
  18220. // for collinear points p, q, r, check if point q lies on segment pr
  18221. function onSegment( p, q, r ) {
  18222. 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 );
  18223. }
  18224. function sign( num ) {
  18225. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  18226. }
  18227. // check if a polygon diagonal intersects any polygon segments
  18228. function intersectsPolygon( a, b ) {
  18229. let p = a;
  18230. do {
  18231. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  18232. intersects( p, p.next, a, b ) ) return true;
  18233. p = p.next;
  18234. } while ( p !== a );
  18235. return false;
  18236. }
  18237. // check if a polygon diagonal is locally inside the polygon
  18238. function locallyInside( a, b ) {
  18239. return area( a.prev, a, a.next ) < 0 ?
  18240. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  18241. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  18242. }
  18243. // check if the middle point of a polygon diagonal is inside the polygon
  18244. function middleInside( a, b ) {
  18245. let p = a,
  18246. inside = false;
  18247. const px = ( a.x + b.x ) / 2,
  18248. py = ( a.y + b.y ) / 2;
  18249. do {
  18250. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  18251. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  18252. inside = ! inside;
  18253. p = p.next;
  18254. } while ( p !== a );
  18255. return inside;
  18256. }
  18257. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18258. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18259. function splitPolygon( a, b ) {
  18260. const a2 = new Node( a.i, a.x, a.y ),
  18261. b2 = new Node( b.i, b.x, b.y ),
  18262. an = a.next,
  18263. bp = b.prev;
  18264. a.next = b;
  18265. b.prev = a;
  18266. a2.next = an;
  18267. an.prev = a2;
  18268. b2.next = a2;
  18269. a2.prev = b2;
  18270. bp.next = b2;
  18271. b2.prev = bp;
  18272. return b2;
  18273. }
  18274. // create a node and optionally link it with previous one (in a circular doubly linked list)
  18275. function insertNode( i, x, y, last ) {
  18276. const p = new Node( i, x, y );
  18277. if ( ! last ) {
  18278. p.prev = p;
  18279. p.next = p;
  18280. } else {
  18281. p.next = last.next;
  18282. p.prev = last;
  18283. last.next.prev = p;
  18284. last.next = p;
  18285. }
  18286. return p;
  18287. }
  18288. function removeNode( p ) {
  18289. p.next.prev = p.prev;
  18290. p.prev.next = p.next;
  18291. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  18292. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  18293. }
  18294. function Node( i, x, y ) {
  18295. // vertex index in coordinates array
  18296. this.i = i;
  18297. // vertex coordinates
  18298. this.x = x;
  18299. this.y = y;
  18300. // previous and next vertex nodes in a polygon ring
  18301. this.prev = null;
  18302. this.next = null;
  18303. // z-order curve value
  18304. this.z = null;
  18305. // previous and next nodes in z-order
  18306. this.prevZ = null;
  18307. this.nextZ = null;
  18308. // indicates whether this is a steiner point
  18309. this.steiner = false;
  18310. }
  18311. function signedArea( data, start, end, dim ) {
  18312. let sum = 0;
  18313. for ( let i = start, j = end - dim; i < end; i += dim ) {
  18314. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  18315. j = i;
  18316. }
  18317. return sum;
  18318. }
  18319. const ShapeUtils = {
  18320. // calculate area of the contour polygon
  18321. area: function ( contour ) {
  18322. const n = contour.length;
  18323. let a = 0.0;
  18324. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  18325. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  18326. }
  18327. return a * 0.5;
  18328. },
  18329. isClockWise: function ( pts ) {
  18330. return ShapeUtils.area( pts ) < 0;
  18331. },
  18332. triangulateShape: function ( contour, holes ) {
  18333. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18334. const holeIndices = []; // array of hole indices
  18335. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18336. removeDupEndPts( contour );
  18337. addContour( vertices, contour );
  18338. //
  18339. let holeIndex = contour.length;
  18340. holes.forEach( removeDupEndPts );
  18341. for ( let i = 0; i < holes.length; i ++ ) {
  18342. holeIndices.push( holeIndex );
  18343. holeIndex += holes[ i ].length;
  18344. addContour( vertices, holes[ i ] );
  18345. }
  18346. //
  18347. const triangles = Earcut.triangulate( vertices, holeIndices );
  18348. //
  18349. for ( let i = 0; i < triangles.length; i += 3 ) {
  18350. faces.push( triangles.slice( i, i + 3 ) );
  18351. }
  18352. return faces;
  18353. }
  18354. };
  18355. function removeDupEndPts( points ) {
  18356. const l = points.length;
  18357. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  18358. points.pop();
  18359. }
  18360. }
  18361. function addContour( vertices, contour ) {
  18362. for ( let i = 0; i < contour.length; i ++ ) {
  18363. vertices.push( contour[ i ].x );
  18364. vertices.push( contour[ i ].y );
  18365. }
  18366. }
  18367. /**
  18368. * Creates extruded geometry from a path shape.
  18369. *
  18370. * parameters = {
  18371. *
  18372. * curveSegments: <int>, // number of points on the curves
  18373. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18374. * depth: <float>, // Depth to extrude the shape
  18375. *
  18376. * bevelEnabled: <bool>, // turn on bevel
  18377. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18378. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18379. * bevelOffset: <float>, // how far from shape outline does bevel start
  18380. * bevelSegments: <int>, // number of bevel layers
  18381. *
  18382. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18383. *
  18384. * UVGenerator: <Object> // object that provides UV generator functions
  18385. *
  18386. * }
  18387. */
  18388. // ExtrudeGeometry
  18389. class ExtrudeGeometry extends Geometry {
  18390. constructor( shapes, options ) {
  18391. super();
  18392. this.type = 'ExtrudeGeometry';
  18393. this.parameters = {
  18394. shapes: shapes,
  18395. options: options
  18396. };
  18397. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  18398. this.mergeVertices();
  18399. }
  18400. toJSON() {
  18401. const data = super.toJSON();
  18402. const shapes = this.parameters.shapes;
  18403. const options = this.parameters.options;
  18404. return toJSON( shapes, options, data );
  18405. }
  18406. }
  18407. // ExtrudeBufferGeometry
  18408. class ExtrudeBufferGeometry extends BufferGeometry {
  18409. constructor( shapes, options ) {
  18410. super();
  18411. this.type = 'ExtrudeBufferGeometry';
  18412. this.parameters = {
  18413. shapes: shapes,
  18414. options: options
  18415. };
  18416. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18417. const scope = this;
  18418. const verticesArray = [];
  18419. const uvArray = [];
  18420. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18421. const shape = shapes[ i ];
  18422. addShape( shape );
  18423. }
  18424. // build geometry
  18425. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  18426. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  18427. this.computeVertexNormals();
  18428. // functions
  18429. function addShape( shape ) {
  18430. const placeholder = [];
  18431. // options
  18432. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18433. const steps = options.steps !== undefined ? options.steps : 1;
  18434. let depth = options.depth !== undefined ? options.depth : 100;
  18435. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18436. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18437. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18438. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18439. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18440. const extrudePath = options.extrudePath;
  18441. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  18442. // deprecated options
  18443. if ( options.amount !== undefined ) {
  18444. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  18445. depth = options.amount;
  18446. }
  18447. //
  18448. let extrudePts, extrudeByPath = false;
  18449. let splineTube, binormal, normal, position2;
  18450. if ( extrudePath ) {
  18451. extrudePts = extrudePath.getSpacedPoints( steps );
  18452. extrudeByPath = true;
  18453. bevelEnabled = false; // bevels not supported for path extrusion
  18454. // SETUP TNB variables
  18455. // TODO1 - have a .isClosed in spline?
  18456. splineTube = extrudePath.computeFrenetFrames( steps, false );
  18457. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18458. binormal = new Vector3();
  18459. normal = new Vector3();
  18460. position2 = new Vector3();
  18461. }
  18462. // Safeguards if bevels are not enabled
  18463. if ( ! bevelEnabled ) {
  18464. bevelSegments = 0;
  18465. bevelThickness = 0;
  18466. bevelSize = 0;
  18467. bevelOffset = 0;
  18468. }
  18469. // Variables initialization
  18470. const shapePoints = shape.extractPoints( curveSegments );
  18471. let vertices = shapePoints.shape;
  18472. const holes = shapePoints.holes;
  18473. const reverse = ! ShapeUtils.isClockWise( vertices );
  18474. if ( reverse ) {
  18475. vertices = vertices.reverse();
  18476. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18477. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18478. const ahole = holes[ h ];
  18479. if ( ShapeUtils.isClockWise( ahole ) ) {
  18480. holes[ h ] = ahole.reverse();
  18481. }
  18482. }
  18483. }
  18484. const faces = ShapeUtils.triangulateShape( vertices, holes );
  18485. /* Vertices */
  18486. const contour = vertices; // vertices has all points but contour has only points of circumference
  18487. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18488. const ahole = holes[ h ];
  18489. vertices = vertices.concat( ahole );
  18490. }
  18491. function scalePt2( pt, vec, size ) {
  18492. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18493. return vec.clone().multiplyScalar( size ).add( pt );
  18494. }
  18495. const vlen = vertices.length, flen = faces.length;
  18496. // Find directions for point movement
  18497. function getBevelVec( inPt, inPrev, inNext ) {
  18498. // computes for inPt the corresponding point inPt' on a new contour
  18499. // shifted by 1 unit (length of normalized vector) to the left
  18500. // if we walk along contour clockwise, this new contour is outside the old one
  18501. //
  18502. // inPt' is the intersection of the two lines parallel to the two
  18503. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18504. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18505. // good reading for geometry algorithms (here: line-line intersection)
  18506. // http://geomalgorithms.com/a05-_intersect-1.html
  18507. const v_prev_x = inPt.x - inPrev.x,
  18508. v_prev_y = inPt.y - inPrev.y;
  18509. const v_next_x = inNext.x - inPt.x,
  18510. v_next_y = inNext.y - inPt.y;
  18511. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18512. // check for collinear edges
  18513. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18514. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  18515. // not collinear
  18516. // length of vectors for normalizing
  18517. const v_prev_len = Math.sqrt( v_prev_lensq );
  18518. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18519. // shift adjacent points by unit vectors to the left
  18520. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18521. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18522. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18523. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18524. // scaling factor for v_prev to intersection point
  18525. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18526. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18527. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18528. // vector from inPt to intersection point
  18529. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18530. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18531. // Don't normalize!, otherwise sharp corners become ugly
  18532. // but prevent crazy spikes
  18533. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18534. if ( v_trans_lensq <= 2 ) {
  18535. return new Vector2( v_trans_x, v_trans_y );
  18536. } else {
  18537. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18538. }
  18539. } else {
  18540. // handle special case of collinear edges
  18541. let direction_eq = false; // assumes: opposite
  18542. if ( v_prev_x > Number.EPSILON ) {
  18543. if ( v_next_x > Number.EPSILON ) {
  18544. direction_eq = true;
  18545. }
  18546. } else {
  18547. if ( v_prev_x < - Number.EPSILON ) {
  18548. if ( v_next_x < - Number.EPSILON ) {
  18549. direction_eq = true;
  18550. }
  18551. } else {
  18552. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  18553. direction_eq = true;
  18554. }
  18555. }
  18556. }
  18557. if ( direction_eq ) {
  18558. // console.log("Warning: lines are a straight sequence");
  18559. v_trans_x = - v_prev_y;
  18560. v_trans_y = v_prev_x;
  18561. shrink_by = Math.sqrt( v_prev_lensq );
  18562. } else {
  18563. // console.log("Warning: lines are a straight spike");
  18564. v_trans_x = v_prev_x;
  18565. v_trans_y = v_prev_y;
  18566. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18567. }
  18568. }
  18569. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18570. }
  18571. const contourMovements = [];
  18572. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18573. if ( j === il ) j = 0;
  18574. if ( k === il ) k = 0;
  18575. // (j)---(i)---(k)
  18576. // console.log('i,j,k', i, j , k)
  18577. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18578. }
  18579. const holesMovements = [];
  18580. let oneHoleMovements, verticesMovements = contourMovements.concat();
  18581. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18582. const ahole = holes[ h ];
  18583. oneHoleMovements = [];
  18584. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18585. if ( j === il ) j = 0;
  18586. if ( k === il ) k = 0;
  18587. // (j)---(i)---(k)
  18588. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18589. }
  18590. holesMovements.push( oneHoleMovements );
  18591. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18592. }
  18593. // Loop bevelSegments, 1 for the front, 1 for the back
  18594. for ( let b = 0; b < bevelSegments; b ++ ) {
  18595. //for ( b = bevelSegments; b > 0; b -- ) {
  18596. const t = b / bevelSegments;
  18597. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18598. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  18599. // contract shape
  18600. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  18601. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18602. v( vert.x, vert.y, - z );
  18603. }
  18604. // expand holes
  18605. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18606. const ahole = holes[ h ];
  18607. oneHoleMovements = holesMovements[ h ];
  18608. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  18609. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18610. v( vert.x, vert.y, - z );
  18611. }
  18612. }
  18613. }
  18614. const bs = bevelSize + bevelOffset;
  18615. // Back facing vertices
  18616. for ( let i = 0; i < vlen; i ++ ) {
  18617. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18618. if ( ! extrudeByPath ) {
  18619. v( vert.x, vert.y, 0 );
  18620. } else {
  18621. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18622. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  18623. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  18624. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  18625. v( position2.x, position2.y, position2.z );
  18626. }
  18627. }
  18628. // Add stepped vertices...
  18629. // Including front facing vertices
  18630. for ( let s = 1; s <= steps; s ++ ) {
  18631. for ( let i = 0; i < vlen; i ++ ) {
  18632. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18633. if ( ! extrudeByPath ) {
  18634. v( vert.x, vert.y, depth / steps * s );
  18635. } else {
  18636. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18637. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  18638. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  18639. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  18640. v( position2.x, position2.y, position2.z );
  18641. }
  18642. }
  18643. }
  18644. // Add bevel segments planes
  18645. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18646. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  18647. const t = b / bevelSegments;
  18648. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18649. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  18650. // contract shape
  18651. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  18652. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18653. v( vert.x, vert.y, depth + z );
  18654. }
  18655. // expand holes
  18656. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18657. const ahole = holes[ h ];
  18658. oneHoleMovements = holesMovements[ h ];
  18659. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  18660. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18661. if ( ! extrudeByPath ) {
  18662. v( vert.x, vert.y, depth + z );
  18663. } else {
  18664. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18665. }
  18666. }
  18667. }
  18668. }
  18669. /* Faces */
  18670. // Top and bottom faces
  18671. buildLidFaces();
  18672. // Sides faces
  18673. buildSideFaces();
  18674. ///// Internal functions
  18675. function buildLidFaces() {
  18676. const start = verticesArray.length / 3;
  18677. if ( bevelEnabled ) {
  18678. let layer = 0; // steps + 1
  18679. let offset = vlen * layer;
  18680. // Bottom faces
  18681. for ( let i = 0; i < flen; i ++ ) {
  18682. const face = faces[ i ];
  18683. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18684. }
  18685. layer = steps + bevelSegments * 2;
  18686. offset = vlen * layer;
  18687. // Top faces
  18688. for ( let i = 0; i < flen; i ++ ) {
  18689. const face = faces[ i ];
  18690. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18691. }
  18692. } else {
  18693. // Bottom faces
  18694. for ( let i = 0; i < flen; i ++ ) {
  18695. const face = faces[ i ];
  18696. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18697. }
  18698. // Top faces
  18699. for ( let i = 0; i < flen; i ++ ) {
  18700. const face = faces[ i ];
  18701. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18702. }
  18703. }
  18704. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  18705. }
  18706. // Create faces for the z-sides of the shape
  18707. function buildSideFaces() {
  18708. const start = verticesArray.length / 3;
  18709. let layeroffset = 0;
  18710. sidewalls( contour, layeroffset );
  18711. layeroffset += contour.length;
  18712. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18713. const ahole = holes[ h ];
  18714. sidewalls( ahole, layeroffset );
  18715. //, true
  18716. layeroffset += ahole.length;
  18717. }
  18718. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  18719. }
  18720. function sidewalls( contour, layeroffset ) {
  18721. let i = contour.length;
  18722. while ( -- i >= 0 ) {
  18723. const j = i;
  18724. let k = i - 1;
  18725. if ( k < 0 ) k = contour.length - 1;
  18726. //console.log('b', i,j, i-1, k,vertices.length);
  18727. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  18728. const slen1 = vlen * s;
  18729. const slen2 = vlen * ( s + 1 );
  18730. const a = layeroffset + j + slen1,
  18731. b = layeroffset + k + slen1,
  18732. c = layeroffset + k + slen2,
  18733. d = layeroffset + j + slen2;
  18734. f4( a, b, c, d );
  18735. }
  18736. }
  18737. }
  18738. function v( x, y, z ) {
  18739. placeholder.push( x );
  18740. placeholder.push( y );
  18741. placeholder.push( z );
  18742. }
  18743. function f3( a, b, c ) {
  18744. addVertex( a );
  18745. addVertex( b );
  18746. addVertex( c );
  18747. const nextIndex = verticesArray.length / 3;
  18748. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  18749. addUV( uvs[ 0 ] );
  18750. addUV( uvs[ 1 ] );
  18751. addUV( uvs[ 2 ] );
  18752. }
  18753. function f4( a, b, c, d ) {
  18754. addVertex( a );
  18755. addVertex( b );
  18756. addVertex( d );
  18757. addVertex( b );
  18758. addVertex( c );
  18759. addVertex( d );
  18760. const nextIndex = verticesArray.length / 3;
  18761. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  18762. addUV( uvs[ 0 ] );
  18763. addUV( uvs[ 1 ] );
  18764. addUV( uvs[ 3 ] );
  18765. addUV( uvs[ 1 ] );
  18766. addUV( uvs[ 2 ] );
  18767. addUV( uvs[ 3 ] );
  18768. }
  18769. function addVertex( index ) {
  18770. verticesArray.push( placeholder[ index * 3 + 0 ] );
  18771. verticesArray.push( placeholder[ index * 3 + 1 ] );
  18772. verticesArray.push( placeholder[ index * 3 + 2 ] );
  18773. }
  18774. function addUV( vector2 ) {
  18775. uvArray.push( vector2.x );
  18776. uvArray.push( vector2.y );
  18777. }
  18778. }
  18779. }
  18780. toJSON() {
  18781. const data = BufferGeometry.prototype.toJSON.call( this );
  18782. const shapes = this.parameters.shapes;
  18783. const options = this.parameters.options;
  18784. return toJSON( shapes, options, data );
  18785. }
  18786. }
  18787. const WorldUVGenerator = {
  18788. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  18789. const a_x = vertices[ indexA * 3 ];
  18790. const a_y = vertices[ indexA * 3 + 1 ];
  18791. const b_x = vertices[ indexB * 3 ];
  18792. const b_y = vertices[ indexB * 3 + 1 ];
  18793. const c_x = vertices[ indexC * 3 ];
  18794. const c_y = vertices[ indexC * 3 + 1 ];
  18795. return [
  18796. new Vector2( a_x, a_y ),
  18797. new Vector2( b_x, b_y ),
  18798. new Vector2( c_x, c_y )
  18799. ];
  18800. },
  18801. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  18802. const a_x = vertices[ indexA * 3 ];
  18803. const a_y = vertices[ indexA * 3 + 1 ];
  18804. const a_z = vertices[ indexA * 3 + 2 ];
  18805. const b_x = vertices[ indexB * 3 ];
  18806. const b_y = vertices[ indexB * 3 + 1 ];
  18807. const b_z = vertices[ indexB * 3 + 2 ];
  18808. const c_x = vertices[ indexC * 3 ];
  18809. const c_y = vertices[ indexC * 3 + 1 ];
  18810. const c_z = vertices[ indexC * 3 + 2 ];
  18811. const d_x = vertices[ indexD * 3 ];
  18812. const d_y = vertices[ indexD * 3 + 1 ];
  18813. const d_z = vertices[ indexD * 3 + 2 ];
  18814. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  18815. return [
  18816. new Vector2( a_x, 1 - a_z ),
  18817. new Vector2( b_x, 1 - b_z ),
  18818. new Vector2( c_x, 1 - c_z ),
  18819. new Vector2( d_x, 1 - d_z )
  18820. ];
  18821. } else {
  18822. return [
  18823. new Vector2( a_y, 1 - a_z ),
  18824. new Vector2( b_y, 1 - b_z ),
  18825. new Vector2( c_y, 1 - c_z ),
  18826. new Vector2( d_y, 1 - d_z )
  18827. ];
  18828. }
  18829. }
  18830. };
  18831. function toJSON( shapes, options, data ) {
  18832. data.shapes = [];
  18833. if ( Array.isArray( shapes ) ) {
  18834. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18835. const shape = shapes[ i ];
  18836. data.shapes.push( shape.uuid );
  18837. }
  18838. } else {
  18839. data.shapes.push( shapes.uuid );
  18840. }
  18841. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  18842. return data;
  18843. }
  18844. /**
  18845. * Text = 3D Text
  18846. *
  18847. * parameters = {
  18848. * font: <THREE.Font>, // font
  18849. *
  18850. * size: <float>, // size of the text
  18851. * height: <float>, // thickness to extrude text
  18852. * curveSegments: <int>, // number of points on the curves
  18853. *
  18854. * bevelEnabled: <bool>, // turn on bevel
  18855. * bevelThickness: <float>, // how deep into text bevel goes
  18856. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18857. * bevelOffset: <float> // how far from text outline does bevel start
  18858. * }
  18859. */
  18860. // TextGeometry
  18861. class TextGeometry extends Geometry {
  18862. constructor( text, parameters ) {
  18863. super();
  18864. this.type = 'TextGeometry';
  18865. this.parameters = {
  18866. text: text,
  18867. parameters: parameters
  18868. };
  18869. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  18870. this.mergeVertices();
  18871. }
  18872. }
  18873. // TextBufferGeometry
  18874. class TextBufferGeometry extends ExtrudeBufferGeometry {
  18875. constructor( text, parameters ) {
  18876. parameters = parameters || {};
  18877. const font = parameters.font;
  18878. if ( ! ( font && font.isFont ) ) {
  18879. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  18880. return new Geometry();
  18881. }
  18882. const shapes = font.generateShapes( text, parameters.size );
  18883. // translate parameters to ExtrudeGeometry API
  18884. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  18885. // defaults
  18886. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18887. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18888. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18889. super( shapes, parameters );
  18890. this.type = 'TextBufferGeometry';
  18891. }
  18892. }
  18893. // SphereGeometry
  18894. class SphereGeometry extends Geometry {
  18895. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18896. super();
  18897. this.type = 'SphereGeometry';
  18898. this.parameters = {
  18899. radius: radius,
  18900. widthSegments: widthSegments,
  18901. heightSegments: heightSegments,
  18902. phiStart: phiStart,
  18903. phiLength: phiLength,
  18904. thetaStart: thetaStart,
  18905. thetaLength: thetaLength
  18906. };
  18907. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  18908. this.mergeVertices();
  18909. }
  18910. }
  18911. // SphereBufferGeometry
  18912. class SphereBufferGeometry extends BufferGeometry {
  18913. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18914. super();
  18915. this.type = 'SphereBufferGeometry';
  18916. this.parameters = {
  18917. radius: radius,
  18918. widthSegments: widthSegments,
  18919. heightSegments: heightSegments,
  18920. phiStart: phiStart,
  18921. phiLength: phiLength,
  18922. thetaStart: thetaStart,
  18923. thetaLength: thetaLength
  18924. };
  18925. radius = radius || 1;
  18926. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18927. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18928. phiStart = phiStart !== undefined ? phiStart : 0;
  18929. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18930. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18931. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18932. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  18933. let index = 0;
  18934. const grid = [];
  18935. const vertex = new Vector3();
  18936. const normal = new Vector3();
  18937. // buffers
  18938. const indices = [];
  18939. const vertices = [];
  18940. const normals = [];
  18941. const uvs = [];
  18942. // generate vertices, normals and uvs
  18943. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  18944. const verticesRow = [];
  18945. const v = iy / heightSegments;
  18946. // special case for the poles
  18947. let uOffset = 0;
  18948. if ( iy == 0 && thetaStart == 0 ) {
  18949. uOffset = 0.5 / widthSegments;
  18950. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  18951. uOffset = - 0.5 / widthSegments;
  18952. }
  18953. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  18954. const u = ix / widthSegments;
  18955. // vertex
  18956. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18957. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18958. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18959. vertices.push( vertex.x, vertex.y, vertex.z );
  18960. // normal
  18961. normal.copy( vertex ).normalize();
  18962. normals.push( normal.x, normal.y, normal.z );
  18963. // uv
  18964. uvs.push( u + uOffset, 1 - v );
  18965. verticesRow.push( index ++ );
  18966. }
  18967. grid.push( verticesRow );
  18968. }
  18969. // indices
  18970. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  18971. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  18972. const a = grid[ iy ][ ix + 1 ];
  18973. const b = grid[ iy ][ ix ];
  18974. const c = grid[ iy + 1 ][ ix ];
  18975. const d = grid[ iy + 1 ][ ix + 1 ];
  18976. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  18977. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  18978. }
  18979. }
  18980. // build geometry
  18981. this.setIndex( indices );
  18982. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18983. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18984. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18985. }
  18986. }
  18987. // RingGeometry
  18988. class RingGeometry extends Geometry {
  18989. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  18990. super();
  18991. this.type = 'RingGeometry';
  18992. this.parameters = {
  18993. innerRadius: innerRadius,
  18994. outerRadius: outerRadius,
  18995. thetaSegments: thetaSegments,
  18996. phiSegments: phiSegments,
  18997. thetaStart: thetaStart,
  18998. thetaLength: thetaLength
  18999. };
  19000. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  19001. this.mergeVertices();
  19002. }
  19003. }
  19004. // RingBufferGeometry
  19005. class RingBufferGeometry extends BufferGeometry {
  19006. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19007. super();
  19008. this.type = 'RingBufferGeometry';
  19009. this.parameters = {
  19010. innerRadius: innerRadius,
  19011. outerRadius: outerRadius,
  19012. thetaSegments: thetaSegments,
  19013. phiSegments: phiSegments,
  19014. thetaStart: thetaStart,
  19015. thetaLength: thetaLength
  19016. };
  19017. innerRadius = innerRadius || 0.5;
  19018. outerRadius = outerRadius || 1;
  19019. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19020. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19021. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19022. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  19023. // buffers
  19024. const indices = [];
  19025. const vertices = [];
  19026. const normals = [];
  19027. const uvs = [];
  19028. // some helper variables
  19029. let radius = innerRadius;
  19030. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19031. const vertex = new Vector3();
  19032. const uv = new Vector2();
  19033. // generate vertices, normals and uvs
  19034. for ( let j = 0; j <= phiSegments; j ++ ) {
  19035. for ( let i = 0; i <= thetaSegments; i ++ ) {
  19036. // values are generate from the inside of the ring to the outside
  19037. const segment = thetaStart + i / thetaSegments * thetaLength;
  19038. // vertex
  19039. vertex.x = radius * Math.cos( segment );
  19040. vertex.y = radius * Math.sin( segment );
  19041. vertices.push( vertex.x, vertex.y, vertex.z );
  19042. // normal
  19043. normals.push( 0, 0, 1 );
  19044. // uv
  19045. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  19046. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  19047. uvs.push( uv.x, uv.y );
  19048. }
  19049. // increase the radius for next row of vertices
  19050. radius += radiusStep;
  19051. }
  19052. // indices
  19053. for ( let j = 0; j < phiSegments; j ++ ) {
  19054. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  19055. for ( let i = 0; i < thetaSegments; i ++ ) {
  19056. const segment = i + thetaSegmentLevel;
  19057. const a = segment;
  19058. const b = segment + thetaSegments + 1;
  19059. const c = segment + thetaSegments + 2;
  19060. const d = segment + 1;
  19061. // faces
  19062. indices.push( a, b, d );
  19063. indices.push( b, c, d );
  19064. }
  19065. }
  19066. // build geometry
  19067. this.setIndex( indices );
  19068. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19069. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19070. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19071. }
  19072. }
  19073. // LatheGeometry
  19074. class LatheGeometry extends Geometry {
  19075. constructor( points, segments, phiStart, phiLength ) {
  19076. super();
  19077. this.type = 'LatheGeometry';
  19078. this.parameters = {
  19079. points: points,
  19080. segments: segments,
  19081. phiStart: phiStart,
  19082. phiLength: phiLength
  19083. };
  19084. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  19085. this.mergeVertices();
  19086. }
  19087. }
  19088. // LatheBufferGeometry
  19089. class LatheBufferGeometry extends BufferGeometry {
  19090. constructor( points, segments, phiStart, phiLength ) {
  19091. super();
  19092. this.type = 'LatheBufferGeometry';
  19093. this.parameters = {
  19094. points: points,
  19095. segments: segments,
  19096. phiStart: phiStart,
  19097. phiLength: phiLength
  19098. };
  19099. segments = Math.floor( segments ) || 12;
  19100. phiStart = phiStart || 0;
  19101. phiLength = phiLength || Math.PI * 2;
  19102. // clamp phiLength so it's in range of [ 0, 2PI ]
  19103. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  19104. // buffers
  19105. const indices = [];
  19106. const vertices = [];
  19107. const uvs = [];
  19108. // helper variables
  19109. const inverseSegments = 1.0 / segments;
  19110. const vertex = new Vector3();
  19111. const uv = new Vector2();
  19112. // generate vertices and uvs
  19113. for ( let i = 0; i <= segments; i ++ ) {
  19114. const phi = phiStart + i * inverseSegments * phiLength;
  19115. const sin = Math.sin( phi );
  19116. const cos = Math.cos( phi );
  19117. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19118. // vertex
  19119. vertex.x = points[ j ].x * sin;
  19120. vertex.y = points[ j ].y;
  19121. vertex.z = points[ j ].x * cos;
  19122. vertices.push( vertex.x, vertex.y, vertex.z );
  19123. // uv
  19124. uv.x = i / segments;
  19125. uv.y = j / ( points.length - 1 );
  19126. uvs.push( uv.x, uv.y );
  19127. }
  19128. }
  19129. // indices
  19130. for ( let i = 0; i < segments; i ++ ) {
  19131. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19132. const base = j + i * points.length;
  19133. const a = base;
  19134. const b = base + points.length;
  19135. const c = base + points.length + 1;
  19136. const d = base + 1;
  19137. // faces
  19138. indices.push( a, b, d );
  19139. indices.push( b, c, d );
  19140. }
  19141. }
  19142. // build geometry
  19143. this.setIndex( indices );
  19144. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19145. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19146. // generate normals
  19147. this.computeVertexNormals();
  19148. // if the geometry is closed, we need to average the normals along the seam.
  19149. // because the corresponding vertices are identical (but still have different UVs).
  19150. if ( phiLength === Math.PI * 2 ) {
  19151. const normals = this.attributes.normal.array;
  19152. const n1 = new Vector3();
  19153. const n2 = new Vector3();
  19154. const n = new Vector3();
  19155. // this is the buffer offset for the last line of vertices
  19156. const base = segments * points.length * 3;
  19157. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  19158. // select the normal of the vertex in the first line
  19159. n1.x = normals[ j + 0 ];
  19160. n1.y = normals[ j + 1 ];
  19161. n1.z = normals[ j + 2 ];
  19162. // select the normal of the vertex in the last line
  19163. n2.x = normals[ base + j + 0 ];
  19164. n2.y = normals[ base + j + 1 ];
  19165. n2.z = normals[ base + j + 2 ];
  19166. // average normals
  19167. n.addVectors( n1, n2 ).normalize();
  19168. // assign the new values to both normals
  19169. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  19170. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  19171. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  19172. }
  19173. }
  19174. }
  19175. }
  19176. // ShapeGeometry
  19177. class ShapeGeometry extends Geometry {
  19178. constructor( shapes, curveSegments ) {
  19179. super();
  19180. this.type = 'ShapeGeometry';
  19181. if ( typeof curveSegments === 'object' ) {
  19182. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  19183. curveSegments = curveSegments.curveSegments;
  19184. }
  19185. this.parameters = {
  19186. shapes: shapes,
  19187. curveSegments: curveSegments
  19188. };
  19189. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  19190. this.mergeVertices();
  19191. }
  19192. toJSON() {
  19193. const data = Geometry.prototype.toJSON.call( this );
  19194. const shapes = this.parameters.shapes;
  19195. return toJSON$1( shapes, data );
  19196. }
  19197. }
  19198. // ShapeBufferGeometry
  19199. class ShapeBufferGeometry extends BufferGeometry {
  19200. constructor( shapes, curveSegments ) {
  19201. super();
  19202. this.type = 'ShapeBufferGeometry';
  19203. this.parameters = {
  19204. shapes: shapes,
  19205. curveSegments: curveSegments
  19206. };
  19207. curveSegments = curveSegments || 12;
  19208. // buffers
  19209. const indices = [];
  19210. const vertices = [];
  19211. const normals = [];
  19212. const uvs = [];
  19213. // helper variables
  19214. let groupStart = 0;
  19215. let groupCount = 0;
  19216. // allow single and array values for "shapes" parameter
  19217. if ( Array.isArray( shapes ) === false ) {
  19218. addShape( shapes );
  19219. } else {
  19220. for ( let i = 0; i < shapes.length; i ++ ) {
  19221. addShape( shapes[ i ] );
  19222. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  19223. groupStart += groupCount;
  19224. groupCount = 0;
  19225. }
  19226. }
  19227. // build geometry
  19228. this.setIndex( indices );
  19229. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19230. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19231. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19232. // helper functions
  19233. function addShape( shape ) {
  19234. const indexOffset = vertices.length / 3;
  19235. const points = shape.extractPoints( curveSegments );
  19236. let shapeVertices = points.shape;
  19237. const shapeHoles = points.holes;
  19238. // check direction of vertices
  19239. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  19240. shapeVertices = shapeVertices.reverse();
  19241. }
  19242. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19243. const shapeHole = shapeHoles[ i ];
  19244. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  19245. shapeHoles[ i ] = shapeHole.reverse();
  19246. }
  19247. }
  19248. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  19249. // join vertices of inner and outer paths to a single array
  19250. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19251. const shapeHole = shapeHoles[ i ];
  19252. shapeVertices = shapeVertices.concat( shapeHole );
  19253. }
  19254. // vertices, normals, uvs
  19255. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  19256. const vertex = shapeVertices[ i ];
  19257. vertices.push( vertex.x, vertex.y, 0 );
  19258. normals.push( 0, 0, 1 );
  19259. uvs.push( vertex.x, vertex.y ); // world uvs
  19260. }
  19261. // incides
  19262. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  19263. const face = faces[ i ];
  19264. const a = face[ 0 ] + indexOffset;
  19265. const b = face[ 1 ] + indexOffset;
  19266. const c = face[ 2 ] + indexOffset;
  19267. indices.push( a, b, c );
  19268. groupCount += 3;
  19269. }
  19270. }
  19271. }
  19272. toJSON() {
  19273. const data = BufferGeometry.prototype.toJSON.call( this );
  19274. const shapes = this.parameters.shapes;
  19275. return toJSON$1( shapes, data );
  19276. }
  19277. }
  19278. //
  19279. function toJSON$1( shapes, data ) {
  19280. data.shapes = [];
  19281. if ( Array.isArray( shapes ) ) {
  19282. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19283. const shape = shapes[ i ];
  19284. data.shapes.push( shape.uuid );
  19285. }
  19286. } else {
  19287. data.shapes.push( shapes.uuid );
  19288. }
  19289. return data;
  19290. }
  19291. const _v0$2 = new Vector3();
  19292. const _v1$5 = new Vector3();
  19293. const _normal$1 = new Vector3();
  19294. const _triangle = new Triangle();
  19295. class EdgesGeometry extends BufferGeometry {
  19296. constructor( geometry, thresholdAngle ) {
  19297. super();
  19298. this.type = 'EdgesGeometry';
  19299. this.parameters = {
  19300. thresholdAngle: thresholdAngle
  19301. };
  19302. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  19303. if ( geometry.isGeometry ) {
  19304. geometry = new BufferGeometry().fromGeometry( geometry );
  19305. }
  19306. const precisionPoints = 4;
  19307. const precision = Math.pow( 10, precisionPoints );
  19308. const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  19309. const indexAttr = geometry.getIndex();
  19310. const positionAttr = geometry.getAttribute( 'position' );
  19311. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19312. const indexArr = [ 0, 0, 0 ];
  19313. const vertKeys = [ 'a', 'b', 'c' ];
  19314. const hashes = new Array( 3 );
  19315. const edgeData = {};
  19316. const vertices = [];
  19317. for ( let i = 0; i < indexCount; i += 3 ) {
  19318. if ( indexAttr ) {
  19319. indexArr[ 0 ] = indexAttr.getX( i );
  19320. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  19321. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  19322. } else {
  19323. indexArr[ 0 ] = i;
  19324. indexArr[ 1 ] = i + 1;
  19325. indexArr[ 2 ] = i + 2;
  19326. }
  19327. const { a, b, c } = _triangle;
  19328. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  19329. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  19330. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  19331. _triangle.getNormal( _normal$1 );
  19332. // create hashes for the edge from the vertices
  19333. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  19334. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  19335. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  19336. // skip degenerate triangles
  19337. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  19338. continue;
  19339. }
  19340. // iterate over every edge
  19341. for ( let j = 0; j < 3; j ++ ) {
  19342. // get the first and next vertex making up the edge
  19343. const jNext = ( j + 1 ) % 3;
  19344. const vecHash0 = hashes[ j ];
  19345. const vecHash1 = hashes[ jNext ];
  19346. const v0 = _triangle[ vertKeys[ j ] ];
  19347. const v1 = _triangle[ vertKeys[ jNext ] ];
  19348. const hash = `${ vecHash0 }_${ vecHash1 }`;
  19349. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  19350. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  19351. // if we found a sibling edge add it into the vertex array if
  19352. // it meets the angle threshold and delete the edge from the map.
  19353. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  19354. vertices.push( v0.x, v0.y, v0.z );
  19355. vertices.push( v1.x, v1.y, v1.z );
  19356. }
  19357. edgeData[ reverseHash ] = null;
  19358. } else if ( ! ( hash in edgeData ) ) {
  19359. // if we've already got an edge here then skip adding a new one
  19360. edgeData[ hash ] = {
  19361. index0: indexArr[ j ],
  19362. index1: indexArr[ jNext ],
  19363. normal: _normal$1.clone(),
  19364. };
  19365. }
  19366. }
  19367. }
  19368. // iterate over all remaining, unmatched edges and add them to the vertex array
  19369. for ( const key in edgeData ) {
  19370. if ( edgeData[ key ] ) {
  19371. const { index0, index1 } = edgeData[ key ];
  19372. _v0$2.fromBufferAttribute( positionAttr, index0 );
  19373. _v1$5.fromBufferAttribute( positionAttr, index1 );
  19374. vertices.push( _v0$2.x, _v0$2.y, _v0$2.z );
  19375. vertices.push( _v1$5.x, _v1$5.y, _v1$5.z );
  19376. }
  19377. }
  19378. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19379. }
  19380. }
  19381. // CylinderGeometry
  19382. class CylinderGeometry extends Geometry {
  19383. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  19384. super();
  19385. this.type = 'CylinderGeometry';
  19386. this.parameters = {
  19387. radiusTop: radiusTop,
  19388. radiusBottom: radiusBottom,
  19389. height: height,
  19390. radialSegments: radialSegments,
  19391. heightSegments: heightSegments,
  19392. openEnded: openEnded,
  19393. thetaStart: thetaStart,
  19394. thetaLength: thetaLength
  19395. };
  19396. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  19397. this.mergeVertices();
  19398. }
  19399. }
  19400. // CylinderBufferGeometry
  19401. class CylinderBufferGeometry extends BufferGeometry {
  19402. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  19403. super();
  19404. this.type = 'CylinderBufferGeometry';
  19405. this.parameters = {
  19406. radiusTop: radiusTop,
  19407. radiusBottom: radiusBottom,
  19408. height: height,
  19409. radialSegments: radialSegments,
  19410. heightSegments: heightSegments,
  19411. openEnded: openEnded,
  19412. thetaStart: thetaStart,
  19413. thetaLength: thetaLength
  19414. };
  19415. const scope = this;
  19416. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  19417. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  19418. height = height || 1;
  19419. radialSegments = Math.floor( radialSegments ) || 8;
  19420. heightSegments = Math.floor( heightSegments ) || 1;
  19421. openEnded = openEnded !== undefined ? openEnded : false;
  19422. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19423. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19424. // buffers
  19425. const indices = [];
  19426. const vertices = [];
  19427. const normals = [];
  19428. const uvs = [];
  19429. // helper variables
  19430. let index = 0;
  19431. const indexArray = [];
  19432. const halfHeight = height / 2;
  19433. let groupStart = 0;
  19434. // generate geometry
  19435. generateTorso();
  19436. if ( openEnded === false ) {
  19437. if ( radiusTop > 0 ) generateCap( true );
  19438. if ( radiusBottom > 0 ) generateCap( false );
  19439. }
  19440. // build geometry
  19441. this.setIndex( indices );
  19442. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19443. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19444. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19445. function generateTorso() {
  19446. const normal = new Vector3();
  19447. const vertex = new Vector3();
  19448. let groupCount = 0;
  19449. // this will be used to calculate the normal
  19450. const slope = ( radiusBottom - radiusTop ) / height;
  19451. // generate vertices, normals and uvs
  19452. for ( let y = 0; y <= heightSegments; y ++ ) {
  19453. const indexRow = [];
  19454. const v = y / heightSegments;
  19455. // calculate the radius of the current row
  19456. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19457. for ( let x = 0; x <= radialSegments; x ++ ) {
  19458. const u = x / radialSegments;
  19459. const theta = u * thetaLength + thetaStart;
  19460. const sinTheta = Math.sin( theta );
  19461. const cosTheta = Math.cos( theta );
  19462. // vertex
  19463. vertex.x = radius * sinTheta;
  19464. vertex.y = - v * height + halfHeight;
  19465. vertex.z = radius * cosTheta;
  19466. vertices.push( vertex.x, vertex.y, vertex.z );
  19467. // normal
  19468. normal.set( sinTheta, slope, cosTheta ).normalize();
  19469. normals.push( normal.x, normal.y, normal.z );
  19470. // uv
  19471. uvs.push( u, 1 - v );
  19472. // save index of vertex in respective row
  19473. indexRow.push( index ++ );
  19474. }
  19475. // now save vertices of the row in our index array
  19476. indexArray.push( indexRow );
  19477. }
  19478. // generate indices
  19479. for ( let x = 0; x < radialSegments; x ++ ) {
  19480. for ( let y = 0; y < heightSegments; y ++ ) {
  19481. // we use the index array to access the correct indices
  19482. const a = indexArray[ y ][ x ];
  19483. const b = indexArray[ y + 1 ][ x ];
  19484. const c = indexArray[ y + 1 ][ x + 1 ];
  19485. const d = indexArray[ y ][ x + 1 ];
  19486. // faces
  19487. indices.push( a, b, d );
  19488. indices.push( b, c, d );
  19489. // update group counter
  19490. groupCount += 6;
  19491. }
  19492. }
  19493. // add a group to the geometry. this will ensure multi material support
  19494. scope.addGroup( groupStart, groupCount, 0 );
  19495. // calculate new start value for groups
  19496. groupStart += groupCount;
  19497. }
  19498. function generateCap( top ) {
  19499. // save the index of the first center vertex
  19500. const centerIndexStart = index;
  19501. const uv = new Vector2();
  19502. const vertex = new Vector3();
  19503. let groupCount = 0;
  19504. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19505. const sign = ( top === true ) ? 1 : - 1;
  19506. // first we generate the center vertex data of the cap.
  19507. // because the geometry needs one set of uvs per face,
  19508. // we must generate a center vertex per face/segment
  19509. for ( let x = 1; x <= radialSegments; x ++ ) {
  19510. // vertex
  19511. vertices.push( 0, halfHeight * sign, 0 );
  19512. // normal
  19513. normals.push( 0, sign, 0 );
  19514. // uv
  19515. uvs.push( 0.5, 0.5 );
  19516. // increase index
  19517. index ++;
  19518. }
  19519. // save the index of the last center vertex
  19520. const centerIndexEnd = index;
  19521. // now we generate the surrounding vertices, normals and uvs
  19522. for ( let x = 0; x <= radialSegments; x ++ ) {
  19523. const u = x / radialSegments;
  19524. const theta = u * thetaLength + thetaStart;
  19525. const cosTheta = Math.cos( theta );
  19526. const sinTheta = Math.sin( theta );
  19527. // vertex
  19528. vertex.x = radius * sinTheta;
  19529. vertex.y = halfHeight * sign;
  19530. vertex.z = radius * cosTheta;
  19531. vertices.push( vertex.x, vertex.y, vertex.z );
  19532. // normal
  19533. normals.push( 0, sign, 0 );
  19534. // uv
  19535. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19536. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19537. uvs.push( uv.x, uv.y );
  19538. // increase index
  19539. index ++;
  19540. }
  19541. // generate indices
  19542. for ( let x = 0; x < radialSegments; x ++ ) {
  19543. const c = centerIndexStart + x;
  19544. const i = centerIndexEnd + x;
  19545. if ( top === true ) {
  19546. // face top
  19547. indices.push( i, i + 1, c );
  19548. } else {
  19549. // face bottom
  19550. indices.push( i + 1, i, c );
  19551. }
  19552. groupCount += 3;
  19553. }
  19554. // add a group to the geometry. this will ensure multi material support
  19555. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19556. // calculate new start value for groups
  19557. groupStart += groupCount;
  19558. }
  19559. }
  19560. }
  19561. // ConeGeometry
  19562. class ConeGeometry extends CylinderGeometry {
  19563. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  19564. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19565. this.type = 'ConeGeometry';
  19566. this.parameters = {
  19567. radius: radius,
  19568. height: height,
  19569. radialSegments: radialSegments,
  19570. heightSegments: heightSegments,
  19571. openEnded: openEnded,
  19572. thetaStart: thetaStart,
  19573. thetaLength: thetaLength
  19574. };
  19575. }
  19576. }
  19577. // ConeBufferGeometry
  19578. class ConeBufferGeometry extends CylinderBufferGeometry {
  19579. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  19580. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19581. this.type = 'ConeBufferGeometry';
  19582. this.parameters = {
  19583. radius: radius,
  19584. height: height,
  19585. radialSegments: radialSegments,
  19586. heightSegments: heightSegments,
  19587. openEnded: openEnded,
  19588. thetaStart: thetaStart,
  19589. thetaLength: thetaLength
  19590. };
  19591. }
  19592. }
  19593. // CircleGeometry
  19594. class CircleGeometry extends Geometry {
  19595. constructor( radius, segments, thetaStart, thetaLength ) {
  19596. super();
  19597. this.type = 'CircleGeometry';
  19598. this.parameters = {
  19599. radius: radius,
  19600. segments: segments,
  19601. thetaStart: thetaStart,
  19602. thetaLength: thetaLength
  19603. };
  19604. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  19605. this.mergeVertices();
  19606. }
  19607. }
  19608. // CircleBufferGeometry
  19609. class CircleBufferGeometry extends BufferGeometry {
  19610. constructor( radius, segments, thetaStart, thetaLength ) {
  19611. super();
  19612. this.type = 'CircleBufferGeometry';
  19613. this.parameters = {
  19614. radius: radius,
  19615. segments: segments,
  19616. thetaStart: thetaStart,
  19617. thetaLength: thetaLength
  19618. };
  19619. radius = radius || 1;
  19620. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19621. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19622. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19623. // buffers
  19624. const indices = [];
  19625. const vertices = [];
  19626. const normals = [];
  19627. const uvs = [];
  19628. // helper variables
  19629. const vertex = new Vector3();
  19630. const uv = new Vector2();
  19631. // center point
  19632. vertices.push( 0, 0, 0 );
  19633. normals.push( 0, 0, 1 );
  19634. uvs.push( 0.5, 0.5 );
  19635. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19636. const segment = thetaStart + s / segments * thetaLength;
  19637. // vertex
  19638. vertex.x = radius * Math.cos( segment );
  19639. vertex.y = radius * Math.sin( segment );
  19640. vertices.push( vertex.x, vertex.y, vertex.z );
  19641. // normal
  19642. normals.push( 0, 0, 1 );
  19643. // uvs
  19644. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19645. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19646. uvs.push( uv.x, uv.y );
  19647. }
  19648. // indices
  19649. for ( let i = 1; i <= segments; i ++ ) {
  19650. indices.push( i, i + 1, 0 );
  19651. }
  19652. // build geometry
  19653. this.setIndex( indices );
  19654. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19655. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19656. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19657. }
  19658. }
  19659. var Geometries = /*#__PURE__*/Object.freeze({
  19660. __proto__: null,
  19661. WireframeGeometry: WireframeGeometry,
  19662. ParametricGeometry: ParametricGeometry,
  19663. ParametricBufferGeometry: ParametricBufferGeometry,
  19664. TetrahedronGeometry: TetrahedronGeometry,
  19665. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19666. OctahedronGeometry: OctahedronGeometry,
  19667. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19668. IcosahedronGeometry: IcosahedronGeometry,
  19669. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19670. DodecahedronGeometry: DodecahedronGeometry,
  19671. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19672. PolyhedronGeometry: PolyhedronGeometry,
  19673. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19674. TubeGeometry: TubeGeometry,
  19675. TubeBufferGeometry: TubeBufferGeometry,
  19676. TorusKnotGeometry: TorusKnotGeometry,
  19677. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19678. TorusGeometry: TorusGeometry,
  19679. TorusBufferGeometry: TorusBufferGeometry,
  19680. TextGeometry: TextGeometry,
  19681. TextBufferGeometry: TextBufferGeometry,
  19682. SphereGeometry: SphereGeometry,
  19683. SphereBufferGeometry: SphereBufferGeometry,
  19684. RingGeometry: RingGeometry,
  19685. RingBufferGeometry: RingBufferGeometry,
  19686. PlaneGeometry: PlaneGeometry,
  19687. PlaneBufferGeometry: PlaneBufferGeometry,
  19688. LatheGeometry: LatheGeometry,
  19689. LatheBufferGeometry: LatheBufferGeometry,
  19690. ShapeGeometry: ShapeGeometry,
  19691. ShapeBufferGeometry: ShapeBufferGeometry,
  19692. ExtrudeGeometry: ExtrudeGeometry,
  19693. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19694. EdgesGeometry: EdgesGeometry,
  19695. ConeGeometry: ConeGeometry,
  19696. ConeBufferGeometry: ConeBufferGeometry,
  19697. CylinderGeometry: CylinderGeometry,
  19698. CylinderBufferGeometry: CylinderBufferGeometry,
  19699. CircleGeometry: CircleGeometry,
  19700. CircleBufferGeometry: CircleBufferGeometry,
  19701. BoxGeometry: BoxGeometry,
  19702. BoxBufferGeometry: BoxBufferGeometry
  19703. });
  19704. /**
  19705. * parameters = {
  19706. * color: <THREE.Color>
  19707. * }
  19708. */
  19709. function ShadowMaterial( parameters ) {
  19710. Material.call( this );
  19711. this.type = 'ShadowMaterial';
  19712. this.color = new Color( 0x000000 );
  19713. this.transparent = true;
  19714. this.setValues( parameters );
  19715. }
  19716. ShadowMaterial.prototype = Object.create( Material.prototype );
  19717. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19718. ShadowMaterial.prototype.isShadowMaterial = true;
  19719. ShadowMaterial.prototype.copy = function ( source ) {
  19720. Material.prototype.copy.call( this, source );
  19721. this.color.copy( source.color );
  19722. return this;
  19723. };
  19724. function RawShaderMaterial( parameters ) {
  19725. ShaderMaterial.call( this, parameters );
  19726. this.type = 'RawShaderMaterial';
  19727. }
  19728. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  19729. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19730. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19731. /**
  19732. * parameters = {
  19733. * color: <hex>,
  19734. * roughness: <float>,
  19735. * metalness: <float>,
  19736. * opacity: <float>,
  19737. *
  19738. * map: new THREE.Texture( <Image> ),
  19739. *
  19740. * lightMap: new THREE.Texture( <Image> ),
  19741. * lightMapIntensity: <float>
  19742. *
  19743. * aoMap: new THREE.Texture( <Image> ),
  19744. * aoMapIntensity: <float>
  19745. *
  19746. * emissive: <hex>,
  19747. * emissiveIntensity: <float>
  19748. * emissiveMap: new THREE.Texture( <Image> ),
  19749. *
  19750. * bumpMap: new THREE.Texture( <Image> ),
  19751. * bumpScale: <float>,
  19752. *
  19753. * normalMap: new THREE.Texture( <Image> ),
  19754. * normalMapType: THREE.TangentSpaceNormalMap,
  19755. * normalScale: <Vector2>,
  19756. *
  19757. * displacementMap: new THREE.Texture( <Image> ),
  19758. * displacementScale: <float>,
  19759. * displacementBias: <float>,
  19760. *
  19761. * roughnessMap: new THREE.Texture( <Image> ),
  19762. *
  19763. * metalnessMap: new THREE.Texture( <Image> ),
  19764. *
  19765. * alphaMap: new THREE.Texture( <Image> ),
  19766. *
  19767. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19768. * envMapIntensity: <float>
  19769. *
  19770. * refractionRatio: <float>,
  19771. *
  19772. * wireframe: <boolean>,
  19773. * wireframeLinewidth: <float>,
  19774. *
  19775. * skinning: <bool>,
  19776. * morphTargets: <bool>,
  19777. * morphNormals: <bool>
  19778. * }
  19779. */
  19780. function MeshStandardMaterial( parameters ) {
  19781. Material.call( this );
  19782. this.defines = { 'STANDARD': '' };
  19783. this.type = 'MeshStandardMaterial';
  19784. this.color = new Color( 0xffffff ); // diffuse
  19785. this.roughness = 1.0;
  19786. this.metalness = 0.0;
  19787. this.map = null;
  19788. this.lightMap = null;
  19789. this.lightMapIntensity = 1.0;
  19790. this.aoMap = null;
  19791. this.aoMapIntensity = 1.0;
  19792. this.emissive = new Color( 0x000000 );
  19793. this.emissiveIntensity = 1.0;
  19794. this.emissiveMap = null;
  19795. this.bumpMap = null;
  19796. this.bumpScale = 1;
  19797. this.normalMap = null;
  19798. this.normalMapType = TangentSpaceNormalMap;
  19799. this.normalScale = new Vector2( 1, 1 );
  19800. this.displacementMap = null;
  19801. this.displacementScale = 1;
  19802. this.displacementBias = 0;
  19803. this.roughnessMap = null;
  19804. this.metalnessMap = null;
  19805. this.alphaMap = null;
  19806. this.envMap = null;
  19807. this.envMapIntensity = 1.0;
  19808. this.refractionRatio = 0.98;
  19809. this.wireframe = false;
  19810. this.wireframeLinewidth = 1;
  19811. this.wireframeLinecap = 'round';
  19812. this.wireframeLinejoin = 'round';
  19813. this.skinning = false;
  19814. this.morphTargets = false;
  19815. this.morphNormals = false;
  19816. this.vertexTangents = false;
  19817. this.setValues( parameters );
  19818. }
  19819. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  19820. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19821. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19822. MeshStandardMaterial.prototype.copy = function ( source ) {
  19823. Material.prototype.copy.call( this, source );
  19824. this.defines = { 'STANDARD': '' };
  19825. this.color.copy( source.color );
  19826. this.roughness = source.roughness;
  19827. this.metalness = source.metalness;
  19828. this.map = source.map;
  19829. this.lightMap = source.lightMap;
  19830. this.lightMapIntensity = source.lightMapIntensity;
  19831. this.aoMap = source.aoMap;
  19832. this.aoMapIntensity = source.aoMapIntensity;
  19833. this.emissive.copy( source.emissive );
  19834. this.emissiveMap = source.emissiveMap;
  19835. this.emissiveIntensity = source.emissiveIntensity;
  19836. this.bumpMap = source.bumpMap;
  19837. this.bumpScale = source.bumpScale;
  19838. this.normalMap = source.normalMap;
  19839. this.normalMapType = source.normalMapType;
  19840. this.normalScale.copy( source.normalScale );
  19841. this.displacementMap = source.displacementMap;
  19842. this.displacementScale = source.displacementScale;
  19843. this.displacementBias = source.displacementBias;
  19844. this.roughnessMap = source.roughnessMap;
  19845. this.metalnessMap = source.metalnessMap;
  19846. this.alphaMap = source.alphaMap;
  19847. this.envMap = source.envMap;
  19848. this.envMapIntensity = source.envMapIntensity;
  19849. this.refractionRatio = source.refractionRatio;
  19850. this.wireframe = source.wireframe;
  19851. this.wireframeLinewidth = source.wireframeLinewidth;
  19852. this.wireframeLinecap = source.wireframeLinecap;
  19853. this.wireframeLinejoin = source.wireframeLinejoin;
  19854. this.skinning = source.skinning;
  19855. this.morphTargets = source.morphTargets;
  19856. this.morphNormals = source.morphNormals;
  19857. this.vertexTangents = source.vertexTangents;
  19858. return this;
  19859. };
  19860. /**
  19861. * parameters = {
  19862. * clearcoat: <float>,
  19863. * clearcoatMap: new THREE.Texture( <Image> ),
  19864. * clearcoatRoughness: <float>,
  19865. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19866. * clearcoatNormalScale: <Vector2>,
  19867. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19868. *
  19869. * reflectivity: <float>,
  19870. *
  19871. * sheen: <Color>,
  19872. *
  19873. * transmission: <float>,
  19874. * transmissionMap: new THREE.Texture( <Image> )
  19875. * }
  19876. */
  19877. function MeshPhysicalMaterial( parameters ) {
  19878. MeshStandardMaterial.call( this );
  19879. this.defines = {
  19880. 'STANDARD': '',
  19881. 'PHYSICAL': ''
  19882. };
  19883. this.type = 'MeshPhysicalMaterial';
  19884. this.clearcoat = 0.0;
  19885. this.clearcoatMap = null;
  19886. this.clearcoatRoughness = 0.0;
  19887. this.clearcoatRoughnessMap = null;
  19888. this.clearcoatNormalScale = new Vector2( 1, 1 );
  19889. this.clearcoatNormalMap = null;
  19890. this.reflectivity = 0.5; // maps to F0 = 0.04
  19891. this.sheen = null; // null will disable sheen bsdf
  19892. this.transmission = 0.0;
  19893. this.transmissionMap = null;
  19894. this.setValues( parameters );
  19895. }
  19896. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  19897. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  19898. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19899. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  19900. MeshStandardMaterial.prototype.copy.call( this, source );
  19901. this.defines = {
  19902. 'STANDARD': '',
  19903. 'PHYSICAL': ''
  19904. };
  19905. this.clearcoat = source.clearcoat;
  19906. this.clearcoatMap = source.clearcoatMap;
  19907. this.clearcoatRoughness = source.clearcoatRoughness;
  19908. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19909. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19910. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  19911. this.reflectivity = source.reflectivity;
  19912. if ( source.sheen ) {
  19913. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  19914. } else {
  19915. this.sheen = null;
  19916. }
  19917. this.transmission = source.transmission;
  19918. this.transmissionMap = source.transmissionMap;
  19919. return this;
  19920. };
  19921. /**
  19922. * parameters = {
  19923. * color: <hex>,
  19924. * specular: <hex>,
  19925. * shininess: <float>,
  19926. * opacity: <float>,
  19927. *
  19928. * map: new THREE.Texture( <Image> ),
  19929. *
  19930. * lightMap: new THREE.Texture( <Image> ),
  19931. * lightMapIntensity: <float>
  19932. *
  19933. * aoMap: new THREE.Texture( <Image> ),
  19934. * aoMapIntensity: <float>
  19935. *
  19936. * emissive: <hex>,
  19937. * emissiveIntensity: <float>
  19938. * emissiveMap: new THREE.Texture( <Image> ),
  19939. *
  19940. * bumpMap: new THREE.Texture( <Image> ),
  19941. * bumpScale: <float>,
  19942. *
  19943. * normalMap: new THREE.Texture( <Image> ),
  19944. * normalMapType: THREE.TangentSpaceNormalMap,
  19945. * normalScale: <Vector2>,
  19946. *
  19947. * displacementMap: new THREE.Texture( <Image> ),
  19948. * displacementScale: <float>,
  19949. * displacementBias: <float>,
  19950. *
  19951. * specularMap: new THREE.Texture( <Image> ),
  19952. *
  19953. * alphaMap: new THREE.Texture( <Image> ),
  19954. *
  19955. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19956. * combine: THREE.MultiplyOperation,
  19957. * reflectivity: <float>,
  19958. * refractionRatio: <float>,
  19959. *
  19960. * wireframe: <boolean>,
  19961. * wireframeLinewidth: <float>,
  19962. *
  19963. * skinning: <bool>,
  19964. * morphTargets: <bool>,
  19965. * morphNormals: <bool>
  19966. * }
  19967. */
  19968. function MeshPhongMaterial( parameters ) {
  19969. Material.call( this );
  19970. this.type = 'MeshPhongMaterial';
  19971. this.color = new Color( 0xffffff ); // diffuse
  19972. this.specular = new Color( 0x111111 );
  19973. this.shininess = 30;
  19974. this.map = null;
  19975. this.lightMap = null;
  19976. this.lightMapIntensity = 1.0;
  19977. this.aoMap = null;
  19978. this.aoMapIntensity = 1.0;
  19979. this.emissive = new Color( 0x000000 );
  19980. this.emissiveIntensity = 1.0;
  19981. this.emissiveMap = null;
  19982. this.bumpMap = null;
  19983. this.bumpScale = 1;
  19984. this.normalMap = null;
  19985. this.normalMapType = TangentSpaceNormalMap;
  19986. this.normalScale = new Vector2( 1, 1 );
  19987. this.displacementMap = null;
  19988. this.displacementScale = 1;
  19989. this.displacementBias = 0;
  19990. this.specularMap = null;
  19991. this.alphaMap = null;
  19992. this.envMap = null;
  19993. this.combine = MultiplyOperation;
  19994. this.reflectivity = 1;
  19995. this.refractionRatio = 0.98;
  19996. this.wireframe = false;
  19997. this.wireframeLinewidth = 1;
  19998. this.wireframeLinecap = 'round';
  19999. this.wireframeLinejoin = 'round';
  20000. this.skinning = false;
  20001. this.morphTargets = false;
  20002. this.morphNormals = false;
  20003. this.setValues( parameters );
  20004. }
  20005. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  20006. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20007. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20008. MeshPhongMaterial.prototype.copy = function ( source ) {
  20009. Material.prototype.copy.call( this, source );
  20010. this.color.copy( source.color );
  20011. this.specular.copy( source.specular );
  20012. this.shininess = source.shininess;
  20013. this.map = source.map;
  20014. this.lightMap = source.lightMap;
  20015. this.lightMapIntensity = source.lightMapIntensity;
  20016. this.aoMap = source.aoMap;
  20017. this.aoMapIntensity = source.aoMapIntensity;
  20018. this.emissive.copy( source.emissive );
  20019. this.emissiveMap = source.emissiveMap;
  20020. this.emissiveIntensity = source.emissiveIntensity;
  20021. this.bumpMap = source.bumpMap;
  20022. this.bumpScale = source.bumpScale;
  20023. this.normalMap = source.normalMap;
  20024. this.normalMapType = source.normalMapType;
  20025. this.normalScale.copy( source.normalScale );
  20026. this.displacementMap = source.displacementMap;
  20027. this.displacementScale = source.displacementScale;
  20028. this.displacementBias = source.displacementBias;
  20029. this.specularMap = source.specularMap;
  20030. this.alphaMap = source.alphaMap;
  20031. this.envMap = source.envMap;
  20032. this.combine = source.combine;
  20033. this.reflectivity = source.reflectivity;
  20034. this.refractionRatio = source.refractionRatio;
  20035. this.wireframe = source.wireframe;
  20036. this.wireframeLinewidth = source.wireframeLinewidth;
  20037. this.wireframeLinecap = source.wireframeLinecap;
  20038. this.wireframeLinejoin = source.wireframeLinejoin;
  20039. this.skinning = source.skinning;
  20040. this.morphTargets = source.morphTargets;
  20041. this.morphNormals = source.morphNormals;
  20042. return this;
  20043. };
  20044. /**
  20045. * parameters = {
  20046. * color: <hex>,
  20047. *
  20048. * map: new THREE.Texture( <Image> ),
  20049. * gradientMap: new THREE.Texture( <Image> ),
  20050. *
  20051. * lightMap: new THREE.Texture( <Image> ),
  20052. * lightMapIntensity: <float>
  20053. *
  20054. * aoMap: new THREE.Texture( <Image> ),
  20055. * aoMapIntensity: <float>
  20056. *
  20057. * emissive: <hex>,
  20058. * emissiveIntensity: <float>
  20059. * emissiveMap: new THREE.Texture( <Image> ),
  20060. *
  20061. * bumpMap: new THREE.Texture( <Image> ),
  20062. * bumpScale: <float>,
  20063. *
  20064. * normalMap: new THREE.Texture( <Image> ),
  20065. * normalMapType: THREE.TangentSpaceNormalMap,
  20066. * normalScale: <Vector2>,
  20067. *
  20068. * displacementMap: new THREE.Texture( <Image> ),
  20069. * displacementScale: <float>,
  20070. * displacementBias: <float>,
  20071. *
  20072. * alphaMap: new THREE.Texture( <Image> ),
  20073. *
  20074. * wireframe: <boolean>,
  20075. * wireframeLinewidth: <float>,
  20076. *
  20077. * skinning: <bool>,
  20078. * morphTargets: <bool>,
  20079. * morphNormals: <bool>
  20080. * }
  20081. */
  20082. function MeshToonMaterial( parameters ) {
  20083. Material.call( this );
  20084. this.defines = { 'TOON': '' };
  20085. this.type = 'MeshToonMaterial';
  20086. this.color = new Color( 0xffffff );
  20087. this.map = null;
  20088. this.gradientMap = null;
  20089. this.lightMap = null;
  20090. this.lightMapIntensity = 1.0;
  20091. this.aoMap = null;
  20092. this.aoMapIntensity = 1.0;
  20093. this.emissive = new Color( 0x000000 );
  20094. this.emissiveIntensity = 1.0;
  20095. this.emissiveMap = null;
  20096. this.bumpMap = null;
  20097. this.bumpScale = 1;
  20098. this.normalMap = null;
  20099. this.normalMapType = TangentSpaceNormalMap;
  20100. this.normalScale = new Vector2( 1, 1 );
  20101. this.displacementMap = null;
  20102. this.displacementScale = 1;
  20103. this.displacementBias = 0;
  20104. this.alphaMap = null;
  20105. this.wireframe = false;
  20106. this.wireframeLinewidth = 1;
  20107. this.wireframeLinecap = 'round';
  20108. this.wireframeLinejoin = 'round';
  20109. this.skinning = false;
  20110. this.morphTargets = false;
  20111. this.morphNormals = false;
  20112. this.setValues( parameters );
  20113. }
  20114. MeshToonMaterial.prototype = Object.create( Material.prototype );
  20115. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20116. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20117. MeshToonMaterial.prototype.copy = function ( source ) {
  20118. Material.prototype.copy.call( this, source );
  20119. this.color.copy( source.color );
  20120. this.map = source.map;
  20121. this.gradientMap = source.gradientMap;
  20122. this.lightMap = source.lightMap;
  20123. this.lightMapIntensity = source.lightMapIntensity;
  20124. this.aoMap = source.aoMap;
  20125. this.aoMapIntensity = source.aoMapIntensity;
  20126. this.emissive.copy( source.emissive );
  20127. this.emissiveMap = source.emissiveMap;
  20128. this.emissiveIntensity = source.emissiveIntensity;
  20129. this.bumpMap = source.bumpMap;
  20130. this.bumpScale = source.bumpScale;
  20131. this.normalMap = source.normalMap;
  20132. this.normalMapType = source.normalMapType;
  20133. this.normalScale.copy( source.normalScale );
  20134. this.displacementMap = source.displacementMap;
  20135. this.displacementScale = source.displacementScale;
  20136. this.displacementBias = source.displacementBias;
  20137. this.alphaMap = source.alphaMap;
  20138. this.wireframe = source.wireframe;
  20139. this.wireframeLinewidth = source.wireframeLinewidth;
  20140. this.wireframeLinecap = source.wireframeLinecap;
  20141. this.wireframeLinejoin = source.wireframeLinejoin;
  20142. this.skinning = source.skinning;
  20143. this.morphTargets = source.morphTargets;
  20144. this.morphNormals = source.morphNormals;
  20145. return this;
  20146. };
  20147. /**
  20148. * parameters = {
  20149. * opacity: <float>,
  20150. *
  20151. * bumpMap: new THREE.Texture( <Image> ),
  20152. * bumpScale: <float>,
  20153. *
  20154. * normalMap: new THREE.Texture( <Image> ),
  20155. * normalMapType: THREE.TangentSpaceNormalMap,
  20156. * normalScale: <Vector2>,
  20157. *
  20158. * displacementMap: new THREE.Texture( <Image> ),
  20159. * displacementScale: <float>,
  20160. * displacementBias: <float>,
  20161. *
  20162. * wireframe: <boolean>,
  20163. * wireframeLinewidth: <float>
  20164. *
  20165. * skinning: <bool>,
  20166. * morphTargets: <bool>,
  20167. * morphNormals: <bool>
  20168. * }
  20169. */
  20170. function MeshNormalMaterial( parameters ) {
  20171. Material.call( this );
  20172. this.type = 'MeshNormalMaterial';
  20173. this.bumpMap = null;
  20174. this.bumpScale = 1;
  20175. this.normalMap = null;
  20176. this.normalMapType = TangentSpaceNormalMap;
  20177. this.normalScale = new Vector2( 1, 1 );
  20178. this.displacementMap = null;
  20179. this.displacementScale = 1;
  20180. this.displacementBias = 0;
  20181. this.wireframe = false;
  20182. this.wireframeLinewidth = 1;
  20183. this.fog = false;
  20184. this.skinning = false;
  20185. this.morphTargets = false;
  20186. this.morphNormals = false;
  20187. this.setValues( parameters );
  20188. }
  20189. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  20190. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20191. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20192. MeshNormalMaterial.prototype.copy = function ( source ) {
  20193. Material.prototype.copy.call( this, source );
  20194. this.bumpMap = source.bumpMap;
  20195. this.bumpScale = source.bumpScale;
  20196. this.normalMap = source.normalMap;
  20197. this.normalMapType = source.normalMapType;
  20198. this.normalScale.copy( source.normalScale );
  20199. this.displacementMap = source.displacementMap;
  20200. this.displacementScale = source.displacementScale;
  20201. this.displacementBias = source.displacementBias;
  20202. this.wireframe = source.wireframe;
  20203. this.wireframeLinewidth = source.wireframeLinewidth;
  20204. this.skinning = source.skinning;
  20205. this.morphTargets = source.morphTargets;
  20206. this.morphNormals = source.morphNormals;
  20207. return this;
  20208. };
  20209. /**
  20210. * parameters = {
  20211. * color: <hex>,
  20212. * opacity: <float>,
  20213. *
  20214. * map: new THREE.Texture( <Image> ),
  20215. *
  20216. * lightMap: new THREE.Texture( <Image> ),
  20217. * lightMapIntensity: <float>
  20218. *
  20219. * aoMap: new THREE.Texture( <Image> ),
  20220. * aoMapIntensity: <float>
  20221. *
  20222. * emissive: <hex>,
  20223. * emissiveIntensity: <float>
  20224. * emissiveMap: new THREE.Texture( <Image> ),
  20225. *
  20226. * specularMap: new THREE.Texture( <Image> ),
  20227. *
  20228. * alphaMap: new THREE.Texture( <Image> ),
  20229. *
  20230. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20231. * combine: THREE.Multiply,
  20232. * reflectivity: <float>,
  20233. * refractionRatio: <float>,
  20234. *
  20235. * wireframe: <boolean>,
  20236. * wireframeLinewidth: <float>,
  20237. *
  20238. * skinning: <bool>,
  20239. * morphTargets: <bool>,
  20240. * morphNormals: <bool>
  20241. * }
  20242. */
  20243. function MeshLambertMaterial( parameters ) {
  20244. Material.call( this );
  20245. this.type = 'MeshLambertMaterial';
  20246. this.color = new Color( 0xffffff ); // diffuse
  20247. this.map = null;
  20248. this.lightMap = null;
  20249. this.lightMapIntensity = 1.0;
  20250. this.aoMap = null;
  20251. this.aoMapIntensity = 1.0;
  20252. this.emissive = new Color( 0x000000 );
  20253. this.emissiveIntensity = 1.0;
  20254. this.emissiveMap = null;
  20255. this.specularMap = null;
  20256. this.alphaMap = null;
  20257. this.envMap = null;
  20258. this.combine = MultiplyOperation;
  20259. this.reflectivity = 1;
  20260. this.refractionRatio = 0.98;
  20261. this.wireframe = false;
  20262. this.wireframeLinewidth = 1;
  20263. this.wireframeLinecap = 'round';
  20264. this.wireframeLinejoin = 'round';
  20265. this.skinning = false;
  20266. this.morphTargets = false;
  20267. this.morphNormals = false;
  20268. this.setValues( parameters );
  20269. }
  20270. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  20271. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20272. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20273. MeshLambertMaterial.prototype.copy = function ( source ) {
  20274. Material.prototype.copy.call( this, source );
  20275. this.color.copy( source.color );
  20276. this.map = source.map;
  20277. this.lightMap = source.lightMap;
  20278. this.lightMapIntensity = source.lightMapIntensity;
  20279. this.aoMap = source.aoMap;
  20280. this.aoMapIntensity = source.aoMapIntensity;
  20281. this.emissive.copy( source.emissive );
  20282. this.emissiveMap = source.emissiveMap;
  20283. this.emissiveIntensity = source.emissiveIntensity;
  20284. this.specularMap = source.specularMap;
  20285. this.alphaMap = source.alphaMap;
  20286. this.envMap = source.envMap;
  20287. this.combine = source.combine;
  20288. this.reflectivity = source.reflectivity;
  20289. this.refractionRatio = source.refractionRatio;
  20290. this.wireframe = source.wireframe;
  20291. this.wireframeLinewidth = source.wireframeLinewidth;
  20292. this.wireframeLinecap = source.wireframeLinecap;
  20293. this.wireframeLinejoin = source.wireframeLinejoin;
  20294. this.skinning = source.skinning;
  20295. this.morphTargets = source.morphTargets;
  20296. this.morphNormals = source.morphNormals;
  20297. return this;
  20298. };
  20299. /**
  20300. * parameters = {
  20301. * color: <hex>,
  20302. * opacity: <float>,
  20303. *
  20304. * matcap: new THREE.Texture( <Image> ),
  20305. *
  20306. * map: new THREE.Texture( <Image> ),
  20307. *
  20308. * bumpMap: new THREE.Texture( <Image> ),
  20309. * bumpScale: <float>,
  20310. *
  20311. * normalMap: new THREE.Texture( <Image> ),
  20312. * normalMapType: THREE.TangentSpaceNormalMap,
  20313. * normalScale: <Vector2>,
  20314. *
  20315. * displacementMap: new THREE.Texture( <Image> ),
  20316. * displacementScale: <float>,
  20317. * displacementBias: <float>,
  20318. *
  20319. * alphaMap: new THREE.Texture( <Image> ),
  20320. *
  20321. * skinning: <bool>,
  20322. * morphTargets: <bool>,
  20323. * morphNormals: <bool>
  20324. * }
  20325. */
  20326. function MeshMatcapMaterial( parameters ) {
  20327. Material.call( this );
  20328. this.defines = { 'MATCAP': '' };
  20329. this.type = 'MeshMatcapMaterial';
  20330. this.color = new Color( 0xffffff ); // diffuse
  20331. this.matcap = null;
  20332. this.map = null;
  20333. this.bumpMap = null;
  20334. this.bumpScale = 1;
  20335. this.normalMap = null;
  20336. this.normalMapType = TangentSpaceNormalMap;
  20337. this.normalScale = new Vector2( 1, 1 );
  20338. this.displacementMap = null;
  20339. this.displacementScale = 1;
  20340. this.displacementBias = 0;
  20341. this.alphaMap = null;
  20342. this.skinning = false;
  20343. this.morphTargets = false;
  20344. this.morphNormals = false;
  20345. this.setValues( parameters );
  20346. }
  20347. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  20348. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20349. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20350. MeshMatcapMaterial.prototype.copy = function ( source ) {
  20351. Material.prototype.copy.call( this, source );
  20352. this.defines = { 'MATCAP': '' };
  20353. this.color.copy( source.color );
  20354. this.matcap = source.matcap;
  20355. this.map = source.map;
  20356. this.bumpMap = source.bumpMap;
  20357. this.bumpScale = source.bumpScale;
  20358. this.normalMap = source.normalMap;
  20359. this.normalMapType = source.normalMapType;
  20360. this.normalScale.copy( source.normalScale );
  20361. this.displacementMap = source.displacementMap;
  20362. this.displacementScale = source.displacementScale;
  20363. this.displacementBias = source.displacementBias;
  20364. this.alphaMap = source.alphaMap;
  20365. this.skinning = source.skinning;
  20366. this.morphTargets = source.morphTargets;
  20367. this.morphNormals = source.morphNormals;
  20368. return this;
  20369. };
  20370. /**
  20371. * parameters = {
  20372. * color: <hex>,
  20373. * opacity: <float>,
  20374. *
  20375. * linewidth: <float>,
  20376. *
  20377. * scale: <float>,
  20378. * dashSize: <float>,
  20379. * gapSize: <float>
  20380. * }
  20381. */
  20382. function LineDashedMaterial( parameters ) {
  20383. LineBasicMaterial.call( this );
  20384. this.type = 'LineDashedMaterial';
  20385. this.scale = 1;
  20386. this.dashSize = 3;
  20387. this.gapSize = 1;
  20388. this.setValues( parameters );
  20389. }
  20390. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  20391. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20392. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20393. LineDashedMaterial.prototype.copy = function ( source ) {
  20394. LineBasicMaterial.prototype.copy.call( this, source );
  20395. this.scale = source.scale;
  20396. this.dashSize = source.dashSize;
  20397. this.gapSize = source.gapSize;
  20398. return this;
  20399. };
  20400. var Materials = /*#__PURE__*/Object.freeze({
  20401. __proto__: null,
  20402. ShadowMaterial: ShadowMaterial,
  20403. SpriteMaterial: SpriteMaterial,
  20404. RawShaderMaterial: RawShaderMaterial,
  20405. ShaderMaterial: ShaderMaterial,
  20406. PointsMaterial: PointsMaterial,
  20407. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20408. MeshStandardMaterial: MeshStandardMaterial,
  20409. MeshPhongMaterial: MeshPhongMaterial,
  20410. MeshToonMaterial: MeshToonMaterial,
  20411. MeshNormalMaterial: MeshNormalMaterial,
  20412. MeshLambertMaterial: MeshLambertMaterial,
  20413. MeshDepthMaterial: MeshDepthMaterial,
  20414. MeshDistanceMaterial: MeshDistanceMaterial,
  20415. MeshBasicMaterial: MeshBasicMaterial,
  20416. MeshMatcapMaterial: MeshMatcapMaterial,
  20417. LineDashedMaterial: LineDashedMaterial,
  20418. LineBasicMaterial: LineBasicMaterial,
  20419. Material: Material
  20420. });
  20421. const AnimationUtils = {
  20422. // same as Array.prototype.slice, but also works on typed arrays
  20423. arraySlice: function ( array, from, to ) {
  20424. if ( AnimationUtils.isTypedArray( array ) ) {
  20425. // in ios9 array.subarray(from, undefined) will return empty array
  20426. // but array.subarray(from) or array.subarray(from, len) is correct
  20427. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  20428. }
  20429. return array.slice( from, to );
  20430. },
  20431. // converts an array to a specific type
  20432. convertArray: function ( array, type, forceClone ) {
  20433. if ( ! array || // let 'undefined' and 'null' pass
  20434. ! forceClone && array.constructor === type ) return array;
  20435. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  20436. return new type( array ); // create typed array
  20437. }
  20438. return Array.prototype.slice.call( array ); // create Array
  20439. },
  20440. isTypedArray: function ( object ) {
  20441. return ArrayBuffer.isView( object ) &&
  20442. ! ( object instanceof DataView );
  20443. },
  20444. // returns an array by which times and values can be sorted
  20445. getKeyframeOrder: function ( times ) {
  20446. function compareTime( i, j ) {
  20447. return times[ i ] - times[ j ];
  20448. }
  20449. const n = times.length;
  20450. const result = new Array( n );
  20451. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  20452. result.sort( compareTime );
  20453. return result;
  20454. },
  20455. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20456. sortedArray: function ( values, stride, order ) {
  20457. const nValues = values.length;
  20458. const result = new values.constructor( nValues );
  20459. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  20460. const srcOffset = order[ i ] * stride;
  20461. for ( let j = 0; j !== stride; ++ j ) {
  20462. result[ dstOffset ++ ] = values[ srcOffset + j ];
  20463. }
  20464. }
  20465. return result;
  20466. },
  20467. // function for parsing AOS keyframe formats
  20468. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  20469. let i = 1, key = jsonKeys[ 0 ];
  20470. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  20471. key = jsonKeys[ i ++ ];
  20472. }
  20473. if ( key === undefined ) return; // no data
  20474. let value = key[ valuePropertyName ];
  20475. if ( value === undefined ) return; // no data
  20476. if ( Array.isArray( value ) ) {
  20477. do {
  20478. value = key[ valuePropertyName ];
  20479. if ( value !== undefined ) {
  20480. times.push( key.time );
  20481. values.push.apply( values, value ); // push all elements
  20482. }
  20483. key = jsonKeys[ i ++ ];
  20484. } while ( key !== undefined );
  20485. } else if ( value.toArray !== undefined ) {
  20486. // ...assume THREE.Math-ish
  20487. do {
  20488. value = key[ valuePropertyName ];
  20489. if ( value !== undefined ) {
  20490. times.push( key.time );
  20491. value.toArray( values, values.length );
  20492. }
  20493. key = jsonKeys[ i ++ ];
  20494. } while ( key !== undefined );
  20495. } else {
  20496. // otherwise push as-is
  20497. do {
  20498. value = key[ valuePropertyName ];
  20499. if ( value !== undefined ) {
  20500. times.push( key.time );
  20501. values.push( value );
  20502. }
  20503. key = jsonKeys[ i ++ ];
  20504. } while ( key !== undefined );
  20505. }
  20506. },
  20507. subclip: function ( sourceClip, name, startFrame, endFrame, fps ) {
  20508. fps = fps || 30;
  20509. const clip = sourceClip.clone();
  20510. clip.name = name;
  20511. const tracks = [];
  20512. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  20513. const track = clip.tracks[ i ];
  20514. const valueSize = track.getValueSize();
  20515. const times = [];
  20516. const values = [];
  20517. for ( let j = 0; j < track.times.length; ++ j ) {
  20518. const frame = track.times[ j ] * fps;
  20519. if ( frame < startFrame || frame >= endFrame ) continue;
  20520. times.push( track.times[ j ] );
  20521. for ( let k = 0; k < valueSize; ++ k ) {
  20522. values.push( track.values[ j * valueSize + k ] );
  20523. }
  20524. }
  20525. if ( times.length === 0 ) continue;
  20526. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  20527. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  20528. tracks.push( track );
  20529. }
  20530. clip.tracks = tracks;
  20531. // find minimum .times value across all tracks in the trimmed clip
  20532. let minStartTime = Infinity;
  20533. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  20534. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  20535. minStartTime = clip.tracks[ i ].times[ 0 ];
  20536. }
  20537. }
  20538. // shift all tracks such that clip begins at t=0
  20539. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  20540. clip.tracks[ i ].shift( - 1 * minStartTime );
  20541. }
  20542. clip.resetDuration();
  20543. return clip;
  20544. },
  20545. makeClipAdditive: function ( targetClip, referenceFrame, referenceClip, fps ) {
  20546. if ( referenceFrame === undefined ) referenceFrame = 0;
  20547. if ( referenceClip === undefined ) referenceClip = targetClip;
  20548. if ( fps === undefined || fps <= 0 ) fps = 30;
  20549. const numTracks = targetClip.tracks.length;
  20550. const referenceTime = referenceFrame / fps;
  20551. // Make each track's values relative to the values at the reference frame
  20552. for ( let i = 0; i < numTracks; ++ i ) {
  20553. const referenceTrack = referenceClip.tracks[ i ];
  20554. const referenceTrackType = referenceTrack.ValueTypeName;
  20555. // Skip this track if it's non-numeric
  20556. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  20557. // Find the track in the target clip whose name and type matches the reference track
  20558. const targetTrack = targetClip.tracks.find( function ( track ) {
  20559. return track.name === referenceTrack.name
  20560. && track.ValueTypeName === referenceTrackType;
  20561. } );
  20562. if ( targetTrack === undefined ) continue;
  20563. let referenceOffset = 0;
  20564. const referenceValueSize = referenceTrack.getValueSize();
  20565. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  20566. referenceOffset = referenceValueSize / 3;
  20567. }
  20568. let targetOffset = 0;
  20569. const targetValueSize = targetTrack.getValueSize();
  20570. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  20571. targetOffset = targetValueSize / 3;
  20572. }
  20573. const lastIndex = referenceTrack.times.length - 1;
  20574. let referenceValue;
  20575. // Find the value to subtract out of the track
  20576. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  20577. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  20578. const startIndex = referenceOffset;
  20579. const endIndex = referenceValueSize - referenceOffset;
  20580. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  20581. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  20582. // Reference frame is after the last keyframe, so just use the last keyframe
  20583. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  20584. const endIndex = startIndex + referenceValueSize - referenceOffset;
  20585. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  20586. } else {
  20587. // Interpolate to the reference value
  20588. const interpolant = referenceTrack.createInterpolant();
  20589. const startIndex = referenceOffset;
  20590. const endIndex = referenceValueSize - referenceOffset;
  20591. interpolant.evaluate( referenceTime );
  20592. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  20593. }
  20594. // Conjugate the quaternion
  20595. if ( referenceTrackType === 'quaternion' ) {
  20596. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  20597. referenceQuat.toArray( referenceValue );
  20598. }
  20599. // Subtract the reference value from all of the track values
  20600. const numTimes = targetTrack.times.length;
  20601. for ( let j = 0; j < numTimes; ++ j ) {
  20602. const valueStart = j * targetValueSize + targetOffset;
  20603. if ( referenceTrackType === 'quaternion' ) {
  20604. // Multiply the conjugate for quaternion track types
  20605. Quaternion.multiplyQuaternionsFlat(
  20606. targetTrack.values,
  20607. valueStart,
  20608. referenceValue,
  20609. 0,
  20610. targetTrack.values,
  20611. valueStart
  20612. );
  20613. } else {
  20614. const valueEnd = targetValueSize - targetOffset * 2;
  20615. // Subtract each value for all other numeric track types
  20616. for ( let k = 0; k < valueEnd; ++ k ) {
  20617. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  20618. }
  20619. }
  20620. }
  20621. }
  20622. targetClip.blendMode = AdditiveAnimationBlendMode;
  20623. return targetClip;
  20624. }
  20625. };
  20626. /**
  20627. * Abstract base class of interpolants over parametric samples.
  20628. *
  20629. * The parameter domain is one dimensional, typically the time or a path
  20630. * along a curve defined by the data.
  20631. *
  20632. * The sample values can have any dimensionality and derived classes may
  20633. * apply special interpretations to the data.
  20634. *
  20635. * This class provides the interval seek in a Template Method, deferring
  20636. * the actual interpolation to derived classes.
  20637. *
  20638. * Time complexity is O(1) for linear access crossing at most two points
  20639. * and O(log N) for random access, where N is the number of positions.
  20640. *
  20641. * References:
  20642. *
  20643. * http://www.oodesign.com/template-method-pattern.html
  20644. *
  20645. */
  20646. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20647. this.parameterPositions = parameterPositions;
  20648. this._cachedIndex = 0;
  20649. this.resultBuffer = resultBuffer !== undefined ?
  20650. resultBuffer : new sampleValues.constructor( sampleSize );
  20651. this.sampleValues = sampleValues;
  20652. this.valueSize = sampleSize;
  20653. }
  20654. Object.assign( Interpolant.prototype, {
  20655. evaluate: function ( t ) {
  20656. const pp = this.parameterPositions;
  20657. let i1 = this._cachedIndex,
  20658. t1 = pp[ i1 ],
  20659. t0 = pp[ i1 - 1 ];
  20660. validate_interval: {
  20661. seek: {
  20662. let right;
  20663. linear_scan: {
  20664. //- See http://jsperf.com/comparison-to-undefined/3
  20665. //- slower code:
  20666. //-
  20667. //- if ( t >= t1 || t1 === undefined ) {
  20668. forward_scan: if ( ! ( t < t1 ) ) {
  20669. for ( let giveUpAt = i1 + 2; ; ) {
  20670. if ( t1 === undefined ) {
  20671. if ( t < t0 ) break forward_scan;
  20672. // after end
  20673. i1 = pp.length;
  20674. this._cachedIndex = i1;
  20675. return this.afterEnd_( i1 - 1, t, t0 );
  20676. }
  20677. if ( i1 === giveUpAt ) break; // this loop
  20678. t0 = t1;
  20679. t1 = pp[ ++ i1 ];
  20680. if ( t < t1 ) {
  20681. // we have arrived at the sought interval
  20682. break seek;
  20683. }
  20684. }
  20685. // prepare binary search on the right side of the index
  20686. right = pp.length;
  20687. break linear_scan;
  20688. }
  20689. //- slower code:
  20690. //- if ( t < t0 || t0 === undefined ) {
  20691. if ( ! ( t >= t0 ) ) {
  20692. // looping?
  20693. const t1global = pp[ 1 ];
  20694. if ( t < t1global ) {
  20695. i1 = 2; // + 1, using the scan for the details
  20696. t0 = t1global;
  20697. }
  20698. // linear reverse scan
  20699. for ( let giveUpAt = i1 - 2; ; ) {
  20700. if ( t0 === undefined ) {
  20701. // before start
  20702. this._cachedIndex = 0;
  20703. return this.beforeStart_( 0, t, t1 );
  20704. }
  20705. if ( i1 === giveUpAt ) break; // this loop
  20706. t1 = t0;
  20707. t0 = pp[ -- i1 - 1 ];
  20708. if ( t >= t0 ) {
  20709. // we have arrived at the sought interval
  20710. break seek;
  20711. }
  20712. }
  20713. // prepare binary search on the left side of the index
  20714. right = i1;
  20715. i1 = 0;
  20716. break linear_scan;
  20717. }
  20718. // the interval is valid
  20719. break validate_interval;
  20720. } // linear scan
  20721. // binary search
  20722. while ( i1 < right ) {
  20723. const mid = ( i1 + right ) >>> 1;
  20724. if ( t < pp[ mid ] ) {
  20725. right = mid;
  20726. } else {
  20727. i1 = mid + 1;
  20728. }
  20729. }
  20730. t1 = pp[ i1 ];
  20731. t0 = pp[ i1 - 1 ];
  20732. // check boundary cases, again
  20733. if ( t0 === undefined ) {
  20734. this._cachedIndex = 0;
  20735. return this.beforeStart_( 0, t, t1 );
  20736. }
  20737. if ( t1 === undefined ) {
  20738. i1 = pp.length;
  20739. this._cachedIndex = i1;
  20740. return this.afterEnd_( i1 - 1, t0, t );
  20741. }
  20742. } // seek
  20743. this._cachedIndex = i1;
  20744. this.intervalChanged_( i1, t0, t1 );
  20745. } // validate_interval
  20746. return this.interpolate_( i1, t0, t, t1 );
  20747. },
  20748. settings: null, // optional, subclass-specific settings structure
  20749. // Note: The indirection allows central control of many interpolants.
  20750. // --- Protected interface
  20751. DefaultSettings_: {},
  20752. getSettings_: function () {
  20753. return this.settings || this.DefaultSettings_;
  20754. },
  20755. copySampleValue_: function ( index ) {
  20756. // copies a sample value to the result buffer
  20757. const result = this.resultBuffer,
  20758. values = this.sampleValues,
  20759. stride = this.valueSize,
  20760. offset = index * stride;
  20761. for ( let i = 0; i !== stride; ++ i ) {
  20762. result[ i ] = values[ offset + i ];
  20763. }
  20764. return result;
  20765. },
  20766. // Template methods for derived classes:
  20767. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  20768. throw new Error( 'call to abstract method' );
  20769. // implementations shall return this.resultBuffer
  20770. },
  20771. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  20772. // empty
  20773. }
  20774. } );
  20775. // DECLARE ALIAS AFTER assign prototype
  20776. Object.assign( Interpolant.prototype, {
  20777. //( 0, t, t0 ), returns this.resultBuffer
  20778. beforeStart_: Interpolant.prototype.copySampleValue_,
  20779. //( N-1, tN-1, t ), returns this.resultBuffer
  20780. afterEnd_: Interpolant.prototype.copySampleValue_,
  20781. } );
  20782. /**
  20783. * Fast and simple cubic spline interpolant.
  20784. *
  20785. * It was derived from a Hermitian construction setting the first derivative
  20786. * at each sample position to the linear slope between neighboring positions
  20787. * over their parameter interval.
  20788. */
  20789. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20790. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  20791. this._weightPrev = - 0;
  20792. this._offsetPrev = - 0;
  20793. this._weightNext = - 0;
  20794. this._offsetNext = - 0;
  20795. }
  20796. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  20797. constructor: CubicInterpolant,
  20798. DefaultSettings_: {
  20799. endingStart: ZeroCurvatureEnding,
  20800. endingEnd: ZeroCurvatureEnding
  20801. },
  20802. intervalChanged_: function ( i1, t0, t1 ) {
  20803. const pp = this.parameterPositions;
  20804. let iPrev = i1 - 2,
  20805. iNext = i1 + 1,
  20806. tPrev = pp[ iPrev ],
  20807. tNext = pp[ iNext ];
  20808. if ( tPrev === undefined ) {
  20809. switch ( this.getSettings_().endingStart ) {
  20810. case ZeroSlopeEnding:
  20811. // f'(t0) = 0
  20812. iPrev = i1;
  20813. tPrev = 2 * t0 - t1;
  20814. break;
  20815. case WrapAroundEnding:
  20816. // use the other end of the curve
  20817. iPrev = pp.length - 2;
  20818. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  20819. break;
  20820. default: // ZeroCurvatureEnding
  20821. // f''(t0) = 0 a.k.a. Natural Spline
  20822. iPrev = i1;
  20823. tPrev = t1;
  20824. }
  20825. }
  20826. if ( tNext === undefined ) {
  20827. switch ( this.getSettings_().endingEnd ) {
  20828. case ZeroSlopeEnding:
  20829. // f'(tN) = 0
  20830. iNext = i1;
  20831. tNext = 2 * t1 - t0;
  20832. break;
  20833. case WrapAroundEnding:
  20834. // use the other end of the curve
  20835. iNext = 1;
  20836. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  20837. break;
  20838. default: // ZeroCurvatureEnding
  20839. // f''(tN) = 0, a.k.a. Natural Spline
  20840. iNext = i1 - 1;
  20841. tNext = t0;
  20842. }
  20843. }
  20844. const halfDt = ( t1 - t0 ) * 0.5,
  20845. stride = this.valueSize;
  20846. this._weightPrev = halfDt / ( t0 - tPrev );
  20847. this._weightNext = halfDt / ( tNext - t1 );
  20848. this._offsetPrev = iPrev * stride;
  20849. this._offsetNext = iNext * stride;
  20850. },
  20851. interpolate_: function ( i1, t0, t, t1 ) {
  20852. const result = this.resultBuffer,
  20853. values = this.sampleValues,
  20854. stride = this.valueSize,
  20855. o1 = i1 * stride, o0 = o1 - stride,
  20856. oP = this._offsetPrev, oN = this._offsetNext,
  20857. wP = this._weightPrev, wN = this._weightNext,
  20858. p = ( t - t0 ) / ( t1 - t0 ),
  20859. pp = p * p,
  20860. ppp = pp * p;
  20861. // evaluate polynomials
  20862. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  20863. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  20864. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  20865. const sN = wN * ppp - wN * pp;
  20866. // combine data linearly
  20867. for ( let i = 0; i !== stride; ++ i ) {
  20868. result[ i ] =
  20869. sP * values[ oP + i ] +
  20870. s0 * values[ o0 + i ] +
  20871. s1 * values[ o1 + i ] +
  20872. sN * values[ oN + i ];
  20873. }
  20874. return result;
  20875. }
  20876. } );
  20877. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20878. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  20879. }
  20880. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  20881. constructor: LinearInterpolant,
  20882. interpolate_: function ( i1, t0, t, t1 ) {
  20883. const result = this.resultBuffer,
  20884. values = this.sampleValues,
  20885. stride = this.valueSize,
  20886. offset1 = i1 * stride,
  20887. offset0 = offset1 - stride,
  20888. weight1 = ( t - t0 ) / ( t1 - t0 ),
  20889. weight0 = 1 - weight1;
  20890. for ( let i = 0; i !== stride; ++ i ) {
  20891. result[ i ] =
  20892. values[ offset0 + i ] * weight0 +
  20893. values[ offset1 + i ] * weight1;
  20894. }
  20895. return result;
  20896. }
  20897. } );
  20898. /**
  20899. *
  20900. * Interpolant that evaluates to the sample value at the position preceeding
  20901. * the parameter.
  20902. */
  20903. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20904. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  20905. }
  20906. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  20907. constructor: DiscreteInterpolant,
  20908. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  20909. return this.copySampleValue_( i1 - 1 );
  20910. }
  20911. } );
  20912. function KeyframeTrack( name, times, values, interpolation ) {
  20913. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  20914. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  20915. this.name = name;
  20916. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  20917. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  20918. this.setInterpolation( interpolation || this.DefaultInterpolation );
  20919. }
  20920. // Static methods
  20921. Object.assign( KeyframeTrack, {
  20922. // Serialization (in static context, because of constructor invocation
  20923. // and automatic invocation of .toJSON):
  20924. toJSON: function ( track ) {
  20925. const trackType = track.constructor;
  20926. let json;
  20927. // derived classes can define a static toJSON method
  20928. if ( trackType.toJSON !== undefined ) {
  20929. json = trackType.toJSON( track );
  20930. } else {
  20931. // by default, we assume the data can be serialized as-is
  20932. json = {
  20933. 'name': track.name,
  20934. 'times': AnimationUtils.convertArray( track.times, Array ),
  20935. 'values': AnimationUtils.convertArray( track.values, Array )
  20936. };
  20937. const interpolation = track.getInterpolation();
  20938. if ( interpolation !== track.DefaultInterpolation ) {
  20939. json.interpolation = interpolation;
  20940. }
  20941. }
  20942. json.type = track.ValueTypeName; // mandatory
  20943. return json;
  20944. }
  20945. } );
  20946. Object.assign( KeyframeTrack.prototype, {
  20947. constructor: KeyframeTrack,
  20948. TimeBufferType: Float32Array,
  20949. ValueBufferType: Float32Array,
  20950. DefaultInterpolation: InterpolateLinear,
  20951. InterpolantFactoryMethodDiscrete: function ( result ) {
  20952. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  20953. },
  20954. InterpolantFactoryMethodLinear: function ( result ) {
  20955. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  20956. },
  20957. InterpolantFactoryMethodSmooth: function ( result ) {
  20958. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  20959. },
  20960. setInterpolation: function ( interpolation ) {
  20961. let factoryMethod;
  20962. switch ( interpolation ) {
  20963. case InterpolateDiscrete:
  20964. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20965. break;
  20966. case InterpolateLinear:
  20967. factoryMethod = this.InterpolantFactoryMethodLinear;
  20968. break;
  20969. case InterpolateSmooth:
  20970. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20971. break;
  20972. }
  20973. if ( factoryMethod === undefined ) {
  20974. const message = "unsupported interpolation for " +
  20975. this.ValueTypeName + " keyframe track named " + this.name;
  20976. if ( this.createInterpolant === undefined ) {
  20977. // fall back to default, unless the default itself is messed up
  20978. if ( interpolation !== this.DefaultInterpolation ) {
  20979. this.setInterpolation( this.DefaultInterpolation );
  20980. } else {
  20981. throw new Error( message ); // fatal, in this case
  20982. }
  20983. }
  20984. console.warn( 'THREE.KeyframeTrack:', message );
  20985. return this;
  20986. }
  20987. this.createInterpolant = factoryMethod;
  20988. return this;
  20989. },
  20990. getInterpolation: function () {
  20991. switch ( this.createInterpolant ) {
  20992. case this.InterpolantFactoryMethodDiscrete:
  20993. return InterpolateDiscrete;
  20994. case this.InterpolantFactoryMethodLinear:
  20995. return InterpolateLinear;
  20996. case this.InterpolantFactoryMethodSmooth:
  20997. return InterpolateSmooth;
  20998. }
  20999. },
  21000. getValueSize: function () {
  21001. return this.values.length / this.times.length;
  21002. },
  21003. // move all keyframes either forwards or backwards in time
  21004. shift: function ( timeOffset ) {
  21005. if ( timeOffset !== 0.0 ) {
  21006. const times = this.times;
  21007. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21008. times[ i ] += timeOffset;
  21009. }
  21010. }
  21011. return this;
  21012. },
  21013. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21014. scale: function ( timeScale ) {
  21015. if ( timeScale !== 1.0 ) {
  21016. const times = this.times;
  21017. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21018. times[ i ] *= timeScale;
  21019. }
  21020. }
  21021. return this;
  21022. },
  21023. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21024. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21025. trim: function ( startTime, endTime ) {
  21026. const times = this.times,
  21027. nKeys = times.length;
  21028. let from = 0,
  21029. to = nKeys - 1;
  21030. while ( from !== nKeys && times[ from ] < startTime ) {
  21031. ++ from;
  21032. }
  21033. while ( to !== - 1 && times[ to ] > endTime ) {
  21034. -- to;
  21035. }
  21036. ++ to; // inclusive -> exclusive bound
  21037. if ( from !== 0 || to !== nKeys ) {
  21038. // empty tracks are forbidden, so keep at least one keyframe
  21039. if ( from >= to ) {
  21040. to = Math.max( to, 1 );
  21041. from = to - 1;
  21042. }
  21043. const stride = this.getValueSize();
  21044. this.times = AnimationUtils.arraySlice( times, from, to );
  21045. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  21046. }
  21047. return this;
  21048. },
  21049. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21050. validate: function () {
  21051. let valid = true;
  21052. const valueSize = this.getValueSize();
  21053. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  21054. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  21055. valid = false;
  21056. }
  21057. const times = this.times,
  21058. values = this.values,
  21059. nKeys = times.length;
  21060. if ( nKeys === 0 ) {
  21061. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  21062. valid = false;
  21063. }
  21064. let prevTime = null;
  21065. for ( let i = 0; i !== nKeys; i ++ ) {
  21066. const currTime = times[ i ];
  21067. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  21068. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  21069. valid = false;
  21070. break;
  21071. }
  21072. if ( prevTime !== null && prevTime > currTime ) {
  21073. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  21074. valid = false;
  21075. break;
  21076. }
  21077. prevTime = currTime;
  21078. }
  21079. if ( values !== undefined ) {
  21080. if ( AnimationUtils.isTypedArray( values ) ) {
  21081. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  21082. const value = values[ i ];
  21083. if ( isNaN( value ) ) {
  21084. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  21085. valid = false;
  21086. break;
  21087. }
  21088. }
  21089. }
  21090. }
  21091. return valid;
  21092. },
  21093. // removes equivalent sequential keys as common in morph target sequences
  21094. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21095. optimize: function () {
  21096. // times or values may be shared with other tracks, so overwriting is unsafe
  21097. const times = AnimationUtils.arraySlice( this.times ),
  21098. values = AnimationUtils.arraySlice( this.values ),
  21099. stride = this.getValueSize(),
  21100. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21101. lastIndex = times.length - 1;
  21102. let writeIndex = 1;
  21103. for ( let i = 1; i < lastIndex; ++ i ) {
  21104. let keep = false;
  21105. const time = times[ i ];
  21106. const timeNext = times[ i + 1 ];
  21107. // remove adjacent keyframes scheduled at the same time
  21108. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  21109. if ( ! smoothInterpolation ) {
  21110. // remove unnecessary keyframes same as their neighbors
  21111. const offset = i * stride,
  21112. offsetP = offset - stride,
  21113. offsetN = offset + stride;
  21114. for ( let j = 0; j !== stride; ++ j ) {
  21115. const value = values[ offset + j ];
  21116. if ( value !== values[ offsetP + j ] ||
  21117. value !== values[ offsetN + j ] ) {
  21118. keep = true;
  21119. break;
  21120. }
  21121. }
  21122. } else {
  21123. keep = true;
  21124. }
  21125. }
  21126. // in-place compaction
  21127. if ( keep ) {
  21128. if ( i !== writeIndex ) {
  21129. times[ writeIndex ] = times[ i ];
  21130. const readOffset = i * stride,
  21131. writeOffset = writeIndex * stride;
  21132. for ( let j = 0; j !== stride; ++ j ) {
  21133. values[ writeOffset + j ] = values[ readOffset + j ];
  21134. }
  21135. }
  21136. ++ writeIndex;
  21137. }
  21138. }
  21139. // flush last keyframe (compaction looks ahead)
  21140. if ( lastIndex > 0 ) {
  21141. times[ writeIndex ] = times[ lastIndex ];
  21142. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  21143. values[ writeOffset + j ] = values[ readOffset + j ];
  21144. }
  21145. ++ writeIndex;
  21146. }
  21147. if ( writeIndex !== times.length ) {
  21148. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  21149. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  21150. } else {
  21151. this.times = times;
  21152. this.values = values;
  21153. }
  21154. return this;
  21155. },
  21156. clone: function () {
  21157. const times = AnimationUtils.arraySlice( this.times, 0 );
  21158. const values = AnimationUtils.arraySlice( this.values, 0 );
  21159. const TypedKeyframeTrack = this.constructor;
  21160. const track = new TypedKeyframeTrack( this.name, times, values );
  21161. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21162. track.createInterpolant = this.createInterpolant;
  21163. return track;
  21164. }
  21165. } );
  21166. /**
  21167. * A Track of Boolean keyframe values.
  21168. */
  21169. function BooleanKeyframeTrack( name, times, values ) {
  21170. KeyframeTrack.call( this, name, times, values );
  21171. }
  21172. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21173. constructor: BooleanKeyframeTrack,
  21174. ValueTypeName: 'bool',
  21175. ValueBufferType: Array,
  21176. DefaultInterpolation: InterpolateDiscrete,
  21177. InterpolantFactoryMethodLinear: undefined,
  21178. InterpolantFactoryMethodSmooth: undefined
  21179. // Note: Actually this track could have a optimized / compressed
  21180. // representation of a single value and a custom interpolant that
  21181. // computes "firstValue ^ isOdd( index )".
  21182. } );
  21183. /**
  21184. * A Track of keyframe values that represent color.
  21185. */
  21186. function ColorKeyframeTrack( name, times, values, interpolation ) {
  21187. KeyframeTrack.call( this, name, times, values, interpolation );
  21188. }
  21189. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21190. constructor: ColorKeyframeTrack,
  21191. ValueTypeName: 'color'
  21192. // ValueBufferType is inherited
  21193. // DefaultInterpolation is inherited
  21194. // Note: Very basic implementation and nothing special yet.
  21195. // However, this is the place for color space parameterization.
  21196. } );
  21197. /**
  21198. * A Track of numeric keyframe values.
  21199. */
  21200. function NumberKeyframeTrack( name, times, values, interpolation ) {
  21201. KeyframeTrack.call( this, name, times, values, interpolation );
  21202. }
  21203. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21204. constructor: NumberKeyframeTrack,
  21205. ValueTypeName: 'number'
  21206. // ValueBufferType is inherited
  21207. // DefaultInterpolation is inherited
  21208. } );
  21209. /**
  21210. * Spherical linear unit quaternion interpolant.
  21211. */
  21212. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21213. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21214. }
  21215. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21216. constructor: QuaternionLinearInterpolant,
  21217. interpolate_: function ( i1, t0, t, t1 ) {
  21218. const result = this.resultBuffer,
  21219. values = this.sampleValues,
  21220. stride = this.valueSize,
  21221. alpha = ( t - t0 ) / ( t1 - t0 );
  21222. let offset = i1 * stride;
  21223. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  21224. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  21225. }
  21226. return result;
  21227. }
  21228. } );
  21229. /**
  21230. * A Track of quaternion keyframe values.
  21231. */
  21232. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  21233. KeyframeTrack.call( this, name, times, values, interpolation );
  21234. }
  21235. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21236. constructor: QuaternionKeyframeTrack,
  21237. ValueTypeName: 'quaternion',
  21238. // ValueBufferType is inherited
  21239. DefaultInterpolation: InterpolateLinear,
  21240. InterpolantFactoryMethodLinear: function ( result ) {
  21241. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  21242. },
  21243. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21244. } );
  21245. /**
  21246. * A Track that interpolates Strings
  21247. */
  21248. function StringKeyframeTrack( name, times, values, interpolation ) {
  21249. KeyframeTrack.call( this, name, times, values, interpolation );
  21250. }
  21251. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21252. constructor: StringKeyframeTrack,
  21253. ValueTypeName: 'string',
  21254. ValueBufferType: Array,
  21255. DefaultInterpolation: InterpolateDiscrete,
  21256. InterpolantFactoryMethodLinear: undefined,
  21257. InterpolantFactoryMethodSmooth: undefined
  21258. } );
  21259. /**
  21260. * A Track of vectored keyframe values.
  21261. */
  21262. function VectorKeyframeTrack( name, times, values, interpolation ) {
  21263. KeyframeTrack.call( this, name, times, values, interpolation );
  21264. }
  21265. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21266. constructor: VectorKeyframeTrack,
  21267. ValueTypeName: 'vector'
  21268. // ValueBufferType is inherited
  21269. // DefaultInterpolation is inherited
  21270. } );
  21271. function AnimationClip( name, duration, tracks, blendMode ) {
  21272. this.name = name;
  21273. this.tracks = tracks;
  21274. this.duration = ( duration !== undefined ) ? duration : - 1;
  21275. this.blendMode = ( blendMode !== undefined ) ? blendMode : NormalAnimationBlendMode;
  21276. this.uuid = MathUtils.generateUUID();
  21277. // this means it should figure out its duration by scanning the tracks
  21278. if ( this.duration < 0 ) {
  21279. this.resetDuration();
  21280. }
  21281. }
  21282. function getTrackTypeForValueTypeName( typeName ) {
  21283. switch ( typeName.toLowerCase() ) {
  21284. case 'scalar':
  21285. case 'double':
  21286. case 'float':
  21287. case 'number':
  21288. case 'integer':
  21289. return NumberKeyframeTrack;
  21290. case 'vector':
  21291. case 'vector2':
  21292. case 'vector3':
  21293. case 'vector4':
  21294. return VectorKeyframeTrack;
  21295. case 'color':
  21296. return ColorKeyframeTrack;
  21297. case 'quaternion':
  21298. return QuaternionKeyframeTrack;
  21299. case 'bool':
  21300. case 'boolean':
  21301. return BooleanKeyframeTrack;
  21302. case 'string':
  21303. return StringKeyframeTrack;
  21304. }
  21305. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  21306. }
  21307. function parseKeyframeTrack( json ) {
  21308. if ( json.type === undefined ) {
  21309. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  21310. }
  21311. const trackType = getTrackTypeForValueTypeName( json.type );
  21312. if ( json.times === undefined ) {
  21313. const times = [], values = [];
  21314. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  21315. json.times = times;
  21316. json.values = values;
  21317. }
  21318. // derived classes can define a static parse method
  21319. if ( trackType.parse !== undefined ) {
  21320. return trackType.parse( json );
  21321. } else {
  21322. // by default, we assume a constructor compatible with the base
  21323. return new trackType( json.name, json.times, json.values, json.interpolation );
  21324. }
  21325. }
  21326. Object.assign( AnimationClip, {
  21327. parse: function ( json ) {
  21328. const tracks = [],
  21329. jsonTracks = json.tracks,
  21330. frameTime = 1.0 / ( json.fps || 1.0 );
  21331. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  21332. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  21333. }
  21334. return new AnimationClip( json.name, json.duration, tracks, json.blendMode );
  21335. },
  21336. toJSON: function ( clip ) {
  21337. const tracks = [],
  21338. clipTracks = clip.tracks;
  21339. const json = {
  21340. 'name': clip.name,
  21341. 'duration': clip.duration,
  21342. 'tracks': tracks,
  21343. 'uuid': clip.uuid,
  21344. 'blendMode': clip.blendMode
  21345. };
  21346. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  21347. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  21348. }
  21349. return json;
  21350. },
  21351. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  21352. const numMorphTargets = morphTargetSequence.length;
  21353. const tracks = [];
  21354. for ( let i = 0; i < numMorphTargets; i ++ ) {
  21355. let times = [];
  21356. let values = [];
  21357. times.push(
  21358. ( i + numMorphTargets - 1 ) % numMorphTargets,
  21359. i,
  21360. ( i + 1 ) % numMorphTargets );
  21361. values.push( 0, 1, 0 );
  21362. const order = AnimationUtils.getKeyframeOrder( times );
  21363. times = AnimationUtils.sortedArray( times, 1, order );
  21364. values = AnimationUtils.sortedArray( values, 1, order );
  21365. // if there is a key at the first frame, duplicate it as the
  21366. // last frame as well for perfect loop.
  21367. if ( ! noLoop && times[ 0 ] === 0 ) {
  21368. times.push( numMorphTargets );
  21369. values.push( values[ 0 ] );
  21370. }
  21371. tracks.push(
  21372. new NumberKeyframeTrack(
  21373. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  21374. times, values
  21375. ).scale( 1.0 / fps ) );
  21376. }
  21377. return new AnimationClip( name, - 1, tracks );
  21378. },
  21379. findByName: function ( objectOrClipArray, name ) {
  21380. let clipArray = objectOrClipArray;
  21381. if ( ! Array.isArray( objectOrClipArray ) ) {
  21382. const o = objectOrClipArray;
  21383. clipArray = o.geometry && o.geometry.animations || o.animations;
  21384. }
  21385. for ( let i = 0; i < clipArray.length; i ++ ) {
  21386. if ( clipArray[ i ].name === name ) {
  21387. return clipArray[ i ];
  21388. }
  21389. }
  21390. return null;
  21391. },
  21392. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  21393. const animationToMorphTargets = {};
  21394. // tested with https://regex101.com/ on trick sequences
  21395. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21396. const pattern = /^([\w-]*?)([\d]+)$/;
  21397. // sort morph target names into animation groups based
  21398. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21399. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  21400. const morphTarget = morphTargets[ i ];
  21401. const parts = morphTarget.name.match( pattern );
  21402. if ( parts && parts.length > 1 ) {
  21403. const name = parts[ 1 ];
  21404. let animationMorphTargets = animationToMorphTargets[ name ];
  21405. if ( ! animationMorphTargets ) {
  21406. animationToMorphTargets[ name ] = animationMorphTargets = [];
  21407. }
  21408. animationMorphTargets.push( morphTarget );
  21409. }
  21410. }
  21411. const clips = [];
  21412. for ( const name in animationToMorphTargets ) {
  21413. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  21414. }
  21415. return clips;
  21416. },
  21417. // parse the animation.hierarchy format
  21418. parseAnimation: function ( animation, bones ) {
  21419. if ( ! animation ) {
  21420. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  21421. return null;
  21422. }
  21423. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  21424. // only return track if there are actually keys.
  21425. if ( animationKeys.length !== 0 ) {
  21426. const times = [];
  21427. const values = [];
  21428. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  21429. // empty keys are filtered out, so check again
  21430. if ( times.length !== 0 ) {
  21431. destTracks.push( new trackType( trackName, times, values ) );
  21432. }
  21433. }
  21434. };
  21435. const tracks = [];
  21436. const clipName = animation.name || 'default';
  21437. const fps = animation.fps || 30;
  21438. const blendMode = animation.blendMode;
  21439. // automatic length determination in AnimationClip.
  21440. let duration = animation.length || - 1;
  21441. const hierarchyTracks = animation.hierarchy || [];
  21442. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  21443. const animationKeys = hierarchyTracks[ h ].keys;
  21444. // skip empty tracks
  21445. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  21446. // process morph targets
  21447. if ( animationKeys[ 0 ].morphTargets ) {
  21448. // figure out all morph targets used in this track
  21449. const morphTargetNames = {};
  21450. let k;
  21451. for ( k = 0; k < animationKeys.length; k ++ ) {
  21452. if ( animationKeys[ k ].morphTargets ) {
  21453. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  21454. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  21455. }
  21456. }
  21457. }
  21458. // create a track for each morph target with all zero
  21459. // morphTargetInfluences except for the keys in which
  21460. // the morphTarget is named.
  21461. for ( const morphTargetName in morphTargetNames ) {
  21462. const times = [];
  21463. const values = [];
  21464. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  21465. const animationKey = animationKeys[ k ];
  21466. times.push( animationKey.time );
  21467. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  21468. }
  21469. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  21470. }
  21471. duration = morphTargetNames.length * ( fps || 1.0 );
  21472. } else {
  21473. // ...assume skeletal animation
  21474. const boneName = '.bones[' + bones[ h ].name + ']';
  21475. addNonemptyTrack(
  21476. VectorKeyframeTrack, boneName + '.position',
  21477. animationKeys, 'pos', tracks );
  21478. addNonemptyTrack(
  21479. QuaternionKeyframeTrack, boneName + '.quaternion',
  21480. animationKeys, 'rot', tracks );
  21481. addNonemptyTrack(
  21482. VectorKeyframeTrack, boneName + '.scale',
  21483. animationKeys, 'scl', tracks );
  21484. }
  21485. }
  21486. if ( tracks.length === 0 ) {
  21487. return null;
  21488. }
  21489. const clip = new AnimationClip( clipName, duration, tracks, blendMode );
  21490. return clip;
  21491. }
  21492. } );
  21493. Object.assign( AnimationClip.prototype, {
  21494. resetDuration: function () {
  21495. const tracks = this.tracks;
  21496. let duration = 0;
  21497. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  21498. const track = this.tracks[ i ];
  21499. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  21500. }
  21501. this.duration = duration;
  21502. return this;
  21503. },
  21504. trim: function () {
  21505. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21506. this.tracks[ i ].trim( 0, this.duration );
  21507. }
  21508. return this;
  21509. },
  21510. validate: function () {
  21511. let valid = true;
  21512. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21513. valid = valid && this.tracks[ i ].validate();
  21514. }
  21515. return valid;
  21516. },
  21517. optimize: function () {
  21518. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21519. this.tracks[ i ].optimize();
  21520. }
  21521. return this;
  21522. },
  21523. clone: function () {
  21524. const tracks = [];
  21525. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21526. tracks.push( this.tracks[ i ].clone() );
  21527. }
  21528. return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
  21529. }
  21530. } );
  21531. const Cache = {
  21532. enabled: false,
  21533. files: {},
  21534. add: function ( key, file ) {
  21535. if ( this.enabled === false ) return;
  21536. // console.log( 'THREE.Cache', 'Adding key:', key );
  21537. this.files[ key ] = file;
  21538. },
  21539. get: function ( key ) {
  21540. if ( this.enabled === false ) return;
  21541. // console.log( 'THREE.Cache', 'Checking key:', key );
  21542. return this.files[ key ];
  21543. },
  21544. remove: function ( key ) {
  21545. delete this.files[ key ];
  21546. },
  21547. clear: function () {
  21548. this.files = {};
  21549. }
  21550. };
  21551. function LoadingManager( onLoad, onProgress, onError ) {
  21552. const scope = this;
  21553. let isLoading = false;
  21554. let itemsLoaded = 0;
  21555. let itemsTotal = 0;
  21556. let urlModifier = undefined;
  21557. const handlers = [];
  21558. // Refer to #5689 for the reason why we don't set .onStart
  21559. // in the constructor
  21560. this.onStart = undefined;
  21561. this.onLoad = onLoad;
  21562. this.onProgress = onProgress;
  21563. this.onError = onError;
  21564. this.itemStart = function ( url ) {
  21565. itemsTotal ++;
  21566. if ( isLoading === false ) {
  21567. if ( scope.onStart !== undefined ) {
  21568. scope.onStart( url, itemsLoaded, itemsTotal );
  21569. }
  21570. }
  21571. isLoading = true;
  21572. };
  21573. this.itemEnd = function ( url ) {
  21574. itemsLoaded ++;
  21575. if ( scope.onProgress !== undefined ) {
  21576. scope.onProgress( url, itemsLoaded, itemsTotal );
  21577. }
  21578. if ( itemsLoaded === itemsTotal ) {
  21579. isLoading = false;
  21580. if ( scope.onLoad !== undefined ) {
  21581. scope.onLoad();
  21582. }
  21583. }
  21584. };
  21585. this.itemError = function ( url ) {
  21586. if ( scope.onError !== undefined ) {
  21587. scope.onError( url );
  21588. }
  21589. };
  21590. this.resolveURL = function ( url ) {
  21591. if ( urlModifier ) {
  21592. return urlModifier( url );
  21593. }
  21594. return url;
  21595. };
  21596. this.setURLModifier = function ( transform ) {
  21597. urlModifier = transform;
  21598. return this;
  21599. };
  21600. this.addHandler = function ( regex, loader ) {
  21601. handlers.push( regex, loader );
  21602. return this;
  21603. };
  21604. this.removeHandler = function ( regex ) {
  21605. const index = handlers.indexOf( regex );
  21606. if ( index !== - 1 ) {
  21607. handlers.splice( index, 2 );
  21608. }
  21609. return this;
  21610. };
  21611. this.getHandler = function ( file ) {
  21612. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  21613. const regex = handlers[ i ];
  21614. const loader = handlers[ i + 1 ];
  21615. if ( regex.global ) regex.lastIndex = 0; // see #17920
  21616. if ( regex.test( file ) ) {
  21617. return loader;
  21618. }
  21619. }
  21620. return null;
  21621. };
  21622. }
  21623. const DefaultLoadingManager = new LoadingManager();
  21624. function Loader( manager ) {
  21625. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21626. this.crossOrigin = 'anonymous';
  21627. this.path = '';
  21628. this.resourcePath = '';
  21629. this.requestHeader = {};
  21630. }
  21631. Object.assign( Loader.prototype, {
  21632. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  21633. loadAsync: function ( url, onProgress ) {
  21634. const scope = this;
  21635. return new Promise( function ( resolve, reject ) {
  21636. scope.load( url, resolve, onProgress, reject );
  21637. } );
  21638. },
  21639. parse: function ( /* data */ ) {},
  21640. setCrossOrigin: function ( crossOrigin ) {
  21641. this.crossOrigin = crossOrigin;
  21642. return this;
  21643. },
  21644. setPath: function ( path ) {
  21645. this.path = path;
  21646. return this;
  21647. },
  21648. setResourcePath: function ( resourcePath ) {
  21649. this.resourcePath = resourcePath;
  21650. return this;
  21651. },
  21652. setRequestHeader: function ( requestHeader ) {
  21653. this.requestHeader = requestHeader;
  21654. return this;
  21655. }
  21656. } );
  21657. const loading = {};
  21658. function FileLoader( manager ) {
  21659. Loader.call( this, manager );
  21660. }
  21661. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21662. constructor: FileLoader,
  21663. load: function ( url, onLoad, onProgress, onError ) {
  21664. if ( url === undefined ) url = '';
  21665. if ( this.path !== undefined ) url = this.path + url;
  21666. url = this.manager.resolveURL( url );
  21667. const scope = this;
  21668. const cached = Cache.get( url );
  21669. if ( cached !== undefined ) {
  21670. scope.manager.itemStart( url );
  21671. setTimeout( function () {
  21672. if ( onLoad ) onLoad( cached );
  21673. scope.manager.itemEnd( url );
  21674. }, 0 );
  21675. return cached;
  21676. }
  21677. // Check if request is duplicate
  21678. if ( loading[ url ] !== undefined ) {
  21679. loading[ url ].push( {
  21680. onLoad: onLoad,
  21681. onProgress: onProgress,
  21682. onError: onError
  21683. } );
  21684. return;
  21685. }
  21686. // Check for data: URI
  21687. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21688. const dataUriRegexResult = url.match( dataUriRegex );
  21689. let request;
  21690. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21691. if ( dataUriRegexResult ) {
  21692. const mimeType = dataUriRegexResult[ 1 ];
  21693. const isBase64 = !! dataUriRegexResult[ 2 ];
  21694. let data = dataUriRegexResult[ 3 ];
  21695. data = decodeURIComponent( data );
  21696. if ( isBase64 ) data = atob( data );
  21697. try {
  21698. let response;
  21699. const responseType = ( this.responseType || '' ).toLowerCase();
  21700. switch ( responseType ) {
  21701. case 'arraybuffer':
  21702. case 'blob':
  21703. const view = new Uint8Array( data.length );
  21704. for ( let i = 0; i < data.length; i ++ ) {
  21705. view[ i ] = data.charCodeAt( i );
  21706. }
  21707. if ( responseType === 'blob' ) {
  21708. response = new Blob( [ view.buffer ], { type: mimeType } );
  21709. } else {
  21710. response = view.buffer;
  21711. }
  21712. break;
  21713. case 'document':
  21714. const parser = new DOMParser();
  21715. response = parser.parseFromString( data, mimeType );
  21716. break;
  21717. case 'json':
  21718. response = JSON.parse( data );
  21719. break;
  21720. default: // 'text' or other
  21721. response = data;
  21722. break;
  21723. }
  21724. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21725. setTimeout( function () {
  21726. if ( onLoad ) onLoad( response );
  21727. scope.manager.itemEnd( url );
  21728. }, 0 );
  21729. } catch ( error ) {
  21730. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21731. setTimeout( function () {
  21732. if ( onError ) onError( error );
  21733. scope.manager.itemError( url );
  21734. scope.manager.itemEnd( url );
  21735. }, 0 );
  21736. }
  21737. } else {
  21738. // Initialise array for duplicate requests
  21739. loading[ url ] = [];
  21740. loading[ url ].push( {
  21741. onLoad: onLoad,
  21742. onProgress: onProgress,
  21743. onError: onError
  21744. } );
  21745. request = new XMLHttpRequest();
  21746. request.open( 'GET', url, true );
  21747. request.addEventListener( 'load', function ( event ) {
  21748. const response = this.response;
  21749. const callbacks = loading[ url ];
  21750. delete loading[ url ];
  21751. if ( this.status === 200 || this.status === 0 ) {
  21752. // Some browsers return HTTP Status 0 when using non-http protocol
  21753. // e.g. 'file://' or 'data://'. Handle as success.
  21754. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  21755. // Add to cache only on HTTP success, so that we do not cache
  21756. // error response bodies as proper responses to requests.
  21757. Cache.add( url, response );
  21758. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21759. const callback = callbacks[ i ];
  21760. if ( callback.onLoad ) callback.onLoad( response );
  21761. }
  21762. scope.manager.itemEnd( url );
  21763. } else {
  21764. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21765. const callback = callbacks[ i ];
  21766. if ( callback.onError ) callback.onError( event );
  21767. }
  21768. scope.manager.itemError( url );
  21769. scope.manager.itemEnd( url );
  21770. }
  21771. }, false );
  21772. request.addEventListener( 'progress', function ( event ) {
  21773. const callbacks = loading[ url ];
  21774. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21775. const callback = callbacks[ i ];
  21776. if ( callback.onProgress ) callback.onProgress( event );
  21777. }
  21778. }, false );
  21779. request.addEventListener( 'error', function ( event ) {
  21780. const callbacks = loading[ url ];
  21781. delete loading[ url ];
  21782. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21783. const callback = callbacks[ i ];
  21784. if ( callback.onError ) callback.onError( event );
  21785. }
  21786. scope.manager.itemError( url );
  21787. scope.manager.itemEnd( url );
  21788. }, false );
  21789. request.addEventListener( 'abort', function ( event ) {
  21790. const callbacks = loading[ url ];
  21791. delete loading[ url ];
  21792. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21793. const callback = callbacks[ i ];
  21794. if ( callback.onError ) callback.onError( event );
  21795. }
  21796. scope.manager.itemError( url );
  21797. scope.manager.itemEnd( url );
  21798. }, false );
  21799. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  21800. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  21801. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  21802. for ( const header in this.requestHeader ) {
  21803. request.setRequestHeader( header, this.requestHeader[ header ] );
  21804. }
  21805. request.send( null );
  21806. }
  21807. scope.manager.itemStart( url );
  21808. return request;
  21809. },
  21810. setResponseType: function ( value ) {
  21811. this.responseType = value;
  21812. return this;
  21813. },
  21814. setWithCredentials: function ( value ) {
  21815. this.withCredentials = value;
  21816. return this;
  21817. },
  21818. setMimeType: function ( value ) {
  21819. this.mimeType = value;
  21820. return this;
  21821. }
  21822. } );
  21823. function AnimationLoader( manager ) {
  21824. Loader.call( this, manager );
  21825. }
  21826. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21827. constructor: AnimationLoader,
  21828. load: function ( url, onLoad, onProgress, onError ) {
  21829. const scope = this;
  21830. const loader = new FileLoader( scope.manager );
  21831. loader.setPath( scope.path );
  21832. loader.setRequestHeader( scope.requestHeader );
  21833. loader.load( url, function ( text ) {
  21834. try {
  21835. onLoad( scope.parse( JSON.parse( text ) ) );
  21836. } catch ( e ) {
  21837. if ( onError ) {
  21838. onError( e );
  21839. } else {
  21840. console.error( e );
  21841. }
  21842. scope.manager.itemError( url );
  21843. }
  21844. }, onProgress, onError );
  21845. },
  21846. parse: function ( json ) {
  21847. const animations = [];
  21848. for ( let i = 0; i < json.length; i ++ ) {
  21849. const clip = AnimationClip.parse( json[ i ] );
  21850. animations.push( clip );
  21851. }
  21852. return animations;
  21853. }
  21854. } );
  21855. /**
  21856. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21857. *
  21858. * Sub classes have to implement the parse() method which will be used in load().
  21859. */
  21860. function CompressedTextureLoader( manager ) {
  21861. Loader.call( this, manager );
  21862. }
  21863. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21864. constructor: CompressedTextureLoader,
  21865. load: function ( url, onLoad, onProgress, onError ) {
  21866. const scope = this;
  21867. const images = [];
  21868. const texture = new CompressedTexture();
  21869. texture.image = images;
  21870. const loader = new FileLoader( this.manager );
  21871. loader.setPath( this.path );
  21872. loader.setResponseType( 'arraybuffer' );
  21873. loader.setRequestHeader( this.requestHeader );
  21874. let loaded = 0;
  21875. function loadTexture( i ) {
  21876. loader.load( url[ i ], function ( buffer ) {
  21877. const texDatas = scope.parse( buffer, true );
  21878. images[ i ] = {
  21879. width: texDatas.width,
  21880. height: texDatas.height,
  21881. format: texDatas.format,
  21882. mipmaps: texDatas.mipmaps
  21883. };
  21884. loaded += 1;
  21885. if ( loaded === 6 ) {
  21886. if ( texDatas.mipmapCount === 1 )
  21887. texture.minFilter = LinearFilter;
  21888. texture.format = texDatas.format;
  21889. texture.needsUpdate = true;
  21890. if ( onLoad ) onLoad( texture );
  21891. }
  21892. }, onProgress, onError );
  21893. }
  21894. if ( Array.isArray( url ) ) {
  21895. for ( let i = 0, il = url.length; i < il; ++ i ) {
  21896. loadTexture( i );
  21897. }
  21898. } else {
  21899. // compressed cubemap texture stored in a single DDS file
  21900. loader.load( url, function ( buffer ) {
  21901. const texDatas = scope.parse( buffer, true );
  21902. if ( texDatas.isCubemap ) {
  21903. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21904. for ( let f = 0; f < faces; f ++ ) {
  21905. images[ f ] = { mipmaps: [] };
  21906. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  21907. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  21908. images[ f ].format = texDatas.format;
  21909. images[ f ].width = texDatas.width;
  21910. images[ f ].height = texDatas.height;
  21911. }
  21912. }
  21913. } else {
  21914. texture.image.width = texDatas.width;
  21915. texture.image.height = texDatas.height;
  21916. texture.mipmaps = texDatas.mipmaps;
  21917. }
  21918. if ( texDatas.mipmapCount === 1 ) {
  21919. texture.minFilter = LinearFilter;
  21920. }
  21921. texture.format = texDatas.format;
  21922. texture.needsUpdate = true;
  21923. if ( onLoad ) onLoad( texture );
  21924. }, onProgress, onError );
  21925. }
  21926. return texture;
  21927. }
  21928. } );
  21929. function ImageLoader( manager ) {
  21930. Loader.call( this, manager );
  21931. }
  21932. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21933. constructor: ImageLoader,
  21934. load: function ( url, onLoad, onProgress, onError ) {
  21935. if ( this.path !== undefined ) url = this.path + url;
  21936. url = this.manager.resolveURL( url );
  21937. const scope = this;
  21938. const cached = Cache.get( url );
  21939. if ( cached !== undefined ) {
  21940. scope.manager.itemStart( url );
  21941. setTimeout( function () {
  21942. if ( onLoad ) onLoad( cached );
  21943. scope.manager.itemEnd( url );
  21944. }, 0 );
  21945. return cached;
  21946. }
  21947. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  21948. function onImageLoad() {
  21949. image.removeEventListener( 'load', onImageLoad, false );
  21950. image.removeEventListener( 'error', onImageError, false );
  21951. Cache.add( url, this );
  21952. if ( onLoad ) onLoad( this );
  21953. scope.manager.itemEnd( url );
  21954. }
  21955. function onImageError( event ) {
  21956. image.removeEventListener( 'load', onImageLoad, false );
  21957. image.removeEventListener( 'error', onImageError, false );
  21958. if ( onError ) onError( event );
  21959. scope.manager.itemError( url );
  21960. scope.manager.itemEnd( url );
  21961. }
  21962. image.addEventListener( 'load', onImageLoad, false );
  21963. image.addEventListener( 'error', onImageError, false );
  21964. if ( url.substr( 0, 5 ) !== 'data:' ) {
  21965. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  21966. }
  21967. scope.manager.itemStart( url );
  21968. image.src = url;
  21969. return image;
  21970. }
  21971. } );
  21972. function CubeTextureLoader( manager ) {
  21973. Loader.call( this, manager );
  21974. }
  21975. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21976. constructor: CubeTextureLoader,
  21977. load: function ( urls, onLoad, onProgress, onError ) {
  21978. const texture = new CubeTexture();
  21979. const loader = new ImageLoader( this.manager );
  21980. loader.setCrossOrigin( this.crossOrigin );
  21981. loader.setPath( this.path );
  21982. let loaded = 0;
  21983. function loadTexture( i ) {
  21984. loader.load( urls[ i ], function ( image ) {
  21985. texture.images[ i ] = image;
  21986. loaded ++;
  21987. if ( loaded === 6 ) {
  21988. texture.needsUpdate = true;
  21989. if ( onLoad ) onLoad( texture );
  21990. }
  21991. }, undefined, onError );
  21992. }
  21993. for ( let i = 0; i < urls.length; ++ i ) {
  21994. loadTexture( i );
  21995. }
  21996. return texture;
  21997. }
  21998. } );
  21999. /**
  22000. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22001. *
  22002. * Sub classes have to implement the parse() method which will be used in load().
  22003. */
  22004. function DataTextureLoader( manager ) {
  22005. Loader.call( this, manager );
  22006. }
  22007. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22008. constructor: DataTextureLoader,
  22009. load: function ( url, onLoad, onProgress, onError ) {
  22010. const scope = this;
  22011. const texture = new DataTexture();
  22012. const loader = new FileLoader( this.manager );
  22013. loader.setResponseType( 'arraybuffer' );
  22014. loader.setRequestHeader( this.requestHeader );
  22015. loader.setPath( this.path );
  22016. loader.load( url, function ( buffer ) {
  22017. const texData = scope.parse( buffer );
  22018. if ( ! texData ) return;
  22019. if ( texData.image !== undefined ) {
  22020. texture.image = texData.image;
  22021. } else if ( texData.data !== undefined ) {
  22022. texture.image.width = texData.width;
  22023. texture.image.height = texData.height;
  22024. texture.image.data = texData.data;
  22025. }
  22026. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22027. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22028. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22029. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22030. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22031. if ( texData.format !== undefined ) {
  22032. texture.format = texData.format;
  22033. }
  22034. if ( texData.type !== undefined ) {
  22035. texture.type = texData.type;
  22036. }
  22037. if ( texData.mipmaps !== undefined ) {
  22038. texture.mipmaps = texData.mipmaps;
  22039. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22040. }
  22041. if ( texData.mipmapCount === 1 ) {
  22042. texture.minFilter = LinearFilter;
  22043. }
  22044. texture.needsUpdate = true;
  22045. if ( onLoad ) onLoad( texture, texData );
  22046. }, onProgress, onError );
  22047. return texture;
  22048. }
  22049. } );
  22050. function TextureLoader( manager ) {
  22051. Loader.call( this, manager );
  22052. }
  22053. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22054. constructor: TextureLoader,
  22055. load: function ( url, onLoad, onProgress, onError ) {
  22056. const texture = new Texture();
  22057. const loader = new ImageLoader( this.manager );
  22058. loader.setCrossOrigin( this.crossOrigin );
  22059. loader.setPath( this.path );
  22060. loader.load( url, function ( image ) {
  22061. texture.image = image;
  22062. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22063. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22064. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22065. texture.needsUpdate = true;
  22066. if ( onLoad !== undefined ) {
  22067. onLoad( texture );
  22068. }
  22069. }, onProgress, onError );
  22070. return texture;
  22071. }
  22072. } );
  22073. /**
  22074. * Extensible curve object.
  22075. *
  22076. * Some common of curve methods:
  22077. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22078. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22079. * .getPoints(), .getSpacedPoints()
  22080. * .getLength()
  22081. * .updateArcLengths()
  22082. *
  22083. * This following curves inherit from THREE.Curve:
  22084. *
  22085. * -- 2D curves --
  22086. * THREE.ArcCurve
  22087. * THREE.CubicBezierCurve
  22088. * THREE.EllipseCurve
  22089. * THREE.LineCurve
  22090. * THREE.QuadraticBezierCurve
  22091. * THREE.SplineCurve
  22092. *
  22093. * -- 3D curves --
  22094. * THREE.CatmullRomCurve3
  22095. * THREE.CubicBezierCurve3
  22096. * THREE.LineCurve3
  22097. * THREE.QuadraticBezierCurve3
  22098. *
  22099. * A series of curves can be represented as a THREE.CurvePath.
  22100. *
  22101. **/
  22102. function Curve() {
  22103. this.type = 'Curve';
  22104. this.arcLengthDivisions = 200;
  22105. }
  22106. Object.assign( Curve.prototype, {
  22107. // Virtual base class method to overwrite and implement in subclasses
  22108. // - t [0 .. 1]
  22109. getPoint: function ( /* t, optionalTarget */ ) {
  22110. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  22111. return null;
  22112. },
  22113. // Get point at relative position in curve according to arc length
  22114. // - u [0 .. 1]
  22115. getPointAt: function ( u, optionalTarget ) {
  22116. const t = this.getUtoTmapping( u );
  22117. return this.getPoint( t, optionalTarget );
  22118. },
  22119. // Get sequence of points using getPoint( t )
  22120. getPoints: function ( divisions ) {
  22121. if ( divisions === undefined ) divisions = 5;
  22122. const points = [];
  22123. for ( let d = 0; d <= divisions; d ++ ) {
  22124. points.push( this.getPoint( d / divisions ) );
  22125. }
  22126. return points;
  22127. },
  22128. // Get sequence of points using getPointAt( u )
  22129. getSpacedPoints: function ( divisions ) {
  22130. if ( divisions === undefined ) divisions = 5;
  22131. const points = [];
  22132. for ( let d = 0; d <= divisions; d ++ ) {
  22133. points.push( this.getPointAt( d / divisions ) );
  22134. }
  22135. return points;
  22136. },
  22137. // Get total curve arc length
  22138. getLength: function () {
  22139. const lengths = this.getLengths();
  22140. return lengths[ lengths.length - 1 ];
  22141. },
  22142. // Get list of cumulative segment lengths
  22143. getLengths: function ( divisions ) {
  22144. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  22145. if ( this.cacheArcLengths &&
  22146. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22147. ! this.needsUpdate ) {
  22148. return this.cacheArcLengths;
  22149. }
  22150. this.needsUpdate = false;
  22151. const cache = [];
  22152. let current, last = this.getPoint( 0 );
  22153. let sum = 0;
  22154. cache.push( 0 );
  22155. for ( let p = 1; p <= divisions; p ++ ) {
  22156. current = this.getPoint( p / divisions );
  22157. sum += current.distanceTo( last );
  22158. cache.push( sum );
  22159. last = current;
  22160. }
  22161. this.cacheArcLengths = cache;
  22162. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22163. },
  22164. updateArcLengths: function () {
  22165. this.needsUpdate = true;
  22166. this.getLengths();
  22167. },
  22168. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22169. getUtoTmapping: function ( u, distance ) {
  22170. const arcLengths = this.getLengths();
  22171. let i = 0;
  22172. const il = arcLengths.length;
  22173. let targetArcLength; // The targeted u distance value to get
  22174. if ( distance ) {
  22175. targetArcLength = distance;
  22176. } else {
  22177. targetArcLength = u * arcLengths[ il - 1 ];
  22178. }
  22179. // binary search for the index with largest value smaller than target u distance
  22180. let low = 0, high = il - 1, comparison;
  22181. while ( low <= high ) {
  22182. 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
  22183. comparison = arcLengths[ i ] - targetArcLength;
  22184. if ( comparison < 0 ) {
  22185. low = i + 1;
  22186. } else if ( comparison > 0 ) {
  22187. high = i - 1;
  22188. } else {
  22189. high = i;
  22190. break;
  22191. // DONE
  22192. }
  22193. }
  22194. i = high;
  22195. if ( arcLengths[ i ] === targetArcLength ) {
  22196. return i / ( il - 1 );
  22197. }
  22198. // we could get finer grain at lengths, or use simple interpolation between two points
  22199. const lengthBefore = arcLengths[ i ];
  22200. const lengthAfter = arcLengths[ i + 1 ];
  22201. const segmentLength = lengthAfter - lengthBefore;
  22202. // determine where we are between the 'before' and 'after' points
  22203. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22204. // add that fractional amount to t
  22205. const t = ( i + segmentFraction ) / ( il - 1 );
  22206. return t;
  22207. },
  22208. // Returns a unit vector tangent at t
  22209. // In case any sub curve does not implement its tangent derivation,
  22210. // 2 points a small delta apart will be used to find its gradient
  22211. // which seems to give a reasonable approximation
  22212. getTangent: function ( t, optionalTarget ) {
  22213. const delta = 0.0001;
  22214. let t1 = t - delta;
  22215. let t2 = t + delta;
  22216. // Capping in case of danger
  22217. if ( t1 < 0 ) t1 = 0;
  22218. if ( t2 > 1 ) t2 = 1;
  22219. const pt1 = this.getPoint( t1 );
  22220. const pt2 = this.getPoint( t2 );
  22221. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22222. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22223. return tangent;
  22224. },
  22225. getTangentAt: function ( u, optionalTarget ) {
  22226. const t = this.getUtoTmapping( u );
  22227. return this.getTangent( t, optionalTarget );
  22228. },
  22229. computeFrenetFrames: function ( segments, closed ) {
  22230. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22231. const normal = new Vector3();
  22232. const tangents = [];
  22233. const normals = [];
  22234. const binormals = [];
  22235. const vec = new Vector3();
  22236. const mat = new Matrix4();
  22237. // compute the tangent vectors for each segment on the curve
  22238. for ( let i = 0; i <= segments; i ++ ) {
  22239. const u = i / segments;
  22240. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  22241. tangents[ i ].normalize();
  22242. }
  22243. // select an initial normal vector perpendicular to the first tangent vector,
  22244. // and in the direction of the minimum tangent xyz component
  22245. normals[ 0 ] = new Vector3();
  22246. binormals[ 0 ] = new Vector3();
  22247. let min = Number.MAX_VALUE;
  22248. const tx = Math.abs( tangents[ 0 ].x );
  22249. const ty = Math.abs( tangents[ 0 ].y );
  22250. const tz = Math.abs( tangents[ 0 ].z );
  22251. if ( tx <= min ) {
  22252. min = tx;
  22253. normal.set( 1, 0, 0 );
  22254. }
  22255. if ( ty <= min ) {
  22256. min = ty;
  22257. normal.set( 0, 1, 0 );
  22258. }
  22259. if ( tz <= min ) {
  22260. normal.set( 0, 0, 1 );
  22261. }
  22262. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22263. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22264. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22265. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22266. for ( let i = 1; i <= segments; i ++ ) {
  22267. normals[ i ] = normals[ i - 1 ].clone();
  22268. binormals[ i ] = binormals[ i - 1 ].clone();
  22269. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22270. if ( vec.length() > Number.EPSILON ) {
  22271. vec.normalize();
  22272. const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  22273. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22274. }
  22275. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22276. }
  22277. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22278. if ( closed === true ) {
  22279. let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  22280. theta /= segments;
  22281. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  22282. theta = - theta;
  22283. }
  22284. for ( let i = 1; i <= segments; i ++ ) {
  22285. // twist a little...
  22286. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22287. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22288. }
  22289. }
  22290. return {
  22291. tangents: tangents,
  22292. normals: normals,
  22293. binormals: binormals
  22294. };
  22295. },
  22296. clone: function () {
  22297. return new this.constructor().copy( this );
  22298. },
  22299. copy: function ( source ) {
  22300. this.arcLengthDivisions = source.arcLengthDivisions;
  22301. return this;
  22302. },
  22303. toJSON: function () {
  22304. const data = {
  22305. metadata: {
  22306. version: 4.5,
  22307. type: 'Curve',
  22308. generator: 'Curve.toJSON'
  22309. }
  22310. };
  22311. data.arcLengthDivisions = this.arcLengthDivisions;
  22312. data.type = this.type;
  22313. return data;
  22314. },
  22315. fromJSON: function ( json ) {
  22316. this.arcLengthDivisions = json.arcLengthDivisions;
  22317. return this;
  22318. }
  22319. } );
  22320. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  22321. Curve.call( this );
  22322. this.type = 'EllipseCurve';
  22323. this.aX = aX || 0;
  22324. this.aY = aY || 0;
  22325. this.xRadius = xRadius || 1;
  22326. this.yRadius = yRadius || 1;
  22327. this.aStartAngle = aStartAngle || 0;
  22328. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22329. this.aClockwise = aClockwise || false;
  22330. this.aRotation = aRotation || 0;
  22331. }
  22332. EllipseCurve.prototype = Object.create( Curve.prototype );
  22333. EllipseCurve.prototype.constructor = EllipseCurve;
  22334. EllipseCurve.prototype.isEllipseCurve = true;
  22335. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  22336. const point = optionalTarget || new Vector2();
  22337. const twoPi = Math.PI * 2;
  22338. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22339. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22340. // ensures that deltaAngle is 0 .. 2 PI
  22341. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22342. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22343. if ( deltaAngle < Number.EPSILON ) {
  22344. if ( samePoints ) {
  22345. deltaAngle = 0;
  22346. } else {
  22347. deltaAngle = twoPi;
  22348. }
  22349. }
  22350. if ( this.aClockwise === true && ! samePoints ) {
  22351. if ( deltaAngle === twoPi ) {
  22352. deltaAngle = - twoPi;
  22353. } else {
  22354. deltaAngle = deltaAngle - twoPi;
  22355. }
  22356. }
  22357. const angle = this.aStartAngle + t * deltaAngle;
  22358. let x = this.aX + this.xRadius * Math.cos( angle );
  22359. let y = this.aY + this.yRadius * Math.sin( angle );
  22360. if ( this.aRotation !== 0 ) {
  22361. const cos = Math.cos( this.aRotation );
  22362. const sin = Math.sin( this.aRotation );
  22363. const tx = x - this.aX;
  22364. const ty = y - this.aY;
  22365. // Rotate the point about the center of the ellipse.
  22366. x = tx * cos - ty * sin + this.aX;
  22367. y = tx * sin + ty * cos + this.aY;
  22368. }
  22369. return point.set( x, y );
  22370. };
  22371. EllipseCurve.prototype.copy = function ( source ) {
  22372. Curve.prototype.copy.call( this, source );
  22373. this.aX = source.aX;
  22374. this.aY = source.aY;
  22375. this.xRadius = source.xRadius;
  22376. this.yRadius = source.yRadius;
  22377. this.aStartAngle = source.aStartAngle;
  22378. this.aEndAngle = source.aEndAngle;
  22379. this.aClockwise = source.aClockwise;
  22380. this.aRotation = source.aRotation;
  22381. return this;
  22382. };
  22383. EllipseCurve.prototype.toJSON = function () {
  22384. const data = Curve.prototype.toJSON.call( this );
  22385. data.aX = this.aX;
  22386. data.aY = this.aY;
  22387. data.xRadius = this.xRadius;
  22388. data.yRadius = this.yRadius;
  22389. data.aStartAngle = this.aStartAngle;
  22390. data.aEndAngle = this.aEndAngle;
  22391. data.aClockwise = this.aClockwise;
  22392. data.aRotation = this.aRotation;
  22393. return data;
  22394. };
  22395. EllipseCurve.prototype.fromJSON = function ( json ) {
  22396. Curve.prototype.fromJSON.call( this, json );
  22397. this.aX = json.aX;
  22398. this.aY = json.aY;
  22399. this.xRadius = json.xRadius;
  22400. this.yRadius = json.yRadius;
  22401. this.aStartAngle = json.aStartAngle;
  22402. this.aEndAngle = json.aEndAngle;
  22403. this.aClockwise = json.aClockwise;
  22404. this.aRotation = json.aRotation;
  22405. return this;
  22406. };
  22407. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22408. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22409. this.type = 'ArcCurve';
  22410. }
  22411. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  22412. ArcCurve.prototype.constructor = ArcCurve;
  22413. ArcCurve.prototype.isArcCurve = true;
  22414. /**
  22415. * Centripetal CatmullRom Curve - which is useful for avoiding
  22416. * cusps and self-intersections in non-uniform catmull rom curves.
  22417. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22418. *
  22419. * curve.type accepts centripetal(default), chordal and catmullrom
  22420. * curve.tension is used for catmullrom which defaults to 0.5
  22421. */
  22422. /*
  22423. Based on an optimized c++ solution in
  22424. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22425. - http://ideone.com/NoEbVM
  22426. This CubicPoly class could be used for reusing some variables and calculations,
  22427. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22428. which can be placed in CurveUtils.
  22429. */
  22430. function CubicPoly() {
  22431. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  22432. /*
  22433. * Compute coefficients for a cubic polynomial
  22434. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22435. * such that
  22436. * p(0) = x0, p(1) = x1
  22437. * and
  22438. * p'(0) = t0, p'(1) = t1.
  22439. */
  22440. function init( x0, x1, t0, t1 ) {
  22441. c0 = x0;
  22442. c1 = t0;
  22443. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  22444. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22445. }
  22446. return {
  22447. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  22448. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  22449. },
  22450. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  22451. // compute tangents when parameterized in [t1,t2]
  22452. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  22453. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  22454. // rescale tangents for parametrization in [0,1]
  22455. t1 *= dt1;
  22456. t2 *= dt1;
  22457. init( x1, x2, t1, t2 );
  22458. },
  22459. calc: function ( t ) {
  22460. const t2 = t * t;
  22461. const t3 = t2 * t;
  22462. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22463. }
  22464. };
  22465. }
  22466. //
  22467. const tmp = new Vector3();
  22468. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  22469. function CatmullRomCurve3( points, closed, curveType, tension ) {
  22470. Curve.call( this );
  22471. this.type = 'CatmullRomCurve3';
  22472. this.points = points || [];
  22473. this.closed = closed || false;
  22474. this.curveType = curveType || 'centripetal';
  22475. this.tension = ( tension !== undefined ) ? tension : 0.5;
  22476. }
  22477. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  22478. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22479. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22480. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  22481. const point = optionalTarget || new Vector3();
  22482. const points = this.points;
  22483. const l = points.length;
  22484. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  22485. let intPoint = Math.floor( p );
  22486. let weight = p - intPoint;
  22487. if ( this.closed ) {
  22488. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  22489. } else if ( weight === 0 && intPoint === l - 1 ) {
  22490. intPoint = l - 2;
  22491. weight = 1;
  22492. }
  22493. let p0, p3; // 4 points (p1 & p2 defined below)
  22494. if ( this.closed || intPoint > 0 ) {
  22495. p0 = points[ ( intPoint - 1 ) % l ];
  22496. } else {
  22497. // extrapolate first point
  22498. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  22499. p0 = tmp;
  22500. }
  22501. const p1 = points[ intPoint % l ];
  22502. const p2 = points[ ( intPoint + 1 ) % l ];
  22503. if ( this.closed || intPoint + 2 < l ) {
  22504. p3 = points[ ( intPoint + 2 ) % l ];
  22505. } else {
  22506. // extrapolate last point
  22507. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  22508. p3 = tmp;
  22509. }
  22510. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  22511. // init Centripetal / Chordal Catmull-Rom
  22512. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22513. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  22514. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  22515. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  22516. // safety check for repeated points
  22517. if ( dt1 < 1e-4 ) dt1 = 1.0;
  22518. if ( dt0 < 1e-4 ) dt0 = dt1;
  22519. if ( dt2 < 1e-4 ) dt2 = dt1;
  22520. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  22521. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  22522. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  22523. } else if ( this.curveType === 'catmullrom' ) {
  22524. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  22525. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  22526. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  22527. }
  22528. point.set(
  22529. px.calc( weight ),
  22530. py.calc( weight ),
  22531. pz.calc( weight )
  22532. );
  22533. return point;
  22534. };
  22535. CatmullRomCurve3.prototype.copy = function ( source ) {
  22536. Curve.prototype.copy.call( this, source );
  22537. this.points = [];
  22538. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  22539. const point = source.points[ i ];
  22540. this.points.push( point.clone() );
  22541. }
  22542. this.closed = source.closed;
  22543. this.curveType = source.curveType;
  22544. this.tension = source.tension;
  22545. return this;
  22546. };
  22547. CatmullRomCurve3.prototype.toJSON = function () {
  22548. const data = Curve.prototype.toJSON.call( this );
  22549. data.points = [];
  22550. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  22551. const point = this.points[ i ];
  22552. data.points.push( point.toArray() );
  22553. }
  22554. data.closed = this.closed;
  22555. data.curveType = this.curveType;
  22556. data.tension = this.tension;
  22557. return data;
  22558. };
  22559. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  22560. Curve.prototype.fromJSON.call( this, json );
  22561. this.points = [];
  22562. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  22563. const point = json.points[ i ];
  22564. this.points.push( new Vector3().fromArray( point ) );
  22565. }
  22566. this.closed = json.closed;
  22567. this.curveType = json.curveType;
  22568. this.tension = json.tension;
  22569. return this;
  22570. };
  22571. /**
  22572. * Bezier Curves formulas obtained from
  22573. * http://en.wikipedia.org/wiki/Bézier_curve
  22574. */
  22575. function CatmullRom( t, p0, p1, p2, p3 ) {
  22576. const v0 = ( p2 - p0 ) * 0.5;
  22577. const v1 = ( p3 - p1 ) * 0.5;
  22578. const t2 = t * t;
  22579. const t3 = t * t2;
  22580. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  22581. }
  22582. //
  22583. function QuadraticBezierP0( t, p ) {
  22584. const k = 1 - t;
  22585. return k * k * p;
  22586. }
  22587. function QuadraticBezierP1( t, p ) {
  22588. return 2 * ( 1 - t ) * t * p;
  22589. }
  22590. function QuadraticBezierP2( t, p ) {
  22591. return t * t * p;
  22592. }
  22593. function QuadraticBezier( t, p0, p1, p2 ) {
  22594. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  22595. QuadraticBezierP2( t, p2 );
  22596. }
  22597. //
  22598. function CubicBezierP0( t, p ) {
  22599. const k = 1 - t;
  22600. return k * k * k * p;
  22601. }
  22602. function CubicBezierP1( t, p ) {
  22603. const k = 1 - t;
  22604. return 3 * k * k * t * p;
  22605. }
  22606. function CubicBezierP2( t, p ) {
  22607. return 3 * ( 1 - t ) * t * t * p;
  22608. }
  22609. function CubicBezierP3( t, p ) {
  22610. return t * t * t * p;
  22611. }
  22612. function CubicBezier( t, p0, p1, p2, p3 ) {
  22613. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  22614. CubicBezierP3( t, p3 );
  22615. }
  22616. function CubicBezierCurve( v0, v1, v2, v3 ) {
  22617. Curve.call( this );
  22618. this.type = 'CubicBezierCurve';
  22619. this.v0 = v0 || new Vector2();
  22620. this.v1 = v1 || new Vector2();
  22621. this.v2 = v2 || new Vector2();
  22622. this.v3 = v3 || new Vector2();
  22623. }
  22624. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  22625. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22626. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22627. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  22628. const point = optionalTarget || new Vector2();
  22629. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22630. point.set(
  22631. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22632. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  22633. );
  22634. return point;
  22635. };
  22636. CubicBezierCurve.prototype.copy = function ( source ) {
  22637. Curve.prototype.copy.call( this, source );
  22638. this.v0.copy( source.v0 );
  22639. this.v1.copy( source.v1 );
  22640. this.v2.copy( source.v2 );
  22641. this.v3.copy( source.v3 );
  22642. return this;
  22643. };
  22644. CubicBezierCurve.prototype.toJSON = function () {
  22645. const data = Curve.prototype.toJSON.call( this );
  22646. data.v0 = this.v0.toArray();
  22647. data.v1 = this.v1.toArray();
  22648. data.v2 = this.v2.toArray();
  22649. data.v3 = this.v3.toArray();
  22650. return data;
  22651. };
  22652. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  22653. Curve.prototype.fromJSON.call( this, json );
  22654. this.v0.fromArray( json.v0 );
  22655. this.v1.fromArray( json.v1 );
  22656. this.v2.fromArray( json.v2 );
  22657. this.v3.fromArray( json.v3 );
  22658. return this;
  22659. };
  22660. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  22661. Curve.call( this );
  22662. this.type = 'CubicBezierCurve3';
  22663. this.v0 = v0 || new Vector3();
  22664. this.v1 = v1 || new Vector3();
  22665. this.v2 = v2 || new Vector3();
  22666. this.v3 = v3 || new Vector3();
  22667. }
  22668. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  22669. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22670. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22671. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  22672. const point = optionalTarget || new Vector3();
  22673. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22674. point.set(
  22675. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22676. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  22677. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  22678. );
  22679. return point;
  22680. };
  22681. CubicBezierCurve3.prototype.copy = function ( source ) {
  22682. Curve.prototype.copy.call( this, source );
  22683. this.v0.copy( source.v0 );
  22684. this.v1.copy( source.v1 );
  22685. this.v2.copy( source.v2 );
  22686. this.v3.copy( source.v3 );
  22687. return this;
  22688. };
  22689. CubicBezierCurve3.prototype.toJSON = function () {
  22690. const data = Curve.prototype.toJSON.call( this );
  22691. data.v0 = this.v0.toArray();
  22692. data.v1 = this.v1.toArray();
  22693. data.v2 = this.v2.toArray();
  22694. data.v3 = this.v3.toArray();
  22695. return data;
  22696. };
  22697. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  22698. Curve.prototype.fromJSON.call( this, json );
  22699. this.v0.fromArray( json.v0 );
  22700. this.v1.fromArray( json.v1 );
  22701. this.v2.fromArray( json.v2 );
  22702. this.v3.fromArray( json.v3 );
  22703. return this;
  22704. };
  22705. function LineCurve( v1, v2 ) {
  22706. Curve.call( this );
  22707. this.type = 'LineCurve';
  22708. this.v1 = v1 || new Vector2();
  22709. this.v2 = v2 || new Vector2();
  22710. }
  22711. LineCurve.prototype = Object.create( Curve.prototype );
  22712. LineCurve.prototype.constructor = LineCurve;
  22713. LineCurve.prototype.isLineCurve = true;
  22714. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  22715. const point = optionalTarget || new Vector2();
  22716. if ( t === 1 ) {
  22717. point.copy( this.v2 );
  22718. } else {
  22719. point.copy( this.v2 ).sub( this.v1 );
  22720. point.multiplyScalar( t ).add( this.v1 );
  22721. }
  22722. return point;
  22723. };
  22724. // Line curve is linear, so we can overwrite default getPointAt
  22725. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  22726. return this.getPoint( u, optionalTarget );
  22727. };
  22728. LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
  22729. const tangent = optionalTarget || new Vector2();
  22730. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  22731. return tangent;
  22732. };
  22733. LineCurve.prototype.copy = function ( source ) {
  22734. Curve.prototype.copy.call( this, source );
  22735. this.v1.copy( source.v1 );
  22736. this.v2.copy( source.v2 );
  22737. return this;
  22738. };
  22739. LineCurve.prototype.toJSON = function () {
  22740. const data = Curve.prototype.toJSON.call( this );
  22741. data.v1 = this.v1.toArray();
  22742. data.v2 = this.v2.toArray();
  22743. return data;
  22744. };
  22745. LineCurve.prototype.fromJSON = function ( json ) {
  22746. Curve.prototype.fromJSON.call( this, json );
  22747. this.v1.fromArray( json.v1 );
  22748. this.v2.fromArray( json.v2 );
  22749. return this;
  22750. };
  22751. function LineCurve3( v1, v2 ) {
  22752. Curve.call( this );
  22753. this.type = 'LineCurve3';
  22754. this.v1 = v1 || new Vector3();
  22755. this.v2 = v2 || new Vector3();
  22756. }
  22757. LineCurve3.prototype = Object.create( Curve.prototype );
  22758. LineCurve3.prototype.constructor = LineCurve3;
  22759. LineCurve3.prototype.isLineCurve3 = true;
  22760. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  22761. const point = optionalTarget || new Vector3();
  22762. if ( t === 1 ) {
  22763. point.copy( this.v2 );
  22764. } else {
  22765. point.copy( this.v2 ).sub( this.v1 );
  22766. point.multiplyScalar( t ).add( this.v1 );
  22767. }
  22768. return point;
  22769. };
  22770. // Line curve is linear, so we can overwrite default getPointAt
  22771. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  22772. return this.getPoint( u, optionalTarget );
  22773. };
  22774. LineCurve3.prototype.copy = function ( source ) {
  22775. Curve.prototype.copy.call( this, source );
  22776. this.v1.copy( source.v1 );
  22777. this.v2.copy( source.v2 );
  22778. return this;
  22779. };
  22780. LineCurve3.prototype.toJSON = function () {
  22781. const data = Curve.prototype.toJSON.call( this );
  22782. data.v1 = this.v1.toArray();
  22783. data.v2 = this.v2.toArray();
  22784. return data;
  22785. };
  22786. LineCurve3.prototype.fromJSON = function ( json ) {
  22787. Curve.prototype.fromJSON.call( this, json );
  22788. this.v1.fromArray( json.v1 );
  22789. this.v2.fromArray( json.v2 );
  22790. return this;
  22791. };
  22792. function QuadraticBezierCurve( v0, v1, v2 ) {
  22793. Curve.call( this );
  22794. this.type = 'QuadraticBezierCurve';
  22795. this.v0 = v0 || new Vector2();
  22796. this.v1 = v1 || new Vector2();
  22797. this.v2 = v2 || new Vector2();
  22798. }
  22799. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  22800. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22801. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22802. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  22803. const point = optionalTarget || new Vector2();
  22804. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  22805. point.set(
  22806. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  22807. QuadraticBezier( t, v0.y, v1.y, v2.y )
  22808. );
  22809. return point;
  22810. };
  22811. QuadraticBezierCurve.prototype.copy = function ( source ) {
  22812. Curve.prototype.copy.call( this, source );
  22813. this.v0.copy( source.v0 );
  22814. this.v1.copy( source.v1 );
  22815. this.v2.copy( source.v2 );
  22816. return this;
  22817. };
  22818. QuadraticBezierCurve.prototype.toJSON = function () {
  22819. const data = Curve.prototype.toJSON.call( this );
  22820. data.v0 = this.v0.toArray();
  22821. data.v1 = this.v1.toArray();
  22822. data.v2 = this.v2.toArray();
  22823. return data;
  22824. };
  22825. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  22826. Curve.prototype.fromJSON.call( this, json );
  22827. this.v0.fromArray( json.v0 );
  22828. this.v1.fromArray( json.v1 );
  22829. this.v2.fromArray( json.v2 );
  22830. return this;
  22831. };
  22832. function QuadraticBezierCurve3( v0, v1, v2 ) {
  22833. Curve.call( this );
  22834. this.type = 'QuadraticBezierCurve3';
  22835. this.v0 = v0 || new Vector3();
  22836. this.v1 = v1 || new Vector3();
  22837. this.v2 = v2 || new Vector3();
  22838. }
  22839. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  22840. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22841. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22842. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  22843. const point = optionalTarget || new Vector3();
  22844. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  22845. point.set(
  22846. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  22847. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  22848. QuadraticBezier( t, v0.z, v1.z, v2.z )
  22849. );
  22850. return point;
  22851. };
  22852. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  22853. Curve.prototype.copy.call( this, source );
  22854. this.v0.copy( source.v0 );
  22855. this.v1.copy( source.v1 );
  22856. this.v2.copy( source.v2 );
  22857. return this;
  22858. };
  22859. QuadraticBezierCurve3.prototype.toJSON = function () {
  22860. const data = Curve.prototype.toJSON.call( this );
  22861. data.v0 = this.v0.toArray();
  22862. data.v1 = this.v1.toArray();
  22863. data.v2 = this.v2.toArray();
  22864. return data;
  22865. };
  22866. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  22867. Curve.prototype.fromJSON.call( this, json );
  22868. this.v0.fromArray( json.v0 );
  22869. this.v1.fromArray( json.v1 );
  22870. this.v2.fromArray( json.v2 );
  22871. return this;
  22872. };
  22873. function SplineCurve( points ) {
  22874. Curve.call( this );
  22875. this.type = 'SplineCurve';
  22876. this.points = points || [];
  22877. }
  22878. SplineCurve.prototype = Object.create( Curve.prototype );
  22879. SplineCurve.prototype.constructor = SplineCurve;
  22880. SplineCurve.prototype.isSplineCurve = true;
  22881. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  22882. const point = optionalTarget || new Vector2();
  22883. const points = this.points;
  22884. const p = ( points.length - 1 ) * t;
  22885. const intPoint = Math.floor( p );
  22886. const weight = p - intPoint;
  22887. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  22888. const p1 = points[ intPoint ];
  22889. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  22890. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  22891. point.set(
  22892. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  22893. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  22894. );
  22895. return point;
  22896. };
  22897. SplineCurve.prototype.copy = function ( source ) {
  22898. Curve.prototype.copy.call( this, source );
  22899. this.points = [];
  22900. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  22901. const point = source.points[ i ];
  22902. this.points.push( point.clone() );
  22903. }
  22904. return this;
  22905. };
  22906. SplineCurve.prototype.toJSON = function () {
  22907. const data = Curve.prototype.toJSON.call( this );
  22908. data.points = [];
  22909. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  22910. const point = this.points[ i ];
  22911. data.points.push( point.toArray() );
  22912. }
  22913. return data;
  22914. };
  22915. SplineCurve.prototype.fromJSON = function ( json ) {
  22916. Curve.prototype.fromJSON.call( this, json );
  22917. this.points = [];
  22918. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  22919. const point = json.points[ i ];
  22920. this.points.push( new Vector2().fromArray( point ) );
  22921. }
  22922. return this;
  22923. };
  22924. var Curves = /*#__PURE__*/Object.freeze({
  22925. __proto__: null,
  22926. ArcCurve: ArcCurve,
  22927. CatmullRomCurve3: CatmullRomCurve3,
  22928. CubicBezierCurve: CubicBezierCurve,
  22929. CubicBezierCurve3: CubicBezierCurve3,
  22930. EllipseCurve: EllipseCurve,
  22931. LineCurve: LineCurve,
  22932. LineCurve3: LineCurve3,
  22933. QuadraticBezierCurve: QuadraticBezierCurve,
  22934. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22935. SplineCurve: SplineCurve
  22936. });
  22937. /**************************************************************
  22938. * Curved Path - a curve path is simply a array of connected
  22939. * curves, but retains the api of a curve
  22940. **************************************************************/
  22941. function CurvePath() {
  22942. Curve.call( this );
  22943. this.type = 'CurvePath';
  22944. this.curves = [];
  22945. this.autoClose = false; // Automatically closes the path
  22946. }
  22947. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  22948. constructor: CurvePath,
  22949. add: function ( curve ) {
  22950. this.curves.push( curve );
  22951. },
  22952. closePath: function () {
  22953. // Add a line curve if start and end of lines are not connected
  22954. const startPoint = this.curves[ 0 ].getPoint( 0 );
  22955. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  22956. if ( ! startPoint.equals( endPoint ) ) {
  22957. this.curves.push( new LineCurve( endPoint, startPoint ) );
  22958. }
  22959. },
  22960. // To get accurate point with reference to
  22961. // entire path distance at time t,
  22962. // following has to be done:
  22963. // 1. Length of each sub path have to be known
  22964. // 2. Locate and identify type of curve
  22965. // 3. Get t for the curve
  22966. // 4. Return curve.getPointAt(t')
  22967. getPoint: function ( t ) {
  22968. const d = t * this.getLength();
  22969. const curveLengths = this.getCurveLengths();
  22970. let i = 0;
  22971. // To think about boundaries points.
  22972. while ( i < curveLengths.length ) {
  22973. if ( curveLengths[ i ] >= d ) {
  22974. const diff = curveLengths[ i ] - d;
  22975. const curve = this.curves[ i ];
  22976. const segmentLength = curve.getLength();
  22977. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22978. return curve.getPointAt( u );
  22979. }
  22980. i ++;
  22981. }
  22982. return null;
  22983. // loop where sum != 0, sum > d , sum+1 <d
  22984. },
  22985. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22986. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22987. // getPoint() depends on getLength
  22988. getLength: function () {
  22989. const lens = this.getCurveLengths();
  22990. return lens[ lens.length - 1 ];
  22991. },
  22992. // cacheLengths must be recalculated.
  22993. updateArcLengths: function () {
  22994. this.needsUpdate = true;
  22995. this.cacheLengths = null;
  22996. this.getCurveLengths();
  22997. },
  22998. // Compute lengths and cache them
  22999. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23000. getCurveLengths: function () {
  23001. // We use cache values if curves and cache array are same length
  23002. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23003. return this.cacheLengths;
  23004. }
  23005. // Get length of sub-curve
  23006. // Push sums into cached array
  23007. const lengths = [];
  23008. let sums = 0;
  23009. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23010. sums += this.curves[ i ].getLength();
  23011. lengths.push( sums );
  23012. }
  23013. this.cacheLengths = lengths;
  23014. return lengths;
  23015. },
  23016. getSpacedPoints: function ( divisions ) {
  23017. if ( divisions === undefined ) divisions = 40;
  23018. const points = [];
  23019. for ( let i = 0; i <= divisions; i ++ ) {
  23020. points.push( this.getPoint( i / divisions ) );
  23021. }
  23022. if ( this.autoClose ) {
  23023. points.push( points[ 0 ] );
  23024. }
  23025. return points;
  23026. },
  23027. getPoints: function ( divisions ) {
  23028. divisions = divisions || 12;
  23029. const points = [];
  23030. let last;
  23031. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23032. const curve = curves[ i ];
  23033. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  23034. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  23035. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  23036. : divisions;
  23037. const pts = curve.getPoints( resolution );
  23038. for ( let j = 0; j < pts.length; j ++ ) {
  23039. const point = pts[ j ];
  23040. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23041. points.push( point );
  23042. last = point;
  23043. }
  23044. }
  23045. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23046. points.push( points[ 0 ] );
  23047. }
  23048. return points;
  23049. },
  23050. copy: function ( source ) {
  23051. Curve.prototype.copy.call( this, source );
  23052. this.curves = [];
  23053. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23054. const curve = source.curves[ i ];
  23055. this.curves.push( curve.clone() );
  23056. }
  23057. this.autoClose = source.autoClose;
  23058. return this;
  23059. },
  23060. toJSON: function () {
  23061. const data = Curve.prototype.toJSON.call( this );
  23062. data.autoClose = this.autoClose;
  23063. data.curves = [];
  23064. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23065. const curve = this.curves[ i ];
  23066. data.curves.push( curve.toJSON() );
  23067. }
  23068. return data;
  23069. },
  23070. fromJSON: function ( json ) {
  23071. Curve.prototype.fromJSON.call( this, json );
  23072. this.autoClose = json.autoClose;
  23073. this.curves = [];
  23074. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23075. const curve = json.curves[ i ];
  23076. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23077. }
  23078. return this;
  23079. }
  23080. } );
  23081. function Path( points ) {
  23082. CurvePath.call( this );
  23083. this.type = 'Path';
  23084. this.currentPoint = new Vector2();
  23085. if ( points ) {
  23086. this.setFromPoints( points );
  23087. }
  23088. }
  23089. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  23090. constructor: Path,
  23091. setFromPoints: function ( points ) {
  23092. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23093. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23094. this.lineTo( points[ i ].x, points[ i ].y );
  23095. }
  23096. return this;
  23097. },
  23098. moveTo: function ( x, y ) {
  23099. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23100. return this;
  23101. },
  23102. lineTo: function ( x, y ) {
  23103. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  23104. this.curves.push( curve );
  23105. this.currentPoint.set( x, y );
  23106. return this;
  23107. },
  23108. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  23109. const curve = new QuadraticBezierCurve(
  23110. this.currentPoint.clone(),
  23111. new Vector2( aCPx, aCPy ),
  23112. new Vector2( aX, aY )
  23113. );
  23114. this.curves.push( curve );
  23115. this.currentPoint.set( aX, aY );
  23116. return this;
  23117. },
  23118. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23119. const curve = new CubicBezierCurve(
  23120. this.currentPoint.clone(),
  23121. new Vector2( aCP1x, aCP1y ),
  23122. new Vector2( aCP2x, aCP2y ),
  23123. new Vector2( aX, aY )
  23124. );
  23125. this.curves.push( curve );
  23126. this.currentPoint.set( aX, aY );
  23127. return this;
  23128. },
  23129. splineThru: function ( pts /*Array of Vector*/ ) {
  23130. const npts = [ this.currentPoint.clone() ].concat( pts );
  23131. const curve = new SplineCurve( npts );
  23132. this.curves.push( curve );
  23133. this.currentPoint.copy( pts[ pts.length - 1 ] );
  23134. return this;
  23135. },
  23136. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23137. const x0 = this.currentPoint.x;
  23138. const y0 = this.currentPoint.y;
  23139. this.absarc( aX + x0, aY + y0, aRadius,
  23140. aStartAngle, aEndAngle, aClockwise );
  23141. return this;
  23142. },
  23143. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23144. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23145. return this;
  23146. },
  23147. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23148. const x0 = this.currentPoint.x;
  23149. const y0 = this.currentPoint.y;
  23150. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23151. return this;
  23152. },
  23153. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23154. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23155. if ( this.curves.length > 0 ) {
  23156. // if a previous curve is present, attempt to join
  23157. const firstPoint = curve.getPoint( 0 );
  23158. if ( ! firstPoint.equals( this.currentPoint ) ) {
  23159. this.lineTo( firstPoint.x, firstPoint.y );
  23160. }
  23161. }
  23162. this.curves.push( curve );
  23163. const lastPoint = curve.getPoint( 1 );
  23164. this.currentPoint.copy( lastPoint );
  23165. return this;
  23166. },
  23167. copy: function ( source ) {
  23168. CurvePath.prototype.copy.call( this, source );
  23169. this.currentPoint.copy( source.currentPoint );
  23170. return this;
  23171. },
  23172. toJSON: function () {
  23173. const data = CurvePath.prototype.toJSON.call( this );
  23174. data.currentPoint = this.currentPoint.toArray();
  23175. return data;
  23176. },
  23177. fromJSON: function ( json ) {
  23178. CurvePath.prototype.fromJSON.call( this, json );
  23179. this.currentPoint.fromArray( json.currentPoint );
  23180. return this;
  23181. }
  23182. } );
  23183. function Shape( points ) {
  23184. Path.call( this, points );
  23185. this.uuid = MathUtils.generateUUID();
  23186. this.type = 'Shape';
  23187. this.holes = [];
  23188. }
  23189. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  23190. constructor: Shape,
  23191. getPointsHoles: function ( divisions ) {
  23192. const holesPts = [];
  23193. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  23194. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  23195. }
  23196. return holesPts;
  23197. },
  23198. // get points of shape and holes (keypoints based on segments parameter)
  23199. extractPoints: function ( divisions ) {
  23200. return {
  23201. shape: this.getPoints( divisions ),
  23202. holes: this.getPointsHoles( divisions )
  23203. };
  23204. },
  23205. copy: function ( source ) {
  23206. Path.prototype.copy.call( this, source );
  23207. this.holes = [];
  23208. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  23209. const hole = source.holes[ i ];
  23210. this.holes.push( hole.clone() );
  23211. }
  23212. return this;
  23213. },
  23214. toJSON: function () {
  23215. const data = Path.prototype.toJSON.call( this );
  23216. data.uuid = this.uuid;
  23217. data.holes = [];
  23218. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  23219. const hole = this.holes[ i ];
  23220. data.holes.push( hole.toJSON() );
  23221. }
  23222. return data;
  23223. },
  23224. fromJSON: function ( json ) {
  23225. Path.prototype.fromJSON.call( this, json );
  23226. this.uuid = json.uuid;
  23227. this.holes = [];
  23228. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  23229. const hole = json.holes[ i ];
  23230. this.holes.push( new Path().fromJSON( hole ) );
  23231. }
  23232. return this;
  23233. }
  23234. } );
  23235. function Light( color, intensity ) {
  23236. Object3D.call( this );
  23237. this.type = 'Light';
  23238. this.color = new Color( color );
  23239. this.intensity = intensity !== undefined ? intensity : 1;
  23240. }
  23241. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  23242. constructor: Light,
  23243. isLight: true,
  23244. copy: function ( source ) {
  23245. Object3D.prototype.copy.call( this, source );
  23246. this.color.copy( source.color );
  23247. this.intensity = source.intensity;
  23248. return this;
  23249. },
  23250. toJSON: function ( meta ) {
  23251. const data = Object3D.prototype.toJSON.call( this, meta );
  23252. data.object.color = this.color.getHex();
  23253. data.object.intensity = this.intensity;
  23254. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23255. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23256. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23257. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23258. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23259. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23260. return data;
  23261. }
  23262. } );
  23263. function HemisphereLight( skyColor, groundColor, intensity ) {
  23264. Light.call( this, skyColor, intensity );
  23265. this.type = 'HemisphereLight';
  23266. this.position.copy( Object3D.DefaultUp );
  23267. this.updateMatrix();
  23268. this.groundColor = new Color( groundColor );
  23269. }
  23270. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23271. constructor: HemisphereLight,
  23272. isHemisphereLight: true,
  23273. copy: function ( source ) {
  23274. Light.prototype.copy.call( this, source );
  23275. this.groundColor.copy( source.groundColor );
  23276. return this;
  23277. }
  23278. } );
  23279. function LightShadow( camera ) {
  23280. this.camera = camera;
  23281. this.bias = 0;
  23282. this.normalBias = 0;
  23283. this.radius = 1;
  23284. this.mapSize = new Vector2( 512, 512 );
  23285. this.map = null;
  23286. this.mapPass = null;
  23287. this.matrix = new Matrix4();
  23288. this.autoUpdate = true;
  23289. this.needsUpdate = false;
  23290. this._frustum = new Frustum();
  23291. this._frameExtents = new Vector2( 1, 1 );
  23292. this._viewportCount = 1;
  23293. this._viewports = [
  23294. new Vector4( 0, 0, 1, 1 )
  23295. ];
  23296. }
  23297. Object.assign( LightShadow.prototype, {
  23298. _projScreenMatrix: new Matrix4(),
  23299. _lightPositionWorld: new Vector3(),
  23300. _lookTarget: new Vector3(),
  23301. getViewportCount: function () {
  23302. return this._viewportCount;
  23303. },
  23304. getFrustum: function () {
  23305. return this._frustum;
  23306. },
  23307. updateMatrices: function ( light ) {
  23308. const shadowCamera = this.camera,
  23309. shadowMatrix = this.matrix,
  23310. projScreenMatrix = this._projScreenMatrix,
  23311. lookTarget = this._lookTarget,
  23312. lightPositionWorld = this._lightPositionWorld;
  23313. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23314. shadowCamera.position.copy( lightPositionWorld );
  23315. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  23316. shadowCamera.lookAt( lookTarget );
  23317. shadowCamera.updateMatrixWorld();
  23318. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23319. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  23320. shadowMatrix.set(
  23321. 0.5, 0.0, 0.0, 0.5,
  23322. 0.0, 0.5, 0.0, 0.5,
  23323. 0.0, 0.0, 0.5, 0.5,
  23324. 0.0, 0.0, 0.0, 1.0
  23325. );
  23326. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23327. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23328. },
  23329. getViewport: function ( viewportIndex ) {
  23330. return this._viewports[ viewportIndex ];
  23331. },
  23332. getFrameExtents: function () {
  23333. return this._frameExtents;
  23334. },
  23335. copy: function ( source ) {
  23336. this.camera = source.camera.clone();
  23337. this.bias = source.bias;
  23338. this.radius = source.radius;
  23339. this.mapSize.copy( source.mapSize );
  23340. return this;
  23341. },
  23342. clone: function () {
  23343. return new this.constructor().copy( this );
  23344. },
  23345. toJSON: function () {
  23346. const object = {};
  23347. if ( this.bias !== 0 ) object.bias = this.bias;
  23348. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23349. if ( this.radius !== 1 ) object.radius = this.radius;
  23350. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23351. object.camera = this.camera.toJSON( false ).object;
  23352. delete object.camera.matrix;
  23353. return object;
  23354. }
  23355. } );
  23356. function SpotLightShadow() {
  23357. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23358. this.focus = 1;
  23359. }
  23360. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23361. constructor: SpotLightShadow,
  23362. isSpotLightShadow: true,
  23363. updateMatrices: function ( light ) {
  23364. const camera = this.camera;
  23365. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  23366. const aspect = this.mapSize.width / this.mapSize.height;
  23367. const far = light.distance || camera.far;
  23368. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23369. camera.fov = fov;
  23370. camera.aspect = aspect;
  23371. camera.far = far;
  23372. camera.updateProjectionMatrix();
  23373. }
  23374. LightShadow.prototype.updateMatrices.call( this, light );
  23375. }
  23376. } );
  23377. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  23378. Light.call( this, color, intensity );
  23379. this.type = 'SpotLight';
  23380. this.position.copy( Object3D.DefaultUp );
  23381. this.updateMatrix();
  23382. this.target = new Object3D();
  23383. Object.defineProperty( this, 'power', {
  23384. get: function () {
  23385. // intensity = power per solid angle.
  23386. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23387. return this.intensity * Math.PI;
  23388. },
  23389. set: function ( power ) {
  23390. // intensity = power per solid angle.
  23391. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23392. this.intensity = power / Math.PI;
  23393. }
  23394. } );
  23395. this.distance = ( distance !== undefined ) ? distance : 0;
  23396. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  23397. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  23398. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  23399. this.shadow = new SpotLightShadow();
  23400. }
  23401. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23402. constructor: SpotLight,
  23403. isSpotLight: true,
  23404. copy: function ( source ) {
  23405. Light.prototype.copy.call( this, source );
  23406. this.distance = source.distance;
  23407. this.angle = source.angle;
  23408. this.penumbra = source.penumbra;
  23409. this.decay = source.decay;
  23410. this.target = source.target.clone();
  23411. this.shadow = source.shadow.clone();
  23412. return this;
  23413. }
  23414. } );
  23415. function PointLightShadow() {
  23416. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23417. this._frameExtents = new Vector2( 4, 2 );
  23418. this._viewportCount = 6;
  23419. this._viewports = [
  23420. // These viewports map a cube-map onto a 2D texture with the
  23421. // following orientation:
  23422. //
  23423. // xzXZ
  23424. // y Y
  23425. //
  23426. // X - Positive x direction
  23427. // x - Negative x direction
  23428. // Y - Positive y direction
  23429. // y - Negative y direction
  23430. // Z - Positive z direction
  23431. // z - Negative z direction
  23432. // positive X
  23433. new Vector4( 2, 1, 1, 1 ),
  23434. // negative X
  23435. new Vector4( 0, 1, 1, 1 ),
  23436. // positive Z
  23437. new Vector4( 3, 1, 1, 1 ),
  23438. // negative Z
  23439. new Vector4( 1, 1, 1, 1 ),
  23440. // positive Y
  23441. new Vector4( 3, 0, 1, 1 ),
  23442. // negative Y
  23443. new Vector4( 1, 0, 1, 1 )
  23444. ];
  23445. this._cubeDirections = [
  23446. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23447. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  23448. ];
  23449. this._cubeUps = [
  23450. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23451. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  23452. ];
  23453. }
  23454. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23455. constructor: PointLightShadow,
  23456. isPointLightShadow: true,
  23457. updateMatrices: function ( light, viewportIndex ) {
  23458. if ( viewportIndex === undefined ) viewportIndex = 0;
  23459. const camera = this.camera,
  23460. shadowMatrix = this.matrix,
  23461. lightPositionWorld = this._lightPositionWorld,
  23462. lookTarget = this._lookTarget,
  23463. projScreenMatrix = this._projScreenMatrix;
  23464. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23465. camera.position.copy( lightPositionWorld );
  23466. lookTarget.copy( camera.position );
  23467. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23468. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23469. camera.lookAt( lookTarget );
  23470. camera.updateMatrixWorld();
  23471. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  23472. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23473. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  23474. }
  23475. } );
  23476. function PointLight( color, intensity, distance, decay ) {
  23477. Light.call( this, color, intensity );
  23478. this.type = 'PointLight';
  23479. Object.defineProperty( this, 'power', {
  23480. get: function () {
  23481. // intensity = power per solid angle.
  23482. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23483. return this.intensity * 4 * Math.PI;
  23484. },
  23485. set: function ( power ) {
  23486. // intensity = power per solid angle.
  23487. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23488. this.intensity = power / ( 4 * Math.PI );
  23489. }
  23490. } );
  23491. this.distance = ( distance !== undefined ) ? distance : 0;
  23492. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  23493. this.shadow = new PointLightShadow();
  23494. }
  23495. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23496. constructor: PointLight,
  23497. isPointLight: true,
  23498. copy: function ( source ) {
  23499. Light.prototype.copy.call( this, source );
  23500. this.distance = source.distance;
  23501. this.decay = source.decay;
  23502. this.shadow = source.shadow.clone();
  23503. return this;
  23504. }
  23505. } );
  23506. function OrthographicCamera( left, right, top, bottom, near, far ) {
  23507. Camera.call( this );
  23508. this.type = 'OrthographicCamera';
  23509. this.zoom = 1;
  23510. this.view = null;
  23511. this.left = ( left !== undefined ) ? left : - 1;
  23512. this.right = ( right !== undefined ) ? right : 1;
  23513. this.top = ( top !== undefined ) ? top : 1;
  23514. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  23515. this.near = ( near !== undefined ) ? near : 0.1;
  23516. this.far = ( far !== undefined ) ? far : 2000;
  23517. this.updateProjectionMatrix();
  23518. }
  23519. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  23520. constructor: OrthographicCamera,
  23521. isOrthographicCamera: true,
  23522. copy: function ( source, recursive ) {
  23523. Camera.prototype.copy.call( this, source, recursive );
  23524. this.left = source.left;
  23525. this.right = source.right;
  23526. this.top = source.top;
  23527. this.bottom = source.bottom;
  23528. this.near = source.near;
  23529. this.far = source.far;
  23530. this.zoom = source.zoom;
  23531. this.view = source.view === null ? null : Object.assign( {}, source.view );
  23532. return this;
  23533. },
  23534. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  23535. if ( this.view === null ) {
  23536. this.view = {
  23537. enabled: true,
  23538. fullWidth: 1,
  23539. fullHeight: 1,
  23540. offsetX: 0,
  23541. offsetY: 0,
  23542. width: 1,
  23543. height: 1
  23544. };
  23545. }
  23546. this.view.enabled = true;
  23547. this.view.fullWidth = fullWidth;
  23548. this.view.fullHeight = fullHeight;
  23549. this.view.offsetX = x;
  23550. this.view.offsetY = y;
  23551. this.view.width = width;
  23552. this.view.height = height;
  23553. this.updateProjectionMatrix();
  23554. },
  23555. clearViewOffset: function () {
  23556. if ( this.view !== null ) {
  23557. this.view.enabled = false;
  23558. }
  23559. this.updateProjectionMatrix();
  23560. },
  23561. updateProjectionMatrix: function () {
  23562. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  23563. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  23564. const cx = ( this.right + this.left ) / 2;
  23565. const cy = ( this.top + this.bottom ) / 2;
  23566. let left = cx - dx;
  23567. let right = cx + dx;
  23568. let top = cy + dy;
  23569. let bottom = cy - dy;
  23570. if ( this.view !== null && this.view.enabled ) {
  23571. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  23572. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  23573. left += scaleW * this.view.offsetX;
  23574. right = left + scaleW * this.view.width;
  23575. top -= scaleH * this.view.offsetY;
  23576. bottom = top - scaleH * this.view.height;
  23577. }
  23578. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  23579. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  23580. },
  23581. toJSON: function ( meta ) {
  23582. const data = Object3D.prototype.toJSON.call( this, meta );
  23583. data.object.zoom = this.zoom;
  23584. data.object.left = this.left;
  23585. data.object.right = this.right;
  23586. data.object.top = this.top;
  23587. data.object.bottom = this.bottom;
  23588. data.object.near = this.near;
  23589. data.object.far = this.far;
  23590. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  23591. return data;
  23592. }
  23593. } );
  23594. function DirectionalLightShadow() {
  23595. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23596. }
  23597. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23598. constructor: DirectionalLightShadow,
  23599. isDirectionalLightShadow: true,
  23600. updateMatrices: function ( light ) {
  23601. LightShadow.prototype.updateMatrices.call( this, light );
  23602. }
  23603. } );
  23604. function DirectionalLight( color, intensity ) {
  23605. Light.call( this, color, intensity );
  23606. this.type = 'DirectionalLight';
  23607. this.position.copy( Object3D.DefaultUp );
  23608. this.updateMatrix();
  23609. this.target = new Object3D();
  23610. this.shadow = new DirectionalLightShadow();
  23611. }
  23612. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23613. constructor: DirectionalLight,
  23614. isDirectionalLight: true,
  23615. copy: function ( source ) {
  23616. Light.prototype.copy.call( this, source );
  23617. this.target = source.target.clone();
  23618. this.shadow = source.shadow.clone();
  23619. return this;
  23620. }
  23621. } );
  23622. function AmbientLight( color, intensity ) {
  23623. Light.call( this, color, intensity );
  23624. this.type = 'AmbientLight';
  23625. }
  23626. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23627. constructor: AmbientLight,
  23628. isAmbientLight: true
  23629. } );
  23630. function RectAreaLight( color, intensity, width, height ) {
  23631. Light.call( this, color, intensity );
  23632. this.type = 'RectAreaLight';
  23633. this.width = ( width !== undefined ) ? width : 10;
  23634. this.height = ( height !== undefined ) ? height : 10;
  23635. }
  23636. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23637. constructor: RectAreaLight,
  23638. isRectAreaLight: true,
  23639. copy: function ( source ) {
  23640. Light.prototype.copy.call( this, source );
  23641. this.width = source.width;
  23642. this.height = source.height;
  23643. return this;
  23644. },
  23645. toJSON: function ( meta ) {
  23646. const data = Light.prototype.toJSON.call( this, meta );
  23647. data.object.width = this.width;
  23648. data.object.height = this.height;
  23649. return data;
  23650. }
  23651. } );
  23652. /**
  23653. * Primary reference:
  23654. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23655. *
  23656. * Secondary reference:
  23657. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23658. */
  23659. // 3-band SH defined by 9 coefficients
  23660. class SphericalHarmonics3 {
  23661. constructor() {
  23662. Object.defineProperty( this, 'isSphericalHarmonics3', { value: true } );
  23663. this.coefficients = [];
  23664. for ( let i = 0; i < 9; i ++ ) {
  23665. this.coefficients.push( new Vector3() );
  23666. }
  23667. }
  23668. set( coefficients ) {
  23669. for ( let i = 0; i < 9; i ++ ) {
  23670. this.coefficients[ i ].copy( coefficients[ i ] );
  23671. }
  23672. return this;
  23673. }
  23674. zero() {
  23675. for ( let i = 0; i < 9; i ++ ) {
  23676. this.coefficients[ i ].set( 0, 0, 0 );
  23677. }
  23678. return this;
  23679. }
  23680. // get the radiance in the direction of the normal
  23681. // target is a Vector3
  23682. getAt( normal, target ) {
  23683. // normal is assumed to be unit length
  23684. const x = normal.x, y = normal.y, z = normal.z;
  23685. const coeff = this.coefficients;
  23686. // band 0
  23687. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23688. // band 1
  23689. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23690. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23691. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23692. // band 2
  23693. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23694. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23695. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23696. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23697. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23698. return target;
  23699. }
  23700. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23701. // target is a Vector3
  23702. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23703. getIrradianceAt( normal, target ) {
  23704. // normal is assumed to be unit length
  23705. const x = normal.x, y = normal.y, z = normal.z;
  23706. const coeff = this.coefficients;
  23707. // band 0
  23708. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23709. // band 1
  23710. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23711. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23712. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23713. // band 2
  23714. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23715. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23716. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23717. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23718. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23719. return target;
  23720. }
  23721. add( sh ) {
  23722. for ( let i = 0; i < 9; i ++ ) {
  23723. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23724. }
  23725. return this;
  23726. }
  23727. addScaledSH( sh, s ) {
  23728. for ( let i = 0; i < 9; i ++ ) {
  23729. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23730. }
  23731. return this;
  23732. }
  23733. scale( s ) {
  23734. for ( let i = 0; i < 9; i ++ ) {
  23735. this.coefficients[ i ].multiplyScalar( s );
  23736. }
  23737. return this;
  23738. }
  23739. lerp( sh, alpha ) {
  23740. for ( let i = 0; i < 9; i ++ ) {
  23741. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  23742. }
  23743. return this;
  23744. }
  23745. equals( sh ) {
  23746. for ( let i = 0; i < 9; i ++ ) {
  23747. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  23748. return false;
  23749. }
  23750. }
  23751. return true;
  23752. }
  23753. copy( sh ) {
  23754. return this.set( sh.coefficients );
  23755. }
  23756. clone() {
  23757. return new this.constructor().copy( this );
  23758. }
  23759. fromArray( array, offset ) {
  23760. if ( offset === undefined ) offset = 0;
  23761. const coefficients = this.coefficients;
  23762. for ( let i = 0; i < 9; i ++ ) {
  23763. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  23764. }
  23765. return this;
  23766. }
  23767. toArray( array, offset ) {
  23768. if ( array === undefined ) array = [];
  23769. if ( offset === undefined ) offset = 0;
  23770. const coefficients = this.coefficients;
  23771. for ( let i = 0; i < 9; i ++ ) {
  23772. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  23773. }
  23774. return array;
  23775. }
  23776. // evaluate the basis functions
  23777. // shBasis is an Array[ 9 ]
  23778. static getBasisAt( normal, shBasis ) {
  23779. // normal is assumed to be unit length
  23780. const x = normal.x, y = normal.y, z = normal.z;
  23781. // band 0
  23782. shBasis[ 0 ] = 0.282095;
  23783. // band 1
  23784. shBasis[ 1 ] = 0.488603 * y;
  23785. shBasis[ 2 ] = 0.488603 * z;
  23786. shBasis[ 3 ] = 0.488603 * x;
  23787. // band 2
  23788. shBasis[ 4 ] = 1.092548 * x * y;
  23789. shBasis[ 5 ] = 1.092548 * y * z;
  23790. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  23791. shBasis[ 7 ] = 1.092548 * x * z;
  23792. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  23793. }
  23794. }
  23795. function LightProbe( sh, intensity ) {
  23796. Light.call( this, undefined, intensity );
  23797. this.type = 'LightProbe';
  23798. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  23799. }
  23800. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  23801. constructor: LightProbe,
  23802. isLightProbe: true,
  23803. copy: function ( source ) {
  23804. Light.prototype.copy.call( this, source );
  23805. this.sh.copy( source.sh );
  23806. return this;
  23807. },
  23808. fromJSON: function ( json ) {
  23809. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23810. this.sh.fromArray( json.sh );
  23811. return this;
  23812. },
  23813. toJSON: function ( meta ) {
  23814. const data = Light.prototype.toJSON.call( this, meta );
  23815. data.object.sh = this.sh.toArray();
  23816. return data;
  23817. }
  23818. } );
  23819. function MaterialLoader( manager ) {
  23820. Loader.call( this, manager );
  23821. this.textures = {};
  23822. }
  23823. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  23824. constructor: MaterialLoader,
  23825. load: function ( url, onLoad, onProgress, onError ) {
  23826. const scope = this;
  23827. const loader = new FileLoader( scope.manager );
  23828. loader.setPath( scope.path );
  23829. loader.setRequestHeader( scope.requestHeader );
  23830. loader.load( url, function ( text ) {
  23831. try {
  23832. onLoad( scope.parse( JSON.parse( text ) ) );
  23833. } catch ( e ) {
  23834. if ( onError ) {
  23835. onError( e );
  23836. } else {
  23837. console.error( e );
  23838. }
  23839. scope.manager.itemError( url );
  23840. }
  23841. }, onProgress, onError );
  23842. },
  23843. parse: function ( json ) {
  23844. const textures = this.textures;
  23845. function getTexture( name ) {
  23846. if ( textures[ name ] === undefined ) {
  23847. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23848. }
  23849. return textures[ name ];
  23850. }
  23851. const material = new Materials[ json.type ]();
  23852. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23853. if ( json.name !== undefined ) material.name = json.name;
  23854. if ( json.color !== undefined ) material.color.setHex( json.color );
  23855. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23856. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23857. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  23858. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23859. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  23860. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23861. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  23862. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  23863. if ( json.fog !== undefined ) material.fog = json.fog;
  23864. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  23865. if ( json.blending !== undefined ) material.blending = json.blending;
  23866. if ( json.combine !== undefined ) material.combine = json.combine;
  23867. if ( json.side !== undefined ) material.side = json.side;
  23868. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  23869. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  23870. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  23871. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  23872. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  23873. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  23874. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  23875. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  23876. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  23877. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  23878. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  23879. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  23880. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  23881. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  23882. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  23883. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  23884. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  23885. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  23886. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  23887. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  23888. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  23889. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  23890. if ( json.scale !== undefined ) material.scale = json.scale;
  23891. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  23892. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23893. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23894. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  23895. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  23896. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  23897. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  23898. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  23899. if ( json.visible !== undefined ) material.visible = json.visible;
  23900. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  23901. if ( json.userData !== undefined ) material.userData = json.userData;
  23902. if ( json.vertexColors !== undefined ) {
  23903. if ( typeof json.vertexColors === 'number' ) {
  23904. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  23905. } else {
  23906. material.vertexColors = json.vertexColors;
  23907. }
  23908. }
  23909. // Shader Material
  23910. if ( json.uniforms !== undefined ) {
  23911. for ( const name in json.uniforms ) {
  23912. const uniform = json.uniforms[ name ];
  23913. material.uniforms[ name ] = {};
  23914. switch ( uniform.type ) {
  23915. case 't':
  23916. material.uniforms[ name ].value = getTexture( uniform.value );
  23917. break;
  23918. case 'c':
  23919. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  23920. break;
  23921. case 'v2':
  23922. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  23923. break;
  23924. case 'v3':
  23925. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  23926. break;
  23927. case 'v4':
  23928. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  23929. break;
  23930. case 'm3':
  23931. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  23932. break;
  23933. case 'm4':
  23934. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  23935. break;
  23936. default:
  23937. material.uniforms[ name ].value = uniform.value;
  23938. }
  23939. }
  23940. }
  23941. if ( json.defines !== undefined ) material.defines = json.defines;
  23942. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  23943. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  23944. if ( json.extensions !== undefined ) {
  23945. for ( const key in json.extensions ) {
  23946. material.extensions[ key ] = json.extensions[ key ];
  23947. }
  23948. }
  23949. // Deprecated
  23950. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  23951. // for PointsMaterial
  23952. if ( json.size !== undefined ) material.size = json.size;
  23953. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  23954. // maps
  23955. if ( json.map !== undefined ) material.map = getTexture( json.map );
  23956. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  23957. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  23958. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  23959. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  23960. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  23961. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  23962. if ( json.normalScale !== undefined ) {
  23963. let normalScale = json.normalScale;
  23964. if ( Array.isArray( normalScale ) === false ) {
  23965. // Blender exporter used to export a scalar. See #7459
  23966. normalScale = [ normalScale, normalScale ];
  23967. }
  23968. material.normalScale = new Vector2().fromArray( normalScale );
  23969. }
  23970. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  23971. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  23972. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  23973. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  23974. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  23975. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  23976. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  23977. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  23978. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  23979. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  23980. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  23981. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  23982. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  23983. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  23984. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  23985. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  23986. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  23987. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  23988. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  23989. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  23990. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  23991. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  23992. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  23993. return material;
  23994. },
  23995. setTextures: function ( value ) {
  23996. this.textures = value;
  23997. return this;
  23998. }
  23999. } );
  24000. const LoaderUtils = {
  24001. decodeText: function ( array ) {
  24002. if ( typeof TextDecoder !== 'undefined' ) {
  24003. return new TextDecoder().decode( array );
  24004. }
  24005. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24006. // throws a "maximum call stack size exceeded" error for large arrays.
  24007. let s = '';
  24008. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24009. // Implicitly assumes little-endian.
  24010. s += String.fromCharCode( array[ i ] );
  24011. }
  24012. try {
  24013. // merges multi-byte utf-8 characters.
  24014. return decodeURIComponent( escape( s ) );
  24015. } catch ( e ) { // see #16358
  24016. return s;
  24017. }
  24018. },
  24019. extractUrlBase: function ( url ) {
  24020. const index = url.lastIndexOf( '/' );
  24021. if ( index === - 1 ) return './';
  24022. return url.substr( 0, index + 1 );
  24023. }
  24024. };
  24025. function InstancedBufferGeometry() {
  24026. BufferGeometry.call( this );
  24027. this.type = 'InstancedBufferGeometry';
  24028. this.instanceCount = Infinity;
  24029. }
  24030. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  24031. constructor: InstancedBufferGeometry,
  24032. isInstancedBufferGeometry: true,
  24033. copy: function ( source ) {
  24034. BufferGeometry.prototype.copy.call( this, source );
  24035. this.instanceCount = source.instanceCount;
  24036. return this;
  24037. },
  24038. clone: function () {
  24039. return new this.constructor().copy( this );
  24040. },
  24041. toJSON: function () {
  24042. const data = BufferGeometry.prototype.toJSON.call( this );
  24043. data.instanceCount = this.instanceCount;
  24044. data.isInstancedBufferGeometry = true;
  24045. return data;
  24046. }
  24047. } );
  24048. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  24049. if ( typeof ( normalized ) === 'number' ) {
  24050. meshPerAttribute = normalized;
  24051. normalized = false;
  24052. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  24053. }
  24054. BufferAttribute.call( this, array, itemSize, normalized );
  24055. this.meshPerAttribute = meshPerAttribute || 1;
  24056. }
  24057. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24058. constructor: InstancedBufferAttribute,
  24059. isInstancedBufferAttribute: true,
  24060. copy: function ( source ) {
  24061. BufferAttribute.prototype.copy.call( this, source );
  24062. this.meshPerAttribute = source.meshPerAttribute;
  24063. return this;
  24064. },
  24065. toJSON: function () {
  24066. const data = BufferAttribute.prototype.toJSON.call( this );
  24067. data.meshPerAttribute = this.meshPerAttribute;
  24068. data.isInstancedBufferAttribute = true;
  24069. return data;
  24070. }
  24071. } );
  24072. function BufferGeometryLoader( manager ) {
  24073. Loader.call( this, manager );
  24074. }
  24075. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24076. constructor: BufferGeometryLoader,
  24077. load: function ( url, onLoad, onProgress, onError ) {
  24078. const scope = this;
  24079. const loader = new FileLoader( scope.manager );
  24080. loader.setPath( scope.path );
  24081. loader.setRequestHeader( scope.requestHeader );
  24082. loader.load( url, function ( text ) {
  24083. try {
  24084. onLoad( scope.parse( JSON.parse( text ) ) );
  24085. } catch ( e ) {
  24086. if ( onError ) {
  24087. onError( e );
  24088. } else {
  24089. console.error( e );
  24090. }
  24091. scope.manager.itemError( url );
  24092. }
  24093. }, onProgress, onError );
  24094. },
  24095. parse: function ( json ) {
  24096. const interleavedBufferMap = {};
  24097. const arrayBufferMap = {};
  24098. function getInterleavedBuffer( json, uuid ) {
  24099. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24100. const interleavedBuffers = json.interleavedBuffers;
  24101. const interleavedBuffer = interleavedBuffers[ uuid ];
  24102. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24103. const array = new TYPED_ARRAYS[ interleavedBuffer.type ]( buffer );
  24104. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24105. ib.uuid = interleavedBuffer.uuid;
  24106. interleavedBufferMap[ uuid ] = ib;
  24107. return ib;
  24108. }
  24109. function getArrayBuffer( json, uuid ) {
  24110. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24111. const arrayBuffers = json.arrayBuffers;
  24112. const arrayBuffer = arrayBuffers[ uuid ];
  24113. const ab = new Uint32Array( arrayBuffer ).buffer;
  24114. arrayBufferMap[ uuid ] = ab;
  24115. return ab;
  24116. }
  24117. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24118. const index = json.data.index;
  24119. if ( index !== undefined ) {
  24120. const typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  24121. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24122. }
  24123. const attributes = json.data.attributes;
  24124. for ( const key in attributes ) {
  24125. const attribute = attributes[ key ];
  24126. let bufferAttribute;
  24127. if ( attribute.isInterleavedBufferAttribute ) {
  24128. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24129. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24130. } else {
  24131. const typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  24132. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24133. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24134. }
  24135. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24136. geometry.setAttribute( key, bufferAttribute );
  24137. }
  24138. const morphAttributes = json.data.morphAttributes;
  24139. if ( morphAttributes ) {
  24140. for ( const key in morphAttributes ) {
  24141. const attributeArray = morphAttributes[ key ];
  24142. const array = [];
  24143. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24144. const attribute = attributeArray[ i ];
  24145. let bufferAttribute;
  24146. if ( attribute.isInterleavedBufferAttribute ) {
  24147. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24148. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24149. } else {
  24150. const typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  24151. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24152. }
  24153. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24154. array.push( bufferAttribute );
  24155. }
  24156. geometry.morphAttributes[ key ] = array;
  24157. }
  24158. }
  24159. const morphTargetsRelative = json.data.morphTargetsRelative;
  24160. if ( morphTargetsRelative ) {
  24161. geometry.morphTargetsRelative = true;
  24162. }
  24163. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24164. if ( groups !== undefined ) {
  24165. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24166. const group = groups[ i ];
  24167. geometry.addGroup( group.start, group.count, group.materialIndex );
  24168. }
  24169. }
  24170. const boundingSphere = json.data.boundingSphere;
  24171. if ( boundingSphere !== undefined ) {
  24172. const center = new Vector3();
  24173. if ( boundingSphere.center !== undefined ) {
  24174. center.fromArray( boundingSphere.center );
  24175. }
  24176. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24177. }
  24178. if ( json.name ) geometry.name = json.name;
  24179. if ( json.userData ) geometry.userData = json.userData;
  24180. return geometry;
  24181. }
  24182. } );
  24183. const TYPED_ARRAYS = {
  24184. Int8Array: Int8Array,
  24185. Uint8Array: Uint8Array,
  24186. // Workaround for IE11 pre KB2929437. See #11440
  24187. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24188. Int16Array: Int16Array,
  24189. Uint16Array: Uint16Array,
  24190. Int32Array: Int32Array,
  24191. Uint32Array: Uint32Array,
  24192. Float32Array: Float32Array,
  24193. Float64Array: Float64Array
  24194. };
  24195. class ObjectLoader extends Loader {
  24196. constructor( manager ) {
  24197. super( manager );
  24198. }
  24199. load( url, onLoad, onProgress, onError ) {
  24200. const scope = this;
  24201. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24202. this.resourcePath = this.resourcePath || path;
  24203. const loader = new FileLoader( scope.manager );
  24204. loader.setPath( this.path );
  24205. loader.setRequestHeader( this.requestHeader );
  24206. loader.load( url, function ( text ) {
  24207. let json = null;
  24208. try {
  24209. json = JSON.parse( text );
  24210. } catch ( error ) {
  24211. if ( onError !== undefined ) onError( error );
  24212. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24213. return;
  24214. }
  24215. const metadata = json.metadata;
  24216. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24217. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24218. return;
  24219. }
  24220. scope.parse( json, onLoad );
  24221. }, onProgress, onError );
  24222. }
  24223. parse( json, onLoad ) {
  24224. const shapes = this.parseShape( json.shapes );
  24225. const geometries = this.parseGeometries( json.geometries, shapes );
  24226. const images = this.parseImages( json.images, function () {
  24227. if ( onLoad !== undefined ) onLoad( object );
  24228. } );
  24229. const textures = this.parseTextures( json.textures, images );
  24230. const materials = this.parseMaterials( json.materials, textures );
  24231. const object = this.parseObject( json.object, geometries, materials );
  24232. if ( json.animations ) {
  24233. object.animations = this.parseAnimations( json.animations );
  24234. }
  24235. if ( json.images === undefined || json.images.length === 0 ) {
  24236. if ( onLoad !== undefined ) onLoad( object );
  24237. }
  24238. return object;
  24239. }
  24240. parseShape( json ) {
  24241. const shapes = {};
  24242. if ( json !== undefined ) {
  24243. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24244. const shape = new Shape().fromJSON( json[ i ] );
  24245. shapes[ shape.uuid ] = shape;
  24246. }
  24247. }
  24248. return shapes;
  24249. }
  24250. parseGeometries( json, shapes ) {
  24251. const geometries = {};
  24252. let geometryShapes;
  24253. if ( json !== undefined ) {
  24254. const bufferGeometryLoader = new BufferGeometryLoader();
  24255. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24256. let geometry;
  24257. const data = json[ i ];
  24258. switch ( data.type ) {
  24259. case 'PlaneGeometry':
  24260. case 'PlaneBufferGeometry':
  24261. geometry = new Geometries[ data.type ](
  24262. data.width,
  24263. data.height,
  24264. data.widthSegments,
  24265. data.heightSegments
  24266. );
  24267. break;
  24268. case 'BoxGeometry':
  24269. case 'BoxBufferGeometry':
  24270. case 'CubeGeometry': // backwards compatible
  24271. geometry = new Geometries[ data.type ](
  24272. data.width,
  24273. data.height,
  24274. data.depth,
  24275. data.widthSegments,
  24276. data.heightSegments,
  24277. data.depthSegments
  24278. );
  24279. break;
  24280. case 'CircleGeometry':
  24281. case 'CircleBufferGeometry':
  24282. geometry = new Geometries[ data.type ](
  24283. data.radius,
  24284. data.segments,
  24285. data.thetaStart,
  24286. data.thetaLength
  24287. );
  24288. break;
  24289. case 'CylinderGeometry':
  24290. case 'CylinderBufferGeometry':
  24291. geometry = new Geometries[ data.type ](
  24292. data.radiusTop,
  24293. data.radiusBottom,
  24294. data.height,
  24295. data.radialSegments,
  24296. data.heightSegments,
  24297. data.openEnded,
  24298. data.thetaStart,
  24299. data.thetaLength
  24300. );
  24301. break;
  24302. case 'ConeGeometry':
  24303. case 'ConeBufferGeometry':
  24304. geometry = new Geometries[ data.type ](
  24305. data.radius,
  24306. data.height,
  24307. data.radialSegments,
  24308. data.heightSegments,
  24309. data.openEnded,
  24310. data.thetaStart,
  24311. data.thetaLength
  24312. );
  24313. break;
  24314. case 'SphereGeometry':
  24315. case 'SphereBufferGeometry':
  24316. geometry = new Geometries[ data.type ](
  24317. data.radius,
  24318. data.widthSegments,
  24319. data.heightSegments,
  24320. data.phiStart,
  24321. data.phiLength,
  24322. data.thetaStart,
  24323. data.thetaLength
  24324. );
  24325. break;
  24326. case 'DodecahedronGeometry':
  24327. case 'DodecahedronBufferGeometry':
  24328. case 'IcosahedronGeometry':
  24329. case 'IcosahedronBufferGeometry':
  24330. case 'OctahedronGeometry':
  24331. case 'OctahedronBufferGeometry':
  24332. case 'TetrahedronGeometry':
  24333. case 'TetrahedronBufferGeometry':
  24334. geometry = new Geometries[ data.type ](
  24335. data.radius,
  24336. data.detail
  24337. );
  24338. break;
  24339. case 'RingGeometry':
  24340. case 'RingBufferGeometry':
  24341. geometry = new Geometries[ data.type ](
  24342. data.innerRadius,
  24343. data.outerRadius,
  24344. data.thetaSegments,
  24345. data.phiSegments,
  24346. data.thetaStart,
  24347. data.thetaLength
  24348. );
  24349. break;
  24350. case 'TorusGeometry':
  24351. case 'TorusBufferGeometry':
  24352. geometry = new Geometries[ data.type ](
  24353. data.radius,
  24354. data.tube,
  24355. data.radialSegments,
  24356. data.tubularSegments,
  24357. data.arc
  24358. );
  24359. break;
  24360. case 'TorusKnotGeometry':
  24361. case 'TorusKnotBufferGeometry':
  24362. geometry = new Geometries[ data.type ](
  24363. data.radius,
  24364. data.tube,
  24365. data.tubularSegments,
  24366. data.radialSegments,
  24367. data.p,
  24368. data.q
  24369. );
  24370. break;
  24371. case 'TubeGeometry':
  24372. case 'TubeBufferGeometry':
  24373. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24374. // User defined curves or instances of CurvePath will not be deserialized.
  24375. geometry = new Geometries[ data.type ](
  24376. new Curves[ data.path.type ]().fromJSON( data.path ),
  24377. data.tubularSegments,
  24378. data.radius,
  24379. data.radialSegments,
  24380. data.closed
  24381. );
  24382. break;
  24383. case 'LatheGeometry':
  24384. case 'LatheBufferGeometry':
  24385. geometry = new Geometries[ data.type ](
  24386. data.points,
  24387. data.segments,
  24388. data.phiStart,
  24389. data.phiLength
  24390. );
  24391. break;
  24392. case 'PolyhedronGeometry':
  24393. case 'PolyhedronBufferGeometry':
  24394. geometry = new Geometries[ data.type ](
  24395. data.vertices,
  24396. data.indices,
  24397. data.radius,
  24398. data.details
  24399. );
  24400. break;
  24401. case 'ShapeGeometry':
  24402. case 'ShapeBufferGeometry':
  24403. geometryShapes = [];
  24404. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  24405. const shape = shapes[ data.shapes[ j ] ];
  24406. geometryShapes.push( shape );
  24407. }
  24408. geometry = new Geometries[ data.type ](
  24409. geometryShapes,
  24410. data.curveSegments
  24411. );
  24412. break;
  24413. case 'ExtrudeGeometry':
  24414. case 'ExtrudeBufferGeometry':
  24415. geometryShapes = [];
  24416. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  24417. const shape = shapes[ data.shapes[ j ] ];
  24418. geometryShapes.push( shape );
  24419. }
  24420. const extrudePath = data.options.extrudePath;
  24421. if ( extrudePath !== undefined ) {
  24422. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  24423. }
  24424. geometry = new Geometries[ data.type ](
  24425. geometryShapes,
  24426. data.options
  24427. );
  24428. break;
  24429. case 'BufferGeometry':
  24430. case 'InstancedBufferGeometry':
  24431. geometry = bufferGeometryLoader.parse( data );
  24432. break;
  24433. case 'Geometry':
  24434. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  24435. break;
  24436. default:
  24437. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  24438. continue;
  24439. }
  24440. geometry.uuid = data.uuid;
  24441. if ( data.name !== undefined ) geometry.name = data.name;
  24442. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24443. geometries[ data.uuid ] = geometry;
  24444. }
  24445. }
  24446. return geometries;
  24447. }
  24448. parseMaterials( json, textures ) {
  24449. const cache = {}; // MultiMaterial
  24450. const materials = {};
  24451. if ( json !== undefined ) {
  24452. const loader = new MaterialLoader();
  24453. loader.setTextures( textures );
  24454. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24455. const data = json[ i ];
  24456. if ( data.type === 'MultiMaterial' ) {
  24457. // Deprecated
  24458. const array = [];
  24459. for ( let j = 0; j < data.materials.length; j ++ ) {
  24460. const material = data.materials[ j ];
  24461. if ( cache[ material.uuid ] === undefined ) {
  24462. cache[ material.uuid ] = loader.parse( material );
  24463. }
  24464. array.push( cache[ material.uuid ] );
  24465. }
  24466. materials[ data.uuid ] = array;
  24467. } else {
  24468. if ( cache[ data.uuid ] === undefined ) {
  24469. cache[ data.uuid ] = loader.parse( data );
  24470. }
  24471. materials[ data.uuid ] = cache[ data.uuid ];
  24472. }
  24473. }
  24474. }
  24475. return materials;
  24476. }
  24477. parseAnimations( json ) {
  24478. const animations = [];
  24479. for ( let i = 0; i < json.length; i ++ ) {
  24480. const data = json[ i ];
  24481. const clip = AnimationClip.parse( data );
  24482. if ( data.uuid !== undefined ) clip.uuid = data.uuid;
  24483. animations.push( clip );
  24484. }
  24485. return animations;
  24486. }
  24487. parseImages( json, onLoad ) {
  24488. const scope = this;
  24489. const images = {};
  24490. let loader;
  24491. function loadImage( url ) {
  24492. scope.manager.itemStart( url );
  24493. return loader.load( url, function () {
  24494. scope.manager.itemEnd( url );
  24495. }, undefined, function () {
  24496. scope.manager.itemError( url );
  24497. scope.manager.itemEnd( url );
  24498. } );
  24499. }
  24500. if ( json !== undefined && json.length > 0 ) {
  24501. const manager = new LoadingManager( onLoad );
  24502. loader = new ImageLoader( manager );
  24503. loader.setCrossOrigin( this.crossOrigin );
  24504. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24505. const image = json[ i ];
  24506. const url = image.url;
  24507. if ( Array.isArray( url ) ) {
  24508. // load array of images e.g CubeTexture
  24509. images[ image.uuid ] = [];
  24510. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24511. const currentUrl = url[ j ];
  24512. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  24513. images[ image.uuid ].push( loadImage( path ) );
  24514. }
  24515. } else {
  24516. // load single image
  24517. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  24518. images[ image.uuid ] = loadImage( path );
  24519. }
  24520. }
  24521. }
  24522. return images;
  24523. }
  24524. parseTextures( json, images ) {
  24525. function parseConstant( value, type ) {
  24526. if ( typeof value === 'number' ) return value;
  24527. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24528. return type[ value ];
  24529. }
  24530. const textures = {};
  24531. if ( json !== undefined ) {
  24532. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24533. const data = json[ i ];
  24534. if ( data.image === undefined ) {
  24535. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24536. }
  24537. if ( images[ data.image ] === undefined ) {
  24538. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24539. }
  24540. let texture;
  24541. if ( Array.isArray( images[ data.image ] ) ) {
  24542. texture = new CubeTexture( images[ data.image ] );
  24543. } else {
  24544. texture = new Texture( images[ data.image ] );
  24545. }
  24546. texture.needsUpdate = true;
  24547. texture.uuid = data.uuid;
  24548. if ( data.name !== undefined ) texture.name = data.name;
  24549. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24550. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24551. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24552. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24553. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24554. if ( data.wrap !== undefined ) {
  24555. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24556. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24557. }
  24558. if ( data.format !== undefined ) texture.format = data.format;
  24559. if ( data.type !== undefined ) texture.type = data.type;
  24560. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  24561. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24562. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24563. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24564. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24565. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24566. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24567. textures[ data.uuid ] = texture;
  24568. }
  24569. }
  24570. return textures;
  24571. }
  24572. parseObject( data, geometries, materials ) {
  24573. let object;
  24574. function getGeometry( name ) {
  24575. if ( geometries[ name ] === undefined ) {
  24576. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24577. }
  24578. return geometries[ name ];
  24579. }
  24580. function getMaterial( name ) {
  24581. if ( name === undefined ) return undefined;
  24582. if ( Array.isArray( name ) ) {
  24583. const array = [];
  24584. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24585. const uuid = name[ i ];
  24586. if ( materials[ uuid ] === undefined ) {
  24587. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24588. }
  24589. array.push( materials[ uuid ] );
  24590. }
  24591. return array;
  24592. }
  24593. if ( materials[ name ] === undefined ) {
  24594. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24595. }
  24596. return materials[ name ];
  24597. }
  24598. let geometry, material;
  24599. switch ( data.type ) {
  24600. case 'Scene':
  24601. object = new Scene();
  24602. if ( data.background !== undefined ) {
  24603. if ( Number.isInteger( data.background ) ) {
  24604. object.background = new Color( data.background );
  24605. }
  24606. }
  24607. if ( data.fog !== undefined ) {
  24608. if ( data.fog.type === 'Fog' ) {
  24609. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24610. } else if ( data.fog.type === 'FogExp2' ) {
  24611. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24612. }
  24613. }
  24614. break;
  24615. case 'PerspectiveCamera':
  24616. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24617. if ( data.focus !== undefined ) object.focus = data.focus;
  24618. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24619. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24620. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24621. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24622. break;
  24623. case 'OrthographicCamera':
  24624. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24625. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24626. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24627. break;
  24628. case 'AmbientLight':
  24629. object = new AmbientLight( data.color, data.intensity );
  24630. break;
  24631. case 'DirectionalLight':
  24632. object = new DirectionalLight( data.color, data.intensity );
  24633. break;
  24634. case 'PointLight':
  24635. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24636. break;
  24637. case 'RectAreaLight':
  24638. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24639. break;
  24640. case 'SpotLight':
  24641. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24642. break;
  24643. case 'HemisphereLight':
  24644. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24645. break;
  24646. case 'LightProbe':
  24647. object = new LightProbe().fromJSON( data );
  24648. break;
  24649. case 'SkinnedMesh':
  24650. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  24651. case 'Mesh':
  24652. geometry = getGeometry( data.geometry );
  24653. material = getMaterial( data.material );
  24654. object = new Mesh( geometry, material );
  24655. break;
  24656. case 'InstancedMesh':
  24657. geometry = getGeometry( data.geometry );
  24658. material = getMaterial( data.material );
  24659. const count = data.count;
  24660. const instanceMatrix = data.instanceMatrix;
  24661. object = new InstancedMesh( geometry, material, count );
  24662. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24663. break;
  24664. case 'LOD':
  24665. object = new LOD();
  24666. break;
  24667. case 'Line':
  24668. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  24669. break;
  24670. case 'LineLoop':
  24671. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  24672. break;
  24673. case 'LineSegments':
  24674. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24675. break;
  24676. case 'PointCloud':
  24677. case 'Points':
  24678. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24679. break;
  24680. case 'Sprite':
  24681. object = new Sprite( getMaterial( data.material ) );
  24682. break;
  24683. case 'Group':
  24684. object = new Group();
  24685. break;
  24686. default:
  24687. object = new Object3D();
  24688. }
  24689. object.uuid = data.uuid;
  24690. if ( data.name !== undefined ) object.name = data.name;
  24691. if ( data.matrix !== undefined ) {
  24692. object.matrix.fromArray( data.matrix );
  24693. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24694. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  24695. } else {
  24696. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24697. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24698. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24699. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24700. }
  24701. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24702. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24703. if ( data.shadow ) {
  24704. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24705. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  24706. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24707. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24708. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24709. }
  24710. if ( data.visible !== undefined ) object.visible = data.visible;
  24711. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  24712. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  24713. if ( data.userData !== undefined ) object.userData = data.userData;
  24714. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  24715. if ( data.children !== undefined ) {
  24716. const children = data.children;
  24717. for ( let i = 0; i < children.length; i ++ ) {
  24718. object.add( this.parseObject( children[ i ], geometries, materials ) );
  24719. }
  24720. }
  24721. if ( data.type === 'LOD' ) {
  24722. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  24723. const levels = data.levels;
  24724. for ( let l = 0; l < levels.length; l ++ ) {
  24725. const level = levels[ l ];
  24726. const child = object.getObjectByProperty( 'uuid', level.object );
  24727. if ( child !== undefined ) {
  24728. object.addLevel( child, level.distance );
  24729. }
  24730. }
  24731. }
  24732. return object;
  24733. }
  24734. /* DEPRECATED */
  24735. setTexturePath( value ) {
  24736. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  24737. return this.setResourcePath( value );
  24738. }
  24739. }
  24740. const TEXTURE_MAPPING = {
  24741. UVMapping: UVMapping,
  24742. CubeReflectionMapping: CubeReflectionMapping,
  24743. CubeRefractionMapping: CubeRefractionMapping,
  24744. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24745. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24746. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24747. CubeUVRefractionMapping: CubeUVRefractionMapping
  24748. };
  24749. const TEXTURE_WRAPPING = {
  24750. RepeatWrapping: RepeatWrapping,
  24751. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24752. MirroredRepeatWrapping: MirroredRepeatWrapping
  24753. };
  24754. const TEXTURE_FILTER = {
  24755. NearestFilter: NearestFilter,
  24756. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24757. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24758. LinearFilter: LinearFilter,
  24759. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24760. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24761. };
  24762. function ImageBitmapLoader( manager ) {
  24763. if ( typeof createImageBitmap === 'undefined' ) {
  24764. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  24765. }
  24766. if ( typeof fetch === 'undefined' ) {
  24767. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  24768. }
  24769. Loader.call( this, manager );
  24770. this.options = { premultiplyAlpha: 'none' };
  24771. }
  24772. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24773. constructor: ImageBitmapLoader,
  24774. isImageBitmapLoader: true,
  24775. setOptions: function setOptions( options ) {
  24776. this.options = options;
  24777. return this;
  24778. },
  24779. load: function ( url, onLoad, onProgress, onError ) {
  24780. if ( url === undefined ) url = '';
  24781. if ( this.path !== undefined ) url = this.path + url;
  24782. url = this.manager.resolveURL( url );
  24783. const scope = this;
  24784. const cached = Cache.get( url );
  24785. if ( cached !== undefined ) {
  24786. scope.manager.itemStart( url );
  24787. setTimeout( function () {
  24788. if ( onLoad ) onLoad( cached );
  24789. scope.manager.itemEnd( url );
  24790. }, 0 );
  24791. return cached;
  24792. }
  24793. const fetchOptions = {};
  24794. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  24795. fetch( url, fetchOptions ).then( function ( res ) {
  24796. return res.blob();
  24797. } ).then( function ( blob ) {
  24798. return createImageBitmap( blob, scope.options );
  24799. } ).then( function ( imageBitmap ) {
  24800. Cache.add( url, imageBitmap );
  24801. if ( onLoad ) onLoad( imageBitmap );
  24802. scope.manager.itemEnd( url );
  24803. } ).catch( function ( e ) {
  24804. if ( onError ) onError( e );
  24805. scope.manager.itemError( url );
  24806. scope.manager.itemEnd( url );
  24807. } );
  24808. scope.manager.itemStart( url );
  24809. }
  24810. } );
  24811. function ShapePath() {
  24812. this.type = 'ShapePath';
  24813. this.color = new Color();
  24814. this.subPaths = [];
  24815. this.currentPath = null;
  24816. }
  24817. Object.assign( ShapePath.prototype, {
  24818. moveTo: function ( x, y ) {
  24819. this.currentPath = new Path();
  24820. this.subPaths.push( this.currentPath );
  24821. this.currentPath.moveTo( x, y );
  24822. return this;
  24823. },
  24824. lineTo: function ( x, y ) {
  24825. this.currentPath.lineTo( x, y );
  24826. return this;
  24827. },
  24828. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  24829. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  24830. return this;
  24831. },
  24832. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24833. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  24834. return this;
  24835. },
  24836. splineThru: function ( pts ) {
  24837. this.currentPath.splineThru( pts );
  24838. return this;
  24839. },
  24840. toShapes: function ( isCCW, noHoles ) {
  24841. function toShapesNoHoles( inSubpaths ) {
  24842. const shapes = [];
  24843. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  24844. const tmpPath = inSubpaths[ i ];
  24845. const tmpShape = new Shape();
  24846. tmpShape.curves = tmpPath.curves;
  24847. shapes.push( tmpShape );
  24848. }
  24849. return shapes;
  24850. }
  24851. function isPointInsidePolygon( inPt, inPolygon ) {
  24852. const polyLen = inPolygon.length;
  24853. // inPt on polygon contour => immediate success or
  24854. // toggling of inside/outside at every single! intersection point of an edge
  24855. // with the horizontal line through inPt, left of inPt
  24856. // not counting lowerY endpoints of edges and whole edges on that line
  24857. let inside = false;
  24858. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  24859. let edgeLowPt = inPolygon[ p ];
  24860. let edgeHighPt = inPolygon[ q ];
  24861. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24862. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24863. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  24864. // not parallel
  24865. if ( edgeDy < 0 ) {
  24866. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  24867. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  24868. }
  24869. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  24870. if ( inPt.y === edgeLowPt.y ) {
  24871. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  24872. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24873. } else {
  24874. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  24875. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  24876. if ( perpEdge < 0 ) continue;
  24877. inside = ! inside; // true intersection left of inPt
  24878. }
  24879. } else {
  24880. // parallel or collinear
  24881. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  24882. // edge lies on the same horizontal line as inPt
  24883. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  24884. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  24885. // continue;
  24886. }
  24887. }
  24888. return inside;
  24889. }
  24890. const isClockWise = ShapeUtils.isClockWise;
  24891. const subPaths = this.subPaths;
  24892. if ( subPaths.length === 0 ) return [];
  24893. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  24894. let solid, tmpPath, tmpShape;
  24895. const shapes = [];
  24896. if ( subPaths.length === 1 ) {
  24897. tmpPath = subPaths[ 0 ];
  24898. tmpShape = new Shape();
  24899. tmpShape.curves = tmpPath.curves;
  24900. shapes.push( tmpShape );
  24901. return shapes;
  24902. }
  24903. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  24904. holesFirst = isCCW ? ! holesFirst : holesFirst;
  24905. // console.log("Holes first", holesFirst);
  24906. const betterShapeHoles = [];
  24907. const newShapes = [];
  24908. let newShapeHoles = [];
  24909. let mainIdx = 0;
  24910. let tmpPoints;
  24911. newShapes[ mainIdx ] = undefined;
  24912. newShapeHoles[ mainIdx ] = [];
  24913. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  24914. tmpPath = subPaths[ i ];
  24915. tmpPoints = tmpPath.getPoints();
  24916. solid = isClockWise( tmpPoints );
  24917. solid = isCCW ? ! solid : solid;
  24918. if ( solid ) {
  24919. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  24920. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  24921. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  24922. if ( holesFirst ) mainIdx ++;
  24923. newShapeHoles[ mainIdx ] = [];
  24924. //console.log('cw', i);
  24925. } else {
  24926. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  24927. //console.log('ccw', i);
  24928. }
  24929. }
  24930. // only Holes? -> probably all Shapes with wrong orientation
  24931. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  24932. if ( newShapes.length > 1 ) {
  24933. let ambiguous = false;
  24934. const toChange = [];
  24935. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  24936. betterShapeHoles[ sIdx ] = [];
  24937. }
  24938. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  24939. const sho = newShapeHoles[ sIdx ];
  24940. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  24941. const ho = sho[ hIdx ];
  24942. let hole_unassigned = true;
  24943. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  24944. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  24945. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  24946. if ( hole_unassigned ) {
  24947. hole_unassigned = false;
  24948. betterShapeHoles[ s2Idx ].push( ho );
  24949. } else {
  24950. ambiguous = true;
  24951. }
  24952. }
  24953. }
  24954. if ( hole_unassigned ) {
  24955. betterShapeHoles[ sIdx ].push( ho );
  24956. }
  24957. }
  24958. }
  24959. // console.log("ambiguous: ", ambiguous);
  24960. if ( toChange.length > 0 ) {
  24961. // console.log("to change: ", toChange);
  24962. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  24963. }
  24964. }
  24965. let tmpHoles;
  24966. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  24967. tmpShape = newShapes[ i ].s;
  24968. shapes.push( tmpShape );
  24969. tmpHoles = newShapeHoles[ i ];
  24970. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  24971. tmpShape.holes.push( tmpHoles[ j ].h );
  24972. }
  24973. }
  24974. //console.log("shape", shapes);
  24975. return shapes;
  24976. }
  24977. } );
  24978. function Font( data ) {
  24979. this.type = 'Font';
  24980. this.data = data;
  24981. }
  24982. Object.assign( Font.prototype, {
  24983. isFont: true,
  24984. generateShapes: function ( text, size ) {
  24985. if ( size === undefined ) size = 100;
  24986. const shapes = [];
  24987. const paths = createPaths( text, size, this.data );
  24988. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  24989. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  24990. }
  24991. return shapes;
  24992. }
  24993. } );
  24994. function createPaths( text, size, data ) {
  24995. const chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  24996. const scale = size / data.resolution;
  24997. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  24998. const paths = [];
  24999. let offsetX = 0, offsetY = 0;
  25000. for ( let i = 0; i < chars.length; i ++ ) {
  25001. const char = chars[ i ];
  25002. if ( char === '\n' ) {
  25003. offsetX = 0;
  25004. offsetY -= line_height;
  25005. } else {
  25006. const ret = createPath( char, scale, offsetX, offsetY, data );
  25007. offsetX += ret.offsetX;
  25008. paths.push( ret.path );
  25009. }
  25010. }
  25011. return paths;
  25012. }
  25013. function createPath( char, scale, offsetX, offsetY, data ) {
  25014. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  25015. if ( ! glyph ) {
  25016. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  25017. return;
  25018. }
  25019. const path = new ShapePath();
  25020. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25021. if ( glyph.o ) {
  25022. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25023. for ( let i = 0, l = outline.length; i < l; ) {
  25024. const action = outline[ i ++ ];
  25025. switch ( action ) {
  25026. case 'm': // moveTo
  25027. x = outline[ i ++ ] * scale + offsetX;
  25028. y = outline[ i ++ ] * scale + offsetY;
  25029. path.moveTo( x, y );
  25030. break;
  25031. case 'l': // lineTo
  25032. x = outline[ i ++ ] * scale + offsetX;
  25033. y = outline[ i ++ ] * scale + offsetY;
  25034. path.lineTo( x, y );
  25035. break;
  25036. case 'q': // quadraticCurveTo
  25037. cpx = outline[ i ++ ] * scale + offsetX;
  25038. cpy = outline[ i ++ ] * scale + offsetY;
  25039. cpx1 = outline[ i ++ ] * scale + offsetX;
  25040. cpy1 = outline[ i ++ ] * scale + offsetY;
  25041. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25042. break;
  25043. case 'b': // bezierCurveTo
  25044. cpx = outline[ i ++ ] * scale + offsetX;
  25045. cpy = outline[ i ++ ] * scale + offsetY;
  25046. cpx1 = outline[ i ++ ] * scale + offsetX;
  25047. cpy1 = outline[ i ++ ] * scale + offsetY;
  25048. cpx2 = outline[ i ++ ] * scale + offsetX;
  25049. cpy2 = outline[ i ++ ] * scale + offsetY;
  25050. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  25051. break;
  25052. }
  25053. }
  25054. }
  25055. return { offsetX: glyph.ha * scale, path: path };
  25056. }
  25057. function FontLoader( manager ) {
  25058. Loader.call( this, manager );
  25059. }
  25060. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25061. constructor: FontLoader,
  25062. load: function ( url, onLoad, onProgress, onError ) {
  25063. const scope = this;
  25064. const loader = new FileLoader( this.manager );
  25065. loader.setPath( this.path );
  25066. loader.setRequestHeader( this.requestHeader );
  25067. loader.load( url, function ( text ) {
  25068. let json;
  25069. try {
  25070. json = JSON.parse( text );
  25071. } catch ( e ) {
  25072. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  25073. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  25074. }
  25075. const font = scope.parse( json );
  25076. if ( onLoad ) onLoad( font );
  25077. }, onProgress, onError );
  25078. },
  25079. parse: function ( json ) {
  25080. return new Font( json );
  25081. }
  25082. } );
  25083. let _context;
  25084. const AudioContext = {
  25085. getContext: function () {
  25086. if ( _context === undefined ) {
  25087. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25088. }
  25089. return _context;
  25090. },
  25091. setContext: function ( value ) {
  25092. _context = value;
  25093. }
  25094. };
  25095. function AudioLoader( manager ) {
  25096. Loader.call( this, manager );
  25097. }
  25098. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25099. constructor: AudioLoader,
  25100. load: function ( url, onLoad, onProgress, onError ) {
  25101. const scope = this;
  25102. const loader = new FileLoader( scope.manager );
  25103. loader.setResponseType( 'arraybuffer' );
  25104. loader.setPath( scope.path );
  25105. loader.setRequestHeader( scope.requestHeader );
  25106. loader.load( url, function ( buffer ) {
  25107. try {
  25108. // Create a copy of the buffer. The `decodeAudioData` method
  25109. // detaches the buffer when complete, preventing reuse.
  25110. const bufferCopy = buffer.slice( 0 );
  25111. const context = AudioContext.getContext();
  25112. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25113. onLoad( audioBuffer );
  25114. } );
  25115. } catch ( e ) {
  25116. if ( onError ) {
  25117. onError( e );
  25118. } else {
  25119. console.error( e );
  25120. }
  25121. scope.manager.itemError( url );
  25122. }
  25123. }, onProgress, onError );
  25124. }
  25125. } );
  25126. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  25127. LightProbe.call( this, undefined, intensity );
  25128. const color1 = new Color().set( skyColor );
  25129. const color2 = new Color().set( groundColor );
  25130. const sky = new Vector3( color1.r, color1.g, color1.b );
  25131. const ground = new Vector3( color2.r, color2.g, color2.b );
  25132. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25133. const c0 = Math.sqrt( Math.PI );
  25134. const c1 = c0 * Math.sqrt( 0.75 );
  25135. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25136. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25137. }
  25138. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  25139. constructor: HemisphereLightProbe,
  25140. isHemisphereLightProbe: true,
  25141. copy: function ( source ) { // modifying colors not currently supported
  25142. LightProbe.prototype.copy.call( this, source );
  25143. return this;
  25144. },
  25145. toJSON: function ( meta ) {
  25146. const data = LightProbe.prototype.toJSON.call( this, meta );
  25147. // data.sh = this.sh.toArray(); // todo
  25148. return data;
  25149. }
  25150. } );
  25151. function AmbientLightProbe( color, intensity ) {
  25152. LightProbe.call( this, undefined, intensity );
  25153. const color1 = new Color().set( color );
  25154. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25155. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25156. }
  25157. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  25158. constructor: AmbientLightProbe,
  25159. isAmbientLightProbe: true,
  25160. copy: function ( source ) { // modifying color not currently supported
  25161. LightProbe.prototype.copy.call( this, source );
  25162. return this;
  25163. },
  25164. toJSON: function ( meta ) {
  25165. const data = LightProbe.prototype.toJSON.call( this, meta );
  25166. // data.sh = this.sh.toArray(); // todo
  25167. return data;
  25168. }
  25169. } );
  25170. const _eyeRight = new Matrix4();
  25171. const _eyeLeft = new Matrix4();
  25172. function StereoCamera() {
  25173. this.type = 'StereoCamera';
  25174. this.aspect = 1;
  25175. this.eyeSep = 0.064;
  25176. this.cameraL = new PerspectiveCamera();
  25177. this.cameraL.layers.enable( 1 );
  25178. this.cameraL.matrixAutoUpdate = false;
  25179. this.cameraR = new PerspectiveCamera();
  25180. this.cameraR.layers.enable( 2 );
  25181. this.cameraR.matrixAutoUpdate = false;
  25182. this._cache = {
  25183. focus: null,
  25184. fov: null,
  25185. aspect: null,
  25186. near: null,
  25187. far: null,
  25188. zoom: null,
  25189. eyeSep: null
  25190. };
  25191. }
  25192. Object.assign( StereoCamera.prototype, {
  25193. update: function ( camera ) {
  25194. const cache = this._cache;
  25195. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25196. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25197. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25198. if ( needsUpdate ) {
  25199. cache.focus = camera.focus;
  25200. cache.fov = camera.fov;
  25201. cache.aspect = camera.aspect * this.aspect;
  25202. cache.near = camera.near;
  25203. cache.far = camera.far;
  25204. cache.zoom = camera.zoom;
  25205. cache.eyeSep = this.eyeSep;
  25206. // Off-axis stereoscopic effect based on
  25207. // http://paulbourke.net/stereographics/stereorender/
  25208. const projectionMatrix = camera.projectionMatrix.clone();
  25209. const eyeSepHalf = cache.eyeSep / 2;
  25210. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25211. const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25212. let xmin, xmax;
  25213. // translate xOffset
  25214. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25215. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25216. // for left eye
  25217. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25218. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25219. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25220. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25221. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25222. // for right eye
  25223. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25224. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25225. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25226. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25227. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25228. }
  25229. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25230. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25231. }
  25232. } );
  25233. class Clock {
  25234. constructor( autoStart ) {
  25235. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  25236. this.startTime = 0;
  25237. this.oldTime = 0;
  25238. this.elapsedTime = 0;
  25239. this.running = false;
  25240. }
  25241. start() {
  25242. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25243. this.oldTime = this.startTime;
  25244. this.elapsedTime = 0;
  25245. this.running = true;
  25246. }
  25247. stop() {
  25248. this.getElapsedTime();
  25249. this.running = false;
  25250. this.autoStart = false;
  25251. }
  25252. getElapsedTime() {
  25253. this.getDelta();
  25254. return this.elapsedTime;
  25255. }
  25256. getDelta() {
  25257. let diff = 0;
  25258. if ( this.autoStart && ! this.running ) {
  25259. this.start();
  25260. return 0;
  25261. }
  25262. if ( this.running ) {
  25263. const newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  25264. diff = ( newTime - this.oldTime ) / 1000;
  25265. this.oldTime = newTime;
  25266. this.elapsedTime += diff;
  25267. }
  25268. return diff;
  25269. }
  25270. }
  25271. const _position$2 = /*@__PURE__*/ new Vector3();
  25272. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  25273. const _scale$1 = /*@__PURE__*/ new Vector3();
  25274. const _orientation = /*@__PURE__*/ new Vector3();
  25275. class AudioListener extends Object3D {
  25276. constructor() {
  25277. super();
  25278. this.type = 'AudioListener';
  25279. this.context = AudioContext.getContext();
  25280. this.gain = this.context.createGain();
  25281. this.gain.connect( this.context.destination );
  25282. this.filter = null;
  25283. this.timeDelta = 0;
  25284. // private
  25285. this._clock = new Clock();
  25286. }
  25287. getInput() {
  25288. return this.gain;
  25289. }
  25290. removeFilter() {
  25291. if ( this.filter !== null ) {
  25292. this.gain.disconnect( this.filter );
  25293. this.filter.disconnect( this.context.destination );
  25294. this.gain.connect( this.context.destination );
  25295. this.filter = null;
  25296. }
  25297. return this;
  25298. }
  25299. getFilter() {
  25300. return this.filter;
  25301. }
  25302. setFilter( value ) {
  25303. if ( this.filter !== null ) {
  25304. this.gain.disconnect( this.filter );
  25305. this.filter.disconnect( this.context.destination );
  25306. } else {
  25307. this.gain.disconnect( this.context.destination );
  25308. }
  25309. this.filter = value;
  25310. this.gain.connect( this.filter );
  25311. this.filter.connect( this.context.destination );
  25312. return this;
  25313. }
  25314. getMasterVolume() {
  25315. return this.gain.gain.value;
  25316. }
  25317. setMasterVolume( value ) {
  25318. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25319. return this;
  25320. }
  25321. updateMatrixWorld( force ) {
  25322. super.updateMatrixWorld( force );
  25323. const listener = this.context.listener;
  25324. const up = this.up;
  25325. this.timeDelta = this._clock.getDelta();
  25326. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  25327. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  25328. if ( listener.positionX ) {
  25329. // code path for Chrome (see #14393)
  25330. const endTime = this.context.currentTime + this.timeDelta;
  25331. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  25332. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  25333. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  25334. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  25335. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  25336. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  25337. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25338. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25339. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25340. } else {
  25341. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  25342. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  25343. }
  25344. }
  25345. }
  25346. class Audio extends Object3D {
  25347. constructor( listener ) {
  25348. super();
  25349. this.type = 'Audio';
  25350. this.listener = listener;
  25351. this.context = listener.context;
  25352. this.gain = this.context.createGain();
  25353. this.gain.connect( listener.getInput() );
  25354. this.autoplay = false;
  25355. this.buffer = null;
  25356. this.detune = 0;
  25357. this.loop = false;
  25358. this.loopStart = 0;
  25359. this.loopEnd = 0;
  25360. this.offset = 0;
  25361. this.duration = undefined;
  25362. this.playbackRate = 1;
  25363. this.isPlaying = false;
  25364. this.hasPlaybackControl = true;
  25365. this.source = null;
  25366. this.sourceType = 'empty';
  25367. this._startedAt = 0;
  25368. this._progress = 0;
  25369. this._connected = false;
  25370. this.filters = [];
  25371. }
  25372. getOutput() {
  25373. return this.gain;
  25374. }
  25375. setNodeSource( audioNode ) {
  25376. this.hasPlaybackControl = false;
  25377. this.sourceType = 'audioNode';
  25378. this.source = audioNode;
  25379. this.connect();
  25380. return this;
  25381. }
  25382. setMediaElementSource( mediaElement ) {
  25383. this.hasPlaybackControl = false;
  25384. this.sourceType = 'mediaNode';
  25385. this.source = this.context.createMediaElementSource( mediaElement );
  25386. this.connect();
  25387. return this;
  25388. }
  25389. setMediaStreamSource( mediaStream ) {
  25390. this.hasPlaybackControl = false;
  25391. this.sourceType = 'mediaStreamNode';
  25392. this.source = this.context.createMediaStreamSource( mediaStream );
  25393. this.connect();
  25394. return this;
  25395. }
  25396. setBuffer( audioBuffer ) {
  25397. this.buffer = audioBuffer;
  25398. this.sourceType = 'buffer';
  25399. if ( this.autoplay ) this.play();
  25400. return this;
  25401. }
  25402. play( delay ) {
  25403. if ( delay === undefined ) delay = 0;
  25404. if ( this.isPlaying === true ) {
  25405. console.warn( 'THREE.Audio: Audio is already playing.' );
  25406. return;
  25407. }
  25408. if ( this.hasPlaybackControl === false ) {
  25409. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25410. return;
  25411. }
  25412. this._startedAt = this.context.currentTime + delay;
  25413. const source = this.context.createBufferSource();
  25414. source.buffer = this.buffer;
  25415. source.loop = this.loop;
  25416. source.loopStart = this.loopStart;
  25417. source.loopEnd = this.loopEnd;
  25418. source.onended = this.onEnded.bind( this );
  25419. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25420. this.isPlaying = true;
  25421. this.source = source;
  25422. this.setDetune( this.detune );
  25423. this.setPlaybackRate( this.playbackRate );
  25424. return this.connect();
  25425. }
  25426. pause() {
  25427. if ( this.hasPlaybackControl === false ) {
  25428. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25429. return;
  25430. }
  25431. if ( this.isPlaying === true ) {
  25432. // update current progress
  25433. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25434. if ( this.loop === true ) {
  25435. // ensure _progress does not exceed duration with looped audios
  25436. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25437. }
  25438. this.source.stop();
  25439. this.source.onended = null;
  25440. this.isPlaying = false;
  25441. }
  25442. return this;
  25443. }
  25444. stop() {
  25445. if ( this.hasPlaybackControl === false ) {
  25446. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25447. return;
  25448. }
  25449. this._progress = 0;
  25450. this.source.stop();
  25451. this.source.onended = null;
  25452. this.isPlaying = false;
  25453. return this;
  25454. }
  25455. connect() {
  25456. if ( this.filters.length > 0 ) {
  25457. this.source.connect( this.filters[ 0 ] );
  25458. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25459. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25460. }
  25461. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25462. } else {
  25463. this.source.connect( this.getOutput() );
  25464. }
  25465. this._connected = true;
  25466. return this;
  25467. }
  25468. disconnect() {
  25469. if ( this.filters.length > 0 ) {
  25470. this.source.disconnect( this.filters[ 0 ] );
  25471. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25472. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25473. }
  25474. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25475. } else {
  25476. this.source.disconnect( this.getOutput() );
  25477. }
  25478. this._connected = false;
  25479. return this;
  25480. }
  25481. getFilters() {
  25482. return this.filters;
  25483. }
  25484. setFilters( value ) {
  25485. if ( ! value ) value = [];
  25486. if ( this._connected === true ) {
  25487. this.disconnect();
  25488. this.filters = value;
  25489. this.connect();
  25490. } else {
  25491. this.filters = value;
  25492. }
  25493. return this;
  25494. }
  25495. setDetune( value ) {
  25496. this.detune = value;
  25497. if ( this.source.detune === undefined ) return; // only set detune when available
  25498. if ( this.isPlaying === true ) {
  25499. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25500. }
  25501. return this;
  25502. }
  25503. getDetune() {
  25504. return this.detune;
  25505. }
  25506. getFilter() {
  25507. return this.getFilters()[ 0 ];
  25508. }
  25509. setFilter( filter ) {
  25510. return this.setFilters( filter ? [ filter ] : [] );
  25511. }
  25512. setPlaybackRate( value ) {
  25513. if ( this.hasPlaybackControl === false ) {
  25514. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25515. return;
  25516. }
  25517. this.playbackRate = value;
  25518. if ( this.isPlaying === true ) {
  25519. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25520. }
  25521. return this;
  25522. }
  25523. getPlaybackRate() {
  25524. return this.playbackRate;
  25525. }
  25526. onEnded() {
  25527. this.isPlaying = false;
  25528. }
  25529. getLoop() {
  25530. if ( this.hasPlaybackControl === false ) {
  25531. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25532. return false;
  25533. }
  25534. return this.loop;
  25535. }
  25536. setLoop( value ) {
  25537. if ( this.hasPlaybackControl === false ) {
  25538. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25539. return;
  25540. }
  25541. this.loop = value;
  25542. if ( this.isPlaying === true ) {
  25543. this.source.loop = this.loop;
  25544. }
  25545. return this;
  25546. }
  25547. setLoopStart( value ) {
  25548. this.loopStart = value;
  25549. return this;
  25550. }
  25551. setLoopEnd( value ) {
  25552. this.loopEnd = value;
  25553. return this;
  25554. }
  25555. getVolume() {
  25556. return this.gain.gain.value;
  25557. }
  25558. setVolume( value ) {
  25559. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25560. return this;
  25561. }
  25562. }
  25563. const _position$3 = /*@__PURE__*/ new Vector3();
  25564. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  25565. const _scale$2 = /*@__PURE__*/ new Vector3();
  25566. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25567. class PositionalAudio extends Audio {
  25568. constructor( listener ) {
  25569. super( listener );
  25570. this.panner = this.context.createPanner();
  25571. this.panner.panningModel = 'HRTF';
  25572. this.panner.connect( this.gain );
  25573. }
  25574. getOutput() {
  25575. return this.panner;
  25576. }
  25577. getRefDistance() {
  25578. return this.panner.refDistance;
  25579. }
  25580. setRefDistance( value ) {
  25581. this.panner.refDistance = value;
  25582. return this;
  25583. }
  25584. getRolloffFactor() {
  25585. return this.panner.rolloffFactor;
  25586. }
  25587. setRolloffFactor( value ) {
  25588. this.panner.rolloffFactor = value;
  25589. return this;
  25590. }
  25591. getDistanceModel() {
  25592. return this.panner.distanceModel;
  25593. }
  25594. setDistanceModel( value ) {
  25595. this.panner.distanceModel = value;
  25596. return this;
  25597. }
  25598. getMaxDistance() {
  25599. return this.panner.maxDistance;
  25600. }
  25601. setMaxDistance( value ) {
  25602. this.panner.maxDistance = value;
  25603. return this;
  25604. }
  25605. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25606. this.panner.coneInnerAngle = coneInnerAngle;
  25607. this.panner.coneOuterAngle = coneOuterAngle;
  25608. this.panner.coneOuterGain = coneOuterGain;
  25609. return this;
  25610. }
  25611. updateMatrixWorld( force ) {
  25612. super.updateMatrixWorld( force );
  25613. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25614. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  25615. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  25616. const panner = this.panner;
  25617. if ( panner.positionX ) {
  25618. // code path for Chrome and Firefox (see #14393)
  25619. const endTime = this.context.currentTime + this.listener.timeDelta;
  25620. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  25621. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  25622. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  25623. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25624. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25625. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25626. } else {
  25627. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  25628. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  25629. }
  25630. }
  25631. }
  25632. class AudioAnalyser {
  25633. constructor( audio, fftSize ) {
  25634. this.analyser = audio.context.createAnalyser();
  25635. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25636. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25637. audio.getOutput().connect( this.analyser );
  25638. }
  25639. getFrequencyData() {
  25640. this.analyser.getByteFrequencyData( this.data );
  25641. return this.data;
  25642. }
  25643. getAverageFrequency() {
  25644. let value = 0;
  25645. const data = this.getFrequencyData();
  25646. for ( let i = 0; i < data.length; i ++ ) {
  25647. value += data[ i ];
  25648. }
  25649. return value / data.length;
  25650. }
  25651. }
  25652. function PropertyMixer( binding, typeName, valueSize ) {
  25653. this.binding = binding;
  25654. this.valueSize = valueSize;
  25655. let mixFunction,
  25656. mixFunctionAdditive,
  25657. setIdentity;
  25658. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25659. //
  25660. // interpolators can use .buffer as their .result
  25661. // the data then goes to 'incoming'
  25662. //
  25663. // 'accu0' and 'accu1' are used frame-interleaved for
  25664. // the cumulative result and are compared to detect
  25665. // changes
  25666. //
  25667. // 'orig' stores the original state of the property
  25668. //
  25669. // 'add' is used for additive cumulative results
  25670. //
  25671. // 'work' is optional and is only present for quaternion types. It is used
  25672. // to store intermediate quaternion multiplication results
  25673. switch ( typeName ) {
  25674. case 'quaternion':
  25675. mixFunction = this._slerp;
  25676. mixFunctionAdditive = this._slerpAdditive;
  25677. setIdentity = this._setAdditiveIdentityQuaternion;
  25678. this.buffer = new Float64Array( valueSize * 6 );
  25679. this._workIndex = 5;
  25680. break;
  25681. case 'string':
  25682. case 'bool':
  25683. mixFunction = this._select;
  25684. // Use the regular mix function and for additive on these types,
  25685. // additive is not relevant for non-numeric types
  25686. mixFunctionAdditive = this._select;
  25687. setIdentity = this._setAdditiveIdentityOther;
  25688. this.buffer = new Array( valueSize * 5 );
  25689. break;
  25690. default:
  25691. mixFunction = this._lerp;
  25692. mixFunctionAdditive = this._lerpAdditive;
  25693. setIdentity = this._setAdditiveIdentityNumeric;
  25694. this.buffer = new Float64Array( valueSize * 5 );
  25695. }
  25696. this._mixBufferRegion = mixFunction;
  25697. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25698. this._setIdentity = setIdentity;
  25699. this._origIndex = 3;
  25700. this._addIndex = 4;
  25701. this.cumulativeWeight = 0;
  25702. this.cumulativeWeightAdditive = 0;
  25703. this.useCount = 0;
  25704. this.referenceCount = 0;
  25705. }
  25706. Object.assign( PropertyMixer.prototype, {
  25707. // accumulate data in the 'incoming' region into 'accu<i>'
  25708. accumulate: function ( accuIndex, weight ) {
  25709. // note: happily accumulating nothing when weight = 0, the caller knows
  25710. // the weight and shouldn't have made the call in the first place
  25711. const buffer = this.buffer,
  25712. stride = this.valueSize,
  25713. offset = accuIndex * stride + stride;
  25714. let currentWeight = this.cumulativeWeight;
  25715. if ( currentWeight === 0 ) {
  25716. // accuN := incoming * weight
  25717. for ( let i = 0; i !== stride; ++ i ) {
  25718. buffer[ offset + i ] = buffer[ i ];
  25719. }
  25720. currentWeight = weight;
  25721. } else {
  25722. // accuN := accuN + incoming * weight
  25723. currentWeight += weight;
  25724. const mix = weight / currentWeight;
  25725. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25726. }
  25727. this.cumulativeWeight = currentWeight;
  25728. },
  25729. // accumulate data in the 'incoming' region into 'add'
  25730. accumulateAdditive: function ( weight ) {
  25731. const buffer = this.buffer,
  25732. stride = this.valueSize,
  25733. offset = stride * this._addIndex;
  25734. if ( this.cumulativeWeightAdditive === 0 ) {
  25735. // add = identity
  25736. this._setIdentity();
  25737. }
  25738. // add := add + incoming * weight
  25739. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25740. this.cumulativeWeightAdditive += weight;
  25741. },
  25742. // apply the state of 'accu<i>' to the binding when accus differ
  25743. apply: function ( accuIndex ) {
  25744. const stride = this.valueSize,
  25745. buffer = this.buffer,
  25746. offset = accuIndex * stride + stride,
  25747. weight = this.cumulativeWeight,
  25748. weightAdditive = this.cumulativeWeightAdditive,
  25749. binding = this.binding;
  25750. this.cumulativeWeight = 0;
  25751. this.cumulativeWeightAdditive = 0;
  25752. if ( weight < 1 ) {
  25753. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25754. const originalValueOffset = stride * this._origIndex;
  25755. this._mixBufferRegion(
  25756. buffer, offset, originalValueOffset, 1 - weight, stride );
  25757. }
  25758. if ( weightAdditive > 0 ) {
  25759. // accuN := accuN + additive accuN
  25760. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25761. }
  25762. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25763. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25764. // value has changed -> update scene graph
  25765. binding.setValue( buffer, offset );
  25766. break;
  25767. }
  25768. }
  25769. },
  25770. // remember the state of the bound property and copy it to both accus
  25771. saveOriginalState: function () {
  25772. const binding = this.binding;
  25773. const buffer = this.buffer,
  25774. stride = this.valueSize,
  25775. originalValueOffset = stride * this._origIndex;
  25776. binding.getValue( buffer, originalValueOffset );
  25777. // accu[0..1] := orig -- initially detect changes against the original
  25778. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25779. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25780. }
  25781. // Add to identity for additive
  25782. this._setIdentity();
  25783. this.cumulativeWeight = 0;
  25784. this.cumulativeWeightAdditive = 0;
  25785. },
  25786. // apply the state previously taken via 'saveOriginalState' to the binding
  25787. restoreOriginalState: function () {
  25788. const originalValueOffset = this.valueSize * 3;
  25789. this.binding.setValue( this.buffer, originalValueOffset );
  25790. },
  25791. _setAdditiveIdentityNumeric: function () {
  25792. const startIndex = this._addIndex * this.valueSize;
  25793. const endIndex = startIndex + this.valueSize;
  25794. for ( let i = startIndex; i < endIndex; i ++ ) {
  25795. this.buffer[ i ] = 0;
  25796. }
  25797. },
  25798. _setAdditiveIdentityQuaternion: function () {
  25799. this._setAdditiveIdentityNumeric();
  25800. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  25801. },
  25802. _setAdditiveIdentityOther: function () {
  25803. const startIndex = this._origIndex * this.valueSize;
  25804. const targetIndex = this._addIndex * this.valueSize;
  25805. for ( let i = 0; i < this.valueSize; i ++ ) {
  25806. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  25807. }
  25808. },
  25809. // mix functions
  25810. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  25811. if ( t >= 0.5 ) {
  25812. for ( let i = 0; i !== stride; ++ i ) {
  25813. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  25814. }
  25815. }
  25816. },
  25817. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  25818. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  25819. },
  25820. _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  25821. const workOffset = this._workIndex * stride;
  25822. // Store result in intermediate buffer offset
  25823. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  25824. // Slerp to the intermediate result
  25825. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  25826. },
  25827. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  25828. const s = 1 - t;
  25829. for ( let i = 0; i !== stride; ++ i ) {
  25830. const j = dstOffset + i;
  25831. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  25832. }
  25833. },
  25834. _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  25835. for ( let i = 0; i !== stride; ++ i ) {
  25836. const j = dstOffset + i;
  25837. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  25838. }
  25839. }
  25840. } );
  25841. // Characters [].:/ are reserved for track binding syntax.
  25842. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25843. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  25844. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25845. // only latin characters, and the unicode \p{L} is not yet supported. So
  25846. // instead, we exclude reserved characters and match everything else.
  25847. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25848. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  25849. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25850. // be matched to parse the rest of the track name.
  25851. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  25852. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25853. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  25854. // Object on target node, and accessor. May not contain reserved
  25855. // characters. Accessor may contain any character except closing bracket.
  25856. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  25857. // Property and accessor. May not contain reserved characters. Accessor may
  25858. // contain any non-bracket characters.
  25859. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  25860. const _trackRe = new RegExp( ''
  25861. + '^'
  25862. + _directoryRe
  25863. + _nodeRe
  25864. + _objectRe
  25865. + _propertyRe
  25866. + '$'
  25867. );
  25868. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  25869. function Composite( targetGroup, path, optionalParsedPath ) {
  25870. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  25871. this._targetGroup = targetGroup;
  25872. this._bindings = targetGroup.subscribe_( path, parsedPath );
  25873. }
  25874. Object.assign( Composite.prototype, {
  25875. getValue: function ( array, offset ) {
  25876. this.bind(); // bind all binding
  25877. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25878. binding = this._bindings[ firstValidIndex ];
  25879. // and only call .getValue on the first
  25880. if ( binding !== undefined ) binding.getValue( array, offset );
  25881. },
  25882. setValue: function ( array, offset ) {
  25883. const bindings = this._bindings;
  25884. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25885. bindings[ i ].setValue( array, offset );
  25886. }
  25887. },
  25888. bind: function () {
  25889. const bindings = this._bindings;
  25890. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25891. bindings[ i ].bind();
  25892. }
  25893. },
  25894. unbind: function () {
  25895. const bindings = this._bindings;
  25896. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25897. bindings[ i ].unbind();
  25898. }
  25899. }
  25900. } );
  25901. function PropertyBinding( rootNode, path, parsedPath ) {
  25902. this.path = path;
  25903. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  25904. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  25905. this.rootNode = rootNode;
  25906. }
  25907. Object.assign( PropertyBinding, {
  25908. Composite: Composite,
  25909. create: function ( root, path, parsedPath ) {
  25910. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  25911. return new PropertyBinding( root, path, parsedPath );
  25912. } else {
  25913. return new PropertyBinding.Composite( root, path, parsedPath );
  25914. }
  25915. },
  25916. /**
  25917. * Replaces spaces with underscores and removes unsupported characters from
  25918. * node names, to ensure compatibility with parseTrackName().
  25919. *
  25920. * @param {string} name Node name to be sanitized.
  25921. * @return {string}
  25922. */
  25923. sanitizeNodeName: function ( name ) {
  25924. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  25925. },
  25926. parseTrackName: function ( trackName ) {
  25927. const matches = _trackRe.exec( trackName );
  25928. if ( ! matches ) {
  25929. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  25930. }
  25931. const results = {
  25932. // directoryName: matches[ 1 ], // (tschw) currently unused
  25933. nodeName: matches[ 2 ],
  25934. objectName: matches[ 3 ],
  25935. objectIndex: matches[ 4 ],
  25936. propertyName: matches[ 5 ], // required
  25937. propertyIndex: matches[ 6 ]
  25938. };
  25939. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  25940. if ( lastDot !== undefined && lastDot !== - 1 ) {
  25941. const objectName = results.nodeName.substring( lastDot + 1 );
  25942. // Object names must be checked against an allowlist. Otherwise, there
  25943. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25944. // 'bar' could be the objectName, or part of a nodeName (which can
  25945. // include '.' characters).
  25946. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  25947. results.nodeName = results.nodeName.substring( 0, lastDot );
  25948. results.objectName = objectName;
  25949. }
  25950. }
  25951. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  25952. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  25953. }
  25954. return results;
  25955. },
  25956. findNode: function ( root, nodeName ) {
  25957. if ( ! nodeName || nodeName === "" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  25958. return root;
  25959. }
  25960. // search into skeleton bones.
  25961. if ( root.skeleton ) {
  25962. const bone = root.skeleton.getBoneByName( nodeName );
  25963. if ( bone !== undefined ) {
  25964. return bone;
  25965. }
  25966. }
  25967. // search into node subtree.
  25968. if ( root.children ) {
  25969. const searchNodeSubtree = function ( children ) {
  25970. for ( let i = 0; i < children.length; i ++ ) {
  25971. const childNode = children[ i ];
  25972. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  25973. return childNode;
  25974. }
  25975. const result = searchNodeSubtree( childNode.children );
  25976. if ( result ) return result;
  25977. }
  25978. return null;
  25979. };
  25980. const subTreeNode = searchNodeSubtree( root.children );
  25981. if ( subTreeNode ) {
  25982. return subTreeNode;
  25983. }
  25984. }
  25985. return null;
  25986. }
  25987. } );
  25988. Object.assign( PropertyBinding.prototype, { // prototype, continued
  25989. // these are used to "bind" a nonexistent property
  25990. _getValue_unavailable: function () {},
  25991. _setValue_unavailable: function () {},
  25992. BindingType: {
  25993. Direct: 0,
  25994. EntireArray: 1,
  25995. ArrayElement: 2,
  25996. HasFromToArray: 3
  25997. },
  25998. Versioning: {
  25999. None: 0,
  26000. NeedsUpdate: 1,
  26001. MatrixWorldNeedsUpdate: 2
  26002. },
  26003. GetterByBindingType: [
  26004. function getValue_direct( buffer, offset ) {
  26005. buffer[ offset ] = this.node[ this.propertyName ];
  26006. },
  26007. function getValue_array( buffer, offset ) {
  26008. const source = this.resolvedProperty;
  26009. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26010. buffer[ offset ++ ] = source[ i ];
  26011. }
  26012. },
  26013. function getValue_arrayElement( buffer, offset ) {
  26014. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26015. },
  26016. function getValue_toArray( buffer, offset ) {
  26017. this.resolvedProperty.toArray( buffer, offset );
  26018. }
  26019. ],
  26020. SetterByBindingTypeAndVersioning: [
  26021. [
  26022. // Direct
  26023. function setValue_direct( buffer, offset ) {
  26024. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26025. },
  26026. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26027. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26028. this.targetObject.needsUpdate = true;
  26029. },
  26030. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26031. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26032. this.targetObject.matrixWorldNeedsUpdate = true;
  26033. }
  26034. ], [
  26035. // EntireArray
  26036. function setValue_array( buffer, offset ) {
  26037. const dest = this.resolvedProperty;
  26038. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26039. dest[ i ] = buffer[ offset ++ ];
  26040. }
  26041. },
  26042. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26043. const dest = this.resolvedProperty;
  26044. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26045. dest[ i ] = buffer[ offset ++ ];
  26046. }
  26047. this.targetObject.needsUpdate = true;
  26048. },
  26049. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26050. const dest = this.resolvedProperty;
  26051. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26052. dest[ i ] = buffer[ offset ++ ];
  26053. }
  26054. this.targetObject.matrixWorldNeedsUpdate = true;
  26055. }
  26056. ], [
  26057. // ArrayElement
  26058. function setValue_arrayElement( buffer, offset ) {
  26059. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26060. },
  26061. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26062. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26063. this.targetObject.needsUpdate = true;
  26064. },
  26065. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26066. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26067. this.targetObject.matrixWorldNeedsUpdate = true;
  26068. }
  26069. ], [
  26070. // HasToFromArray
  26071. function setValue_fromArray( buffer, offset ) {
  26072. this.resolvedProperty.fromArray( buffer, offset );
  26073. },
  26074. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26075. this.resolvedProperty.fromArray( buffer, offset );
  26076. this.targetObject.needsUpdate = true;
  26077. },
  26078. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26079. this.resolvedProperty.fromArray( buffer, offset );
  26080. this.targetObject.matrixWorldNeedsUpdate = true;
  26081. }
  26082. ]
  26083. ],
  26084. getValue: function getValue_unbound( targetArray, offset ) {
  26085. this.bind();
  26086. this.getValue( targetArray, offset );
  26087. // Note: This class uses a State pattern on a per-method basis:
  26088. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26089. // prototype version of these methods with one that represents
  26090. // the bound state. When the property is not found, the methods
  26091. // become no-ops.
  26092. },
  26093. setValue: function getValue_unbound( sourceArray, offset ) {
  26094. this.bind();
  26095. this.setValue( sourceArray, offset );
  26096. },
  26097. // create getter / setter pair for a property in the scene graph
  26098. bind: function () {
  26099. let targetObject = this.node;
  26100. const parsedPath = this.parsedPath;
  26101. const objectName = parsedPath.objectName;
  26102. const propertyName = parsedPath.propertyName;
  26103. let propertyIndex = parsedPath.propertyIndex;
  26104. if ( ! targetObject ) {
  26105. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26106. this.node = targetObject;
  26107. }
  26108. // set fail state so we can just 'return' on error
  26109. this.getValue = this._getValue_unavailable;
  26110. this.setValue = this._setValue_unavailable;
  26111. // ensure there is a value node
  26112. if ( ! targetObject ) {
  26113. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26114. return;
  26115. }
  26116. if ( objectName ) {
  26117. let objectIndex = parsedPath.objectIndex;
  26118. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26119. switch ( objectName ) {
  26120. case 'materials':
  26121. if ( ! targetObject.material ) {
  26122. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26123. return;
  26124. }
  26125. if ( ! targetObject.material.materials ) {
  26126. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26127. return;
  26128. }
  26129. targetObject = targetObject.material.materials;
  26130. break;
  26131. case 'bones':
  26132. if ( ! targetObject.skeleton ) {
  26133. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26134. return;
  26135. }
  26136. // potential future optimization: skip this if propertyIndex is already an integer
  26137. // and convert the integer string to a true integer.
  26138. targetObject = targetObject.skeleton.bones;
  26139. // support resolving morphTarget names into indices.
  26140. for ( let i = 0; i < targetObject.length; i ++ ) {
  26141. if ( targetObject[ i ].name === objectIndex ) {
  26142. objectIndex = i;
  26143. break;
  26144. }
  26145. }
  26146. break;
  26147. default:
  26148. if ( targetObject[ objectName ] === undefined ) {
  26149. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26150. return;
  26151. }
  26152. targetObject = targetObject[ objectName ];
  26153. }
  26154. if ( objectIndex !== undefined ) {
  26155. if ( targetObject[ objectIndex ] === undefined ) {
  26156. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26157. return;
  26158. }
  26159. targetObject = targetObject[ objectIndex ];
  26160. }
  26161. }
  26162. // resolve property
  26163. const nodeProperty = targetObject[ propertyName ];
  26164. if ( nodeProperty === undefined ) {
  26165. const nodeName = parsedPath.nodeName;
  26166. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26167. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26168. return;
  26169. }
  26170. // determine versioning scheme
  26171. let versioning = this.Versioning.None;
  26172. this.targetObject = targetObject;
  26173. if ( targetObject.needsUpdate !== undefined ) { // material
  26174. versioning = this.Versioning.NeedsUpdate;
  26175. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26176. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26177. }
  26178. // determine how the property gets bound
  26179. let bindingType = this.BindingType.Direct;
  26180. if ( propertyIndex !== undefined ) {
  26181. // access a sub element of the property array (only primitives are supported right now)
  26182. if ( propertyName === "morphTargetInfluences" ) {
  26183. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26184. // support resolving morphTarget names into indices.
  26185. if ( ! targetObject.geometry ) {
  26186. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26187. return;
  26188. }
  26189. if ( targetObject.geometry.isBufferGeometry ) {
  26190. if ( ! targetObject.geometry.morphAttributes ) {
  26191. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26192. return;
  26193. }
  26194. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26195. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26196. }
  26197. } else {
  26198. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  26199. return;
  26200. }
  26201. }
  26202. bindingType = this.BindingType.ArrayElement;
  26203. this.resolvedProperty = nodeProperty;
  26204. this.propertyIndex = propertyIndex;
  26205. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26206. // must use copy for Object3D.Euler/Quaternion
  26207. bindingType = this.BindingType.HasFromToArray;
  26208. this.resolvedProperty = nodeProperty;
  26209. } else if ( Array.isArray( nodeProperty ) ) {
  26210. bindingType = this.BindingType.EntireArray;
  26211. this.resolvedProperty = nodeProperty;
  26212. } else {
  26213. this.propertyName = propertyName;
  26214. }
  26215. // select getter / setter
  26216. this.getValue = this.GetterByBindingType[ bindingType ];
  26217. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26218. },
  26219. unbind: function () {
  26220. this.node = null;
  26221. // back to the prototype version of getValue / setValue
  26222. // note: avoiding to mutate the shape of 'this' via 'delete'
  26223. this.getValue = this._getValue_unbound;
  26224. this.setValue = this._setValue_unbound;
  26225. }
  26226. } );
  26227. // DECLARE ALIAS AFTER assign prototype
  26228. Object.assign( PropertyBinding.prototype, {
  26229. // initial state of these methods that calls 'bind'
  26230. _getValue_unbound: PropertyBinding.prototype.getValue,
  26231. _setValue_unbound: PropertyBinding.prototype.setValue,
  26232. } );
  26233. /**
  26234. *
  26235. * A group of objects that receives a shared animation state.
  26236. *
  26237. * Usage:
  26238. *
  26239. * - Add objects you would otherwise pass as 'root' to the
  26240. * constructor or the .clipAction method of AnimationMixer.
  26241. *
  26242. * - Instead pass this object as 'root'.
  26243. *
  26244. * - You can also add and remove objects later when the mixer
  26245. * is running.
  26246. *
  26247. * Note:
  26248. *
  26249. * Objects of this class appear as one object to the mixer,
  26250. * so cache control of the individual objects must be done
  26251. * on the group.
  26252. *
  26253. * Limitation:
  26254. *
  26255. * - The animated properties must be compatible among the
  26256. * all objects in the group.
  26257. *
  26258. * - A single property can either be controlled through a
  26259. * target group or directly, but not both.
  26260. */
  26261. function AnimationObjectGroup() {
  26262. this.uuid = MathUtils.generateUUID();
  26263. // cached objects followed by the active ones
  26264. this._objects = Array.prototype.slice.call( arguments );
  26265. this.nCachedObjects_ = 0; // threshold
  26266. // note: read by PropertyBinding.Composite
  26267. const indices = {};
  26268. this._indicesByUUID = indices; // for bookkeeping
  26269. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26270. indices[ arguments[ i ].uuid ] = i;
  26271. }
  26272. this._paths = []; // inside: string
  26273. this._parsedPaths = []; // inside: { we don't care, here }
  26274. this._bindings = []; // inside: Array< PropertyBinding >
  26275. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26276. const scope = this;
  26277. this.stats = {
  26278. objects: {
  26279. get total() {
  26280. return scope._objects.length;
  26281. },
  26282. get inUse() {
  26283. return this.total - scope.nCachedObjects_;
  26284. }
  26285. },
  26286. get bindingsPerObject() {
  26287. return scope._bindings.length;
  26288. }
  26289. };
  26290. }
  26291. Object.assign( AnimationObjectGroup.prototype, {
  26292. isAnimationObjectGroup: true,
  26293. add: function () {
  26294. const objects = this._objects,
  26295. indicesByUUID = this._indicesByUUID,
  26296. paths = this._paths,
  26297. parsedPaths = this._parsedPaths,
  26298. bindings = this._bindings,
  26299. nBindings = bindings.length;
  26300. let knownObject = undefined,
  26301. nObjects = objects.length,
  26302. nCachedObjects = this.nCachedObjects_;
  26303. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26304. const object = arguments[ i ],
  26305. uuid = object.uuid;
  26306. let index = indicesByUUID[ uuid ];
  26307. if ( index === undefined ) {
  26308. // unknown object -> add it to the ACTIVE region
  26309. index = nObjects ++;
  26310. indicesByUUID[ uuid ] = index;
  26311. objects.push( object );
  26312. // accounting is done, now do the same for all bindings
  26313. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26314. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26315. }
  26316. } else if ( index < nCachedObjects ) {
  26317. knownObject = objects[ index ];
  26318. // move existing object to the ACTIVE region
  26319. const firstActiveIndex = -- nCachedObjects,
  26320. lastCachedObject = objects[ firstActiveIndex ];
  26321. indicesByUUID[ lastCachedObject.uuid ] = index;
  26322. objects[ index ] = lastCachedObject;
  26323. indicesByUUID[ uuid ] = firstActiveIndex;
  26324. objects[ firstActiveIndex ] = object;
  26325. // accounting is done, now do the same for all bindings
  26326. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26327. const bindingsForPath = bindings[ j ],
  26328. lastCached = bindingsForPath[ firstActiveIndex ];
  26329. let binding = bindingsForPath[ index ];
  26330. bindingsForPath[ index ] = lastCached;
  26331. if ( binding === undefined ) {
  26332. // since we do not bother to create new bindings
  26333. // for objects that are cached, the binding may
  26334. // or may not exist
  26335. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26336. }
  26337. bindingsForPath[ firstActiveIndex ] = binding;
  26338. }
  26339. } else if ( objects[ index ] !== knownObject ) {
  26340. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26341. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26342. } // else the object is already where we want it to be
  26343. } // for arguments
  26344. this.nCachedObjects_ = nCachedObjects;
  26345. },
  26346. remove: function () {
  26347. const objects = this._objects,
  26348. indicesByUUID = this._indicesByUUID,
  26349. bindings = this._bindings,
  26350. nBindings = bindings.length;
  26351. let nCachedObjects = this.nCachedObjects_;
  26352. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26353. const object = arguments[ i ],
  26354. uuid = object.uuid,
  26355. index = indicesByUUID[ uuid ];
  26356. if ( index !== undefined && index >= nCachedObjects ) {
  26357. // move existing object into the CACHED region
  26358. const lastCachedIndex = nCachedObjects ++,
  26359. firstActiveObject = objects[ lastCachedIndex ];
  26360. indicesByUUID[ firstActiveObject.uuid ] = index;
  26361. objects[ index ] = firstActiveObject;
  26362. indicesByUUID[ uuid ] = lastCachedIndex;
  26363. objects[ lastCachedIndex ] = object;
  26364. // accounting is done, now do the same for all bindings
  26365. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26366. const bindingsForPath = bindings[ j ],
  26367. firstActive = bindingsForPath[ lastCachedIndex ],
  26368. binding = bindingsForPath[ index ];
  26369. bindingsForPath[ index ] = firstActive;
  26370. bindingsForPath[ lastCachedIndex ] = binding;
  26371. }
  26372. }
  26373. } // for arguments
  26374. this.nCachedObjects_ = nCachedObjects;
  26375. },
  26376. // remove & forget
  26377. uncache: function () {
  26378. const objects = this._objects,
  26379. indicesByUUID = this._indicesByUUID,
  26380. bindings = this._bindings,
  26381. nBindings = bindings.length;
  26382. let nCachedObjects = this.nCachedObjects_,
  26383. nObjects = objects.length;
  26384. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26385. const object = arguments[ i ],
  26386. uuid = object.uuid,
  26387. index = indicesByUUID[ uuid ];
  26388. if ( index !== undefined ) {
  26389. delete indicesByUUID[ uuid ];
  26390. if ( index < nCachedObjects ) {
  26391. // object is cached, shrink the CACHED region
  26392. const firstActiveIndex = -- nCachedObjects,
  26393. lastCachedObject = objects[ firstActiveIndex ],
  26394. lastIndex = -- nObjects,
  26395. lastObject = objects[ lastIndex ];
  26396. // last cached object takes this object's place
  26397. indicesByUUID[ lastCachedObject.uuid ] = index;
  26398. objects[ index ] = lastCachedObject;
  26399. // last object goes to the activated slot and pop
  26400. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26401. objects[ firstActiveIndex ] = lastObject;
  26402. objects.pop();
  26403. // accounting is done, now do the same for all bindings
  26404. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26405. const bindingsForPath = bindings[ j ],
  26406. lastCached = bindingsForPath[ firstActiveIndex ],
  26407. last = bindingsForPath[ lastIndex ];
  26408. bindingsForPath[ index ] = lastCached;
  26409. bindingsForPath[ firstActiveIndex ] = last;
  26410. bindingsForPath.pop();
  26411. }
  26412. } else {
  26413. // object is active, just swap with the last and pop
  26414. const lastIndex = -- nObjects,
  26415. lastObject = objects[ lastIndex ];
  26416. indicesByUUID[ lastObject.uuid ] = index;
  26417. objects[ index ] = lastObject;
  26418. objects.pop();
  26419. // accounting is done, now do the same for all bindings
  26420. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26421. const bindingsForPath = bindings[ j ];
  26422. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26423. bindingsForPath.pop();
  26424. }
  26425. } // cached or active
  26426. } // if object is known
  26427. } // for arguments
  26428. this.nCachedObjects_ = nCachedObjects;
  26429. },
  26430. // Internal interface used by befriended PropertyBinding.Composite:
  26431. subscribe_: function ( path, parsedPath ) {
  26432. // returns an array of bindings for the given path that is changed
  26433. // according to the contained objects in the group
  26434. const indicesByPath = this._bindingsIndicesByPath;
  26435. let index = indicesByPath[ path ];
  26436. const bindings = this._bindings;
  26437. if ( index !== undefined ) return bindings[ index ];
  26438. const paths = this._paths,
  26439. parsedPaths = this._parsedPaths,
  26440. objects = this._objects,
  26441. nObjects = objects.length,
  26442. nCachedObjects = this.nCachedObjects_,
  26443. bindingsForPath = new Array( nObjects );
  26444. index = bindings.length;
  26445. indicesByPath[ path ] = index;
  26446. paths.push( path );
  26447. parsedPaths.push( parsedPath );
  26448. bindings.push( bindingsForPath );
  26449. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26450. const object = objects[ i ];
  26451. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26452. }
  26453. return bindingsForPath;
  26454. },
  26455. unsubscribe_: function ( path ) {
  26456. // tells the group to forget about a property path and no longer
  26457. // update the array previously obtained with 'subscribe_'
  26458. const indicesByPath = this._bindingsIndicesByPath,
  26459. index = indicesByPath[ path ];
  26460. if ( index !== undefined ) {
  26461. const paths = this._paths,
  26462. parsedPaths = this._parsedPaths,
  26463. bindings = this._bindings,
  26464. lastBindingsIndex = bindings.length - 1,
  26465. lastBindings = bindings[ lastBindingsIndex ],
  26466. lastBindingsPath = path[ lastBindingsIndex ];
  26467. indicesByPath[ lastBindingsPath ] = index;
  26468. bindings[ index ] = lastBindings;
  26469. bindings.pop();
  26470. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26471. parsedPaths.pop();
  26472. paths[ index ] = paths[ lastBindingsIndex ];
  26473. paths.pop();
  26474. }
  26475. }
  26476. } );
  26477. class AnimationAction {
  26478. constructor( mixer, clip, localRoot, blendMode ) {
  26479. this._mixer = mixer;
  26480. this._clip = clip;
  26481. this._localRoot = localRoot || null;
  26482. this.blendMode = blendMode || clip.blendMode;
  26483. const tracks = clip.tracks,
  26484. nTracks = tracks.length,
  26485. interpolants = new Array( nTracks );
  26486. const interpolantSettings = {
  26487. endingStart: ZeroCurvatureEnding,
  26488. endingEnd: ZeroCurvatureEnding
  26489. };
  26490. for ( let i = 0; i !== nTracks; ++ i ) {
  26491. const interpolant = tracks[ i ].createInterpolant( null );
  26492. interpolants[ i ] = interpolant;
  26493. interpolant.settings = interpolantSettings;
  26494. }
  26495. this._interpolantSettings = interpolantSettings;
  26496. this._interpolants = interpolants; // bound by the mixer
  26497. // inside: PropertyMixer (managed by the mixer)
  26498. this._propertyBindings = new Array( nTracks );
  26499. this._cacheIndex = null; // for the memory manager
  26500. this._byClipCacheIndex = null; // for the memory manager
  26501. this._timeScaleInterpolant = null;
  26502. this._weightInterpolant = null;
  26503. this.loop = LoopRepeat;
  26504. this._loopCount = - 1;
  26505. // global mixer time when the action is to be started
  26506. // it's set back to 'null' upon start of the action
  26507. this._startTime = null;
  26508. // scaled local time of the action
  26509. // gets clamped or wrapped to 0..clip.duration according to loop
  26510. this.time = 0;
  26511. this.timeScale = 1;
  26512. this._effectiveTimeScale = 1;
  26513. this.weight = 1;
  26514. this._effectiveWeight = 1;
  26515. this.repetitions = Infinity; // no. of repetitions when looping
  26516. this.paused = false; // true -> zero effective time scale
  26517. this.enabled = true; // false -> zero effective weight
  26518. this.clampWhenFinished = false;// keep feeding the last frame?
  26519. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26520. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26521. }
  26522. // State & Scheduling
  26523. play() {
  26524. this._mixer._activateAction( this );
  26525. return this;
  26526. }
  26527. stop() {
  26528. this._mixer._deactivateAction( this );
  26529. return this.reset();
  26530. }
  26531. reset() {
  26532. this.paused = false;
  26533. this.enabled = true;
  26534. this.time = 0; // restart clip
  26535. this._loopCount = - 1;// forget previous loops
  26536. this._startTime = null;// forget scheduling
  26537. return this.stopFading().stopWarping();
  26538. }
  26539. isRunning() {
  26540. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26541. this._startTime === null && this._mixer._isActiveAction( this );
  26542. }
  26543. // return true when play has been called
  26544. isScheduled() {
  26545. return this._mixer._isActiveAction( this );
  26546. }
  26547. startAt( time ) {
  26548. this._startTime = time;
  26549. return this;
  26550. }
  26551. setLoop( mode, repetitions ) {
  26552. this.loop = mode;
  26553. this.repetitions = repetitions;
  26554. return this;
  26555. }
  26556. // Weight
  26557. // set the weight stopping any scheduled fading
  26558. // although .enabled = false yields an effective weight of zero, this
  26559. // method does *not* change .enabled, because it would be confusing
  26560. setEffectiveWeight( weight ) {
  26561. this.weight = weight;
  26562. // note: same logic as when updated at runtime
  26563. this._effectiveWeight = this.enabled ? weight : 0;
  26564. return this.stopFading();
  26565. }
  26566. // return the weight considering fading and .enabled
  26567. getEffectiveWeight() {
  26568. return this._effectiveWeight;
  26569. }
  26570. fadeIn( duration ) {
  26571. return this._scheduleFading( duration, 0, 1 );
  26572. }
  26573. fadeOut( duration ) {
  26574. return this._scheduleFading( duration, 1, 0 );
  26575. }
  26576. crossFadeFrom( fadeOutAction, duration, warp ) {
  26577. fadeOutAction.fadeOut( duration );
  26578. this.fadeIn( duration );
  26579. if ( warp ) {
  26580. const fadeInDuration = this._clip.duration,
  26581. fadeOutDuration = fadeOutAction._clip.duration,
  26582. startEndRatio = fadeOutDuration / fadeInDuration,
  26583. endStartRatio = fadeInDuration / fadeOutDuration;
  26584. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26585. this.warp( endStartRatio, 1.0, duration );
  26586. }
  26587. return this;
  26588. }
  26589. crossFadeTo( fadeInAction, duration, warp ) {
  26590. return fadeInAction.crossFadeFrom( this, duration, warp );
  26591. }
  26592. stopFading() {
  26593. const weightInterpolant = this._weightInterpolant;
  26594. if ( weightInterpolant !== null ) {
  26595. this._weightInterpolant = null;
  26596. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26597. }
  26598. return this;
  26599. }
  26600. // Time Scale Control
  26601. // set the time scale stopping any scheduled warping
  26602. // although .paused = true yields an effective time scale of zero, this
  26603. // method does *not* change .paused, because it would be confusing
  26604. setEffectiveTimeScale( timeScale ) {
  26605. this.timeScale = timeScale;
  26606. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26607. return this.stopWarping();
  26608. }
  26609. // return the time scale considering warping and .paused
  26610. getEffectiveTimeScale() {
  26611. return this._effectiveTimeScale;
  26612. }
  26613. setDuration( duration ) {
  26614. this.timeScale = this._clip.duration / duration;
  26615. return this.stopWarping();
  26616. }
  26617. syncWith( action ) {
  26618. this.time = action.time;
  26619. this.timeScale = action.timeScale;
  26620. return this.stopWarping();
  26621. }
  26622. halt( duration ) {
  26623. return this.warp( this._effectiveTimeScale, 0, duration );
  26624. }
  26625. warp( startTimeScale, endTimeScale, duration ) {
  26626. const mixer = this._mixer,
  26627. now = mixer.time,
  26628. timeScale = this.timeScale;
  26629. let interpolant = this._timeScaleInterpolant;
  26630. if ( interpolant === null ) {
  26631. interpolant = mixer._lendControlInterpolant();
  26632. this._timeScaleInterpolant = interpolant;
  26633. }
  26634. const times = interpolant.parameterPositions,
  26635. values = interpolant.sampleValues;
  26636. times[ 0 ] = now;
  26637. times[ 1 ] = now + duration;
  26638. values[ 0 ] = startTimeScale / timeScale;
  26639. values[ 1 ] = endTimeScale / timeScale;
  26640. return this;
  26641. }
  26642. stopWarping() {
  26643. const timeScaleInterpolant = this._timeScaleInterpolant;
  26644. if ( timeScaleInterpolant !== null ) {
  26645. this._timeScaleInterpolant = null;
  26646. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26647. }
  26648. return this;
  26649. }
  26650. // Object Accessors
  26651. getMixer() {
  26652. return this._mixer;
  26653. }
  26654. getClip() {
  26655. return this._clip;
  26656. }
  26657. getRoot() {
  26658. return this._localRoot || this._mixer._root;
  26659. }
  26660. // Interna
  26661. _update( time, deltaTime, timeDirection, accuIndex ) {
  26662. // called by the mixer
  26663. if ( ! this.enabled ) {
  26664. // call ._updateWeight() to update ._effectiveWeight
  26665. this._updateWeight( time );
  26666. return;
  26667. }
  26668. const startTime = this._startTime;
  26669. if ( startTime !== null ) {
  26670. // check for scheduled start of action
  26671. const timeRunning = ( time - startTime ) * timeDirection;
  26672. if ( timeRunning < 0 || timeDirection === 0 ) {
  26673. return; // yet to come / don't decide when delta = 0
  26674. }
  26675. // start
  26676. this._startTime = null; // unschedule
  26677. deltaTime = timeDirection * timeRunning;
  26678. }
  26679. // apply time scale and advance time
  26680. deltaTime *= this._updateTimeScale( time );
  26681. const clipTime = this._updateTime( deltaTime );
  26682. // note: _updateTime may disable the action resulting in
  26683. // an effective weight of 0
  26684. const weight = this._updateWeight( time );
  26685. if ( weight > 0 ) {
  26686. const interpolants = this._interpolants;
  26687. const propertyMixers = this._propertyBindings;
  26688. switch ( this.blendMode ) {
  26689. case AdditiveAnimationBlendMode:
  26690. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26691. interpolants[ j ].evaluate( clipTime );
  26692. propertyMixers[ j ].accumulateAdditive( weight );
  26693. }
  26694. break;
  26695. case NormalAnimationBlendMode:
  26696. default:
  26697. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26698. interpolants[ j ].evaluate( clipTime );
  26699. propertyMixers[ j ].accumulate( accuIndex, weight );
  26700. }
  26701. }
  26702. }
  26703. }
  26704. _updateWeight( time ) {
  26705. let weight = 0;
  26706. if ( this.enabled ) {
  26707. weight = this.weight;
  26708. const interpolant = this._weightInterpolant;
  26709. if ( interpolant !== null ) {
  26710. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26711. weight *= interpolantValue;
  26712. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26713. this.stopFading();
  26714. if ( interpolantValue === 0 ) {
  26715. // faded out, disable
  26716. this.enabled = false;
  26717. }
  26718. }
  26719. }
  26720. }
  26721. this._effectiveWeight = weight;
  26722. return weight;
  26723. }
  26724. _updateTimeScale( time ) {
  26725. let timeScale = 0;
  26726. if ( ! this.paused ) {
  26727. timeScale = this.timeScale;
  26728. const interpolant = this._timeScaleInterpolant;
  26729. if ( interpolant !== null ) {
  26730. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26731. timeScale *= interpolantValue;
  26732. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26733. this.stopWarping();
  26734. if ( timeScale === 0 ) {
  26735. // motion has halted, pause
  26736. this.paused = true;
  26737. } else {
  26738. // warp done - apply final time scale
  26739. this.timeScale = timeScale;
  26740. }
  26741. }
  26742. }
  26743. }
  26744. this._effectiveTimeScale = timeScale;
  26745. return timeScale;
  26746. }
  26747. _updateTime( deltaTime ) {
  26748. const duration = this._clip.duration;
  26749. const loop = this.loop;
  26750. let time = this.time + deltaTime;
  26751. let loopCount = this._loopCount;
  26752. const pingPong = ( loop === LoopPingPong );
  26753. if ( deltaTime === 0 ) {
  26754. if ( loopCount === - 1 ) return time;
  26755. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26756. }
  26757. if ( loop === LoopOnce ) {
  26758. if ( loopCount === - 1 ) {
  26759. // just started
  26760. this._loopCount = 0;
  26761. this._setEndings( true, true, false );
  26762. }
  26763. handle_stop: {
  26764. if ( time >= duration ) {
  26765. time = duration;
  26766. } else if ( time < 0 ) {
  26767. time = 0;
  26768. } else {
  26769. this.time = time;
  26770. break handle_stop;
  26771. }
  26772. if ( this.clampWhenFinished ) this.paused = true;
  26773. else this.enabled = false;
  26774. this.time = time;
  26775. this._mixer.dispatchEvent( {
  26776. type: 'finished', action: this,
  26777. direction: deltaTime < 0 ? - 1 : 1
  26778. } );
  26779. }
  26780. } else { // repetitive Repeat or PingPong
  26781. if ( loopCount === - 1 ) {
  26782. // just started
  26783. if ( deltaTime >= 0 ) {
  26784. loopCount = 0;
  26785. this._setEndings( true, this.repetitions === 0, pingPong );
  26786. } else {
  26787. // when looping in reverse direction, the initial
  26788. // transition through zero counts as a repetition,
  26789. // so leave loopCount at -1
  26790. this._setEndings( this.repetitions === 0, true, pingPong );
  26791. }
  26792. }
  26793. if ( time >= duration || time < 0 ) {
  26794. // wrap around
  26795. const loopDelta = Math.floor( time / duration ); // signed
  26796. time -= duration * loopDelta;
  26797. loopCount += Math.abs( loopDelta );
  26798. const pending = this.repetitions - loopCount;
  26799. if ( pending <= 0 ) {
  26800. // have to stop (switch state, clamp time, fire event)
  26801. if ( this.clampWhenFinished ) this.paused = true;
  26802. else this.enabled = false;
  26803. time = deltaTime > 0 ? duration : 0;
  26804. this.time = time;
  26805. this._mixer.dispatchEvent( {
  26806. type: 'finished', action: this,
  26807. direction: deltaTime > 0 ? 1 : - 1
  26808. } );
  26809. } else {
  26810. // keep running
  26811. if ( pending === 1 ) {
  26812. // entering the last round
  26813. const atStart = deltaTime < 0;
  26814. this._setEndings( atStart, ! atStart, pingPong );
  26815. } else {
  26816. this._setEndings( false, false, pingPong );
  26817. }
  26818. this._loopCount = loopCount;
  26819. this.time = time;
  26820. this._mixer.dispatchEvent( {
  26821. type: 'loop', action: this, loopDelta: loopDelta
  26822. } );
  26823. }
  26824. } else {
  26825. this.time = time;
  26826. }
  26827. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  26828. // invert time for the "pong round"
  26829. return duration - time;
  26830. }
  26831. }
  26832. return time;
  26833. }
  26834. _setEndings( atStart, atEnd, pingPong ) {
  26835. const settings = this._interpolantSettings;
  26836. if ( pingPong ) {
  26837. settings.endingStart = ZeroSlopeEnding;
  26838. settings.endingEnd = ZeroSlopeEnding;
  26839. } else {
  26840. // assuming for LoopOnce atStart == atEnd == true
  26841. if ( atStart ) {
  26842. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26843. } else {
  26844. settings.endingStart = WrapAroundEnding;
  26845. }
  26846. if ( atEnd ) {
  26847. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26848. } else {
  26849. settings.endingEnd = WrapAroundEnding;
  26850. }
  26851. }
  26852. }
  26853. _scheduleFading( duration, weightNow, weightThen ) {
  26854. const mixer = this._mixer, now = mixer.time;
  26855. let interpolant = this._weightInterpolant;
  26856. if ( interpolant === null ) {
  26857. interpolant = mixer._lendControlInterpolant();
  26858. this._weightInterpolant = interpolant;
  26859. }
  26860. const times = interpolant.parameterPositions,
  26861. values = interpolant.sampleValues;
  26862. times[ 0 ] = now;
  26863. values[ 0 ] = weightNow;
  26864. times[ 1 ] = now + duration;
  26865. values[ 1 ] = weightThen;
  26866. return this;
  26867. }
  26868. }
  26869. function AnimationMixer( root ) {
  26870. this._root = root;
  26871. this._initMemoryManager();
  26872. this._accuIndex = 0;
  26873. this.time = 0;
  26874. this.timeScale = 1.0;
  26875. }
  26876. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  26877. constructor: AnimationMixer,
  26878. _bindAction: function ( action, prototypeAction ) {
  26879. const root = action._localRoot || this._root,
  26880. tracks = action._clip.tracks,
  26881. nTracks = tracks.length,
  26882. bindings = action._propertyBindings,
  26883. interpolants = action._interpolants,
  26884. rootUuid = root.uuid,
  26885. bindingsByRoot = this._bindingsByRootAndName;
  26886. let bindingsByName = bindingsByRoot[ rootUuid ];
  26887. if ( bindingsByName === undefined ) {
  26888. bindingsByName = {};
  26889. bindingsByRoot[ rootUuid ] = bindingsByName;
  26890. }
  26891. for ( let i = 0; i !== nTracks; ++ i ) {
  26892. const track = tracks[ i ],
  26893. trackName = track.name;
  26894. let binding = bindingsByName[ trackName ];
  26895. if ( binding !== undefined ) {
  26896. bindings[ i ] = binding;
  26897. } else {
  26898. binding = bindings[ i ];
  26899. if ( binding !== undefined ) {
  26900. // existing binding, make sure the cache knows
  26901. if ( binding._cacheIndex === null ) {
  26902. ++ binding.referenceCount;
  26903. this._addInactiveBinding( binding, rootUuid, trackName );
  26904. }
  26905. continue;
  26906. }
  26907. const path = prototypeAction && prototypeAction.
  26908. _propertyBindings[ i ].binding.parsedPath;
  26909. binding = new PropertyMixer(
  26910. PropertyBinding.create( root, trackName, path ),
  26911. track.ValueTypeName, track.getValueSize() );
  26912. ++ binding.referenceCount;
  26913. this._addInactiveBinding( binding, rootUuid, trackName );
  26914. bindings[ i ] = binding;
  26915. }
  26916. interpolants[ i ].resultBuffer = binding.buffer;
  26917. }
  26918. },
  26919. _activateAction: function ( action ) {
  26920. if ( ! this._isActiveAction( action ) ) {
  26921. if ( action._cacheIndex === null ) {
  26922. // this action has been forgotten by the cache, but the user
  26923. // appears to be still using it -> rebind
  26924. const rootUuid = ( action._localRoot || this._root ).uuid,
  26925. clipUuid = action._clip.uuid,
  26926. actionsForClip = this._actionsByClip[ clipUuid ];
  26927. this._bindAction( action,
  26928. actionsForClip && actionsForClip.knownActions[ 0 ] );
  26929. this._addInactiveAction( action, clipUuid, rootUuid );
  26930. }
  26931. const bindings = action._propertyBindings;
  26932. // increment reference counts / sort out state
  26933. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26934. const binding = bindings[ i ];
  26935. if ( binding.useCount ++ === 0 ) {
  26936. this._lendBinding( binding );
  26937. binding.saveOriginalState();
  26938. }
  26939. }
  26940. this._lendAction( action );
  26941. }
  26942. },
  26943. _deactivateAction: function ( action ) {
  26944. if ( this._isActiveAction( action ) ) {
  26945. const bindings = action._propertyBindings;
  26946. // decrement reference counts / sort out state
  26947. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26948. const binding = bindings[ i ];
  26949. if ( -- binding.useCount === 0 ) {
  26950. binding.restoreOriginalState();
  26951. this._takeBackBinding( binding );
  26952. }
  26953. }
  26954. this._takeBackAction( action );
  26955. }
  26956. },
  26957. // Memory manager
  26958. _initMemoryManager: function () {
  26959. this._actions = []; // 'nActiveActions' followed by inactive ones
  26960. this._nActiveActions = 0;
  26961. this._actionsByClip = {};
  26962. // inside:
  26963. // {
  26964. // knownActions: Array< AnimationAction > - used as prototypes
  26965. // actionByRoot: AnimationAction - lookup
  26966. // }
  26967. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26968. this._nActiveBindings = 0;
  26969. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26970. this._controlInterpolants = []; // same game as above
  26971. this._nActiveControlInterpolants = 0;
  26972. const scope = this;
  26973. this.stats = {
  26974. actions: {
  26975. get total() {
  26976. return scope._actions.length;
  26977. },
  26978. get inUse() {
  26979. return scope._nActiveActions;
  26980. }
  26981. },
  26982. bindings: {
  26983. get total() {
  26984. return scope._bindings.length;
  26985. },
  26986. get inUse() {
  26987. return scope._nActiveBindings;
  26988. }
  26989. },
  26990. controlInterpolants: {
  26991. get total() {
  26992. return scope._controlInterpolants.length;
  26993. },
  26994. get inUse() {
  26995. return scope._nActiveControlInterpolants;
  26996. }
  26997. }
  26998. };
  26999. },
  27000. // Memory management for AnimationAction objects
  27001. _isActiveAction: function ( action ) {
  27002. const index = action._cacheIndex;
  27003. return index !== null && index < this._nActiveActions;
  27004. },
  27005. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27006. const actions = this._actions,
  27007. actionsByClip = this._actionsByClip;
  27008. let actionsForClip = actionsByClip[ clipUuid ];
  27009. if ( actionsForClip === undefined ) {
  27010. actionsForClip = {
  27011. knownActions: [ action ],
  27012. actionByRoot: {}
  27013. };
  27014. action._byClipCacheIndex = 0;
  27015. actionsByClip[ clipUuid ] = actionsForClip;
  27016. } else {
  27017. const knownActions = actionsForClip.knownActions;
  27018. action._byClipCacheIndex = knownActions.length;
  27019. knownActions.push( action );
  27020. }
  27021. action._cacheIndex = actions.length;
  27022. actions.push( action );
  27023. actionsForClip.actionByRoot[ rootUuid ] = action;
  27024. },
  27025. _removeInactiveAction: function ( action ) {
  27026. const actions = this._actions,
  27027. lastInactiveAction = actions[ actions.length - 1 ],
  27028. cacheIndex = action._cacheIndex;
  27029. lastInactiveAction._cacheIndex = cacheIndex;
  27030. actions[ cacheIndex ] = lastInactiveAction;
  27031. actions.pop();
  27032. action._cacheIndex = null;
  27033. const clipUuid = action._clip.uuid,
  27034. actionsByClip = this._actionsByClip,
  27035. actionsForClip = actionsByClip[ clipUuid ],
  27036. knownActionsForClip = actionsForClip.knownActions,
  27037. lastKnownAction =
  27038. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27039. byClipCacheIndex = action._byClipCacheIndex;
  27040. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27041. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27042. knownActionsForClip.pop();
  27043. action._byClipCacheIndex = null;
  27044. const actionByRoot = actionsForClip.actionByRoot,
  27045. rootUuid = ( action._localRoot || this._root ).uuid;
  27046. delete actionByRoot[ rootUuid ];
  27047. if ( knownActionsForClip.length === 0 ) {
  27048. delete actionsByClip[ clipUuid ];
  27049. }
  27050. this._removeInactiveBindingsForAction( action );
  27051. },
  27052. _removeInactiveBindingsForAction: function ( action ) {
  27053. const bindings = action._propertyBindings;
  27054. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27055. const binding = bindings[ i ];
  27056. if ( -- binding.referenceCount === 0 ) {
  27057. this._removeInactiveBinding( binding );
  27058. }
  27059. }
  27060. },
  27061. _lendAction: function ( action ) {
  27062. // [ active actions | inactive actions ]
  27063. // [ active actions >| inactive actions ]
  27064. // s a
  27065. // <-swap->
  27066. // a s
  27067. const actions = this._actions,
  27068. prevIndex = action._cacheIndex,
  27069. lastActiveIndex = this._nActiveActions ++,
  27070. firstInactiveAction = actions[ lastActiveIndex ];
  27071. action._cacheIndex = lastActiveIndex;
  27072. actions[ lastActiveIndex ] = action;
  27073. firstInactiveAction._cacheIndex = prevIndex;
  27074. actions[ prevIndex ] = firstInactiveAction;
  27075. },
  27076. _takeBackAction: function ( action ) {
  27077. // [ active actions | inactive actions ]
  27078. // [ active actions |< inactive actions ]
  27079. // a s
  27080. // <-swap->
  27081. // s a
  27082. const actions = this._actions,
  27083. prevIndex = action._cacheIndex,
  27084. firstInactiveIndex = -- this._nActiveActions,
  27085. lastActiveAction = actions[ firstInactiveIndex ];
  27086. action._cacheIndex = firstInactiveIndex;
  27087. actions[ firstInactiveIndex ] = action;
  27088. lastActiveAction._cacheIndex = prevIndex;
  27089. actions[ prevIndex ] = lastActiveAction;
  27090. },
  27091. // Memory management for PropertyMixer objects
  27092. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  27093. const bindingsByRoot = this._bindingsByRootAndName,
  27094. bindings = this._bindings;
  27095. let bindingByName = bindingsByRoot[ rootUuid ];
  27096. if ( bindingByName === undefined ) {
  27097. bindingByName = {};
  27098. bindingsByRoot[ rootUuid ] = bindingByName;
  27099. }
  27100. bindingByName[ trackName ] = binding;
  27101. binding._cacheIndex = bindings.length;
  27102. bindings.push( binding );
  27103. },
  27104. _removeInactiveBinding: function ( binding ) {
  27105. const bindings = this._bindings,
  27106. propBinding = binding.binding,
  27107. rootUuid = propBinding.rootNode.uuid,
  27108. trackName = propBinding.path,
  27109. bindingsByRoot = this._bindingsByRootAndName,
  27110. bindingByName = bindingsByRoot[ rootUuid ],
  27111. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27112. cacheIndex = binding._cacheIndex;
  27113. lastInactiveBinding._cacheIndex = cacheIndex;
  27114. bindings[ cacheIndex ] = lastInactiveBinding;
  27115. bindings.pop();
  27116. delete bindingByName[ trackName ];
  27117. if ( Object.keys( bindingByName ).length === 0 ) {
  27118. delete bindingsByRoot[ rootUuid ];
  27119. }
  27120. },
  27121. _lendBinding: function ( binding ) {
  27122. const bindings = this._bindings,
  27123. prevIndex = binding._cacheIndex,
  27124. lastActiveIndex = this._nActiveBindings ++,
  27125. firstInactiveBinding = bindings[ lastActiveIndex ];
  27126. binding._cacheIndex = lastActiveIndex;
  27127. bindings[ lastActiveIndex ] = binding;
  27128. firstInactiveBinding._cacheIndex = prevIndex;
  27129. bindings[ prevIndex ] = firstInactiveBinding;
  27130. },
  27131. _takeBackBinding: function ( binding ) {
  27132. const bindings = this._bindings,
  27133. prevIndex = binding._cacheIndex,
  27134. firstInactiveIndex = -- this._nActiveBindings,
  27135. lastActiveBinding = bindings[ firstInactiveIndex ];
  27136. binding._cacheIndex = firstInactiveIndex;
  27137. bindings[ firstInactiveIndex ] = binding;
  27138. lastActiveBinding._cacheIndex = prevIndex;
  27139. bindings[ prevIndex ] = lastActiveBinding;
  27140. },
  27141. // Memory management of Interpolants for weight and time scale
  27142. _lendControlInterpolant: function () {
  27143. const interpolants = this._controlInterpolants,
  27144. lastActiveIndex = this._nActiveControlInterpolants ++;
  27145. let interpolant = interpolants[ lastActiveIndex ];
  27146. if ( interpolant === undefined ) {
  27147. interpolant = new LinearInterpolant(
  27148. new Float32Array( 2 ), new Float32Array( 2 ),
  27149. 1, this._controlInterpolantsResultBuffer );
  27150. interpolant.__cacheIndex = lastActiveIndex;
  27151. interpolants[ lastActiveIndex ] = interpolant;
  27152. }
  27153. return interpolant;
  27154. },
  27155. _takeBackControlInterpolant: function ( interpolant ) {
  27156. const interpolants = this._controlInterpolants,
  27157. prevIndex = interpolant.__cacheIndex,
  27158. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27159. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27160. interpolant.__cacheIndex = firstInactiveIndex;
  27161. interpolants[ firstInactiveIndex ] = interpolant;
  27162. lastActiveInterpolant.__cacheIndex = prevIndex;
  27163. interpolants[ prevIndex ] = lastActiveInterpolant;
  27164. },
  27165. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  27166. // return an action for a clip optionally using a custom root target
  27167. // object (this method allocates a lot of dynamic memory in case a
  27168. // previously unknown clip/root combination is specified)
  27169. clipAction: function ( clip, optionalRoot, blendMode ) {
  27170. const root = optionalRoot || this._root,
  27171. rootUuid = root.uuid;
  27172. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27173. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27174. const actionsForClip = this._actionsByClip[ clipUuid ];
  27175. let prototypeAction = null;
  27176. if ( blendMode === undefined ) {
  27177. if ( clipObject !== null ) {
  27178. blendMode = clipObject.blendMode;
  27179. } else {
  27180. blendMode = NormalAnimationBlendMode;
  27181. }
  27182. }
  27183. if ( actionsForClip !== undefined ) {
  27184. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27185. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27186. return existingAction;
  27187. }
  27188. // we know the clip, so we don't have to parse all
  27189. // the bindings again but can just copy
  27190. prototypeAction = actionsForClip.knownActions[ 0 ];
  27191. // also, take the clip from the prototype action
  27192. if ( clipObject === null )
  27193. clipObject = prototypeAction._clip;
  27194. }
  27195. // clip must be known when specified via string
  27196. if ( clipObject === null ) return null;
  27197. // allocate all resources required to run it
  27198. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27199. this._bindAction( newAction, prototypeAction );
  27200. // and make the action known to the memory manager
  27201. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27202. return newAction;
  27203. },
  27204. // get an existing action
  27205. existingAction: function ( clip, optionalRoot ) {
  27206. const root = optionalRoot || this._root,
  27207. rootUuid = root.uuid,
  27208. clipObject = typeof clip === 'string' ?
  27209. AnimationClip.findByName( root, clip ) : clip,
  27210. clipUuid = clipObject ? clipObject.uuid : clip,
  27211. actionsForClip = this._actionsByClip[ clipUuid ];
  27212. if ( actionsForClip !== undefined ) {
  27213. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27214. }
  27215. return null;
  27216. },
  27217. // deactivates all previously scheduled actions
  27218. stopAllAction: function () {
  27219. const actions = this._actions,
  27220. nActions = this._nActiveActions;
  27221. for ( let i = nActions - 1; i >= 0; -- i ) {
  27222. actions[ i ].stop();
  27223. }
  27224. return this;
  27225. },
  27226. // advance the time and update apply the animation
  27227. update: function ( deltaTime ) {
  27228. deltaTime *= this.timeScale;
  27229. const actions = this._actions,
  27230. nActions = this._nActiveActions,
  27231. time = this.time += deltaTime,
  27232. timeDirection = Math.sign( deltaTime ),
  27233. accuIndex = this._accuIndex ^= 1;
  27234. // run active actions
  27235. for ( let i = 0; i !== nActions; ++ i ) {
  27236. const action = actions[ i ];
  27237. action._update( time, deltaTime, timeDirection, accuIndex );
  27238. }
  27239. // update scene graph
  27240. const bindings = this._bindings,
  27241. nBindings = this._nActiveBindings;
  27242. for ( let i = 0; i !== nBindings; ++ i ) {
  27243. bindings[ i ].apply( accuIndex );
  27244. }
  27245. return this;
  27246. },
  27247. // Allows you to seek to a specific time in an animation.
  27248. setTime: function ( timeInSeconds ) {
  27249. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27250. for ( let i = 0; i < this._actions.length; i ++ ) {
  27251. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27252. }
  27253. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27254. },
  27255. // return this mixer's root target object
  27256. getRoot: function () {
  27257. return this._root;
  27258. },
  27259. // free all resources specific to a particular clip
  27260. uncacheClip: function ( clip ) {
  27261. const actions = this._actions,
  27262. clipUuid = clip.uuid,
  27263. actionsByClip = this._actionsByClip,
  27264. actionsForClip = actionsByClip[ clipUuid ];
  27265. if ( actionsForClip !== undefined ) {
  27266. // note: just calling _removeInactiveAction would mess up the
  27267. // iteration state and also require updating the state we can
  27268. // just throw away
  27269. const actionsToRemove = actionsForClip.knownActions;
  27270. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27271. const action = actionsToRemove[ i ];
  27272. this._deactivateAction( action );
  27273. const cacheIndex = action._cacheIndex,
  27274. lastInactiveAction = actions[ actions.length - 1 ];
  27275. action._cacheIndex = null;
  27276. action._byClipCacheIndex = null;
  27277. lastInactiveAction._cacheIndex = cacheIndex;
  27278. actions[ cacheIndex ] = lastInactiveAction;
  27279. actions.pop();
  27280. this._removeInactiveBindingsForAction( action );
  27281. }
  27282. delete actionsByClip[ clipUuid ];
  27283. }
  27284. },
  27285. // free all resources specific to a particular root target object
  27286. uncacheRoot: function ( root ) {
  27287. const rootUuid = root.uuid,
  27288. actionsByClip = this._actionsByClip;
  27289. for ( const clipUuid in actionsByClip ) {
  27290. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27291. action = actionByRoot[ rootUuid ];
  27292. if ( action !== undefined ) {
  27293. this._deactivateAction( action );
  27294. this._removeInactiveAction( action );
  27295. }
  27296. }
  27297. const bindingsByRoot = this._bindingsByRootAndName,
  27298. bindingByName = bindingsByRoot[ rootUuid ];
  27299. if ( bindingByName !== undefined ) {
  27300. for ( const trackName in bindingByName ) {
  27301. const binding = bindingByName[ trackName ];
  27302. binding.restoreOriginalState();
  27303. this._removeInactiveBinding( binding );
  27304. }
  27305. }
  27306. },
  27307. // remove a targeted clip from the cache
  27308. uncacheAction: function ( clip, optionalRoot ) {
  27309. const action = this.existingAction( clip, optionalRoot );
  27310. if ( action !== null ) {
  27311. this._deactivateAction( action );
  27312. this._removeInactiveAction( action );
  27313. }
  27314. }
  27315. } );
  27316. class Uniform {
  27317. constructor( value ) {
  27318. if ( typeof value === 'string' ) {
  27319. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27320. value = arguments[ 1 ];
  27321. }
  27322. this.value = value;
  27323. }
  27324. clone() {
  27325. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27326. }
  27327. }
  27328. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  27329. InterleavedBuffer.call( this, array, stride );
  27330. this.meshPerAttribute = meshPerAttribute || 1;
  27331. }
  27332. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  27333. constructor: InstancedInterleavedBuffer,
  27334. isInstancedInterleavedBuffer: true,
  27335. copy: function ( source ) {
  27336. InterleavedBuffer.prototype.copy.call( this, source );
  27337. this.meshPerAttribute = source.meshPerAttribute;
  27338. return this;
  27339. },
  27340. clone: function ( data ) {
  27341. const ib = InterleavedBuffer.prototype.clone.call( this, data );
  27342. ib.meshPerAttribute = this.meshPerAttribute;
  27343. return ib;
  27344. },
  27345. toJSON: function ( data ) {
  27346. const json = InterleavedBuffer.prototype.toJSON.call( this, data );
  27347. json.isInstancedInterleavedBuffer = true;
  27348. json.meshPerAttribute = this.meshPerAttribute;
  27349. return json;
  27350. }
  27351. } );
  27352. function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) {
  27353. this.buffer = buffer;
  27354. this.type = type;
  27355. this.itemSize = itemSize;
  27356. this.elementSize = elementSize;
  27357. this.count = count;
  27358. this.version = 0;
  27359. }
  27360. Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', {
  27361. set: function ( value ) {
  27362. if ( value === true ) this.version ++;
  27363. }
  27364. } );
  27365. Object.assign( GLBufferAttribute.prototype, {
  27366. isGLBufferAttribute: true,
  27367. setBuffer: function ( buffer ) {
  27368. this.buffer = buffer;
  27369. return this;
  27370. },
  27371. setType: function ( type, elementSize ) {
  27372. this.type = type;
  27373. this.elementSize = elementSize;
  27374. return this;
  27375. },
  27376. setItemSize: function ( itemSize ) {
  27377. this.itemSize = itemSize;
  27378. return this;
  27379. },
  27380. setCount: function ( count ) {
  27381. this.count = count;
  27382. return this;
  27383. },
  27384. } );
  27385. function Raycaster( origin, direction, near, far ) {
  27386. this.ray = new Ray( origin, direction );
  27387. // direction is assumed to be normalized (for accurate distance calculations)
  27388. this.near = near || 0;
  27389. this.far = far || Infinity;
  27390. this.camera = null;
  27391. this.layers = new Layers();
  27392. this.params = {
  27393. Mesh: {},
  27394. Line: { threshold: 1 },
  27395. LOD: {},
  27396. Points: { threshold: 1 },
  27397. Sprite: {}
  27398. };
  27399. Object.defineProperties( this.params, {
  27400. PointCloud: {
  27401. get: function () {
  27402. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  27403. return this.Points;
  27404. }
  27405. }
  27406. } );
  27407. }
  27408. function ascSort( a, b ) {
  27409. return a.distance - b.distance;
  27410. }
  27411. function intersectObject( object, raycaster, intersects, recursive ) {
  27412. if ( object.layers.test( raycaster.layers ) ) {
  27413. object.raycast( raycaster, intersects );
  27414. }
  27415. if ( recursive === true ) {
  27416. const children = object.children;
  27417. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27418. intersectObject( children[ i ], raycaster, intersects, true );
  27419. }
  27420. }
  27421. }
  27422. Object.assign( Raycaster.prototype, {
  27423. set: function ( origin, direction ) {
  27424. // direction is assumed to be normalized (for accurate distance calculations)
  27425. this.ray.set( origin, direction );
  27426. },
  27427. setFromCamera: function ( coords, camera ) {
  27428. if ( ( camera && camera.isPerspectiveCamera ) ) {
  27429. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27430. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27431. this.camera = camera;
  27432. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  27433. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27434. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27435. this.camera = camera;
  27436. } else {
  27437. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  27438. }
  27439. },
  27440. intersectObject: function ( object, recursive, optionalTarget ) {
  27441. const intersects = optionalTarget || [];
  27442. intersectObject( object, this, intersects, recursive );
  27443. intersects.sort( ascSort );
  27444. return intersects;
  27445. },
  27446. intersectObjects: function ( objects, recursive, optionalTarget ) {
  27447. const intersects = optionalTarget || [];
  27448. if ( Array.isArray( objects ) === false ) {
  27449. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  27450. return intersects;
  27451. }
  27452. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27453. intersectObject( objects[ i ], this, intersects, recursive );
  27454. }
  27455. intersects.sort( ascSort );
  27456. return intersects;
  27457. }
  27458. } );
  27459. /**
  27460. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27461. *
  27462. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27463. * The azimuthal angle (theta) is measured from the positive z-axis.
  27464. */
  27465. class Spherical {
  27466. constructor( radius = 1, phi = 0, theta = 0 ) {
  27467. this.radius = radius;
  27468. this.phi = phi; // polar angle
  27469. this.theta = theta; // azimuthal angle
  27470. return this;
  27471. }
  27472. set( radius, phi, theta ) {
  27473. this.radius = radius;
  27474. this.phi = phi;
  27475. this.theta = theta;
  27476. return this;
  27477. }
  27478. clone() {
  27479. return new this.constructor().copy( this );
  27480. }
  27481. copy( other ) {
  27482. this.radius = other.radius;
  27483. this.phi = other.phi;
  27484. this.theta = other.theta;
  27485. return this;
  27486. }
  27487. // restrict phi to be betwee EPS and PI-EPS
  27488. makeSafe() {
  27489. const EPS = 0.000001;
  27490. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27491. return this;
  27492. }
  27493. setFromVector3( v ) {
  27494. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27495. }
  27496. setFromCartesianCoords( x, y, z ) {
  27497. this.radius = Math.sqrt( x * x + y * y + z * z );
  27498. if ( this.radius === 0 ) {
  27499. this.theta = 0;
  27500. this.phi = 0;
  27501. } else {
  27502. this.theta = Math.atan2( x, z );
  27503. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  27504. }
  27505. return this;
  27506. }
  27507. }
  27508. /**
  27509. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27510. */
  27511. class Cylindrical {
  27512. constructor( radius, theta, y ) {
  27513. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27514. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27515. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  27516. return this;
  27517. }
  27518. set( radius, theta, y ) {
  27519. this.radius = radius;
  27520. this.theta = theta;
  27521. this.y = y;
  27522. return this;
  27523. }
  27524. clone() {
  27525. return new this.constructor().copy( this );
  27526. }
  27527. copy( other ) {
  27528. this.radius = other.radius;
  27529. this.theta = other.theta;
  27530. this.y = other.y;
  27531. return this;
  27532. }
  27533. setFromVector3( v ) {
  27534. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27535. }
  27536. setFromCartesianCoords( x, y, z ) {
  27537. this.radius = Math.sqrt( x * x + z * z );
  27538. this.theta = Math.atan2( x, z );
  27539. this.y = y;
  27540. return this;
  27541. }
  27542. }
  27543. const _vector$7 = /*@__PURE__*/ new Vector2();
  27544. class Box2 {
  27545. constructor( min, max ) {
  27546. Object.defineProperty( this, 'isBox2', { value: true } );
  27547. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  27548. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  27549. }
  27550. set( min, max ) {
  27551. this.min.copy( min );
  27552. this.max.copy( max );
  27553. return this;
  27554. }
  27555. setFromPoints( points ) {
  27556. this.makeEmpty();
  27557. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27558. this.expandByPoint( points[ i ] );
  27559. }
  27560. return this;
  27561. }
  27562. setFromCenterAndSize( center, size ) {
  27563. const halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 );
  27564. this.min.copy( center ).sub( halfSize );
  27565. this.max.copy( center ).add( halfSize );
  27566. return this;
  27567. }
  27568. clone() {
  27569. return new this.constructor().copy( this );
  27570. }
  27571. copy( box ) {
  27572. this.min.copy( box.min );
  27573. this.max.copy( box.max );
  27574. return this;
  27575. }
  27576. makeEmpty() {
  27577. this.min.x = this.min.y = + Infinity;
  27578. this.max.x = this.max.y = - Infinity;
  27579. return this;
  27580. }
  27581. isEmpty() {
  27582. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27583. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27584. }
  27585. getCenter( target ) {
  27586. if ( target === undefined ) {
  27587. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  27588. target = new Vector2();
  27589. }
  27590. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27591. }
  27592. getSize( target ) {
  27593. if ( target === undefined ) {
  27594. console.warn( 'THREE.Box2: .getSize() target is now required' );
  27595. target = new Vector2();
  27596. }
  27597. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27598. }
  27599. expandByPoint( point ) {
  27600. this.min.min( point );
  27601. this.max.max( point );
  27602. return this;
  27603. }
  27604. expandByVector( vector ) {
  27605. this.min.sub( vector );
  27606. this.max.add( vector );
  27607. return this;
  27608. }
  27609. expandByScalar( scalar ) {
  27610. this.min.addScalar( - scalar );
  27611. this.max.addScalar( scalar );
  27612. return this;
  27613. }
  27614. containsPoint( point ) {
  27615. return point.x < this.min.x || point.x > this.max.x ||
  27616. point.y < this.min.y || point.y > this.max.y ? false : true;
  27617. }
  27618. containsBox( box ) {
  27619. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27620. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27621. }
  27622. getParameter( point, target ) {
  27623. // This can potentially have a divide by zero if the box
  27624. // has a size dimension of 0.
  27625. if ( target === undefined ) {
  27626. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  27627. target = new Vector2();
  27628. }
  27629. return target.set(
  27630. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27631. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27632. );
  27633. }
  27634. intersectsBox( box ) {
  27635. // using 4 splitting planes to rule out intersections
  27636. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27637. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27638. }
  27639. clampPoint( point, target ) {
  27640. if ( target === undefined ) {
  27641. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  27642. target = new Vector2();
  27643. }
  27644. return target.copy( point ).clamp( this.min, this.max );
  27645. }
  27646. distanceToPoint( point ) {
  27647. const clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max );
  27648. return clampedPoint.sub( point ).length();
  27649. }
  27650. intersect( box ) {
  27651. this.min.max( box.min );
  27652. this.max.min( box.max );
  27653. return this;
  27654. }
  27655. union( box ) {
  27656. this.min.min( box.min );
  27657. this.max.max( box.max );
  27658. return this;
  27659. }
  27660. translate( offset ) {
  27661. this.min.add( offset );
  27662. this.max.add( offset );
  27663. return this;
  27664. }
  27665. equals( box ) {
  27666. return box.min.equals( this.min ) && box.max.equals( this.max );
  27667. }
  27668. }
  27669. const _startP = /*@__PURE__*/ new Vector3();
  27670. const _startEnd = /*@__PURE__*/ new Vector3();
  27671. class Line3 {
  27672. constructor( start, end ) {
  27673. this.start = ( start !== undefined ) ? start : new Vector3();
  27674. this.end = ( end !== undefined ) ? end : new Vector3();
  27675. }
  27676. set( start, end ) {
  27677. this.start.copy( start );
  27678. this.end.copy( end );
  27679. return this;
  27680. }
  27681. clone() {
  27682. return new this.constructor().copy( this );
  27683. }
  27684. copy( line ) {
  27685. this.start.copy( line.start );
  27686. this.end.copy( line.end );
  27687. return this;
  27688. }
  27689. getCenter( target ) {
  27690. if ( target === undefined ) {
  27691. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  27692. target = new Vector3();
  27693. }
  27694. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27695. }
  27696. delta( target ) {
  27697. if ( target === undefined ) {
  27698. console.warn( 'THREE.Line3: .delta() target is now required' );
  27699. target = new Vector3();
  27700. }
  27701. return target.subVectors( this.end, this.start );
  27702. }
  27703. distanceSq() {
  27704. return this.start.distanceToSquared( this.end );
  27705. }
  27706. distance() {
  27707. return this.start.distanceTo( this.end );
  27708. }
  27709. at( t, target ) {
  27710. if ( target === undefined ) {
  27711. console.warn( 'THREE.Line3: .at() target is now required' );
  27712. target = new Vector3();
  27713. }
  27714. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27715. }
  27716. closestPointToPointParameter( point, clampToLine ) {
  27717. _startP.subVectors( point, this.start );
  27718. _startEnd.subVectors( this.end, this.start );
  27719. const startEnd2 = _startEnd.dot( _startEnd );
  27720. const startEnd_startP = _startEnd.dot( _startP );
  27721. let t = startEnd_startP / startEnd2;
  27722. if ( clampToLine ) {
  27723. t = MathUtils.clamp( t, 0, 1 );
  27724. }
  27725. return t;
  27726. }
  27727. closestPointToPoint( point, clampToLine, target ) {
  27728. const t = this.closestPointToPointParameter( point, clampToLine );
  27729. if ( target === undefined ) {
  27730. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  27731. target = new Vector3();
  27732. }
  27733. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27734. }
  27735. applyMatrix4( matrix ) {
  27736. this.start.applyMatrix4( matrix );
  27737. this.end.applyMatrix4( matrix );
  27738. return this;
  27739. }
  27740. equals( line ) {
  27741. return line.start.equals( this.start ) && line.end.equals( this.end );
  27742. }
  27743. }
  27744. function ImmediateRenderObject( material ) {
  27745. Object3D.call( this );
  27746. this.material = material;
  27747. this.render = function ( /* renderCallback */ ) {};
  27748. this.hasPositions = false;
  27749. this.hasNormals = false;
  27750. this.hasColors = false;
  27751. this.hasUvs = false;
  27752. this.positionArray = null;
  27753. this.normalArray = null;
  27754. this.colorArray = null;
  27755. this.uvArray = null;
  27756. this.count = 0;
  27757. }
  27758. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  27759. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27760. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27761. const _vector$8 = /*@__PURE__*/ new Vector3();
  27762. class SpotLightHelper extends Object3D {
  27763. constructor( light, color ) {
  27764. super();
  27765. this.light = light;
  27766. this.light.updateMatrixWorld();
  27767. this.matrix = light.matrixWorld;
  27768. this.matrixAutoUpdate = false;
  27769. this.color = color;
  27770. const geometry = new BufferGeometry();
  27771. const positions = [
  27772. 0, 0, 0, 0, 0, 1,
  27773. 0, 0, 0, 1, 0, 1,
  27774. 0, 0, 0, - 1, 0, 1,
  27775. 0, 0, 0, 0, 1, 1,
  27776. 0, 0, 0, 0, - 1, 1
  27777. ];
  27778. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27779. const p1 = ( i / l ) * Math.PI * 2;
  27780. const p2 = ( j / l ) * Math.PI * 2;
  27781. positions.push(
  27782. Math.cos( p1 ), Math.sin( p1 ), 1,
  27783. Math.cos( p2 ), Math.sin( p2 ), 1
  27784. );
  27785. }
  27786. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27787. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27788. this.cone = new LineSegments( geometry, material );
  27789. this.add( this.cone );
  27790. this.update();
  27791. }
  27792. dispose() {
  27793. this.cone.geometry.dispose();
  27794. this.cone.material.dispose();
  27795. }
  27796. update() {
  27797. this.light.updateMatrixWorld();
  27798. const coneLength = this.light.distance ? this.light.distance : 1000;
  27799. const coneWidth = coneLength * Math.tan( this.light.angle );
  27800. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  27801. _vector$8.setFromMatrixPosition( this.light.target.matrixWorld );
  27802. this.cone.lookAt( _vector$8 );
  27803. if ( this.color !== undefined ) {
  27804. this.cone.material.color.set( this.color );
  27805. } else {
  27806. this.cone.material.color.copy( this.light.color );
  27807. }
  27808. }
  27809. }
  27810. const _vector$9 = /*@__PURE__*/ new Vector3();
  27811. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  27812. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  27813. class SkeletonHelper extends LineSegments {
  27814. constructor( object ) {
  27815. const bones = getBoneList( object );
  27816. const geometry = new BufferGeometry();
  27817. const vertices = [];
  27818. const colors = [];
  27819. const color1 = new Color( 0, 0, 1 );
  27820. const color2 = new Color( 0, 1, 0 );
  27821. for ( let i = 0; i < bones.length; i ++ ) {
  27822. const bone = bones[ i ];
  27823. if ( bone.parent && bone.parent.isBone ) {
  27824. vertices.push( 0, 0, 0 );
  27825. vertices.push( 0, 0, 0 );
  27826. colors.push( color1.r, color1.g, color1.b );
  27827. colors.push( color2.r, color2.g, color2.b );
  27828. }
  27829. }
  27830. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27831. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27832. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  27833. super( geometry, material );
  27834. this.type = 'SkeletonHelper';
  27835. this.isSkeletonHelper = true;
  27836. this.root = object;
  27837. this.bones = bones;
  27838. this.matrix = object.matrixWorld;
  27839. this.matrixAutoUpdate = false;
  27840. }
  27841. updateMatrixWorld( force ) {
  27842. const bones = this.bones;
  27843. const geometry = this.geometry;
  27844. const position = geometry.getAttribute( 'position' );
  27845. _matrixWorldInv.getInverse( this.root.matrixWorld );
  27846. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  27847. const bone = bones[ i ];
  27848. if ( bone.parent && bone.parent.isBone ) {
  27849. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  27850. _vector$9.setFromMatrixPosition( _boneMatrix );
  27851. position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z );
  27852. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  27853. _vector$9.setFromMatrixPosition( _boneMatrix );
  27854. position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z );
  27855. j += 2;
  27856. }
  27857. }
  27858. geometry.getAttribute( 'position' ).needsUpdate = true;
  27859. super.updateMatrixWorld( force );
  27860. }
  27861. }
  27862. function getBoneList( object ) {
  27863. const boneList = [];
  27864. if ( object && object.isBone ) {
  27865. boneList.push( object );
  27866. }
  27867. for ( let i = 0; i < object.children.length; i ++ ) {
  27868. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  27869. }
  27870. return boneList;
  27871. }
  27872. class PointLightHelper extends Mesh {
  27873. constructor( light, sphereSize, color ) {
  27874. const geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  27875. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27876. super( geometry, material );
  27877. this.light = light;
  27878. this.light.updateMatrixWorld();
  27879. this.color = color;
  27880. this.type = 'PointLightHelper';
  27881. this.matrix = this.light.matrixWorld;
  27882. this.matrixAutoUpdate = false;
  27883. this.update();
  27884. /*
  27885. // TODO: delete this comment?
  27886. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27887. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27888. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27889. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27890. const d = light.distance;
  27891. if ( d === 0.0 ) {
  27892. this.lightDistance.visible = false;
  27893. } else {
  27894. this.lightDistance.scale.set( d, d, d );
  27895. }
  27896. this.add( this.lightDistance );
  27897. */
  27898. }
  27899. dispose() {
  27900. this.geometry.dispose();
  27901. this.material.dispose();
  27902. }
  27903. update() {
  27904. if ( this.color !== undefined ) {
  27905. this.material.color.set( this.color );
  27906. } else {
  27907. this.material.color.copy( this.light.color );
  27908. }
  27909. /*
  27910. const d = this.light.distance;
  27911. if ( d === 0.0 ) {
  27912. this.lightDistance.visible = false;
  27913. } else {
  27914. this.lightDistance.visible = true;
  27915. this.lightDistance.scale.set( d, d, d );
  27916. }
  27917. */
  27918. }
  27919. }
  27920. const _vector$a = /*@__PURE__*/ new Vector3();
  27921. const _color1 = /*@__PURE__*/ new Color();
  27922. const _color2 = /*@__PURE__*/ new Color();
  27923. class HemisphereLightHelper extends Object3D {
  27924. constructor( light, size, color ) {
  27925. super();
  27926. this.light = light;
  27927. this.light.updateMatrixWorld();
  27928. this.matrix = light.matrixWorld;
  27929. this.matrixAutoUpdate = false;
  27930. this.color = color;
  27931. const geometry = new OctahedronBufferGeometry( size );
  27932. geometry.rotateY( Math.PI * 0.5 );
  27933. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27934. if ( this.color === undefined ) this.material.vertexColors = true;
  27935. const position = geometry.getAttribute( 'position' );
  27936. const colors = new Float32Array( position.count * 3 );
  27937. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  27938. this.add( new Mesh( geometry, this.material ) );
  27939. this.update();
  27940. }
  27941. dispose() {
  27942. this.children[ 0 ].geometry.dispose();
  27943. this.children[ 0 ].material.dispose();
  27944. }
  27945. update() {
  27946. const mesh = this.children[ 0 ];
  27947. if ( this.color !== undefined ) {
  27948. this.material.color.set( this.color );
  27949. } else {
  27950. const colors = mesh.geometry.getAttribute( 'color' );
  27951. _color1.copy( this.light.color );
  27952. _color2.copy( this.light.groundColor );
  27953. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  27954. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  27955. colors.setXYZ( i, color.r, color.g, color.b );
  27956. }
  27957. colors.needsUpdate = true;
  27958. }
  27959. mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  27960. }
  27961. }
  27962. class GridHelper extends LineSegments {
  27963. constructor( size, divisions, color1, color2 ) {
  27964. size = size || 10;
  27965. divisions = divisions || 10;
  27966. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  27967. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  27968. const center = divisions / 2;
  27969. const step = size / divisions;
  27970. const halfSize = size / 2;
  27971. const vertices = [], colors = [];
  27972. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  27973. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  27974. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  27975. const color = i === center ? color1 : color2;
  27976. color.toArray( colors, j ); j += 3;
  27977. color.toArray( colors, j ); j += 3;
  27978. color.toArray( colors, j ); j += 3;
  27979. color.toArray( colors, j ); j += 3;
  27980. }
  27981. const geometry = new BufferGeometry();
  27982. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27983. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27984. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27985. super( geometry, material );
  27986. this.type = 'GridHelper';
  27987. }
  27988. }
  27989. class PolarGridHelper extends LineSegments {
  27990. constructor( radius, radials, circles, divisions, color1, color2 ) {
  27991. radius = radius || 10;
  27992. radials = radials || 16;
  27993. circles = circles || 8;
  27994. divisions = divisions || 64;
  27995. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  27996. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  27997. const vertices = [];
  27998. const colors = [];
  27999. // create the radials
  28000. for ( let i = 0; i <= radials; i ++ ) {
  28001. const v = ( i / radials ) * ( Math.PI * 2 );
  28002. const x = Math.sin( v ) * radius;
  28003. const z = Math.cos( v ) * radius;
  28004. vertices.push( 0, 0, 0 );
  28005. vertices.push( x, 0, z );
  28006. const color = ( i & 1 ) ? color1 : color2;
  28007. colors.push( color.r, color.g, color.b );
  28008. colors.push( color.r, color.g, color.b );
  28009. }
  28010. // create the circles
  28011. for ( let i = 0; i <= circles; i ++ ) {
  28012. const color = ( i & 1 ) ? color1 : color2;
  28013. const r = radius - ( radius / circles * i );
  28014. for ( let j = 0; j < divisions; j ++ ) {
  28015. // first vertex
  28016. let v = ( j / divisions ) * ( Math.PI * 2 );
  28017. let x = Math.sin( v ) * r;
  28018. let z = Math.cos( v ) * r;
  28019. vertices.push( x, 0, z );
  28020. colors.push( color.r, color.g, color.b );
  28021. // second vertex
  28022. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28023. x = Math.sin( v ) * r;
  28024. z = Math.cos( v ) * r;
  28025. vertices.push( x, 0, z );
  28026. colors.push( color.r, color.g, color.b );
  28027. }
  28028. }
  28029. const geometry = new BufferGeometry();
  28030. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28031. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28032. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28033. super( geometry, material );
  28034. this.type = 'PolarGridHelper';
  28035. }
  28036. }
  28037. const _v1$6 = /*@__PURE__*/ new Vector3();
  28038. const _v2$3 = /*@__PURE__*/ new Vector3();
  28039. const _v3$1 = /*@__PURE__*/ new Vector3();
  28040. class DirectionalLightHelper extends Object3D {
  28041. constructor( light, size, color ) {
  28042. super();
  28043. this.light = light;
  28044. this.light.updateMatrixWorld();
  28045. this.matrix = light.matrixWorld;
  28046. this.matrixAutoUpdate = false;
  28047. this.color = color;
  28048. if ( size === undefined ) size = 1;
  28049. let geometry = new BufferGeometry();
  28050. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28051. - size, size, 0,
  28052. size, size, 0,
  28053. size, - size, 0,
  28054. - size, - size, 0,
  28055. - size, size, 0
  28056. ], 3 ) );
  28057. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28058. this.lightPlane = new Line( geometry, material );
  28059. this.add( this.lightPlane );
  28060. geometry = new BufferGeometry();
  28061. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28062. this.targetLine = new Line( geometry, material );
  28063. this.add( this.targetLine );
  28064. this.update();
  28065. }
  28066. dispose() {
  28067. this.lightPlane.geometry.dispose();
  28068. this.lightPlane.material.dispose();
  28069. this.targetLine.geometry.dispose();
  28070. this.targetLine.material.dispose();
  28071. }
  28072. update() {
  28073. _v1$6.setFromMatrixPosition( this.light.matrixWorld );
  28074. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28075. _v3$1.subVectors( _v2$3, _v1$6 );
  28076. this.lightPlane.lookAt( _v2$3 );
  28077. if ( this.color !== undefined ) {
  28078. this.lightPlane.material.color.set( this.color );
  28079. this.targetLine.material.color.set( this.color );
  28080. } else {
  28081. this.lightPlane.material.color.copy( this.light.color );
  28082. this.targetLine.material.color.copy( this.light.color );
  28083. }
  28084. this.targetLine.lookAt( _v2$3 );
  28085. this.targetLine.scale.z = _v3$1.length();
  28086. }
  28087. }
  28088. const _vector$b = /*@__PURE__*/ new Vector3();
  28089. const _camera = /*@__PURE__*/ new Camera();
  28090. /**
  28091. * - shows frustum, line of sight and up of the camera
  28092. * - suitable for fast updates
  28093. * - based on frustum visualization in lightgl.js shadowmap example
  28094. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28095. */
  28096. class CameraHelper extends LineSegments {
  28097. constructor( camera ) {
  28098. const geometry = new BufferGeometry();
  28099. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28100. const vertices = [];
  28101. const colors = [];
  28102. const pointMap = {};
  28103. // colors
  28104. const colorFrustum = new Color( 0xffaa00 );
  28105. const colorCone = new Color( 0xff0000 );
  28106. const colorUp = new Color( 0x00aaff );
  28107. const colorTarget = new Color( 0xffffff );
  28108. const colorCross = new Color( 0x333333 );
  28109. // near
  28110. addLine( 'n1', 'n2', colorFrustum );
  28111. addLine( 'n2', 'n4', colorFrustum );
  28112. addLine( 'n4', 'n3', colorFrustum );
  28113. addLine( 'n3', 'n1', colorFrustum );
  28114. // far
  28115. addLine( 'f1', 'f2', colorFrustum );
  28116. addLine( 'f2', 'f4', colorFrustum );
  28117. addLine( 'f4', 'f3', colorFrustum );
  28118. addLine( 'f3', 'f1', colorFrustum );
  28119. // sides
  28120. addLine( 'n1', 'f1', colorFrustum );
  28121. addLine( 'n2', 'f2', colorFrustum );
  28122. addLine( 'n3', 'f3', colorFrustum );
  28123. addLine( 'n4', 'f4', colorFrustum );
  28124. // cone
  28125. addLine( 'p', 'n1', colorCone );
  28126. addLine( 'p', 'n2', colorCone );
  28127. addLine( 'p', 'n3', colorCone );
  28128. addLine( 'p', 'n4', colorCone );
  28129. // up
  28130. addLine( 'u1', 'u2', colorUp );
  28131. addLine( 'u2', 'u3', colorUp );
  28132. addLine( 'u3', 'u1', colorUp );
  28133. // target
  28134. addLine( 'c', 't', colorTarget );
  28135. addLine( 'p', 'c', colorCross );
  28136. // cross
  28137. addLine( 'cn1', 'cn2', colorCross );
  28138. addLine( 'cn3', 'cn4', colorCross );
  28139. addLine( 'cf1', 'cf2', colorCross );
  28140. addLine( 'cf3', 'cf4', colorCross );
  28141. function addLine( a, b, color ) {
  28142. addPoint( a, color );
  28143. addPoint( b, color );
  28144. }
  28145. function addPoint( id, color ) {
  28146. vertices.push( 0, 0, 0 );
  28147. colors.push( color.r, color.g, color.b );
  28148. if ( pointMap[ id ] === undefined ) {
  28149. pointMap[ id ] = [];
  28150. }
  28151. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28152. }
  28153. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28154. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28155. super( geometry, material );
  28156. this.type = 'CameraHelper';
  28157. this.camera = camera;
  28158. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28159. this.matrix = camera.matrixWorld;
  28160. this.matrixAutoUpdate = false;
  28161. this.pointMap = pointMap;
  28162. this.update();
  28163. }
  28164. update() {
  28165. const geometry = this.geometry;
  28166. const pointMap = this.pointMap;
  28167. const w = 1, h = 1;
  28168. // we need just camera projection matrix inverse
  28169. // world matrix must be identity
  28170. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28171. // center / target
  28172. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28173. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28174. // near
  28175. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28176. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28177. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28178. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28179. // far
  28180. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28181. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28182. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28183. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28184. // up
  28185. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28186. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28187. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28188. // cross
  28189. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28190. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28191. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28192. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28193. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28194. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28195. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28196. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28197. geometry.getAttribute( 'position' ).needsUpdate = true;
  28198. }
  28199. }
  28200. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28201. _vector$b.set( x, y, z ).unproject( camera );
  28202. const points = pointMap[ point ];
  28203. if ( points !== undefined ) {
  28204. const position = geometry.getAttribute( 'position' );
  28205. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28206. position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z );
  28207. }
  28208. }
  28209. }
  28210. const _box$3 = /*@__PURE__*/ new Box3();
  28211. class BoxHelper extends LineSegments {
  28212. constructor( object, color = 0xffff00 ) {
  28213. 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 ] );
  28214. const positions = new Float32Array( 8 * 3 );
  28215. const geometry = new BufferGeometry();
  28216. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28217. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28218. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28219. this.object = object;
  28220. this.type = 'BoxHelper';
  28221. this.matrixAutoUpdate = false;
  28222. this.update();
  28223. }
  28224. update( object ) {
  28225. if ( object !== undefined ) {
  28226. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28227. }
  28228. if ( this.object !== undefined ) {
  28229. _box$3.setFromObject( this.object );
  28230. }
  28231. if ( _box$3.isEmpty() ) return;
  28232. const min = _box$3.min;
  28233. const max = _box$3.max;
  28234. /*
  28235. 5____4
  28236. 1/___0/|
  28237. | 6__|_7
  28238. 2/___3/
  28239. 0: max.x, max.y, max.z
  28240. 1: min.x, max.y, max.z
  28241. 2: min.x, min.y, max.z
  28242. 3: max.x, min.y, max.z
  28243. 4: max.x, max.y, min.z
  28244. 5: min.x, max.y, min.z
  28245. 6: min.x, min.y, min.z
  28246. 7: max.x, min.y, min.z
  28247. */
  28248. const position = this.geometry.attributes.position;
  28249. const array = position.array;
  28250. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28251. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28252. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28253. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28254. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28255. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28256. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28257. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28258. position.needsUpdate = true;
  28259. this.geometry.computeBoundingSphere();
  28260. }
  28261. setFromObject( object ) {
  28262. this.object = object;
  28263. this.update();
  28264. return this;
  28265. }
  28266. copy( source ) {
  28267. LineSegments.prototype.copy.call( this, source );
  28268. this.object = source.object;
  28269. return this;
  28270. }
  28271. }
  28272. class Box3Helper extends LineSegments {
  28273. constructor( box, color = 0xffff00 ) {
  28274. 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 ] );
  28275. 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 ];
  28276. const geometry = new BufferGeometry();
  28277. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28278. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28279. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28280. this.box = box;
  28281. this.type = 'Box3Helper';
  28282. this.geometry.computeBoundingSphere();
  28283. }
  28284. updateMatrixWorld( force ) {
  28285. const box = this.box;
  28286. if ( box.isEmpty() ) return;
  28287. box.getCenter( this.position );
  28288. box.getSize( this.scale );
  28289. this.scale.multiplyScalar( 0.5 );
  28290. super.updateMatrixWorld( force );
  28291. }
  28292. }
  28293. class PlaneHelper extends Line {
  28294. constructor( plane, size, hex ) {
  28295. const color = ( hex !== undefined ) ? hex : 0xffff00;
  28296. 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 ];
  28297. const geometry = new BufferGeometry();
  28298. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28299. geometry.computeBoundingSphere();
  28300. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28301. this.type = 'PlaneHelper';
  28302. this.plane = plane;
  28303. this.size = ( size === undefined ) ? 1 : size;
  28304. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28305. const geometry2 = new BufferGeometry();
  28306. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28307. geometry2.computeBoundingSphere();
  28308. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28309. }
  28310. updateMatrixWorld( force ) {
  28311. let scale = - this.plane.constant;
  28312. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28313. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28314. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28315. this.lookAt( this.plane.normal );
  28316. super.updateMatrixWorld( force );
  28317. }
  28318. }
  28319. const _axis = /*@__PURE__*/ new Vector3();
  28320. let _lineGeometry, _coneGeometry;
  28321. class ArrowHelper extends Object3D {
  28322. constructor( dir, origin, length, color, headLength, headWidth ) {
  28323. super();
  28324. // dir is assumed to be normalized
  28325. this.type = 'ArrowHelper';
  28326. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  28327. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  28328. if ( length === undefined ) length = 1;
  28329. if ( color === undefined ) color = 0xffff00;
  28330. if ( headLength === undefined ) headLength = 0.2 * length;
  28331. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28332. if ( _lineGeometry === undefined ) {
  28333. _lineGeometry = new BufferGeometry();
  28334. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28335. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  28336. _coneGeometry.translate( 0, - 0.5, 0 );
  28337. }
  28338. this.position.copy( origin );
  28339. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28340. this.line.matrixAutoUpdate = false;
  28341. this.add( this.line );
  28342. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28343. this.cone.matrixAutoUpdate = false;
  28344. this.add( this.cone );
  28345. this.setDirection( dir );
  28346. this.setLength( length, headLength, headWidth );
  28347. }
  28348. setDirection( dir ) {
  28349. // dir is assumed to be normalized
  28350. if ( dir.y > 0.99999 ) {
  28351. this.quaternion.set( 0, 0, 0, 1 );
  28352. } else if ( dir.y < - 0.99999 ) {
  28353. this.quaternion.set( 1, 0, 0, 0 );
  28354. } else {
  28355. _axis.set( dir.z, 0, - dir.x ).normalize();
  28356. const radians = Math.acos( dir.y );
  28357. this.quaternion.setFromAxisAngle( _axis, radians );
  28358. }
  28359. }
  28360. setLength( length, headLength, headWidth ) {
  28361. if ( headLength === undefined ) headLength = 0.2 * length;
  28362. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28363. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28364. this.line.updateMatrix();
  28365. this.cone.scale.set( headWidth, headLength, headWidth );
  28366. this.cone.position.y = length;
  28367. this.cone.updateMatrix();
  28368. }
  28369. setColor( color ) {
  28370. this.line.material.color.set( color );
  28371. this.cone.material.color.set( color );
  28372. }
  28373. copy( source ) {
  28374. super.copy( source, false );
  28375. this.line.copy( source.line );
  28376. this.cone.copy( source.cone );
  28377. return this;
  28378. }
  28379. }
  28380. class AxesHelper extends LineSegments {
  28381. constructor( size = 1 ) {
  28382. const vertices = [
  28383. 0, 0, 0, size, 0, 0,
  28384. 0, 0, 0, 0, size, 0,
  28385. 0, 0, 0, 0, 0, size
  28386. ];
  28387. const colors = [
  28388. 1, 0, 0, 1, 0.6, 0,
  28389. 0, 1, 0, 0.6, 1, 0,
  28390. 0, 0, 1, 0, 0.6, 1
  28391. ];
  28392. const geometry = new BufferGeometry();
  28393. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28394. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28395. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28396. super( geometry, material );
  28397. this.type = 'AxesHelper';
  28398. }
  28399. }
  28400. const LOD_MIN = 4;
  28401. const LOD_MAX = 8;
  28402. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  28403. // The standard deviations (radians) associated with the extra mips. These are
  28404. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28405. // geometric shadowing function. These sigma values squared must match the
  28406. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28407. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28408. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  28409. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28410. // samples and exit early, but not recompile the shader.
  28411. const MAX_SAMPLES = 20;
  28412. const ENCODINGS = {
  28413. [ LinearEncoding ]: 0,
  28414. [ sRGBEncoding ]: 1,
  28415. [ RGBEEncoding ]: 2,
  28416. [ RGBM7Encoding ]: 3,
  28417. [ RGBM16Encoding ]: 4,
  28418. [ RGBDEncoding ]: 5,
  28419. [ GammaEncoding ]: 6
  28420. };
  28421. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  28422. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  28423. let _oldTarget = null;
  28424. // Golden Ratio
  28425. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28426. const INV_PHI = 1 / PHI;
  28427. // Vertices of a dodecahedron (except the opposites, which represent the
  28428. // same axis), used as axis directions evenly spread on a sphere.
  28429. const _axisDirections = [
  28430. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  28431. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28432. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28433. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28434. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28435. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28436. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28437. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28438. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28439. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  28440. /**
  28441. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28442. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28443. * blur to be quickly accessed based on material roughness. It is packed into a
  28444. * special CubeUV format that allows us to perform custom interpolation so that
  28445. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28446. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28447. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28448. * higher roughness levels. In this way we maintain resolution to smoothly
  28449. * interpolate diffuse lighting while limiting sampling computation.
  28450. */
  28451. class PMREMGenerator {
  28452. constructor( renderer ) {
  28453. this._renderer = renderer;
  28454. this._pingPongRenderTarget = null;
  28455. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  28456. this._equirectShader = null;
  28457. this._cubemapShader = null;
  28458. this._compileMaterial( this._blurMaterial );
  28459. }
  28460. /**
  28461. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28462. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28463. * in radians to be applied to the scene before PMREM generation. Optional near
  28464. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28465. * is placed at the origin).
  28466. */
  28467. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  28468. _oldTarget = this._renderer.getRenderTarget();
  28469. const cubeUVRenderTarget = this._allocateTargets();
  28470. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  28471. if ( sigma > 0 ) {
  28472. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  28473. }
  28474. this._applyPMREM( cubeUVRenderTarget );
  28475. this._cleanup( cubeUVRenderTarget );
  28476. return cubeUVRenderTarget;
  28477. }
  28478. /**
  28479. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28480. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28481. * as this matches best with the 256 x 256 cubemap output.
  28482. */
  28483. fromEquirectangular( equirectangular ) {
  28484. return this._fromTexture( equirectangular );
  28485. }
  28486. /**
  28487. * Generates a PMREM from an cubemap texture, which can be either LDR
  28488. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28489. * as this matches best with the 256 x 256 cubemap output.
  28490. */
  28491. fromCubemap( cubemap ) {
  28492. return this._fromTexture( cubemap );
  28493. }
  28494. /**
  28495. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28496. * your texture's network fetch for increased concurrency.
  28497. */
  28498. compileCubemapShader() {
  28499. if ( this._cubemapShader === null ) {
  28500. this._cubemapShader = _getCubemapShader();
  28501. this._compileMaterial( this._cubemapShader );
  28502. }
  28503. }
  28504. /**
  28505. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28506. * your texture's network fetch for increased concurrency.
  28507. */
  28508. compileEquirectangularShader() {
  28509. if ( this._equirectShader === null ) {
  28510. this._equirectShader = _getEquirectShader();
  28511. this._compileMaterial( this._equirectShader );
  28512. }
  28513. }
  28514. /**
  28515. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28516. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28517. * one of them will cause any others to also become unusable.
  28518. */
  28519. dispose() {
  28520. this._blurMaterial.dispose();
  28521. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  28522. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  28523. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  28524. _lodPlanes[ i ].dispose();
  28525. }
  28526. }
  28527. // private interface
  28528. _cleanup( outputTarget ) {
  28529. this._pingPongRenderTarget.dispose();
  28530. this._renderer.setRenderTarget( _oldTarget );
  28531. outputTarget.scissorTest = false;
  28532. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  28533. }
  28534. _fromTexture( texture ) {
  28535. _oldTarget = this._renderer.getRenderTarget();
  28536. const cubeUVRenderTarget = this._allocateTargets( texture );
  28537. this._textureToCubeUV( texture, cubeUVRenderTarget );
  28538. this._applyPMREM( cubeUVRenderTarget );
  28539. this._cleanup( cubeUVRenderTarget );
  28540. return cubeUVRenderTarget;
  28541. }
  28542. _allocateTargets( texture ) { // warning: null texture is valid
  28543. const params = {
  28544. magFilter: NearestFilter,
  28545. minFilter: NearestFilter,
  28546. generateMipmaps: false,
  28547. type: UnsignedByteType,
  28548. format: RGBEFormat,
  28549. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  28550. depthBuffer: false
  28551. };
  28552. const cubeUVRenderTarget = _createRenderTarget( params );
  28553. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  28554. this._pingPongRenderTarget = _createRenderTarget( params );
  28555. return cubeUVRenderTarget;
  28556. }
  28557. _compileMaterial( material ) {
  28558. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  28559. this._renderer.compile( tmpMesh, _flatCamera );
  28560. }
  28561. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  28562. const fov = 90;
  28563. const aspect = 1;
  28564. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  28565. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  28566. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  28567. const renderer = this._renderer;
  28568. const outputEncoding = renderer.outputEncoding;
  28569. const toneMapping = renderer.toneMapping;
  28570. const clearColor = renderer.getClearColor();
  28571. const clearAlpha = renderer.getClearAlpha();
  28572. renderer.toneMapping = NoToneMapping;
  28573. renderer.outputEncoding = LinearEncoding;
  28574. let background = scene.background;
  28575. if ( background && background.isColor ) {
  28576. background.convertSRGBToLinear();
  28577. // Convert linear to RGBE
  28578. const maxComponent = Math.max( background.r, background.g, background.b );
  28579. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  28580. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  28581. const alpha = ( fExp + 128.0 ) / 255.0;
  28582. renderer.setClearColor( background, alpha );
  28583. scene.background = null;
  28584. }
  28585. for ( let i = 0; i < 6; i ++ ) {
  28586. const col = i % 3;
  28587. if ( col == 0 ) {
  28588. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28589. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  28590. } else if ( col == 1 ) {
  28591. cubeCamera.up.set( 0, 0, upSign[ i ] );
  28592. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  28593. } else {
  28594. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28595. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  28596. }
  28597. _setViewport( cubeUVRenderTarget,
  28598. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  28599. renderer.setRenderTarget( cubeUVRenderTarget );
  28600. renderer.render( scene, cubeCamera );
  28601. }
  28602. renderer.toneMapping = toneMapping;
  28603. renderer.outputEncoding = outputEncoding;
  28604. renderer.setClearColor( clearColor, clearAlpha );
  28605. }
  28606. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  28607. const renderer = this._renderer;
  28608. if ( texture.isCubeTexture ) {
  28609. if ( this._cubemapShader == null ) {
  28610. this._cubemapShader = _getCubemapShader();
  28611. }
  28612. } else {
  28613. if ( this._equirectShader == null ) {
  28614. this._equirectShader = _getEquirectShader();
  28615. }
  28616. }
  28617. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  28618. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  28619. const uniforms = material.uniforms;
  28620. uniforms[ 'envMap' ].value = texture;
  28621. if ( ! texture.isCubeTexture ) {
  28622. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  28623. }
  28624. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  28625. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  28626. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  28627. renderer.setRenderTarget( cubeUVRenderTarget );
  28628. renderer.render( mesh, _flatCamera );
  28629. }
  28630. _applyPMREM( cubeUVRenderTarget ) {
  28631. const renderer = this._renderer;
  28632. const autoClear = renderer.autoClear;
  28633. renderer.autoClear = false;
  28634. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  28635. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  28636. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  28637. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  28638. }
  28639. renderer.autoClear = autoClear;
  28640. }
  28641. /**
  28642. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28643. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28644. * the blur latitudinally (around the poles), and then longitudinally (towards
  28645. * the poles) to approximate the orthogonally-separable blur. It is least
  28646. * accurate at the poles, but still does a decent job.
  28647. */
  28648. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  28649. const pingPongRenderTarget = this._pingPongRenderTarget;
  28650. this._halfBlur(
  28651. cubeUVRenderTarget,
  28652. pingPongRenderTarget,
  28653. lodIn,
  28654. lodOut,
  28655. sigma,
  28656. 'latitudinal',
  28657. poleAxis );
  28658. this._halfBlur(
  28659. pingPongRenderTarget,
  28660. cubeUVRenderTarget,
  28661. lodOut,
  28662. lodOut,
  28663. sigma,
  28664. 'longitudinal',
  28665. poleAxis );
  28666. }
  28667. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  28668. const renderer = this._renderer;
  28669. const blurMaterial = this._blurMaterial;
  28670. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  28671. console.error(
  28672. 'blur direction must be either latitudinal or longitudinal!' );
  28673. }
  28674. // Number of standard deviations at which to cut off the discrete approximation.
  28675. const STANDARD_DEVIATIONS = 3;
  28676. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  28677. const blurUniforms = blurMaterial.uniforms;
  28678. const pixels = _sizeLods[ lodIn ] - 1;
  28679. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  28680. const sigmaPixels = sigmaRadians / radiansPerPixel;
  28681. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  28682. if ( samples > MAX_SAMPLES ) {
  28683. console.warn( `sigmaRadians, ${
  28684. sigmaRadians}, is too large and will clip, as it requested ${
  28685. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  28686. }
  28687. const weights = [];
  28688. let sum = 0;
  28689. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  28690. const x = i / sigmaPixels;
  28691. const weight = Math.exp( - x * x / 2 );
  28692. weights.push( weight );
  28693. if ( i == 0 ) {
  28694. sum += weight;
  28695. } else if ( i < samples ) {
  28696. sum += 2 * weight;
  28697. }
  28698. }
  28699. for ( let i = 0; i < weights.length; i ++ ) {
  28700. weights[ i ] = weights[ i ] / sum;
  28701. }
  28702. blurUniforms[ 'envMap' ].value = targetIn.texture;
  28703. blurUniforms[ 'samples' ].value = samples;
  28704. blurUniforms[ 'weights' ].value = weights;
  28705. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  28706. if ( poleAxis ) {
  28707. blurUniforms[ 'poleAxis' ].value = poleAxis;
  28708. }
  28709. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  28710. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  28711. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  28712. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  28713. const outputSize = _sizeLods[ lodOut ];
  28714. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  28715. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  28716. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  28717. renderer.setRenderTarget( targetOut );
  28718. renderer.render( blurMesh, _flatCamera );
  28719. }
  28720. }
  28721. function _isLDR( texture ) {
  28722. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  28723. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  28724. }
  28725. function _createPlanes() {
  28726. const _lodPlanes = [];
  28727. const _sizeLods = [];
  28728. const _sigmas = [];
  28729. let lod = LOD_MAX;
  28730. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  28731. const sizeLod = Math.pow( 2, lod );
  28732. _sizeLods.push( sizeLod );
  28733. let sigma = 1.0 / sizeLod;
  28734. if ( i > LOD_MAX - LOD_MIN ) {
  28735. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  28736. } else if ( i == 0 ) {
  28737. sigma = 0;
  28738. }
  28739. _sigmas.push( sigma );
  28740. const texelSize = 1.0 / ( sizeLod - 1 );
  28741. const min = - texelSize / 2;
  28742. const max = 1 + texelSize / 2;
  28743. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  28744. const cubeFaces = 6;
  28745. const vertices = 6;
  28746. const positionSize = 3;
  28747. const uvSize = 2;
  28748. const faceIndexSize = 1;
  28749. const position = new Float32Array( positionSize * vertices * cubeFaces );
  28750. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  28751. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  28752. for ( let face = 0; face < cubeFaces; face ++ ) {
  28753. const x = ( face % 3 ) * 2 / 3 - 1;
  28754. const y = face > 2 ? 0 : - 1;
  28755. const coordinates = [
  28756. x, y, 0,
  28757. x + 2 / 3, y, 0,
  28758. x + 2 / 3, y + 1, 0,
  28759. x, y, 0,
  28760. x + 2 / 3, y + 1, 0,
  28761. x, y + 1, 0
  28762. ];
  28763. position.set( coordinates, positionSize * vertices * face );
  28764. uv.set( uv1, uvSize * vertices * face );
  28765. const fill = [ face, face, face, face, face, face ];
  28766. faceIndex.set( fill, faceIndexSize * vertices * face );
  28767. }
  28768. const planes = new BufferGeometry();
  28769. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  28770. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  28771. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  28772. _lodPlanes.push( planes );
  28773. if ( lod > LOD_MIN ) {
  28774. lod --;
  28775. }
  28776. }
  28777. return { _lodPlanes, _sizeLods, _sigmas };
  28778. }
  28779. function _createRenderTarget( params ) {
  28780. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  28781. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  28782. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  28783. cubeUVRenderTarget.scissorTest = true;
  28784. return cubeUVRenderTarget;
  28785. }
  28786. function _setViewport( target, x, y, width, height ) {
  28787. target.viewport.set( x, y, width, height );
  28788. target.scissor.set( x, y, width, height );
  28789. }
  28790. function _getBlurShader( maxSamples ) {
  28791. const weights = new Float32Array( maxSamples );
  28792. const poleAxis = new Vector3( 0, 1, 0 );
  28793. const shaderMaterial = new RawShaderMaterial( {
  28794. name: 'SphericalGaussianBlur',
  28795. defines: { 'n': maxSamples },
  28796. uniforms: {
  28797. 'envMap': { value: null },
  28798. 'samples': { value: 1 },
  28799. 'weights': { value: weights },
  28800. 'latitudinal': { value: false },
  28801. 'dTheta': { value: 0 },
  28802. 'mipInt': { value: 0 },
  28803. 'poleAxis': { value: poleAxis },
  28804. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  28805. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  28806. },
  28807. vertexShader: _getCommonVertexShader(),
  28808. fragmentShader: /* glsl */`
  28809. precision mediump float;
  28810. precision mediump int;
  28811. varying vec3 vOutputDirection;
  28812. uniform sampler2D envMap;
  28813. uniform int samples;
  28814. uniform float weights[ n ];
  28815. uniform bool latitudinal;
  28816. uniform float dTheta;
  28817. uniform float mipInt;
  28818. uniform vec3 poleAxis;
  28819. ${ _getEncodings() }
  28820. #define ENVMAP_TYPE_CUBE_UV
  28821. #include <cube_uv_reflection_fragment>
  28822. vec3 getSample( float theta, vec3 axis ) {
  28823. float cosTheta = cos( theta );
  28824. // Rodrigues' axis-angle rotation
  28825. vec3 sampleDirection = vOutputDirection * cosTheta
  28826. + cross( axis, vOutputDirection ) * sin( theta )
  28827. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  28828. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  28829. }
  28830. void main() {
  28831. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  28832. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  28833. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  28834. }
  28835. axis = normalize( axis );
  28836. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  28837. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  28838. for ( int i = 1; i < n; i++ ) {
  28839. if ( i >= samples ) {
  28840. break;
  28841. }
  28842. float theta = dTheta * float( i );
  28843. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  28844. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  28845. }
  28846. gl_FragColor = linearToOutputTexel( gl_FragColor );
  28847. }
  28848. `,
  28849. blending: NoBlending,
  28850. depthTest: false,
  28851. depthWrite: false
  28852. } );
  28853. return shaderMaterial;
  28854. }
  28855. function _getEquirectShader() {
  28856. const texelSize = new Vector2( 1, 1 );
  28857. const shaderMaterial = new RawShaderMaterial( {
  28858. name: 'EquirectangularToCubeUV',
  28859. uniforms: {
  28860. 'envMap': { value: null },
  28861. 'texelSize': { value: texelSize },
  28862. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  28863. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  28864. },
  28865. vertexShader: _getCommonVertexShader(),
  28866. fragmentShader: /* glsl */`
  28867. precision mediump float;
  28868. precision mediump int;
  28869. varying vec3 vOutputDirection;
  28870. uniform sampler2D envMap;
  28871. uniform vec2 texelSize;
  28872. ${ _getEncodings() }
  28873. #include <common>
  28874. void main() {
  28875. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  28876. vec3 outputDirection = normalize( vOutputDirection );
  28877. vec2 uv = equirectUv( outputDirection );
  28878. vec2 f = fract( uv / texelSize - 0.5 );
  28879. uv -= f * texelSize;
  28880. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28881. uv.x += texelSize.x;
  28882. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28883. uv.y += texelSize.y;
  28884. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28885. uv.x -= texelSize.x;
  28886. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  28887. vec3 tm = mix( tl, tr, f.x );
  28888. vec3 bm = mix( bl, br, f.x );
  28889. gl_FragColor.rgb = mix( tm, bm, f.y );
  28890. gl_FragColor = linearToOutputTexel( gl_FragColor );
  28891. }
  28892. `,
  28893. blending: NoBlending,
  28894. depthTest: false,
  28895. depthWrite: false
  28896. } );
  28897. return shaderMaterial;
  28898. }
  28899. function _getCubemapShader() {
  28900. const shaderMaterial = new RawShaderMaterial( {
  28901. name: 'CubemapToCubeUV',
  28902. uniforms: {
  28903. 'envMap': { value: null },
  28904. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  28905. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  28906. },
  28907. vertexShader: _getCommonVertexShader(),
  28908. fragmentShader: /* glsl */`
  28909. precision mediump float;
  28910. precision mediump int;
  28911. varying vec3 vOutputDirection;
  28912. uniform samplerCube envMap;
  28913. ${ _getEncodings() }
  28914. void main() {
  28915. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  28916. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  28917. gl_FragColor = linearToOutputTexel( gl_FragColor );
  28918. }
  28919. `,
  28920. blending: NoBlending,
  28921. depthTest: false,
  28922. depthWrite: false
  28923. } );
  28924. return shaderMaterial;
  28925. }
  28926. function _getCommonVertexShader() {
  28927. return /* glsl */`
  28928. precision mediump float;
  28929. precision mediump int;
  28930. attribute vec3 position;
  28931. attribute vec2 uv;
  28932. attribute float faceIndex;
  28933. varying vec3 vOutputDirection;
  28934. // RH coordinate system; PMREM face-indexing convention
  28935. vec3 getDirection( vec2 uv, float face ) {
  28936. uv = 2.0 * uv - 1.0;
  28937. vec3 direction = vec3( uv, 1.0 );
  28938. if ( face == 0.0 ) {
  28939. direction = direction.zyx; // ( 1, v, u ) pos x
  28940. } else if ( face == 1.0 ) {
  28941. direction = direction.xzy;
  28942. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  28943. } else if ( face == 2.0 ) {
  28944. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  28945. } else if ( face == 3.0 ) {
  28946. direction = direction.zyx;
  28947. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  28948. } else if ( face == 4.0 ) {
  28949. direction = direction.xzy;
  28950. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  28951. } else if ( face == 5.0 ) {
  28952. direction.z *= -1.0; // ( u, v, -1 ) neg z
  28953. }
  28954. return direction;
  28955. }
  28956. void main() {
  28957. vOutputDirection = getDirection( uv, faceIndex );
  28958. gl_Position = vec4( position, 1.0 );
  28959. }
  28960. `;
  28961. }
  28962. function _getEncodings() {
  28963. return /* glsl */`
  28964. uniform int inputEncoding;
  28965. uniform int outputEncoding;
  28966. #include <encodings_pars_fragment>
  28967. vec4 inputTexelToLinear( vec4 value ) {
  28968. if ( inputEncoding == 0 ) {
  28969. return value;
  28970. } else if ( inputEncoding == 1 ) {
  28971. return sRGBToLinear( value );
  28972. } else if ( inputEncoding == 2 ) {
  28973. return RGBEToLinear( value );
  28974. } else if ( inputEncoding == 3 ) {
  28975. return RGBMToLinear( value, 7.0 );
  28976. } else if ( inputEncoding == 4 ) {
  28977. return RGBMToLinear( value, 16.0 );
  28978. } else if ( inputEncoding == 5 ) {
  28979. return RGBDToLinear( value, 256.0 );
  28980. } else {
  28981. return GammaToLinear( value, 2.2 );
  28982. }
  28983. }
  28984. vec4 linearToOutputTexel( vec4 value ) {
  28985. if ( outputEncoding == 0 ) {
  28986. return value;
  28987. } else if ( outputEncoding == 1 ) {
  28988. return LinearTosRGB( value );
  28989. } else if ( outputEncoding == 2 ) {
  28990. return LinearToRGBE( value );
  28991. } else if ( outputEncoding == 3 ) {
  28992. return LinearToRGBM( value, 7.0 );
  28993. } else if ( outputEncoding == 4 ) {
  28994. return LinearToRGBM( value, 16.0 );
  28995. } else if ( outputEncoding == 5 ) {
  28996. return LinearToRGBD( value, 256.0 );
  28997. } else {
  28998. return LinearToGamma( value, 2.2 );
  28999. }
  29000. }
  29001. vec4 envMapTexelToLinear( vec4 color ) {
  29002. return inputTexelToLinear( color );
  29003. }
  29004. `;
  29005. }
  29006. function Face4( a, b, c, d, normal, color, materialIndex ) {
  29007. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  29008. return new Face3( a, b, c, normal, color, materialIndex );
  29009. }
  29010. const LineStrip = 0;
  29011. const LinePieces = 1;
  29012. const NoColors = 0;
  29013. const FaceColors = 1;
  29014. const VertexColors = 2;
  29015. function MeshFaceMaterial( materials ) {
  29016. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  29017. return materials;
  29018. }
  29019. function MultiMaterial( materials ) {
  29020. if ( materials === undefined ) materials = [];
  29021. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  29022. materials.isMultiMaterial = true;
  29023. materials.materials = materials;
  29024. materials.clone = function () {
  29025. return materials.slice();
  29026. };
  29027. return materials;
  29028. }
  29029. function PointCloud( geometry, material ) {
  29030. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29031. return new Points( geometry, material );
  29032. }
  29033. function Particle( material ) {
  29034. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29035. return new Sprite( material );
  29036. }
  29037. function ParticleSystem( geometry, material ) {
  29038. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29039. return new Points( geometry, material );
  29040. }
  29041. function PointCloudMaterial( parameters ) {
  29042. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29043. return new PointsMaterial( parameters );
  29044. }
  29045. function ParticleBasicMaterial( parameters ) {
  29046. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29047. return new PointsMaterial( parameters );
  29048. }
  29049. function ParticleSystemMaterial( parameters ) {
  29050. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29051. return new PointsMaterial( parameters );
  29052. }
  29053. function Vertex( x, y, z ) {
  29054. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29055. return new Vector3( x, y, z );
  29056. }
  29057. //
  29058. function DynamicBufferAttribute( array, itemSize ) {
  29059. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  29060. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  29061. }
  29062. function Int8Attribute( array, itemSize ) {
  29063. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29064. return new Int8BufferAttribute( array, itemSize );
  29065. }
  29066. function Uint8Attribute( array, itemSize ) {
  29067. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29068. return new Uint8BufferAttribute( array, itemSize );
  29069. }
  29070. function Uint8ClampedAttribute( array, itemSize ) {
  29071. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29072. return new Uint8ClampedBufferAttribute( array, itemSize );
  29073. }
  29074. function Int16Attribute( array, itemSize ) {
  29075. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29076. return new Int16BufferAttribute( array, itemSize );
  29077. }
  29078. function Uint16Attribute( array, itemSize ) {
  29079. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29080. return new Uint16BufferAttribute( array, itemSize );
  29081. }
  29082. function Int32Attribute( array, itemSize ) {
  29083. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29084. return new Int32BufferAttribute( array, itemSize );
  29085. }
  29086. function Uint32Attribute( array, itemSize ) {
  29087. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29088. return new Uint32BufferAttribute( array, itemSize );
  29089. }
  29090. function Float32Attribute( array, itemSize ) {
  29091. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29092. return new Float32BufferAttribute( array, itemSize );
  29093. }
  29094. function Float64Attribute( array, itemSize ) {
  29095. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29096. return new Float64BufferAttribute( array, itemSize );
  29097. }
  29098. //
  29099. Curve.create = function ( construct, getPoint ) {
  29100. console.log( 'THREE.Curve.create() has been deprecated' );
  29101. construct.prototype = Object.create( Curve.prototype );
  29102. construct.prototype.constructor = construct;
  29103. construct.prototype.getPoint = getPoint;
  29104. return construct;
  29105. };
  29106. //
  29107. Object.assign( CurvePath.prototype, {
  29108. createPointsGeometry: function ( divisions ) {
  29109. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  29110. // generate geometry from path points (for Line or Points objects)
  29111. const pts = this.getPoints( divisions );
  29112. return this.createGeometry( pts );
  29113. },
  29114. createSpacedPointsGeometry: function ( divisions ) {
  29115. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  29116. // generate geometry from equidistant sampling along the path
  29117. const pts = this.getSpacedPoints( divisions );
  29118. return this.createGeometry( pts );
  29119. },
  29120. createGeometry: function ( points ) {
  29121. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  29122. const geometry = new Geometry();
  29123. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29124. const point = points[ i ];
  29125. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  29126. }
  29127. return geometry;
  29128. }
  29129. } );
  29130. //
  29131. Object.assign( Path.prototype, {
  29132. fromPoints: function ( points ) {
  29133. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  29134. return this.setFromPoints( points );
  29135. }
  29136. } );
  29137. //
  29138. function ClosedSplineCurve3( points ) {
  29139. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29140. CatmullRomCurve3.call( this, points );
  29141. this.type = 'catmullrom';
  29142. this.closed = true;
  29143. }
  29144. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29145. //
  29146. function SplineCurve3( points ) {
  29147. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29148. CatmullRomCurve3.call( this, points );
  29149. this.type = 'catmullrom';
  29150. }
  29151. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29152. //
  29153. function Spline( points ) {
  29154. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  29155. CatmullRomCurve3.call( this, points );
  29156. this.type = 'catmullrom';
  29157. }
  29158. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  29159. Object.assign( Spline.prototype, {
  29160. initFromArray: function ( /* a */ ) {
  29161. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  29162. },
  29163. getControlPointsArray: function ( /* optionalTarget */ ) {
  29164. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  29165. },
  29166. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  29167. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  29168. }
  29169. } );
  29170. //
  29171. function AxisHelper( size ) {
  29172. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  29173. return new AxesHelper( size );
  29174. }
  29175. function BoundingBoxHelper( object, color ) {
  29176. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29177. return new BoxHelper( object, color );
  29178. }
  29179. function EdgesHelper( object, hex ) {
  29180. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29181. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29182. }
  29183. GridHelper.prototype.setColors = function () {
  29184. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29185. };
  29186. SkeletonHelper.prototype.update = function () {
  29187. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  29188. };
  29189. function WireframeHelper( object, hex ) {
  29190. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29191. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29192. }
  29193. //
  29194. Object.assign( Loader.prototype, {
  29195. extractUrlBase: function ( url ) {
  29196. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  29197. return LoaderUtils.extractUrlBase( url );
  29198. }
  29199. } );
  29200. Loader.Handlers = {
  29201. add: function ( /* regex, loader */ ) {
  29202. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  29203. },
  29204. get: function ( /* file */ ) {
  29205. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  29206. }
  29207. };
  29208. function XHRLoader( manager ) {
  29209. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29210. return new FileLoader( manager );
  29211. }
  29212. function BinaryTextureLoader( manager ) {
  29213. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29214. return new DataTextureLoader( manager );
  29215. }
  29216. //
  29217. Object.assign( Box2.prototype, {
  29218. center: function ( optionalTarget ) {
  29219. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29220. return this.getCenter( optionalTarget );
  29221. },
  29222. empty: function () {
  29223. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29224. return this.isEmpty();
  29225. },
  29226. isIntersectionBox: function ( box ) {
  29227. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29228. return this.intersectsBox( box );
  29229. },
  29230. size: function ( optionalTarget ) {
  29231. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29232. return this.getSize( optionalTarget );
  29233. }
  29234. } );
  29235. Object.assign( Box3.prototype, {
  29236. center: function ( optionalTarget ) {
  29237. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29238. return this.getCenter( optionalTarget );
  29239. },
  29240. empty: function () {
  29241. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29242. return this.isEmpty();
  29243. },
  29244. isIntersectionBox: function ( box ) {
  29245. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29246. return this.intersectsBox( box );
  29247. },
  29248. isIntersectionSphere: function ( sphere ) {
  29249. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29250. return this.intersectsSphere( sphere );
  29251. },
  29252. size: function ( optionalTarget ) {
  29253. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29254. return this.getSize( optionalTarget );
  29255. }
  29256. } );
  29257. Object.assign( Sphere.prototype, {
  29258. empty: function () {
  29259. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  29260. return this.isEmpty();
  29261. },
  29262. } );
  29263. Frustum.prototype.setFromMatrix = function ( m ) {
  29264. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  29265. return this.setFromProjectionMatrix( m );
  29266. };
  29267. Line3.prototype.center = function ( optionalTarget ) {
  29268. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29269. return this.getCenter( optionalTarget );
  29270. };
  29271. Object.assign( MathUtils, {
  29272. random16: function () {
  29273. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  29274. return Math.random();
  29275. },
  29276. nearestPowerOfTwo: function ( value ) {
  29277. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  29278. return MathUtils.floorPowerOfTwo( value );
  29279. },
  29280. nextPowerOfTwo: function ( value ) {
  29281. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  29282. return MathUtils.ceilPowerOfTwo( value );
  29283. }
  29284. } );
  29285. Object.assign( Matrix3.prototype, {
  29286. flattenToArrayOffset: function ( array, offset ) {
  29287. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29288. return this.toArray( array, offset );
  29289. },
  29290. multiplyVector3: function ( vector ) {
  29291. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29292. return vector.applyMatrix3( this );
  29293. },
  29294. multiplyVector3Array: function ( /* a */ ) {
  29295. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  29296. },
  29297. applyToBufferAttribute: function ( attribute ) {
  29298. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  29299. return attribute.applyMatrix3( this );
  29300. },
  29301. applyToVector3Array: function ( /* array, offset, length */ ) {
  29302. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29303. }
  29304. } );
  29305. Object.assign( Matrix4.prototype, {
  29306. extractPosition: function ( m ) {
  29307. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29308. return this.copyPosition( m );
  29309. },
  29310. flattenToArrayOffset: function ( array, offset ) {
  29311. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29312. return this.toArray( array, offset );
  29313. },
  29314. getPosition: function () {
  29315. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29316. return new Vector3().setFromMatrixColumn( this, 3 );
  29317. },
  29318. setRotationFromQuaternion: function ( q ) {
  29319. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29320. return this.makeRotationFromQuaternion( q );
  29321. },
  29322. multiplyToArray: function () {
  29323. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  29324. },
  29325. multiplyVector3: function ( vector ) {
  29326. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29327. return vector.applyMatrix4( this );
  29328. },
  29329. multiplyVector4: function ( vector ) {
  29330. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29331. return vector.applyMatrix4( this );
  29332. },
  29333. multiplyVector3Array: function ( /* a */ ) {
  29334. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  29335. },
  29336. rotateAxis: function ( v ) {
  29337. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29338. v.transformDirection( this );
  29339. },
  29340. crossVector: function ( vector ) {
  29341. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29342. return vector.applyMatrix4( this );
  29343. },
  29344. translate: function () {
  29345. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29346. },
  29347. rotateX: function () {
  29348. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29349. },
  29350. rotateY: function () {
  29351. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29352. },
  29353. rotateZ: function () {
  29354. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29355. },
  29356. rotateByAxis: function () {
  29357. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29358. },
  29359. applyToBufferAttribute: function ( attribute ) {
  29360. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  29361. return attribute.applyMatrix4( this );
  29362. },
  29363. applyToVector3Array: function ( /* array, offset, length */ ) {
  29364. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29365. },
  29366. makeFrustum: function ( left, right, bottom, top, near, far ) {
  29367. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29368. return this.makePerspective( left, right, top, bottom, near, far );
  29369. }
  29370. } );
  29371. Plane.prototype.isIntersectionLine = function ( line ) {
  29372. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29373. return this.intersectsLine( line );
  29374. };
  29375. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29376. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29377. return vector.applyQuaternion( this );
  29378. };
  29379. Object.assign( Ray.prototype, {
  29380. isIntersectionBox: function ( box ) {
  29381. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29382. return this.intersectsBox( box );
  29383. },
  29384. isIntersectionPlane: function ( plane ) {
  29385. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29386. return this.intersectsPlane( plane );
  29387. },
  29388. isIntersectionSphere: function ( sphere ) {
  29389. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29390. return this.intersectsSphere( sphere );
  29391. }
  29392. } );
  29393. Object.assign( Triangle.prototype, {
  29394. area: function () {
  29395. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  29396. return this.getArea();
  29397. },
  29398. barycoordFromPoint: function ( point, target ) {
  29399. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29400. return this.getBarycoord( point, target );
  29401. },
  29402. midpoint: function ( target ) {
  29403. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  29404. return this.getMidpoint( target );
  29405. },
  29406. normal: function ( target ) {
  29407. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29408. return this.getNormal( target );
  29409. },
  29410. plane: function ( target ) {
  29411. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  29412. return this.getPlane( target );
  29413. }
  29414. } );
  29415. Object.assign( Triangle, {
  29416. barycoordFromPoint: function ( point, a, b, c, target ) {
  29417. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29418. return Triangle.getBarycoord( point, a, b, c, target );
  29419. },
  29420. normal: function ( a, b, c, target ) {
  29421. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29422. return Triangle.getNormal( a, b, c, target );
  29423. }
  29424. } );
  29425. Object.assign( Shape.prototype, {
  29426. extractAllPoints: function ( divisions ) {
  29427. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  29428. return this.extractPoints( divisions );
  29429. },
  29430. extrude: function ( options ) {
  29431. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29432. return new ExtrudeGeometry( this, options );
  29433. },
  29434. makeGeometry: function ( options ) {
  29435. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29436. return new ShapeGeometry( this, options );
  29437. }
  29438. } );
  29439. Object.assign( Vector2.prototype, {
  29440. fromAttribute: function ( attribute, index, offset ) {
  29441. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29442. return this.fromBufferAttribute( attribute, index, offset );
  29443. },
  29444. distanceToManhattan: function ( v ) {
  29445. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29446. return this.manhattanDistanceTo( v );
  29447. },
  29448. lengthManhattan: function () {
  29449. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  29450. return this.manhattanLength();
  29451. }
  29452. } );
  29453. Object.assign( Vector3.prototype, {
  29454. setEulerFromRotationMatrix: function () {
  29455. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29456. },
  29457. setEulerFromQuaternion: function () {
  29458. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29459. },
  29460. getPositionFromMatrix: function ( m ) {
  29461. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29462. return this.setFromMatrixPosition( m );
  29463. },
  29464. getScaleFromMatrix: function ( m ) {
  29465. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29466. return this.setFromMatrixScale( m );
  29467. },
  29468. getColumnFromMatrix: function ( index, matrix ) {
  29469. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29470. return this.setFromMatrixColumn( matrix, index );
  29471. },
  29472. applyProjection: function ( m ) {
  29473. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  29474. return this.applyMatrix4( m );
  29475. },
  29476. fromAttribute: function ( attribute, index, offset ) {
  29477. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29478. return this.fromBufferAttribute( attribute, index, offset );
  29479. },
  29480. distanceToManhattan: function ( v ) {
  29481. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29482. return this.manhattanDistanceTo( v );
  29483. },
  29484. lengthManhattan: function () {
  29485. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  29486. return this.manhattanLength();
  29487. }
  29488. } );
  29489. Object.assign( Vector4.prototype, {
  29490. fromAttribute: function ( attribute, index, offset ) {
  29491. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29492. return this.fromBufferAttribute( attribute, index, offset );
  29493. },
  29494. lengthManhattan: function () {
  29495. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  29496. return this.manhattanLength();
  29497. }
  29498. } );
  29499. //
  29500. Object.assign( Geometry.prototype, {
  29501. computeTangents: function () {
  29502. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  29503. },
  29504. computeLineDistances: function () {
  29505. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  29506. },
  29507. applyMatrix: function ( matrix ) {
  29508. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29509. return this.applyMatrix4( matrix );
  29510. }
  29511. } );
  29512. Object.assign( Object3D.prototype, {
  29513. getChildByName: function ( name ) {
  29514. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29515. return this.getObjectByName( name );
  29516. },
  29517. renderDepth: function () {
  29518. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29519. },
  29520. translate: function ( distance, axis ) {
  29521. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29522. return this.translateOnAxis( axis, distance );
  29523. },
  29524. getWorldRotation: function () {
  29525. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  29526. },
  29527. applyMatrix: function ( matrix ) {
  29528. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  29529. return this.applyMatrix4( matrix );
  29530. }
  29531. } );
  29532. Object.defineProperties( Object3D.prototype, {
  29533. eulerOrder: {
  29534. get: function () {
  29535. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29536. return this.rotation.order;
  29537. },
  29538. set: function ( value ) {
  29539. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29540. this.rotation.order = value;
  29541. }
  29542. },
  29543. useQuaternion: {
  29544. get: function () {
  29545. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29546. },
  29547. set: function () {
  29548. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29549. }
  29550. }
  29551. } );
  29552. Object.assign( Mesh.prototype, {
  29553. setDrawMode: function () {
  29554. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29555. },
  29556. } );
  29557. Object.defineProperties( Mesh.prototype, {
  29558. drawMode: {
  29559. get: function () {
  29560. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  29561. return TrianglesDrawMode;
  29562. },
  29563. set: function () {
  29564. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29565. }
  29566. }
  29567. } );
  29568. Object.defineProperties( LOD.prototype, {
  29569. objects: {
  29570. get: function () {
  29571. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  29572. return this.levels;
  29573. }
  29574. }
  29575. } );
  29576. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  29577. get: function () {
  29578. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  29579. },
  29580. set: function () {
  29581. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  29582. }
  29583. } );
  29584. SkinnedMesh.prototype.initBones = function () {
  29585. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  29586. };
  29587. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  29588. get: function () {
  29589. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  29590. return this.arcLengthDivisions;
  29591. },
  29592. set: function ( value ) {
  29593. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  29594. this.arcLengthDivisions = value;
  29595. }
  29596. } );
  29597. //
  29598. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29599. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  29600. "Use .setFocalLength and .filmGauge for a photographic setup." );
  29601. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29602. this.setFocalLength( focalLength );
  29603. };
  29604. //
  29605. Object.defineProperties( Light.prototype, {
  29606. onlyShadow: {
  29607. set: function () {
  29608. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29609. }
  29610. },
  29611. shadowCameraFov: {
  29612. set: function ( value ) {
  29613. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29614. this.shadow.camera.fov = value;
  29615. }
  29616. },
  29617. shadowCameraLeft: {
  29618. set: function ( value ) {
  29619. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29620. this.shadow.camera.left = value;
  29621. }
  29622. },
  29623. shadowCameraRight: {
  29624. set: function ( value ) {
  29625. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29626. this.shadow.camera.right = value;
  29627. }
  29628. },
  29629. shadowCameraTop: {
  29630. set: function ( value ) {
  29631. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29632. this.shadow.camera.top = value;
  29633. }
  29634. },
  29635. shadowCameraBottom: {
  29636. set: function ( value ) {
  29637. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29638. this.shadow.camera.bottom = value;
  29639. }
  29640. },
  29641. shadowCameraNear: {
  29642. set: function ( value ) {
  29643. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29644. this.shadow.camera.near = value;
  29645. }
  29646. },
  29647. shadowCameraFar: {
  29648. set: function ( value ) {
  29649. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29650. this.shadow.camera.far = value;
  29651. }
  29652. },
  29653. shadowCameraVisible: {
  29654. set: function () {
  29655. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29656. }
  29657. },
  29658. shadowBias: {
  29659. set: function ( value ) {
  29660. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29661. this.shadow.bias = value;
  29662. }
  29663. },
  29664. shadowDarkness: {
  29665. set: function () {
  29666. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29667. }
  29668. },
  29669. shadowMapWidth: {
  29670. set: function ( value ) {
  29671. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29672. this.shadow.mapSize.width = value;
  29673. }
  29674. },
  29675. shadowMapHeight: {
  29676. set: function ( value ) {
  29677. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29678. this.shadow.mapSize.height = value;
  29679. }
  29680. }
  29681. } );
  29682. //
  29683. Object.defineProperties( BufferAttribute.prototype, {
  29684. length: {
  29685. get: function () {
  29686. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29687. return this.array.length;
  29688. }
  29689. },
  29690. dynamic: {
  29691. get: function () {
  29692. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29693. return this.usage === DynamicDrawUsage;
  29694. },
  29695. set: function ( /* value */ ) {
  29696. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29697. this.setUsage( DynamicDrawUsage );
  29698. }
  29699. }
  29700. } );
  29701. Object.assign( BufferAttribute.prototype, {
  29702. setDynamic: function ( value ) {
  29703. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29704. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29705. return this;
  29706. },
  29707. copyIndicesArray: function ( /* indices */ ) {
  29708. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  29709. },
  29710. setArray: function ( /* array */ ) {
  29711. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29712. }
  29713. } );
  29714. Object.assign( BufferGeometry.prototype, {
  29715. addIndex: function ( index ) {
  29716. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29717. this.setIndex( index );
  29718. },
  29719. addAttribute: function ( name, attribute ) {
  29720. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  29721. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  29722. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  29723. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  29724. }
  29725. if ( name === 'index' ) {
  29726. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  29727. this.setIndex( attribute );
  29728. return this;
  29729. }
  29730. return this.setAttribute( name, attribute );
  29731. },
  29732. addDrawCall: function ( start, count, indexOffset ) {
  29733. if ( indexOffset !== undefined ) {
  29734. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29735. }
  29736. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29737. this.addGroup( start, count );
  29738. },
  29739. clearDrawCalls: function () {
  29740. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29741. this.clearGroups();
  29742. },
  29743. computeTangents: function () {
  29744. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  29745. },
  29746. computeOffsets: function () {
  29747. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29748. },
  29749. removeAttribute: function ( name ) {
  29750. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  29751. return this.deleteAttribute( name );
  29752. },
  29753. applyMatrix: function ( matrix ) {
  29754. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29755. return this.applyMatrix4( matrix );
  29756. }
  29757. } );
  29758. Object.defineProperties( BufferGeometry.prototype, {
  29759. drawcalls: {
  29760. get: function () {
  29761. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29762. return this.groups;
  29763. }
  29764. },
  29765. offsets: {
  29766. get: function () {
  29767. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29768. return this.groups;
  29769. }
  29770. }
  29771. } );
  29772. Object.defineProperties( InstancedBufferGeometry.prototype, {
  29773. maxInstancedCount: {
  29774. get: function () {
  29775. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  29776. return this.instanceCount;
  29777. },
  29778. set: function ( value ) {
  29779. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  29780. this.instanceCount = value;
  29781. }
  29782. }
  29783. } );
  29784. Object.defineProperties( Raycaster.prototype, {
  29785. linePrecision: {
  29786. get: function () {
  29787. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  29788. return this.params.Line.threshold;
  29789. },
  29790. set: function ( value ) {
  29791. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  29792. this.params.Line.threshold = value;
  29793. }
  29794. }
  29795. } );
  29796. Object.defineProperties( InterleavedBuffer.prototype, {
  29797. dynamic: {
  29798. get: function () {
  29799. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  29800. return this.usage === DynamicDrawUsage;
  29801. },
  29802. set: function ( value ) {
  29803. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  29804. this.setUsage( value );
  29805. }
  29806. }
  29807. } );
  29808. Object.assign( InterleavedBuffer.prototype, {
  29809. setDynamic: function ( value ) {
  29810. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29811. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29812. return this;
  29813. },
  29814. setArray: function ( /* array */ ) {
  29815. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29816. }
  29817. } );
  29818. //
  29819. Object.assign( ExtrudeBufferGeometry.prototype, {
  29820. getArrays: function () {
  29821. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  29822. },
  29823. addShapeList: function () {
  29824. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  29825. },
  29826. addShape: function () {
  29827. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  29828. }
  29829. } );
  29830. //
  29831. Object.assign( Scene.prototype, {
  29832. dispose: function () {
  29833. console.error( 'THREE.Scene: .dispose() has been removed.' );
  29834. }
  29835. } );
  29836. //
  29837. Object.defineProperties( Uniform.prototype, {
  29838. dynamic: {
  29839. set: function () {
  29840. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  29841. }
  29842. },
  29843. onUpdate: {
  29844. value: function () {
  29845. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29846. return this;
  29847. }
  29848. }
  29849. } );
  29850. //
  29851. Object.defineProperties( Material.prototype, {
  29852. wrapAround: {
  29853. get: function () {
  29854. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29855. },
  29856. set: function () {
  29857. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29858. }
  29859. },
  29860. overdraw: {
  29861. get: function () {
  29862. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29863. },
  29864. set: function () {
  29865. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29866. }
  29867. },
  29868. wrapRGB: {
  29869. get: function () {
  29870. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  29871. return new Color();
  29872. }
  29873. },
  29874. shading: {
  29875. get: function () {
  29876. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29877. },
  29878. set: function ( value ) {
  29879. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29880. this.flatShading = ( value === FlatShading );
  29881. }
  29882. },
  29883. stencilMask: {
  29884. get: function () {
  29885. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29886. return this.stencilFuncMask;
  29887. },
  29888. set: function ( value ) {
  29889. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29890. this.stencilFuncMask = value;
  29891. }
  29892. }
  29893. } );
  29894. Object.defineProperties( MeshPhongMaterial.prototype, {
  29895. metal: {
  29896. get: function () {
  29897. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  29898. return false;
  29899. },
  29900. set: function () {
  29901. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  29902. }
  29903. }
  29904. } );
  29905. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  29906. transparency: {
  29907. get: function () {
  29908. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  29909. return this.transmission;
  29910. },
  29911. set: function ( value ) {
  29912. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  29913. this.transmission = value;
  29914. }
  29915. }
  29916. } );
  29917. Object.defineProperties( ShaderMaterial.prototype, {
  29918. derivatives: {
  29919. get: function () {
  29920. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29921. return this.extensions.derivatives;
  29922. },
  29923. set: function ( value ) {
  29924. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29925. this.extensions.derivatives = value;
  29926. }
  29927. }
  29928. } );
  29929. //
  29930. Object.assign( WebGLRenderer.prototype, {
  29931. clearTarget: function ( renderTarget, color, depth, stencil ) {
  29932. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  29933. this.setRenderTarget( renderTarget );
  29934. this.clear( color, depth, stencil );
  29935. },
  29936. animate: function ( callback ) {
  29937. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  29938. this.setAnimationLoop( callback );
  29939. },
  29940. getCurrentRenderTarget: function () {
  29941. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  29942. return this.getRenderTarget();
  29943. },
  29944. getMaxAnisotropy: function () {
  29945. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  29946. return this.capabilities.getMaxAnisotropy();
  29947. },
  29948. getPrecision: function () {
  29949. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  29950. return this.capabilities.precision;
  29951. },
  29952. resetGLState: function () {
  29953. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  29954. return this.state.reset();
  29955. },
  29956. supportsFloatTextures: function () {
  29957. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29958. return this.extensions.get( 'OES_texture_float' );
  29959. },
  29960. supportsHalfFloatTextures: function () {
  29961. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29962. return this.extensions.get( 'OES_texture_half_float' );
  29963. },
  29964. supportsStandardDerivatives: function () {
  29965. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29966. return this.extensions.get( 'OES_standard_derivatives' );
  29967. },
  29968. supportsCompressedTextureS3TC: function () {
  29969. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29970. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29971. },
  29972. supportsCompressedTexturePVRTC: function () {
  29973. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29974. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29975. },
  29976. supportsBlendMinMax: function () {
  29977. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29978. return this.extensions.get( 'EXT_blend_minmax' );
  29979. },
  29980. supportsVertexTextures: function () {
  29981. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29982. return this.capabilities.vertexTextures;
  29983. },
  29984. supportsInstancedArrays: function () {
  29985. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29986. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29987. },
  29988. enableScissorTest: function ( boolean ) {
  29989. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29990. this.setScissorTest( boolean );
  29991. },
  29992. initMaterial: function () {
  29993. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29994. },
  29995. addPrePlugin: function () {
  29996. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29997. },
  29998. addPostPlugin: function () {
  29999. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  30000. },
  30001. updateShadowMap: function () {
  30002. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  30003. },
  30004. setFaceCulling: function () {
  30005. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  30006. },
  30007. allocTextureUnit: function () {
  30008. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  30009. },
  30010. setTexture: function () {
  30011. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  30012. },
  30013. setTexture2D: function () {
  30014. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  30015. },
  30016. setTextureCube: function () {
  30017. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  30018. },
  30019. getActiveMipMapLevel: function () {
  30020. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  30021. return this.getActiveMipmapLevel();
  30022. }
  30023. } );
  30024. Object.defineProperties( WebGLRenderer.prototype, {
  30025. shadowMapEnabled: {
  30026. get: function () {
  30027. return this.shadowMap.enabled;
  30028. },
  30029. set: function ( value ) {
  30030. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  30031. this.shadowMap.enabled = value;
  30032. }
  30033. },
  30034. shadowMapType: {
  30035. get: function () {
  30036. return this.shadowMap.type;
  30037. },
  30038. set: function ( value ) {
  30039. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  30040. this.shadowMap.type = value;
  30041. }
  30042. },
  30043. shadowMapCullFace: {
  30044. get: function () {
  30045. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30046. return undefined;
  30047. },
  30048. set: function ( /* value */ ) {
  30049. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30050. }
  30051. },
  30052. context: {
  30053. get: function () {
  30054. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  30055. return this.getContext();
  30056. }
  30057. },
  30058. vr: {
  30059. get: function () {
  30060. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  30061. return this.xr;
  30062. }
  30063. },
  30064. gammaInput: {
  30065. get: function () {
  30066. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30067. return false;
  30068. },
  30069. set: function () {
  30070. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30071. }
  30072. },
  30073. gammaOutput: {
  30074. get: function () {
  30075. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30076. return false;
  30077. },
  30078. set: function ( value ) {
  30079. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30080. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  30081. }
  30082. },
  30083. toneMappingWhitePoint: {
  30084. get: function () {
  30085. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30086. return 1.0;
  30087. },
  30088. set: function () {
  30089. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30090. }
  30091. },
  30092. } );
  30093. Object.defineProperties( WebGLShadowMap.prototype, {
  30094. cullFace: {
  30095. get: function () {
  30096. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30097. return undefined;
  30098. },
  30099. set: function ( /* cullFace */ ) {
  30100. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30101. }
  30102. },
  30103. renderReverseSided: {
  30104. get: function () {
  30105. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30106. return undefined;
  30107. },
  30108. set: function () {
  30109. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30110. }
  30111. },
  30112. renderSingleSided: {
  30113. get: function () {
  30114. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30115. return undefined;
  30116. },
  30117. set: function () {
  30118. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30119. }
  30120. }
  30121. } );
  30122. function WebGLRenderTargetCube( width, height, options ) {
  30123. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  30124. return new WebGLCubeRenderTarget( width, options );
  30125. }
  30126. //
  30127. Object.defineProperties( WebGLRenderTarget.prototype, {
  30128. wrapS: {
  30129. get: function () {
  30130. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30131. return this.texture.wrapS;
  30132. },
  30133. set: function ( value ) {
  30134. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30135. this.texture.wrapS = value;
  30136. }
  30137. },
  30138. wrapT: {
  30139. get: function () {
  30140. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30141. return this.texture.wrapT;
  30142. },
  30143. set: function ( value ) {
  30144. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30145. this.texture.wrapT = value;
  30146. }
  30147. },
  30148. magFilter: {
  30149. get: function () {
  30150. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30151. return this.texture.magFilter;
  30152. },
  30153. set: function ( value ) {
  30154. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30155. this.texture.magFilter = value;
  30156. }
  30157. },
  30158. minFilter: {
  30159. get: function () {
  30160. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30161. return this.texture.minFilter;
  30162. },
  30163. set: function ( value ) {
  30164. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30165. this.texture.minFilter = value;
  30166. }
  30167. },
  30168. anisotropy: {
  30169. get: function () {
  30170. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30171. return this.texture.anisotropy;
  30172. },
  30173. set: function ( value ) {
  30174. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30175. this.texture.anisotropy = value;
  30176. }
  30177. },
  30178. offset: {
  30179. get: function () {
  30180. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30181. return this.texture.offset;
  30182. },
  30183. set: function ( value ) {
  30184. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30185. this.texture.offset = value;
  30186. }
  30187. },
  30188. repeat: {
  30189. get: function () {
  30190. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30191. return this.texture.repeat;
  30192. },
  30193. set: function ( value ) {
  30194. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30195. this.texture.repeat = value;
  30196. }
  30197. },
  30198. format: {
  30199. get: function () {
  30200. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30201. return this.texture.format;
  30202. },
  30203. set: function ( value ) {
  30204. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30205. this.texture.format = value;
  30206. }
  30207. },
  30208. type: {
  30209. get: function () {
  30210. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30211. return this.texture.type;
  30212. },
  30213. set: function ( value ) {
  30214. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30215. this.texture.type = value;
  30216. }
  30217. },
  30218. generateMipmaps: {
  30219. get: function () {
  30220. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30221. return this.texture.generateMipmaps;
  30222. },
  30223. set: function ( value ) {
  30224. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30225. this.texture.generateMipmaps = value;
  30226. }
  30227. }
  30228. } );
  30229. //
  30230. Object.defineProperties( Audio.prototype, {
  30231. load: {
  30232. value: function ( file ) {
  30233. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30234. const scope = this;
  30235. const audioLoader = new AudioLoader();
  30236. audioLoader.load( file, function ( buffer ) {
  30237. scope.setBuffer( buffer );
  30238. } );
  30239. return this;
  30240. }
  30241. },
  30242. startTime: {
  30243. set: function () {
  30244. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  30245. }
  30246. }
  30247. } );
  30248. AudioAnalyser.prototype.getData = function () {
  30249. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30250. return this.getFrequencyData();
  30251. };
  30252. //
  30253. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  30254. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  30255. return this.update( renderer, scene );
  30256. };
  30257. //
  30258. const GeometryUtils = {
  30259. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  30260. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  30261. let matrix;
  30262. if ( geometry2.isMesh ) {
  30263. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30264. matrix = geometry2.matrix;
  30265. geometry2 = geometry2.geometry;
  30266. }
  30267. geometry1.merge( geometry2, matrix, materialIndexOffset );
  30268. },
  30269. center: function ( geometry ) {
  30270. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  30271. return geometry.center();
  30272. }
  30273. };
  30274. ImageUtils.crossOrigin = undefined;
  30275. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  30276. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30277. const loader = new TextureLoader();
  30278. loader.setCrossOrigin( this.crossOrigin );
  30279. const texture = loader.load( url, onLoad, undefined, onError );
  30280. if ( mapping ) texture.mapping = mapping;
  30281. return texture;
  30282. };
  30283. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  30284. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30285. const loader = new CubeTextureLoader();
  30286. loader.setCrossOrigin( this.crossOrigin );
  30287. const texture = loader.load( urls, onLoad, undefined, onError );
  30288. if ( mapping ) texture.mapping = mapping;
  30289. return texture;
  30290. };
  30291. ImageUtils.loadCompressedTexture = function () {
  30292. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30293. };
  30294. ImageUtils.loadCompressedTextureCube = function () {
  30295. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30296. };
  30297. //
  30298. function CanvasRenderer() {
  30299. console.error( 'THREE.CanvasRenderer has been removed' );
  30300. }
  30301. //
  30302. function JSONLoader() {
  30303. console.error( 'THREE.JSONLoader has been removed.' );
  30304. }
  30305. //
  30306. const SceneUtils = {
  30307. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  30308. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30309. },
  30310. detach: function ( /* child, parent, scene */ ) {
  30311. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30312. },
  30313. attach: function ( /* child, scene, parent */ ) {
  30314. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30315. }
  30316. };
  30317. //
  30318. function LensFlare() {
  30319. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  30320. }
  30321. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30322. /* eslint-disable no-undef */
  30323. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30324. revision: REVISION,
  30325. } } ) );
  30326. /* eslint-enable no-undef */
  30327. }
  30328. 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, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, BoxGeometry as CubeGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, 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, 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, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, 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, 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, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, 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, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };